Automated Commit: Committing new LKGM version 7252.0.0 for chromeos.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blobdd6a0501f573be3e212c77340956747f01ec8c7a
1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
8 import itertools
9 import os
10 import os.path
11 import sys
12 import re
13 import platform
14 from optparse import OptionParser
15 from subprocess import call
17 _SIZE_OF_UINT32 = 4
18 _SIZE_OF_COMMAND_HEADER = 4
19 _FIRST_SPECIFIC_COMMAND_ID = 256
21 _LICENSE = """// Copyright 2014 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
25 """
27 _DO_NOT_EDIT_WARNING = """// This file is auto-generated from
28 // gpu/command_buffer/build_gles2_cmd_buffer.py
29 // It's formatted by clang-format using chromium coding style:
30 // clang-format -i -style=chromium filename
31 // DO NOT EDIT!
33 """
35 # This string is copied directly out of the gl2.h file from GLES2.0
37 # Edits:
39 # *) Any argument that is a resourceID has been changed to GLid<Type>.
40 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
41 # If it's allowed to not exist it's GLidBind<Type>
43 # *) All GLenums have been changed to GLenumTypeOfEnum
45 _GL_TYPES = {
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
50 'GLshort': 'short',
51 'GLint': 'int',
52 'GLsizei': 'int',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
56 'GLfloat': 'float',
57 'GLclampf': 'float',
58 'GLvoid': 'void',
59 'GLfixed': 'int',
60 'GLclampx': 'int'
63 _GL_TYPES_32 = {
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
68 _GL_TYPES_64 = {
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
74 _CAPABILITY_FLAGS = [
75 {'name': 'blend'},
76 {'name': 'cull_face'},
77 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
78 {'name': 'dither', 'default': True},
79 {'name': 'polygon_offset_fill'},
80 {'name': 'sample_alpha_to_coverage'},
81 {'name': 'sample_coverage'},
82 {'name': 'scissor_test'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
85 {'name': 'rasterizer_discard', 'es3': True},
86 {'name': 'primitive_restart_fixed_index', 'es3': True},
89 _STATES = {
90 'ClearColor': {
91 'type': 'Normal',
92 'func': 'ClearColor',
93 'enum': 'GL_COLOR_CLEAR_VALUE',
94 'states': [
95 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
97 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
98 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
101 'ClearDepthf': {
102 'type': 'Normal',
103 'func': 'ClearDepth',
104 'enum': 'GL_DEPTH_CLEAR_VALUE',
105 'states': [
106 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
109 'ColorMask': {
110 'type': 'Normal',
111 'func': 'ColorMask',
112 'enum': 'GL_COLOR_WRITEMASK',
113 'states': [
115 'name': 'color_mask_red',
116 'type': 'GLboolean',
117 'default': 'true',
118 'cached': True
121 'name': 'color_mask_green',
122 'type': 'GLboolean',
123 'default': 'true',
124 'cached': True
127 'name': 'color_mask_blue',
128 'type': 'GLboolean',
129 'default': 'true',
130 'cached': True
133 'name': 'color_mask_alpha',
134 'type': 'GLboolean',
135 'default': 'true',
136 'cached': True
139 'state_flag': 'framebuffer_state_.clear_state_dirty',
141 'ClearStencil': {
142 'type': 'Normal',
143 'func': 'ClearStencil',
144 'enum': 'GL_STENCIL_CLEAR_VALUE',
145 'states': [
146 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
149 'BlendColor': {
150 'type': 'Normal',
151 'func': 'BlendColor',
152 'enum': 'GL_BLEND_COLOR',
153 'states': [
154 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
156 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
157 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
160 'BlendEquation': {
161 'type': 'SrcDst',
162 'func': 'BlendEquationSeparate',
163 'states': [
165 'name': 'blend_equation_rgb',
166 'type': 'GLenum',
167 'enum': 'GL_BLEND_EQUATION_RGB',
168 'default': 'GL_FUNC_ADD',
171 'name': 'blend_equation_alpha',
172 'type': 'GLenum',
173 'enum': 'GL_BLEND_EQUATION_ALPHA',
174 'default': 'GL_FUNC_ADD',
178 'BlendFunc': {
179 'type': 'SrcDst',
180 'func': 'BlendFuncSeparate',
181 'states': [
183 'name': 'blend_source_rgb',
184 'type': 'GLenum',
185 'enum': 'GL_BLEND_SRC_RGB',
186 'default': 'GL_ONE',
189 'name': 'blend_dest_rgb',
190 'type': 'GLenum',
191 'enum': 'GL_BLEND_DST_RGB',
192 'default': 'GL_ZERO',
195 'name': 'blend_source_alpha',
196 'type': 'GLenum',
197 'enum': 'GL_BLEND_SRC_ALPHA',
198 'default': 'GL_ONE',
201 'name': 'blend_dest_alpha',
202 'type': 'GLenum',
203 'enum': 'GL_BLEND_DST_ALPHA',
204 'default': 'GL_ZERO',
208 'PolygonOffset': {
209 'type': 'Normal',
210 'func': 'PolygonOffset',
211 'states': [
213 'name': 'polygon_offset_factor',
214 'type': 'GLfloat',
215 'enum': 'GL_POLYGON_OFFSET_FACTOR',
216 'default': '0.0f',
219 'name': 'polygon_offset_units',
220 'type': 'GLfloat',
221 'enum': 'GL_POLYGON_OFFSET_UNITS',
222 'default': '0.0f',
226 'CullFace': {
227 'type': 'Normal',
228 'func': 'CullFace',
229 'enum': 'GL_CULL_FACE_MODE',
230 'states': [
232 'name': 'cull_mode',
233 'type': 'GLenum',
234 'default': 'GL_BACK',
238 'FrontFace': {
239 'type': 'Normal',
240 'func': 'FrontFace',
241 'enum': 'GL_FRONT_FACE',
242 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
244 'DepthFunc': {
245 'type': 'Normal',
246 'func': 'DepthFunc',
247 'enum': 'GL_DEPTH_FUNC',
248 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
250 'DepthRange': {
251 'type': 'Normal',
252 'func': 'DepthRange',
253 'enum': 'GL_DEPTH_RANGE',
254 'states': [
255 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
256 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
259 'SampleCoverage': {
260 'type': 'Normal',
261 'func': 'SampleCoverage',
262 'states': [
264 'name': 'sample_coverage_value',
265 'type': 'GLclampf',
266 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
267 'default': '1.0f',
270 'name': 'sample_coverage_invert',
271 'type': 'GLboolean',
272 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
273 'default': 'false',
277 'StencilMask': {
278 'type': 'FrontBack',
279 'func': 'StencilMaskSeparate',
280 'state_flag': 'framebuffer_state_.clear_state_dirty',
281 'states': [
283 'name': 'stencil_front_writemask',
284 'type': 'GLuint',
285 'enum': 'GL_STENCIL_WRITEMASK',
286 'default': '0xFFFFFFFFU',
287 'cached': True,
290 'name': 'stencil_back_writemask',
291 'type': 'GLuint',
292 'enum': 'GL_STENCIL_BACK_WRITEMASK',
293 'default': '0xFFFFFFFFU',
294 'cached': True,
298 'StencilOp': {
299 'type': 'FrontBack',
300 'func': 'StencilOpSeparate',
301 'states': [
303 'name': 'stencil_front_fail_op',
304 'type': 'GLenum',
305 'enum': 'GL_STENCIL_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_front_z_fail_op',
310 'type': 'GLenum',
311 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
312 'default': 'GL_KEEP',
315 'name': 'stencil_front_z_pass_op',
316 'type': 'GLenum',
317 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
318 'default': 'GL_KEEP',
321 'name': 'stencil_back_fail_op',
322 'type': 'GLenum',
323 'enum': 'GL_STENCIL_BACK_FAIL',
324 'default': 'GL_KEEP',
327 'name': 'stencil_back_z_fail_op',
328 'type': 'GLenum',
329 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
330 'default': 'GL_KEEP',
333 'name': 'stencil_back_z_pass_op',
334 'type': 'GLenum',
335 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
336 'default': 'GL_KEEP',
340 'StencilFunc': {
341 'type': 'FrontBack',
342 'func': 'StencilFuncSeparate',
343 'states': [
345 'name': 'stencil_front_func',
346 'type': 'GLenum',
347 'enum': 'GL_STENCIL_FUNC',
348 'default': 'GL_ALWAYS',
351 'name': 'stencil_front_ref',
352 'type': 'GLint',
353 'enum': 'GL_STENCIL_REF',
354 'default': '0',
357 'name': 'stencil_front_mask',
358 'type': 'GLuint',
359 'enum': 'GL_STENCIL_VALUE_MASK',
360 'default': '0xFFFFFFFFU',
363 'name': 'stencil_back_func',
364 'type': 'GLenum',
365 'enum': 'GL_STENCIL_BACK_FUNC',
366 'default': 'GL_ALWAYS',
369 'name': 'stencil_back_ref',
370 'type': 'GLint',
371 'enum': 'GL_STENCIL_BACK_REF',
372 'default': '0',
375 'name': 'stencil_back_mask',
376 'type': 'GLuint',
377 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
378 'default': '0xFFFFFFFFU',
382 'Hint': {
383 'type': 'NamedParameter',
384 'func': 'Hint',
385 'states': [
387 'name': 'hint_generate_mipmap',
388 'type': 'GLenum',
389 'enum': 'GL_GENERATE_MIPMAP_HINT',
390 'default': 'GL_DONT_CARE',
391 'gl_version_flag': '!is_desktop_core_profile'
394 'name': 'hint_fragment_shader_derivative',
395 'type': 'GLenum',
396 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
397 'default': 'GL_DONT_CARE',
398 'extension_flag': 'oes_standard_derivatives'
402 'PixelStore': {
403 'type': 'NamedParameter',
404 'func': 'PixelStorei',
405 'states': [
407 'name': 'pack_alignment',
408 'type': 'GLint',
409 'enum': 'GL_PACK_ALIGNMENT',
410 'default': '4'
413 'name': 'unpack_alignment',
414 'type': 'GLint',
415 'enum': 'GL_UNPACK_ALIGNMENT',
416 'default': '4'
420 # TODO: Consider implemenenting these states
421 # GL_ACTIVE_TEXTURE
422 'LineWidth': {
423 'type': 'Normal',
424 'func': 'LineWidth',
425 'enum': 'GL_LINE_WIDTH',
426 'states': [
428 'name': 'line_width',
429 'type': 'GLfloat',
430 'default': '1.0f',
431 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
432 'nan_check': True,
435 'DepthMask': {
436 'type': 'Normal',
437 'func': 'DepthMask',
438 'enum': 'GL_DEPTH_WRITEMASK',
439 'states': [
441 'name': 'depth_mask',
442 'type': 'GLboolean',
443 'default': 'true',
444 'cached': True
447 'state_flag': 'framebuffer_state_.clear_state_dirty',
449 'Scissor': {
450 'type': 'Normal',
451 'func': 'Scissor',
452 'enum': 'GL_SCISSOR_BOX',
453 'states': [
454 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
456 'name': 'scissor_x',
457 'type': 'GLint',
458 'default': '0',
459 'expected': 'kViewportX',
462 'name': 'scissor_y',
463 'type': 'GLint',
464 'default': '0',
465 'expected': 'kViewportY',
468 'name': 'scissor_width',
469 'type': 'GLsizei',
470 'default': '1',
471 'expected': 'kViewportWidth',
474 'name': 'scissor_height',
475 'type': 'GLsizei',
476 'default': '1',
477 'expected': 'kViewportHeight',
481 'Viewport': {
482 'type': 'Normal',
483 'func': 'Viewport',
484 'enum': 'GL_VIEWPORT',
485 'states': [
486 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
488 'name': 'viewport_x',
489 'type': 'GLint',
490 'default': '0',
491 'expected': 'kViewportX',
494 'name': 'viewport_y',
495 'type': 'GLint',
496 'default': '0',
497 'expected': 'kViewportY',
500 'name': 'viewport_width',
501 'type': 'GLsizei',
502 'default': '1',
503 'expected': 'kViewportWidth',
506 'name': 'viewport_height',
507 'type': 'GLsizei',
508 'default': '1',
509 'expected': 'kViewportHeight',
513 'MatrixValuesCHROMIUM': {
514 'type': 'NamedParameter',
515 'func': 'MatrixLoadfEXT',
516 'states': [
517 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
518 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
519 'name': 'modelview_matrix',
520 'type': 'GLfloat',
521 'default': [
522 '1.0f', '0.0f','0.0f','0.0f',
523 '0.0f', '1.0f','0.0f','0.0f',
524 '0.0f', '0.0f','1.0f','0.0f',
525 '0.0f', '0.0f','0.0f','1.0f',
527 'extension_flag': 'chromium_path_rendering',
529 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
530 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
531 'name': 'projection_matrix',
532 'type': 'GLfloat',
533 'default': [
534 '1.0f', '0.0f','0.0f','0.0f',
535 '0.0f', '1.0f','0.0f','0.0f',
536 '0.0f', '0.0f','1.0f','0.0f',
537 '0.0f', '0.0f','0.0f','1.0f',
539 'extension_flag': 'chromium_path_rendering',
545 # Named type info object represents a named type that is used in OpenGL call
546 # arguments. Each named type defines a set of valid OpenGL call arguments. The
547 # named types are used in 'cmd_buffer_functions.txt'.
548 # type: The actual GL type of the named type.
549 # valid: The list of values that are valid for both the client and the service.
550 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
551 # invalid: Examples of invalid values for the type. At least these values
552 # should be tested to be invalid.
553 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
554 # deprecated in ES 3.
555 # is_complete: The list of valid values of type are final and will not be
556 # modified during runtime.
557 _NAMED_TYPE_INFO = {
558 'BlitFilter': {
559 'type': 'GLenum',
560 'valid': [
561 'GL_NEAREST',
562 'GL_LINEAR',
564 'invalid': [
565 'GL_LINEAR_MIPMAP_LINEAR',
568 'FrameBufferTarget': {
569 'type': 'GLenum',
570 'valid': [
571 'GL_FRAMEBUFFER',
573 'valid_es3': [
574 'GL_DRAW_FRAMEBUFFER' ,
575 'GL_READ_FRAMEBUFFER' ,
577 'invalid': [
578 'GL_RENDERBUFFER',
581 'InvalidateFrameBufferTarget': {
582 'type': 'GLenum',
583 'valid': [
584 'GL_FRAMEBUFFER',
586 'invalid': [
587 'GL_DRAW_FRAMEBUFFER' ,
588 'GL_READ_FRAMEBUFFER' ,
591 'RenderBufferTarget': {
592 'type': 'GLenum',
593 'valid': [
594 'GL_RENDERBUFFER',
596 'invalid': [
597 'GL_FRAMEBUFFER',
600 'BufferTarget': {
601 'type': 'GLenum',
602 'valid': [
603 'GL_ARRAY_BUFFER',
604 'GL_ELEMENT_ARRAY_BUFFER',
606 'valid_es3': [
607 'GL_COPY_READ_BUFFER',
608 'GL_COPY_WRITE_BUFFER',
609 'GL_PIXEL_PACK_BUFFER',
610 'GL_PIXEL_UNPACK_BUFFER',
611 'GL_TRANSFORM_FEEDBACK_BUFFER',
612 'GL_UNIFORM_BUFFER',
614 'invalid': [
615 'GL_RENDERBUFFER',
618 'IndexedBufferTarget': {
619 'type': 'GLenum',
620 'valid': [
621 'GL_TRANSFORM_FEEDBACK_BUFFER',
622 'GL_UNIFORM_BUFFER',
624 'invalid': [
625 'GL_RENDERBUFFER',
628 'MapBufferAccess': {
629 'type': 'GLenum',
630 'valid': [
631 'GL_MAP_READ_BIT',
632 'GL_MAP_WRITE_BIT',
633 'GL_MAP_INVALIDATE_RANGE_BIT',
634 'GL_MAP_INVALIDATE_BUFFER_BIT',
635 'GL_MAP_FLUSH_EXPLICIT_BIT',
636 'GL_MAP_UNSYNCHRONIZED_BIT',
638 'invalid': [
639 'GL_SYNC_FLUSH_COMMANDS_BIT',
642 'Bufferiv': {
643 'type': 'GLenum',
644 'valid': [
645 'GL_COLOR',
646 'GL_STENCIL',
648 'invalid': [
649 'GL_RENDERBUFFER',
652 'Bufferuiv': {
653 'type': 'GLenum',
654 'valid': [
655 'GL_COLOR',
657 'invalid': [
658 'GL_RENDERBUFFER',
661 'Bufferfv': {
662 'type': 'GLenum',
663 'valid': [
664 'GL_COLOR',
665 'GL_DEPTH',
667 'invalid': [
668 'GL_RENDERBUFFER',
671 'Bufferfi': {
672 'type': 'GLenum',
673 'valid': [
674 'GL_DEPTH_STENCIL',
676 'invalid': [
677 'GL_RENDERBUFFER',
680 'BufferUsage': {
681 'type': 'GLenum',
682 'valid': [
683 'GL_STREAM_DRAW',
684 'GL_STATIC_DRAW',
685 'GL_DYNAMIC_DRAW',
687 'valid_es3': [
688 'GL_STREAM_READ',
689 'GL_STREAM_COPY',
690 'GL_STATIC_READ',
691 'GL_STATIC_COPY',
692 'GL_DYNAMIC_READ',
693 'GL_DYNAMIC_COPY',
695 'invalid': [
696 'GL_NONE',
699 'CompressedTextureFormat': {
700 'type': 'GLenum',
701 'valid': [
703 'valid_es3': [
704 'GL_COMPRESSED_R11_EAC',
705 'GL_COMPRESSED_SIGNED_R11_EAC',
706 'GL_COMPRESSED_RG11_EAC',
707 'GL_COMPRESSED_SIGNED_RG11_EAC',
708 'GL_COMPRESSED_RGB8_ETC2',
709 'GL_COMPRESSED_SRGB8_ETC2',
710 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
711 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
712 'GL_COMPRESSED_RGBA8_ETC2_EAC',
713 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
716 'GLState': {
717 'type': 'GLenum',
718 'valid': [
719 # NOTE: State an Capability entries added later.
720 'GL_ACTIVE_TEXTURE',
721 'GL_ALIASED_LINE_WIDTH_RANGE',
722 'GL_ALIASED_POINT_SIZE_RANGE',
723 'GL_ALPHA_BITS',
724 'GL_ARRAY_BUFFER_BINDING',
725 'GL_BLUE_BITS',
726 'GL_COMPRESSED_TEXTURE_FORMATS',
727 'GL_CURRENT_PROGRAM',
728 'GL_DEPTH_BITS',
729 'GL_DEPTH_RANGE',
730 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
731 'GL_FRAMEBUFFER_BINDING',
732 'GL_GENERATE_MIPMAP_HINT',
733 'GL_GREEN_BITS',
734 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
735 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
736 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
737 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
738 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
739 'GL_MAX_RENDERBUFFER_SIZE',
740 'GL_MAX_TEXTURE_IMAGE_UNITS',
741 'GL_MAX_TEXTURE_SIZE',
742 'GL_MAX_VARYING_VECTORS',
743 'GL_MAX_VERTEX_ATTRIBS',
744 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
745 'GL_MAX_VERTEX_UNIFORM_VECTORS',
746 'GL_MAX_VIEWPORT_DIMS',
747 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
748 'GL_NUM_SHADER_BINARY_FORMATS',
749 'GL_PACK_ALIGNMENT',
750 'GL_RED_BITS',
751 'GL_RENDERBUFFER_BINDING',
752 'GL_SAMPLE_BUFFERS',
753 'GL_SAMPLE_COVERAGE_INVERT',
754 'GL_SAMPLE_COVERAGE_VALUE',
755 'GL_SAMPLES',
756 'GL_SCISSOR_BOX',
757 'GL_SHADER_BINARY_FORMATS',
758 'GL_SHADER_COMPILER',
759 'GL_SUBPIXEL_BITS',
760 'GL_STENCIL_BITS',
761 'GL_TEXTURE_BINDING_2D',
762 'GL_TEXTURE_BINDING_CUBE_MAP',
763 'GL_UNPACK_ALIGNMENT',
764 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
765 # we can add this because we emulate it if the driver does not support it.
766 'GL_VERTEX_ARRAY_BINDING_OES',
767 'GL_VIEWPORT',
769 'valid_es3': [
770 'GL_COPY_READ_BUFFER_BINDING',
771 'GL_COPY_WRITE_BUFFER_BINDING',
772 'GL_DRAW_BUFFER0',
773 'GL_DRAW_BUFFER1',
774 'GL_DRAW_BUFFER2',
775 'GL_DRAW_BUFFER3',
776 'GL_DRAW_BUFFER4',
777 'GL_DRAW_BUFFER5',
778 'GL_DRAW_BUFFER6',
779 'GL_DRAW_BUFFER7',
780 'GL_DRAW_BUFFER8',
781 'GL_DRAW_BUFFER9',
782 'GL_DRAW_BUFFER10',
783 'GL_DRAW_BUFFER11',
784 'GL_DRAW_BUFFER12',
785 'GL_DRAW_BUFFER13',
786 'GL_DRAW_BUFFER14',
787 'GL_DRAW_BUFFER15',
788 'GL_DRAW_FRAMEBUFFER_BINDING',
789 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
790 'GL_MAJOR_VERSION',
791 'GL_MAX_3D_TEXTURE_SIZE',
792 'GL_MAX_ARRAY_TEXTURE_LAYERS',
793 'GL_MAX_COLOR_ATTACHMENTS',
794 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
795 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
796 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
797 'GL_MAX_DRAW_BUFFERS',
798 'GL_MAX_ELEMENT_INDEX',
799 'GL_MAX_ELEMENTS_INDICES',
800 'GL_MAX_ELEMENTS_VERTICES',
801 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
802 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
803 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
804 'GL_MAX_PROGRAM_TEXEL_OFFSET',
805 'GL_MAX_SAMPLES',
806 'GL_MAX_SERVER_WAIT_TIMEOUT',
807 'GL_MAX_TEXTURE_LOD_BIAS',
808 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
809 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
810 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
811 'GL_MAX_UNIFORM_BLOCK_SIZE',
812 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
813 'GL_MAX_VARYING_COMPONENTS',
814 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
815 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
816 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
817 'GL_MIN_PROGRAM_TEXEL_OFFSET',
818 'GL_MINOR_VERSION',
819 'GL_NUM_EXTENSIONS',
820 'GL_NUM_PROGRAM_BINARY_FORMATS',
821 'GL_PACK_ROW_LENGTH',
822 'GL_PACK_SKIP_PIXELS',
823 'GL_PACK_SKIP_ROWS',
824 'GL_PIXEL_PACK_BUFFER_BINDING',
825 'GL_PIXEL_UNPACK_BUFFER_BINDING',
826 'GL_PROGRAM_BINARY_FORMATS',
827 'GL_READ_BUFFER',
828 'GL_READ_FRAMEBUFFER_BINDING',
829 'GL_SAMPLER_BINDING',
830 'GL_TEXTURE_BINDING_2D_ARRAY',
831 'GL_TEXTURE_BINDING_3D',
832 'GL_TRANSFORM_FEEDBACK_BINDING',
833 'GL_TRANSFORM_FEEDBACK_ACTIVE',
834 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
835 'GL_TRANSFORM_FEEDBACK_PAUSED',
836 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
837 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
838 'GL_UNIFORM_BUFFER_BINDING',
839 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
840 'GL_UNIFORM_BUFFER_SIZE',
841 'GL_UNIFORM_BUFFER_START',
842 'GL_UNPACK_IMAGE_HEIGHT',
843 'GL_UNPACK_ROW_LENGTH',
844 'GL_UNPACK_SKIP_IMAGES',
845 'GL_UNPACK_SKIP_PIXELS',
846 'GL_UNPACK_SKIP_ROWS',
847 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
848 # 'GL_VERTEX_ARRAY_BINDING',
850 'invalid': [
851 'GL_FOG_HINT',
854 'IndexedGLState': {
855 'type': 'GLenum',
856 'valid': [
857 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
858 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
859 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
860 'GL_UNIFORM_BUFFER_BINDING',
861 'GL_UNIFORM_BUFFER_SIZE',
862 'GL_UNIFORM_BUFFER_START',
864 'invalid': [
865 'GL_FOG_HINT',
868 'GetTexParamTarget': {
869 'type': 'GLenum',
870 'valid': [
871 'GL_TEXTURE_2D',
872 'GL_TEXTURE_CUBE_MAP',
874 'valid_es3': [
875 'GL_TEXTURE_2D_ARRAY',
876 'GL_TEXTURE_3D',
878 'invalid': [
879 'GL_PROXY_TEXTURE_CUBE_MAP',
882 'TextureTarget': {
883 'type': 'GLenum',
884 'valid': [
885 'GL_TEXTURE_2D',
886 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
887 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
888 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
889 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
890 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
891 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
893 'invalid': [
894 'GL_PROXY_TEXTURE_CUBE_MAP',
897 'Texture3DTarget': {
898 'type': 'GLenum',
899 'valid': [
900 'GL_TEXTURE_3D',
901 'GL_TEXTURE_2D_ARRAY',
903 'invalid': [
904 'GL_TEXTURE_2D',
907 'TextureBindTarget': {
908 'type': 'GLenum',
909 'valid': [
910 'GL_TEXTURE_2D',
911 'GL_TEXTURE_CUBE_MAP',
913 'valid_es3': [
914 'GL_TEXTURE_3D',
915 'GL_TEXTURE_2D_ARRAY',
917 'invalid': [
918 'GL_TEXTURE_1D',
919 'GL_TEXTURE_3D',
922 'TransformFeedbackBindTarget': {
923 'type': 'GLenum',
924 'valid': [
925 'GL_TRANSFORM_FEEDBACK',
927 'invalid': [
928 'GL_TEXTURE_2D',
931 'TransformFeedbackPrimitiveMode': {
932 'type': 'GLenum',
933 'valid': [
934 'GL_POINTS',
935 'GL_LINES',
936 'GL_TRIANGLES',
938 'invalid': [
939 'GL_LINE_LOOP',
942 'ShaderType': {
943 'type': 'GLenum',
944 'valid': [
945 'GL_VERTEX_SHADER',
946 'GL_FRAGMENT_SHADER',
948 'invalid': [
949 'GL_GEOMETRY_SHADER',
952 'FaceType': {
953 'type': 'GLenum',
954 'valid': [
955 'GL_FRONT',
956 'GL_BACK',
957 'GL_FRONT_AND_BACK',
960 'FaceMode': {
961 'type': 'GLenum',
962 'valid': [
963 'GL_CW',
964 'GL_CCW',
967 'CmpFunction': {
968 'type': 'GLenum',
969 'valid': [
970 'GL_NEVER',
971 'GL_LESS',
972 'GL_EQUAL',
973 'GL_LEQUAL',
974 'GL_GREATER',
975 'GL_NOTEQUAL',
976 'GL_GEQUAL',
977 'GL_ALWAYS',
980 'Equation': {
981 'type': 'GLenum',
982 'valid': [
983 'GL_FUNC_ADD',
984 'GL_FUNC_SUBTRACT',
985 'GL_FUNC_REVERSE_SUBTRACT',
987 'valid_es3': [
988 'GL_MIN',
989 'GL_MAX',
991 'invalid': [
992 'GL_NONE',
995 'SrcBlendFactor': {
996 'type': 'GLenum',
997 'valid': [
998 'GL_ZERO',
999 'GL_ONE',
1000 'GL_SRC_COLOR',
1001 'GL_ONE_MINUS_SRC_COLOR',
1002 'GL_DST_COLOR',
1003 'GL_ONE_MINUS_DST_COLOR',
1004 'GL_SRC_ALPHA',
1005 'GL_ONE_MINUS_SRC_ALPHA',
1006 'GL_DST_ALPHA',
1007 'GL_ONE_MINUS_DST_ALPHA',
1008 'GL_CONSTANT_COLOR',
1009 'GL_ONE_MINUS_CONSTANT_COLOR',
1010 'GL_CONSTANT_ALPHA',
1011 'GL_ONE_MINUS_CONSTANT_ALPHA',
1012 'GL_SRC_ALPHA_SATURATE',
1015 'DstBlendFactor': {
1016 'type': 'GLenum',
1017 'valid': [
1018 'GL_ZERO',
1019 'GL_ONE',
1020 'GL_SRC_COLOR',
1021 'GL_ONE_MINUS_SRC_COLOR',
1022 'GL_DST_COLOR',
1023 'GL_ONE_MINUS_DST_COLOR',
1024 'GL_SRC_ALPHA',
1025 'GL_ONE_MINUS_SRC_ALPHA',
1026 'GL_DST_ALPHA',
1027 'GL_ONE_MINUS_DST_ALPHA',
1028 'GL_CONSTANT_COLOR',
1029 'GL_ONE_MINUS_CONSTANT_COLOR',
1030 'GL_CONSTANT_ALPHA',
1031 'GL_ONE_MINUS_CONSTANT_ALPHA',
1034 'Capability': {
1035 'type': 'GLenum',
1036 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1037 if 'es3' not in cap or cap['es3'] != True],
1038 'valid_es3': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1039 if 'es3' in cap and cap['es3'] == True],
1040 'invalid': [
1041 'GL_CLIP_PLANE0',
1042 'GL_POINT_SPRITE',
1045 'DrawMode': {
1046 'type': 'GLenum',
1047 'valid': [
1048 'GL_POINTS',
1049 'GL_LINE_STRIP',
1050 'GL_LINE_LOOP',
1051 'GL_LINES',
1052 'GL_TRIANGLE_STRIP',
1053 'GL_TRIANGLE_FAN',
1054 'GL_TRIANGLES',
1056 'invalid': [
1057 'GL_QUADS',
1058 'GL_POLYGON',
1061 'IndexType': {
1062 'type': 'GLenum',
1063 'valid': [
1064 'GL_UNSIGNED_BYTE',
1065 'GL_UNSIGNED_SHORT',
1067 'valid_es3': [
1068 'GL_UNSIGNED_INT',
1070 'invalid': [
1071 'GL_INT',
1074 'GetMaxIndexType': {
1075 'type': 'GLenum',
1076 'valid': [
1077 'GL_UNSIGNED_BYTE',
1078 'GL_UNSIGNED_SHORT',
1079 'GL_UNSIGNED_INT',
1081 'invalid': [
1082 'GL_INT',
1085 'Attachment': {
1086 'type': 'GLenum',
1087 'valid': [
1088 'GL_COLOR_ATTACHMENT0',
1089 'GL_DEPTH_ATTACHMENT',
1090 'GL_STENCIL_ATTACHMENT',
1092 'valid_es3': [
1093 'GL_DEPTH_STENCIL_ATTACHMENT',
1096 'BackbufferAttachment': {
1097 'type': 'GLenum',
1098 'valid': [
1099 'GL_COLOR_EXT',
1100 'GL_DEPTH_EXT',
1101 'GL_STENCIL_EXT',
1104 'BufferParameter': {
1105 'type': 'GLenum',
1106 'valid': [
1107 'GL_BUFFER_SIZE',
1108 'GL_BUFFER_USAGE',
1110 'valid_es3': [
1111 'GL_BUFFER_ACCESS_FLAGS',
1112 'GL_BUFFER_MAPPED',
1113 'GL_BUFFER_MAP_LENGTH',
1114 'GL_BUFFER_MAP_OFFSET',
1116 'invalid': [
1117 'GL_PIXEL_PACK_BUFFER',
1120 'BufferMode': {
1121 'type': 'GLenum',
1122 'valid': [
1123 'GL_INTERLEAVED_ATTRIBS',
1124 'GL_SEPARATE_ATTRIBS',
1126 'invalid': [
1127 'GL_PIXEL_PACK_BUFFER',
1130 'FrameBufferParameter': {
1131 'type': 'GLenum',
1132 'valid': [
1133 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1134 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1135 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1136 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1138 'valid_es3': [
1139 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1140 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1141 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1142 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1143 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1144 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1145 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1146 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1147 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1150 'MatrixMode': {
1151 'type': 'GLenum',
1152 'valid': [
1153 'GL_PATH_PROJECTION_CHROMIUM',
1154 'GL_PATH_MODELVIEW_CHROMIUM',
1157 'ProgramParameter': {
1158 'type': 'GLenum',
1159 'valid': [
1160 'GL_DELETE_STATUS',
1161 'GL_LINK_STATUS',
1162 'GL_VALIDATE_STATUS',
1163 'GL_INFO_LOG_LENGTH',
1164 'GL_ATTACHED_SHADERS',
1165 'GL_ACTIVE_ATTRIBUTES',
1166 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1167 'GL_ACTIVE_UNIFORMS',
1168 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1170 'valid_es3': [
1171 'GL_ACTIVE_UNIFORM_BLOCKS',
1172 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1173 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1174 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1175 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1177 'invalid': [
1178 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1181 'QueryObjectParameter': {
1182 'type': 'GLenum',
1183 'valid': [
1184 'GL_QUERY_RESULT_EXT',
1185 'GL_QUERY_RESULT_AVAILABLE_EXT',
1188 'QueryParameter': {
1189 'type': 'GLenum',
1190 'valid': [
1191 'GL_CURRENT_QUERY_EXT',
1194 'QueryTarget': {
1195 'type': 'GLenum',
1196 'valid': [
1197 'GL_ANY_SAMPLES_PASSED_EXT',
1198 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1199 'GL_COMMANDS_ISSUED_CHROMIUM',
1200 'GL_LATENCY_QUERY_CHROMIUM',
1201 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1202 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1203 'GL_COMMANDS_COMPLETED_CHROMIUM',
1206 'RenderBufferParameter': {
1207 'type': 'GLenum',
1208 'valid': [
1209 'GL_RENDERBUFFER_RED_SIZE',
1210 'GL_RENDERBUFFER_GREEN_SIZE',
1211 'GL_RENDERBUFFER_BLUE_SIZE',
1212 'GL_RENDERBUFFER_ALPHA_SIZE',
1213 'GL_RENDERBUFFER_DEPTH_SIZE',
1214 'GL_RENDERBUFFER_STENCIL_SIZE',
1215 'GL_RENDERBUFFER_WIDTH',
1216 'GL_RENDERBUFFER_HEIGHT',
1217 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1219 'valid_es3': [
1220 'GL_RENDERBUFFER_SAMPLES',
1223 'InternalFormatParameter': {
1224 'type': 'GLenum',
1225 'valid': [
1226 'GL_NUM_SAMPLE_COUNTS',
1227 'GL_SAMPLES',
1230 'SamplerParameter': {
1231 'type': 'GLenum',
1232 'valid': [
1233 'GL_TEXTURE_MAG_FILTER',
1234 'GL_TEXTURE_MIN_FILTER',
1235 'GL_TEXTURE_MIN_LOD',
1236 'GL_TEXTURE_MAX_LOD',
1237 'GL_TEXTURE_WRAP_S',
1238 'GL_TEXTURE_WRAP_T',
1239 'GL_TEXTURE_WRAP_R',
1240 'GL_TEXTURE_COMPARE_MODE',
1241 'GL_TEXTURE_COMPARE_FUNC',
1243 'invalid': [
1244 'GL_GENERATE_MIPMAP',
1247 'ShaderParameter': {
1248 'type': 'GLenum',
1249 'valid': [
1250 'GL_SHADER_TYPE',
1251 'GL_DELETE_STATUS',
1252 'GL_COMPILE_STATUS',
1253 'GL_INFO_LOG_LENGTH',
1254 'GL_SHADER_SOURCE_LENGTH',
1255 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1258 'ShaderPrecision': {
1259 'type': 'GLenum',
1260 'valid': [
1261 'GL_LOW_FLOAT',
1262 'GL_MEDIUM_FLOAT',
1263 'GL_HIGH_FLOAT',
1264 'GL_LOW_INT',
1265 'GL_MEDIUM_INT',
1266 'GL_HIGH_INT',
1269 'StringType': {
1270 'type': 'GLenum',
1271 'valid': [
1272 'GL_VENDOR',
1273 'GL_RENDERER',
1274 'GL_VERSION',
1275 'GL_SHADING_LANGUAGE_VERSION',
1276 'GL_EXTENSIONS',
1279 'TextureParameter': {
1280 'type': 'GLenum',
1281 'valid': [
1282 'GL_TEXTURE_MAG_FILTER',
1283 'GL_TEXTURE_MIN_FILTER',
1284 'GL_TEXTURE_POOL_CHROMIUM',
1285 'GL_TEXTURE_WRAP_S',
1286 'GL_TEXTURE_WRAP_T',
1288 'valid_es3': [
1289 'GL_TEXTURE_BASE_LEVEL',
1290 'GL_TEXTURE_COMPARE_FUNC',
1291 'GL_TEXTURE_COMPARE_MODE',
1292 'GL_TEXTURE_IMMUTABLE_FORMAT',
1293 'GL_TEXTURE_IMMUTABLE_LEVELS',
1294 'GL_TEXTURE_MAX_LEVEL',
1295 'GL_TEXTURE_MAX_LOD',
1296 'GL_TEXTURE_MIN_LOD',
1297 'GL_TEXTURE_WRAP_R',
1299 'invalid': [
1300 'GL_GENERATE_MIPMAP',
1303 'TexturePool': {
1304 'type': 'GLenum',
1305 'valid': [
1306 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1307 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1310 'TextureWrapMode': {
1311 'type': 'GLenum',
1312 'valid': [
1313 'GL_CLAMP_TO_EDGE',
1314 'GL_MIRRORED_REPEAT',
1315 'GL_REPEAT',
1318 'TextureMinFilterMode': {
1319 'type': 'GLenum',
1320 'valid': [
1321 'GL_NEAREST',
1322 'GL_LINEAR',
1323 'GL_NEAREST_MIPMAP_NEAREST',
1324 'GL_LINEAR_MIPMAP_NEAREST',
1325 'GL_NEAREST_MIPMAP_LINEAR',
1326 'GL_LINEAR_MIPMAP_LINEAR',
1329 'TextureMagFilterMode': {
1330 'type': 'GLenum',
1331 'valid': [
1332 'GL_NEAREST',
1333 'GL_LINEAR',
1336 'TextureCompareFunc': {
1337 'type': 'GLenum',
1338 'valid': [
1339 'GL_LEQUAL',
1340 'GL_GEQUAL',
1341 'GL_LESS',
1342 'GL_GREATER',
1343 'GL_EQUAL',
1344 'GL_NOTEQUAL',
1345 'GL_ALWAYS',
1346 'GL_NEVER',
1349 'TextureCompareMode': {
1350 'type': 'GLenum',
1351 'valid': [
1352 'GL_NONE',
1353 'GL_COMPARE_REF_TO_TEXTURE',
1356 'TextureUsage': {
1357 'type': 'GLenum',
1358 'valid': [
1359 'GL_NONE',
1360 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1363 'VertexAttribute': {
1364 'type': 'GLenum',
1365 'valid': [
1366 # some enum that the decoder actually passes through to GL needs
1367 # to be the first listed here since it's used in unit tests.
1368 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1369 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1370 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1371 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1372 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1373 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1374 'GL_CURRENT_VERTEX_ATTRIB',
1376 'valid_es3': [
1377 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1378 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1381 'VertexPointer': {
1382 'type': 'GLenum',
1383 'valid': [
1384 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1387 'HintTarget': {
1388 'type': 'GLenum',
1389 'valid': [
1390 'GL_GENERATE_MIPMAP_HINT',
1392 'valid_es3': [
1393 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1395 'invalid': [
1396 'GL_PERSPECTIVE_CORRECTION_HINT',
1399 'HintMode': {
1400 'type': 'GLenum',
1401 'valid': [
1402 'GL_FASTEST',
1403 'GL_NICEST',
1404 'GL_DONT_CARE',
1407 'PixelStore': {
1408 'type': 'GLenum',
1409 'valid': [
1410 'GL_PACK_ALIGNMENT',
1411 'GL_UNPACK_ALIGNMENT',
1413 'valid_es3': [
1414 'GL_PACK_ROW_LENGTH',
1415 'GL_PACK_SKIP_PIXELS',
1416 'GL_PACK_SKIP_ROWS',
1417 'GL_UNPACK_ROW_LENGTH',
1418 'GL_UNPACK_IMAGE_HEIGHT',
1419 'GL_UNPACK_SKIP_PIXELS',
1420 'GL_UNPACK_SKIP_ROWS',
1421 'GL_UNPACK_SKIP_IMAGES',
1423 'invalid': [
1424 'GL_PACK_SWAP_BYTES',
1425 'GL_UNPACK_SWAP_BYTES',
1428 'PixelStoreAlignment': {
1429 'type': 'GLint',
1430 'valid': [
1431 '1',
1432 '2',
1433 '4',
1434 '8',
1436 'invalid': [
1437 '3',
1438 '9',
1441 'ReadPixelFormat': {
1442 'type': 'GLenum',
1443 'valid': [
1444 'GL_ALPHA',
1445 'GL_RGB',
1446 'GL_RGBA',
1448 'valid_es3': [
1449 'GL_RGBA_INTEGER',
1451 'deprecated_es3': [
1452 'GL_ALPHA',
1453 'GL_RGB',
1456 'PixelType': {
1457 'type': 'GLenum',
1458 'valid': [
1459 'GL_UNSIGNED_BYTE',
1460 'GL_UNSIGNED_SHORT_5_6_5',
1461 'GL_UNSIGNED_SHORT_4_4_4_4',
1462 'GL_UNSIGNED_SHORT_5_5_5_1',
1464 'valid_es3': [
1465 'GL_BYTE',
1466 'GL_UNSIGNED_SHORT',
1467 'GL_SHORT',
1468 'GL_UNSIGNED_INT',
1469 'GL_INT',
1470 'GL_HALF_FLOAT',
1471 'GL_FLOAT',
1472 'GL_UNSIGNED_INT_2_10_10_10_REV',
1473 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1474 'GL_UNSIGNED_INT_5_9_9_9_REV',
1475 'GL_UNSIGNED_INT_24_8',
1476 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1478 'invalid': [
1479 'GL_UNSIGNED_BYTE_3_3_2',
1482 'ReadPixelType': {
1483 'type': 'GLenum',
1484 'valid': [
1485 'GL_UNSIGNED_BYTE',
1486 'GL_UNSIGNED_SHORT_5_6_5',
1487 'GL_UNSIGNED_SHORT_4_4_4_4',
1488 'GL_UNSIGNED_SHORT_5_5_5_1',
1490 'invalid': [
1491 'GL_SHORT',
1493 'valid_es3': [
1494 'GL_UNSIGNED_INT',
1495 'GL_INT',
1496 'GL_FLOAT',
1498 'deprecated_es3': [
1499 'GL_UNSIGNED_SHORT_5_6_5',
1500 'GL_UNSIGNED_SHORT_4_4_4_4',
1501 'GL_UNSIGNED_SHORT_5_5_5_1',
1504 'RenderBufferFormat': {
1505 'type': 'GLenum',
1506 'valid': [
1507 'GL_RGBA4',
1508 'GL_RGB565',
1509 'GL_RGB5_A1',
1510 'GL_DEPTH_COMPONENT16',
1511 'GL_STENCIL_INDEX8',
1513 'valid_es3': [
1514 'GL_R8',
1515 'GL_R8UI',
1516 'GL_R8I',
1517 'GL_R16UI',
1518 'GL_R16I',
1519 'GL_R32UI',
1520 'GL_R32I',
1521 'GL_RG8',
1522 'GL_RG8UI',
1523 'GL_RG8I',
1524 'GL_RG16UI',
1525 'GL_RG16I',
1526 'GL_RG32UI',
1527 'GL_RG32I',
1528 'GL_RGB8',
1529 'GL_RGBA8',
1530 'GL_SRGB8_ALPHA8',
1531 'GL_RGB10_A2',
1532 'GL_RGBA8UI',
1533 'GL_RGBA8I',
1534 'GL_RGB10_A2UI',
1535 'GL_RGBA16UI',
1536 'GL_RGBA16I',
1537 'GL_RGBA32UI',
1538 'GL_RGBA32I',
1539 'GL_DEPTH_COMPONENT24',
1540 'GL_DEPTH_COMPONENT32F',
1541 'GL_DEPTH24_STENCIL8',
1542 'GL_DEPTH32F_STENCIL8',
1545 'ShaderBinaryFormat': {
1546 'type': 'GLenum',
1547 'valid': [
1550 'StencilOp': {
1551 'type': 'GLenum',
1552 'valid': [
1553 'GL_KEEP',
1554 'GL_ZERO',
1555 'GL_REPLACE',
1556 'GL_INCR',
1557 'GL_INCR_WRAP',
1558 'GL_DECR',
1559 'GL_DECR_WRAP',
1560 'GL_INVERT',
1563 'TextureFormat': {
1564 'type': 'GLenum',
1565 'valid': [
1566 'GL_ALPHA',
1567 'GL_LUMINANCE',
1568 'GL_LUMINANCE_ALPHA',
1569 'GL_RGB',
1570 'GL_RGBA',
1572 'valid_es3': [
1573 'GL_RED',
1574 'GL_RED_INTEGER',
1575 'GL_RG',
1576 'GL_RG_INTEGER',
1577 'GL_RGB_INTEGER',
1578 'GL_RGBA_INTEGER',
1579 'GL_DEPTH_COMPONENT',
1580 'GL_DEPTH_STENCIL',
1582 'invalid': [
1583 'GL_BGRA',
1584 'GL_BGR',
1587 'TextureInternalFormat': {
1588 'type': 'GLenum',
1589 'valid': [
1590 'GL_ALPHA',
1591 'GL_LUMINANCE',
1592 'GL_LUMINANCE_ALPHA',
1593 'GL_RGB',
1594 'GL_RGBA',
1596 'valid_es3': [
1597 'GL_R8',
1598 'GL_R8_SNORM',
1599 'GL_R16F',
1600 'GL_R32F',
1601 'GL_R8UI',
1602 'GL_R8I',
1603 'GL_R16UI',
1604 'GL_R16I',
1605 'GL_R32UI',
1606 'GL_R32I',
1607 'GL_RG8',
1608 'GL_RG8_SNORM',
1609 'GL_RG16F',
1610 'GL_RG32F',
1611 'GL_RG8UI',
1612 'GL_RG8I',
1613 'GL_RG16UI',
1614 'GL_RG16I',
1615 'GL_RG32UI',
1616 'GL_RG32I',
1617 'GL_RGB8',
1618 'GL_SRGB8',
1619 'GL_RGB565',
1620 'GL_RGB8_SNORM',
1621 'GL_R11F_G11F_B10F',
1622 'GL_RGB9_E5',
1623 'GL_RGB16F',
1624 'GL_RGB32F',
1625 'GL_RGB8UI',
1626 'GL_RGB8I',
1627 'GL_RGB16UI',
1628 'GL_RGB16I',
1629 'GL_RGB32UI',
1630 'GL_RGB32I',
1631 'GL_RGBA8',
1632 'GL_SRGB8_ALPHA8',
1633 'GL_RGBA8_SNORM',
1634 'GL_RGB5_A1',
1635 'GL_RGBA4',
1636 'GL_RGB10_A2',
1637 'GL_RGBA16F',
1638 'GL_RGBA32F',
1639 'GL_RGBA8UI',
1640 'GL_RGBA8I',
1641 'GL_RGB10_A2UI',
1642 'GL_RGBA16UI',
1643 'GL_RGBA16I',
1644 'GL_RGBA32UI',
1645 'GL_RGBA32I',
1646 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1647 # We will reject them dynamically in GPU command buffer.
1648 'GL_DEPTH_COMPONENT16',
1649 'GL_DEPTH_COMPONENT24',
1650 'GL_DEPTH_COMPONENT32F',
1651 'GL_DEPTH24_STENCIL8',
1652 'GL_DEPTH32F_STENCIL8',
1654 'invalid': [
1655 'GL_BGRA',
1656 'GL_BGR',
1659 'TextureInternalFormatStorage': {
1660 'type': 'GLenum',
1661 'valid': [
1662 'GL_RGB565',
1663 'GL_RGBA4',
1664 'GL_RGB5_A1',
1665 'GL_ALPHA8_EXT',
1666 'GL_LUMINANCE8_EXT',
1667 'GL_LUMINANCE8_ALPHA8_EXT',
1668 'GL_RGB8_OES',
1669 'GL_RGBA8_OES',
1671 'valid_es3': [
1672 'GL_R8',
1673 'GL_R8_SNORM',
1674 'GL_R16F',
1675 'GL_R32F',
1676 'GL_R8UI',
1677 'GL_R8I',
1678 'GL_R16UI',
1679 'GL_R16I',
1680 'GL_R32UI',
1681 'GL_R32I',
1682 'GL_RG8',
1683 'GL_RG8_SNORM',
1684 'GL_RG16F',
1685 'GL_RG32F',
1686 'GL_RG8UI',
1687 'GL_RG8I',
1688 'GL_RG16UI',
1689 'GL_RG16I',
1690 'GL_RG32UI',
1691 'GL_RG32I',
1692 'GL_RGB8',
1693 'GL_SRGB8',
1694 'GL_RGB8_SNORM',
1695 'GL_R11F_G11F_B10F',
1696 'GL_RGB9_E5',
1697 'GL_RGB16F',
1698 'GL_RGB32F',
1699 'GL_RGB8UI',
1700 'GL_RGB8I',
1701 'GL_RGB16UI',
1702 'GL_RGB16I',
1703 'GL_RGB32UI',
1704 'GL_RGB32I',
1705 'GL_RGBA8',
1706 'GL_SRGB8_ALPHA8',
1707 'GL_RGBA8_SNORM',
1708 'GL_RGB10_A2',
1709 'GL_RGBA16F',
1710 'GL_RGBA32F',
1711 'GL_RGBA8UI',
1712 'GL_RGBA8I',
1713 'GL_RGB10_A2UI',
1714 'GL_RGBA16UI',
1715 'GL_RGBA16I',
1716 'GL_RGBA32UI',
1717 'GL_RGBA32I',
1718 'GL_DEPTH_COMPONENT16',
1719 'GL_DEPTH_COMPONENT24',
1720 'GL_DEPTH_COMPONENT32F',
1721 'GL_DEPTH24_STENCIL8',
1722 'GL_DEPTH32F_STENCIL8',
1723 'GL_COMPRESSED_R11_EAC',
1724 'GL_COMPRESSED_SIGNED_R11_EAC',
1725 'GL_COMPRESSED_RG11_EAC',
1726 'GL_COMPRESSED_SIGNED_RG11_EAC',
1727 'GL_COMPRESSED_RGB8_ETC2',
1728 'GL_COMPRESSED_SRGB8_ETC2',
1729 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1730 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1731 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1732 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1734 'deprecated_es3': [
1735 'GL_ALPHA8_EXT',
1736 'GL_LUMINANCE8_EXT',
1737 'GL_LUMINANCE8_ALPHA8_EXT',
1738 'GL_ALPHA16F_EXT',
1739 'GL_LUMINANCE16F_EXT',
1740 'GL_LUMINANCE_ALPHA16F_EXT',
1741 'GL_ALPHA32F_EXT',
1742 'GL_LUMINANCE32F_EXT',
1743 'GL_LUMINANCE_ALPHA32F_EXT',
1746 'ImageInternalFormat': {
1747 'type': 'GLenum',
1748 'valid': [
1749 'GL_RGB',
1750 'GL_RGB_YUV_420_CHROMIUM',
1751 'GL_RGBA',
1754 'ImageUsage': {
1755 'type': 'GLenum',
1756 'valid': [
1757 'GL_MAP_CHROMIUM',
1758 'GL_SCANOUT_CHROMIUM'
1761 'ValueBufferTarget': {
1762 'type': 'GLenum',
1763 'valid': [
1764 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1767 'SubscriptionTarget': {
1768 'type': 'GLenum',
1769 'valid': [
1770 'GL_MOUSE_POSITION_CHROMIUM',
1773 'UniformParameter': {
1774 'type': 'GLenum',
1775 'valid': [
1776 'GL_UNIFORM_SIZE',
1777 'GL_UNIFORM_TYPE',
1778 'GL_UNIFORM_NAME_LENGTH',
1779 'GL_UNIFORM_BLOCK_INDEX',
1780 'GL_UNIFORM_OFFSET',
1781 'GL_UNIFORM_ARRAY_STRIDE',
1782 'GL_UNIFORM_MATRIX_STRIDE',
1783 'GL_UNIFORM_IS_ROW_MAJOR',
1785 'invalid': [
1786 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1789 'UniformBlockParameter': {
1790 'type': 'GLenum',
1791 'valid': [
1792 'GL_UNIFORM_BLOCK_BINDING',
1793 'GL_UNIFORM_BLOCK_DATA_SIZE',
1794 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1795 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1796 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1797 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1798 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1800 'invalid': [
1801 'GL_NEAREST',
1804 'VertexAttribType': {
1805 'type': 'GLenum',
1806 'valid': [
1807 'GL_BYTE',
1808 'GL_UNSIGNED_BYTE',
1809 'GL_SHORT',
1810 'GL_UNSIGNED_SHORT',
1811 # 'GL_FIXED', // This is not available on Desktop GL.
1812 'GL_FLOAT',
1814 'valid_es3': [
1815 'GL_INT',
1816 'GL_UNSIGNED_INT',
1817 'GL_HALF_FLOAT',
1818 'GL_INT_2_10_10_10_REV',
1819 'GL_UNSIGNED_INT_2_10_10_10_REV',
1821 'invalid': [
1822 'GL_DOUBLE',
1825 'VertexAttribIType': {
1826 'type': 'GLenum',
1827 'valid': [
1828 'GL_BYTE',
1829 'GL_UNSIGNED_BYTE',
1830 'GL_SHORT',
1831 'GL_UNSIGNED_SHORT',
1832 'GL_INT',
1833 'GL_UNSIGNED_INT',
1835 'invalid': [
1836 'GL_FLOAT',
1837 'GL_DOUBLE',
1840 'TextureBorder': {
1841 'type': 'GLint',
1842 'is_complete': True,
1843 'valid': [
1844 '0',
1846 'invalid': [
1847 '1',
1850 'VertexAttribSize': {
1851 'type': 'GLint',
1852 'valid': [
1853 '1',
1854 '2',
1855 '3',
1856 '4',
1858 'invalid': [
1859 '0',
1860 '5',
1863 'ZeroOnly': {
1864 'type': 'GLint',
1865 'is_complete': True,
1866 'valid': [
1867 '0',
1869 'invalid': [
1870 '1',
1873 'FalseOnly': {
1874 'type': 'GLboolean',
1875 'is_complete': True,
1876 'valid': [
1877 'false',
1879 'invalid': [
1880 'true',
1883 'ResetStatus': {
1884 'type': 'GLenum',
1885 'valid': [
1886 'GL_GUILTY_CONTEXT_RESET_ARB',
1887 'GL_INNOCENT_CONTEXT_RESET_ARB',
1888 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1891 'SyncCondition': {
1892 'type': 'GLenum',
1893 'is_complete': True,
1894 'valid': [
1895 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1897 'invalid': [
1898 '0',
1901 'SyncFlags': {
1902 'type': 'GLbitfield',
1903 'is_complete': True,
1904 'valid': [
1905 '0',
1907 'invalid': [
1908 '1',
1911 'SyncFlushFlags': {
1912 'type': 'GLbitfield',
1913 'valid': [
1914 'GL_SYNC_FLUSH_COMMANDS_BIT',
1915 '0',
1917 'invalid': [
1918 '0xFFFFFFFF',
1921 'SyncParameter': {
1922 'type': 'GLenum',
1923 'valid': [
1924 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1925 'GL_OBJECT_TYPE',
1926 'GL_SYNC_CONDITION',
1927 'GL_SYNC_FLAGS',
1929 'invalid': [
1930 'GL_SYNC_FENCE',
1935 # This table specifies the different pepper interfaces that are supported for
1936 # GL commands. 'dev' is true if it's a dev interface.
1937 _PEPPER_INTERFACES = [
1938 {'name': '', 'dev': False},
1939 {'name': 'InstancedArrays', 'dev': False},
1940 {'name': 'FramebufferBlit', 'dev': False},
1941 {'name': 'FramebufferMultisample', 'dev': False},
1942 {'name': 'ChromiumEnableFeature', 'dev': False},
1943 {'name': 'ChromiumMapSub', 'dev': False},
1944 {'name': 'Query', 'dev': False},
1945 {'name': 'VertexArrayObject', 'dev': False},
1946 {'name': 'DrawBuffers', 'dev': True},
1949 # A function info object specifies the type and other special data for the
1950 # command that will be generated. A base function info object is generated by
1951 # parsing the "cmd_buffer_functions.txt", one for each function in the
1952 # file. These function info objects can be augmented and their values can be
1953 # overridden by adding an object to the table below.
1955 # Must match function names specified in "cmd_buffer_functions.txt".
1957 # cmd_comment: A comment added to the cmd format.
1958 # type: defines which handler will be used to generate code.
1959 # decoder_func: defines which function to call in the decoder to execute the
1960 # corresponding GL command. If not specified the GL command will
1961 # be called directly.
1962 # gl_test_func: GL function that is expected to be called when testing.
1963 # cmd_args: The arguments to use for the command. This overrides generating
1964 # them based on the GL function arguments.
1965 # gen_cmd: Whether or not this function geneates a command. Default = True.
1966 # data_transfer_methods: Array of methods that are used for transfering the
1967 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1968 # The default is 'immediate' if the command has one pointer
1969 # argument, otherwise 'shm'. One command is generated for each
1970 # transfer method. Affects only commands which are not of type
1971 # 'HandWritten', 'GETn' or 'GLcharN'.
1972 # Note: the command arguments that affect this are the final args,
1973 # taking cmd_args override into consideration.
1974 # impl_func: Whether or not to generate the GLES2Implementation part of this
1975 # command.
1976 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1977 # for this command.
1978 # needs_size: If True a data_size field is added to the command.
1979 # count: The number of units per element. For PUTn or PUT types.
1980 # use_count_func: If True the actual data count needs to be computed; the count
1981 # argument specifies the maximum count.
1982 # unit_test: If False no service side unit test will be generated.
1983 # client_test: If False no client side unit test will be generated.
1984 # expectation: If False the unit test will have no expected calls.
1985 # gen_func: Name of function that generates GL resource for corresponding
1986 # bind function.
1987 # states: array of states that get set by this function corresponding to
1988 # the given arguments
1989 # state_flag: name of flag that is set to true when function is called.
1990 # no_gl: no GL function is called.
1991 # valid_args: A dictionary of argument indices to args to use in unit tests
1992 # when they can not be automatically determined.
1993 # pepper_interface: The pepper interface that is used for this extension
1994 # pepper_name: The name of the function as exposed to pepper.
1995 # pepper_args: A string representing the argument list (what would appear in
1996 # C/C++ between the parentheses for the function declaration)
1997 # that the Pepper API expects for this function. Use this only if
1998 # the stable Pepper API differs from the GLES2 argument list.
1999 # invalid_test: False if no invalid test needed.
2000 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2001 # first_element_only: For PUT types, True if only the first element of an
2002 # array is used and we end up calling the single value
2003 # corresponding function. eg. TexParameteriv -> TexParameteri
2004 # extension: Function is an extension to GL and should not be exposed to
2005 # pepper unless pepper_interface is defined.
2006 # extension_flag: Function is an extension and should be enabled only when
2007 # the corresponding feature info flag is enabled. Implies
2008 # 'extension': True.
2009 # not_shared: For GENn types, True if objects can't be shared between contexts
2010 # unsafe: True = no validation is implemented on the service side and the
2011 # command is only available with --enable-unsafe-es3-apis.
2012 # id_mapping: A list of resource type names whose client side IDs need to be
2013 # mapped to service side IDs. This is only used for unsafe APIs.
2015 _FUNCTION_INFO = {
2016 'ActiveTexture': {
2017 'decoder_func': 'DoActiveTexture',
2018 'unit_test': False,
2019 'impl_func': False,
2020 'client_test': False,
2022 'AttachShader': {'decoder_func': 'DoAttachShader'},
2023 'BindAttribLocation': {
2024 'type': 'GLchar',
2025 'data_transfer_methods': ['bucket'],
2026 'needs_size': True,
2028 'BindBuffer': {
2029 'type': 'Bind',
2030 'decoder_func': 'DoBindBuffer',
2031 'gen_func': 'GenBuffersARB',
2033 'BindBufferBase': {
2034 'type': 'Bind',
2035 'id_mapping': [ 'Buffer' ],
2036 'gen_func': 'GenBuffersARB',
2037 'unsafe': True,
2039 'BindBufferRange': {
2040 'type': 'Bind',
2041 'id_mapping': [ 'Buffer' ],
2042 'gen_func': 'GenBuffersARB',
2043 'valid_args': {
2044 '3': '4',
2045 '4': '4'
2047 'unsafe': True,
2049 'BindFramebuffer': {
2050 'type': 'Bind',
2051 'decoder_func': 'DoBindFramebuffer',
2052 'gl_test_func': 'glBindFramebufferEXT',
2053 'gen_func': 'GenFramebuffersEXT',
2054 'trace_level': 1,
2056 'BindRenderbuffer': {
2057 'type': 'Bind',
2058 'decoder_func': 'DoBindRenderbuffer',
2059 'gl_test_func': 'glBindRenderbufferEXT',
2060 'gen_func': 'GenRenderbuffersEXT',
2062 'BindSampler': {
2063 'type': 'Bind',
2064 'id_mapping': [ 'Sampler' ],
2065 'unsafe': True,
2067 'BindTexture': {
2068 'type': 'Bind',
2069 'decoder_func': 'DoBindTexture',
2070 'gen_func': 'GenTextures',
2071 # TODO(gman): remove this once client side caching works.
2072 'client_test': False,
2073 'trace_level': 2,
2075 'BindTransformFeedback': {
2076 'type': 'Bind',
2077 'id_mapping': [ 'TransformFeedback' ],
2078 'unsafe': True,
2080 'BlitFramebufferCHROMIUM': {
2081 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2082 'unit_test': False,
2083 'extension_flag': 'chromium_framebuffer_multisample',
2084 'pepper_interface': 'FramebufferBlit',
2085 'pepper_name': 'BlitFramebufferEXT',
2086 'defer_reads': True,
2087 'defer_draws': True,
2088 'trace_level': 1,
2090 'BufferData': {
2091 'type': 'Manual',
2092 'data_transfer_methods': ['shm'],
2093 'client_test': False,
2094 'trace_level': 2,
2096 'BufferSubData': {
2097 'type': 'Data',
2098 'client_test': False,
2099 'decoder_func': 'DoBufferSubData',
2100 'data_transfer_methods': ['shm'],
2101 'trace_level': 2,
2103 'CheckFramebufferStatus': {
2104 'type': 'Is',
2105 'decoder_func': 'DoCheckFramebufferStatus',
2106 'gl_test_func': 'glCheckFramebufferStatusEXT',
2107 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2108 'result': ['GLenum'],
2110 'Clear': {
2111 'decoder_func': 'DoClear',
2112 'defer_draws': True,
2113 'trace_level': 2,
2115 'ClearBufferiv': {
2116 'type': 'PUT',
2117 'use_count_func': True,
2118 'count': 4,
2119 'unsafe': True,
2120 'trace_level': 2,
2122 'ClearBufferuiv': {
2123 'type': 'PUT',
2124 'count': 4,
2125 'unsafe': True,
2126 'trace_level': 2,
2128 'ClearBufferfv': {
2129 'type': 'PUT',
2130 'use_count_func': True,
2131 'count': 4,
2132 'unsafe': True,
2133 'trace_level': 2,
2135 'ClearBufferfi': {
2136 'unsafe': True,
2137 'trace_level': 2,
2139 'ClearColor': {
2140 'type': 'StateSet',
2141 'state': 'ClearColor',
2143 'ClearDepthf': {
2144 'type': 'StateSet',
2145 'state': 'ClearDepthf',
2146 'decoder_func': 'glClearDepth',
2147 'gl_test_func': 'glClearDepth',
2148 'valid_args': {
2149 '0': '0.5f'
2152 'ClientWaitSync': {
2153 'type': 'Custom',
2154 'data_transfer_methods': ['shm'],
2155 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2156 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2157 'unsafe': True,
2158 'result': ['GLenum'],
2159 'trace_level': 2,
2161 'ColorMask': {
2162 'type': 'StateSet',
2163 'state': 'ColorMask',
2164 'no_gl': True,
2165 'expectation': False,
2167 'ConsumeTextureCHROMIUM': {
2168 'decoder_func': 'DoConsumeTextureCHROMIUM',
2169 'impl_func': False,
2170 'type': 'PUT',
2171 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2172 'unit_test': False,
2173 'client_test': False,
2174 'extension': "CHROMIUM_texture_mailbox",
2175 'chromium': True,
2176 'trace_level': 2,
2178 'CopyBufferSubData': {
2179 'unsafe': True,
2181 'CreateAndConsumeTextureCHROMIUM': {
2182 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2183 'impl_func': False,
2184 'type': 'HandWritten',
2185 'data_transfer_methods': ['immediate'],
2186 'unit_test': False,
2187 'client_test': False,
2188 'extension': "CHROMIUM_texture_mailbox",
2189 'chromium': True,
2190 'trace_level': 2,
2192 'GenValuebuffersCHROMIUM': {
2193 'type': 'GENn',
2194 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2195 'resource_type': 'Valuebuffer',
2196 'resource_types': 'Valuebuffers',
2197 'unit_test': False,
2198 'extension': True,
2199 'chromium': True,
2201 'DeleteValuebuffersCHROMIUM': {
2202 'type': 'DELn',
2203 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2204 'resource_type': 'Valuebuffer',
2205 'resource_types': 'Valuebuffers',
2206 'unit_test': False,
2207 'extension': True,
2208 'chromium': True,
2210 'IsValuebufferCHROMIUM': {
2211 'type': 'Is',
2212 'decoder_func': 'DoIsValuebufferCHROMIUM',
2213 'expectation': False,
2214 'extension': True,
2215 'chromium': True,
2217 'BindValuebufferCHROMIUM': {
2218 'type': 'Bind',
2219 'decoder_func': 'DoBindValueBufferCHROMIUM',
2220 'gen_func': 'GenValueBuffersCHROMIUM',
2221 'unit_test': False,
2222 'extension': True,
2223 'chromium': True,
2225 'SubscribeValueCHROMIUM': {
2226 'decoder_func': 'DoSubscribeValueCHROMIUM',
2227 'unit_test': False,
2228 'extension': True,
2229 'chromium': True,
2231 'PopulateSubscribedValuesCHROMIUM': {
2232 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2233 'unit_test': False,
2234 'extension': True,
2235 'chromium': True,
2237 'UniformValuebufferCHROMIUM': {
2238 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2239 'unit_test': False,
2240 'extension': True,
2241 'chromium': True,
2243 'ClearStencil': {
2244 'type': 'StateSet',
2245 'state': 'ClearStencil',
2247 'EnableFeatureCHROMIUM': {
2248 'type': 'Custom',
2249 'data_transfer_methods': ['shm'],
2250 'decoder_func': 'DoEnableFeatureCHROMIUM',
2251 'expectation': False,
2252 'cmd_args': 'GLuint bucket_id, GLint* result',
2253 'result': ['GLint'],
2254 'extension': True,
2255 'chromium': True,
2256 'pepper_interface': 'ChromiumEnableFeature',
2258 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2259 'CompressedTexImage2D': {
2260 'type': 'Manual',
2261 'data_transfer_methods': ['bucket', 'shm'],
2262 'trace_level': 1,
2264 'CompressedTexSubImage2D': {
2265 'type': 'Data',
2266 'data_transfer_methods': ['bucket', 'shm'],
2267 'decoder_func': 'DoCompressedTexSubImage2D',
2268 'trace_level': 1,
2270 'CopyTexImage2D': {
2271 'decoder_func': 'DoCopyTexImage2D',
2272 'unit_test': False,
2273 'defer_reads': True,
2274 'trace_level': 1,
2276 'CopyTexSubImage2D': {
2277 'decoder_func': 'DoCopyTexSubImage2D',
2278 'defer_reads': True,
2279 'trace_level': 1,
2281 'CompressedTexImage3D': {
2282 'type': 'Manual',
2283 'data_transfer_methods': ['bucket', 'shm'],
2284 'unsafe': True,
2285 'trace_level': 1,
2287 'CompressedTexSubImage3D': {
2288 'type': 'Data',
2289 'data_transfer_methods': ['bucket', 'shm'],
2290 'decoder_func': 'DoCompressedTexSubImage3D',
2291 'unsafe': True,
2292 'trace_level': 1,
2294 'CopyTexSubImage3D': {
2295 'defer_reads': True,
2296 'unsafe': True,
2297 'trace_level': 1,
2299 'CreateImageCHROMIUM': {
2300 'type': 'Manual',
2301 'cmd_args':
2302 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2303 'GLenum internalformat',
2304 'result': ['GLuint'],
2305 'client_test': False,
2306 'gen_cmd': False,
2307 'expectation': False,
2308 'extension': "CHROMIUM_image",
2309 'chromium': True,
2310 'trace_level': 1,
2312 'DestroyImageCHROMIUM': {
2313 'type': 'Manual',
2314 'client_test': False,
2315 'gen_cmd': False,
2316 'extension': "CHROMIUM_image",
2317 'chromium': True,
2318 'trace_level': 1,
2320 'CreateGpuMemoryBufferImageCHROMIUM': {
2321 'type': 'Manual',
2322 'cmd_args':
2323 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2324 'result': ['GLuint'],
2325 'client_test': False,
2326 'gen_cmd': False,
2327 'expectation': False,
2328 'extension': "CHROMIUM_image",
2329 'chromium': True,
2330 'trace_level': 1,
2332 'CreateProgram': {
2333 'type': 'Create',
2334 'client_test': False,
2336 'CreateShader': {
2337 'type': 'Create',
2338 'client_test': False,
2340 'BlendColor': {
2341 'type': 'StateSet',
2342 'state': 'BlendColor',
2344 'BlendEquation': {
2345 'type': 'StateSetRGBAlpha',
2346 'state': 'BlendEquation',
2347 'valid_args': {
2348 '0': 'GL_FUNC_SUBTRACT'
2351 'BlendEquationSeparate': {
2352 'type': 'StateSet',
2353 'state': 'BlendEquation',
2354 'valid_args': {
2355 '0': 'GL_FUNC_SUBTRACT'
2358 'BlendFunc': {
2359 'type': 'StateSetRGBAlpha',
2360 'state': 'BlendFunc',
2362 'BlendFuncSeparate': {
2363 'type': 'StateSet',
2364 'state': 'BlendFunc',
2366 'BlendBarrierKHR': {
2367 'gl_test_func': 'glBlendBarrierKHR',
2368 'extension': True,
2369 'extension_flag': 'blend_equation_advanced',
2370 'client_test': False,
2372 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2373 'StencilFunc': {
2374 'type': 'StateSetFrontBack',
2375 'state': 'StencilFunc',
2377 'StencilFuncSeparate': {
2378 'type': 'StateSetFrontBackSeparate',
2379 'state': 'StencilFunc',
2381 'StencilOp': {
2382 'type': 'StateSetFrontBack',
2383 'state': 'StencilOp',
2384 'valid_args': {
2385 '1': 'GL_INCR'
2388 'StencilOpSeparate': {
2389 'type': 'StateSetFrontBackSeparate',
2390 'state': 'StencilOp',
2391 'valid_args': {
2392 '1': 'GL_INCR'
2395 'Hint': {
2396 'type': 'StateSetNamedParameter',
2397 'state': 'Hint',
2399 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2400 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2401 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2402 'LineWidth': {
2403 'type': 'StateSet',
2404 'state': 'LineWidth',
2405 'valid_args': {
2406 '0': '0.5f'
2409 'PolygonOffset': {
2410 'type': 'StateSet',
2411 'state': 'PolygonOffset',
2413 'DeleteBuffers': {
2414 'type': 'DELn',
2415 'gl_test_func': 'glDeleteBuffersARB',
2416 'resource_type': 'Buffer',
2417 'resource_types': 'Buffers',
2419 'DeleteFramebuffers': {
2420 'type': 'DELn',
2421 'gl_test_func': 'glDeleteFramebuffersEXT',
2422 'resource_type': 'Framebuffer',
2423 'resource_types': 'Framebuffers',
2424 'trace_level': 2,
2426 'DeleteProgram': { 'type': 'Delete' },
2427 'DeleteRenderbuffers': {
2428 'type': 'DELn',
2429 'gl_test_func': 'glDeleteRenderbuffersEXT',
2430 'resource_type': 'Renderbuffer',
2431 'resource_types': 'Renderbuffers',
2432 'trace_level': 2,
2434 'DeleteSamplers': {
2435 'type': 'DELn',
2436 'resource_type': 'Sampler',
2437 'resource_types': 'Samplers',
2438 'unsafe': True,
2440 'DeleteShader': { 'type': 'Delete' },
2441 'DeleteSync': {
2442 'type': 'Delete',
2443 'cmd_args': 'GLuint sync',
2444 'resource_type': 'Sync',
2445 'unsafe': True,
2447 'DeleteTextures': {
2448 'type': 'DELn',
2449 'resource_type': 'Texture',
2450 'resource_types': 'Textures',
2452 'DeleteTransformFeedbacks': {
2453 'type': 'DELn',
2454 'resource_type': 'TransformFeedback',
2455 'resource_types': 'TransformFeedbacks',
2456 'unsafe': True,
2458 'DepthRangef': {
2459 'decoder_func': 'DoDepthRangef',
2460 'gl_test_func': 'glDepthRange',
2462 'DepthMask': {
2463 'type': 'StateSet',
2464 'state': 'DepthMask',
2465 'no_gl': True,
2466 'expectation': False,
2468 'DetachShader': {'decoder_func': 'DoDetachShader'},
2469 'Disable': {
2470 'decoder_func': 'DoDisable',
2471 'impl_func': False,
2472 'client_test': False,
2474 'DisableVertexAttribArray': {
2475 'decoder_func': 'DoDisableVertexAttribArray',
2476 'impl_decl': False,
2478 'DrawArrays': {
2479 'type': 'Manual',
2480 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2481 'defer_draws': True,
2482 'trace_level': 2,
2484 'DrawElements': {
2485 'type': 'Manual',
2486 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2487 'GLenumIndexType type, GLuint index_offset',
2488 'client_test': False,
2489 'defer_draws': True,
2490 'trace_level': 2,
2492 'DrawRangeElements': {
2493 'type': 'Manual',
2494 'gen_cmd': 'False',
2495 'unsafe': True,
2497 'Enable': {
2498 'decoder_func': 'DoEnable',
2499 'impl_func': False,
2500 'client_test': False,
2502 'EnableVertexAttribArray': {
2503 'decoder_func': 'DoEnableVertexAttribArray',
2504 'impl_decl': False,
2506 'FenceSync': {
2507 'type': 'Create',
2508 'client_test': False,
2509 'unsafe': True,
2510 'trace_level': 1,
2512 'Finish': {
2513 'impl_func': False,
2514 'client_test': False,
2515 'decoder_func': 'DoFinish',
2516 'defer_reads': True,
2517 'trace_level': 1,
2519 'Flush': {
2520 'impl_func': False,
2521 'decoder_func': 'DoFlush',
2522 'trace_level': 1,
2524 'FramebufferRenderbuffer': {
2525 'decoder_func': 'DoFramebufferRenderbuffer',
2526 'gl_test_func': 'glFramebufferRenderbufferEXT',
2527 'trace_level': 1,
2529 'FramebufferTexture2D': {
2530 'decoder_func': 'DoFramebufferTexture2D',
2531 'gl_test_func': 'glFramebufferTexture2DEXT',
2532 'trace_level': 1,
2534 'FramebufferTexture2DMultisampleEXT': {
2535 'decoder_func': 'DoFramebufferTexture2DMultisample',
2536 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2537 'expectation': False,
2538 'unit_test': False,
2539 'extension_flag': 'multisampled_render_to_texture',
2540 'trace_level': 1,
2542 'FramebufferTextureLayer': {
2543 'decoder_func': 'DoFramebufferTextureLayer',
2544 'unsafe': True,
2545 'trace_level': 1,
2547 'GenerateMipmap': {
2548 'decoder_func': 'DoGenerateMipmap',
2549 'gl_test_func': 'glGenerateMipmapEXT',
2550 'trace_level': 1,
2552 'GenBuffers': {
2553 'type': 'GENn',
2554 'gl_test_func': 'glGenBuffersARB',
2555 'resource_type': 'Buffer',
2556 'resource_types': 'Buffers',
2558 'GenMailboxCHROMIUM': {
2559 'type': 'HandWritten',
2560 'impl_func': False,
2561 'extension': "CHROMIUM_texture_mailbox",
2562 'chromium': True,
2564 'GenFramebuffers': {
2565 'type': 'GENn',
2566 'gl_test_func': 'glGenFramebuffersEXT',
2567 'resource_type': 'Framebuffer',
2568 'resource_types': 'Framebuffers',
2570 'GenRenderbuffers': {
2571 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2572 'resource_type': 'Renderbuffer',
2573 'resource_types': 'Renderbuffers',
2575 'GenSamplers': {
2576 'type': 'GENn',
2577 'gl_test_func': 'glGenSamplers',
2578 'resource_type': 'Sampler',
2579 'resource_types': 'Samplers',
2580 'unsafe': True,
2582 'GenTextures': {
2583 'type': 'GENn',
2584 'gl_test_func': 'glGenTextures',
2585 'resource_type': 'Texture',
2586 'resource_types': 'Textures',
2588 'GenTransformFeedbacks': {
2589 'type': 'GENn',
2590 'gl_test_func': 'glGenTransformFeedbacks',
2591 'resource_type': 'TransformFeedback',
2592 'resource_types': 'TransformFeedbacks',
2593 'unsafe': True,
2595 'GetActiveAttrib': {
2596 'type': 'Custom',
2597 'data_transfer_methods': ['shm'],
2598 'cmd_args':
2599 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2600 'void* result',
2601 'result': [
2602 'int32_t success',
2603 'int32_t size',
2604 'uint32_t type',
2607 'GetActiveUniform': {
2608 'type': 'Custom',
2609 'data_transfer_methods': ['shm'],
2610 'cmd_args':
2611 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2612 'void* result',
2613 'result': [
2614 'int32_t success',
2615 'int32_t size',
2616 'uint32_t type',
2619 'GetActiveUniformBlockiv': {
2620 'type': 'Custom',
2621 'data_transfer_methods': ['shm'],
2622 'result': ['SizedResult<GLint>'],
2623 'unsafe': True,
2625 'GetActiveUniformBlockName': {
2626 'type': 'Custom',
2627 'data_transfer_methods': ['shm'],
2628 'cmd_args':
2629 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2630 'void* result',
2631 'result': ['int32_t'],
2632 'unsafe': True,
2634 'GetActiveUniformsiv': {
2635 'type': 'Custom',
2636 'data_transfer_methods': ['shm'],
2637 'cmd_args':
2638 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2639 'GLint* params',
2640 'result': ['SizedResult<GLint>'],
2641 'unsafe': True,
2643 'GetAttachedShaders': {
2644 'type': 'Custom',
2645 'data_transfer_methods': ['shm'],
2646 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2647 'result': ['SizedResult<GLuint>'],
2649 'GetAttribLocation': {
2650 'type': 'Custom',
2651 'data_transfer_methods': ['shm'],
2652 'cmd_args':
2653 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2654 'result': ['GLint'],
2655 'error_return': -1,
2657 'GetFragDataLocation': {
2658 'type': 'Custom',
2659 'data_transfer_methods': ['shm'],
2660 'cmd_args':
2661 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2662 'result': ['GLint'],
2663 'error_return': -1,
2664 'unsafe': True,
2666 'GetBooleanv': {
2667 'type': 'GETn',
2668 'result': ['SizedResult<GLboolean>'],
2669 'decoder_func': 'DoGetBooleanv',
2670 'gl_test_func': 'glGetBooleanv',
2672 'GetBufferParameteriv': {
2673 'type': 'GETn',
2674 'result': ['SizedResult<GLint>'],
2675 'decoder_func': 'DoGetBufferParameteriv',
2676 'expectation': False,
2677 'shadowed': True,
2679 'GetError': {
2680 'type': 'Is',
2681 'decoder_func': 'GetErrorState()->GetGLError',
2682 'impl_func': False,
2683 'result': ['GLenum'],
2684 'client_test': False,
2686 'GetFloatv': {
2687 'type': 'GETn',
2688 'result': ['SizedResult<GLfloat>'],
2689 'decoder_func': 'DoGetFloatv',
2690 'gl_test_func': 'glGetFloatv',
2692 'GetFramebufferAttachmentParameteriv': {
2693 'type': 'GETn',
2694 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2695 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2696 'result': ['SizedResult<GLint>'],
2698 'GetGraphicsResetStatusKHR': {
2699 'extension': True,
2700 'client_test': False,
2701 'gen_cmd': False,
2702 'trace_level': 1,
2704 'GetInteger64v': {
2705 'type': 'GETn',
2706 'result': ['SizedResult<GLint64>'],
2707 'client_test': False,
2708 'decoder_func': 'DoGetInteger64v',
2709 'unsafe': True
2711 'GetIntegerv': {
2712 'type': 'GETn',
2713 'result': ['SizedResult<GLint>'],
2714 'decoder_func': 'DoGetIntegerv',
2715 'client_test': False,
2717 'GetInteger64i_v': {
2718 'type': 'GETn',
2719 'result': ['SizedResult<GLint64>'],
2720 'client_test': False,
2721 'unsafe': True
2723 'GetIntegeri_v': {
2724 'type': 'GETn',
2725 'result': ['SizedResult<GLint>'],
2726 'client_test': False,
2727 'unsafe': True
2729 'GetInternalformativ': {
2730 'type': 'Custom',
2731 'data_transfer_methods': ['shm'],
2732 'result': ['SizedResult<GLint>'],
2733 'cmd_args':
2734 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2735 'GLenumInternalFormatParameter pname, GLint* params',
2736 'unsafe': True,
2738 'GetMaxValueInBufferCHROMIUM': {
2739 'type': 'Is',
2740 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2741 'result': ['GLuint'],
2742 'unit_test': False,
2743 'client_test': False,
2744 'extension': True,
2745 'chromium': True,
2746 'impl_func': False,
2748 'GetProgramiv': {
2749 'type': 'GETn',
2750 'decoder_func': 'DoGetProgramiv',
2751 'result': ['SizedResult<GLint>'],
2752 'expectation': False,
2754 'GetProgramInfoCHROMIUM': {
2755 'type': 'Custom',
2756 'expectation': False,
2757 'impl_func': False,
2758 'extension': True,
2759 'chromium': True,
2760 'client_test': False,
2761 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2762 'result': [
2763 'uint32_t link_status',
2764 'uint32_t num_attribs',
2765 'uint32_t num_uniforms',
2768 'GetProgramInfoLog': {
2769 'type': 'STRn',
2770 'expectation': False,
2772 'GetRenderbufferParameteriv': {
2773 'type': 'GETn',
2774 'decoder_func': 'DoGetRenderbufferParameteriv',
2775 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2776 'result': ['SizedResult<GLint>'],
2778 'GetSamplerParameterfv': {
2779 'type': 'GETn',
2780 'result': ['SizedResult<GLfloat>'],
2781 'id_mapping': [ 'Sampler' ],
2782 'unsafe': True,
2784 'GetSamplerParameteriv': {
2785 'type': 'GETn',
2786 'result': ['SizedResult<GLint>'],
2787 'id_mapping': [ 'Sampler' ],
2788 'unsafe': True,
2790 'GetShaderiv': {
2791 'type': 'GETn',
2792 'decoder_func': 'DoGetShaderiv',
2793 'result': ['SizedResult<GLint>'],
2795 'GetShaderInfoLog': {
2796 'type': 'STRn',
2797 'get_len_func': 'glGetShaderiv',
2798 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2799 'unit_test': False,
2801 'GetShaderPrecisionFormat': {
2802 'type': 'Custom',
2803 'data_transfer_methods': ['shm'],
2804 'cmd_args':
2805 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2806 'void* result',
2807 'result': [
2808 'int32_t success',
2809 'int32_t min_range',
2810 'int32_t max_range',
2811 'int32_t precision',
2814 'GetShaderSource': {
2815 'type': 'STRn',
2816 'get_len_func': 'DoGetShaderiv',
2817 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2818 'unit_test': False,
2819 'client_test': False,
2821 'GetString': {
2822 'type': 'Custom',
2823 'client_test': False,
2824 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2826 'GetSynciv': {
2827 'type': 'GETn',
2828 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2829 'result': ['SizedResult<GLint>'],
2830 'id_mapping': ['Sync'],
2831 'unsafe': True,
2833 'GetTexParameterfv': {
2834 'type': 'GETn',
2835 'decoder_func': 'DoGetTexParameterfv',
2836 'result': ['SizedResult<GLfloat>']
2838 'GetTexParameteriv': {
2839 'type': 'GETn',
2840 'decoder_func': 'DoGetTexParameteriv',
2841 'result': ['SizedResult<GLint>']
2843 'GetTranslatedShaderSourceANGLE': {
2844 'type': 'STRn',
2845 'get_len_func': 'DoGetShaderiv',
2846 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2847 'unit_test': False,
2848 'extension': True,
2850 'GetUniformBlockIndex': {
2851 'type': 'Custom',
2852 'data_transfer_methods': ['shm'],
2853 'cmd_args':
2854 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2855 'result': ['GLuint'],
2856 'error_return': 'GL_INVALID_INDEX',
2857 'unsafe': True,
2859 'GetUniformBlocksCHROMIUM': {
2860 'type': 'Custom',
2861 'expectation': False,
2862 'impl_func': False,
2863 'extension': True,
2864 'chromium': True,
2865 'client_test': False,
2866 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2867 'result': ['uint32_t'],
2868 'unsafe': True,
2870 'GetUniformsES3CHROMIUM': {
2871 'type': 'Custom',
2872 'expectation': False,
2873 'impl_func': False,
2874 'extension': True,
2875 'chromium': True,
2876 'client_test': False,
2877 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2878 'result': ['uint32_t'],
2879 'unsafe': True,
2881 'GetTransformFeedbackVarying': {
2882 'type': 'Custom',
2883 'data_transfer_methods': ['shm'],
2884 'cmd_args':
2885 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2886 'void* result',
2887 'result': [
2888 'int32_t success',
2889 'int32_t size',
2890 'uint32_t type',
2892 'unsafe': True,
2894 'GetTransformFeedbackVaryingsCHROMIUM': {
2895 'type': 'Custom',
2896 'expectation': False,
2897 'impl_func': False,
2898 'extension': True,
2899 'chromium': True,
2900 'client_test': False,
2901 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2902 'result': ['uint32_t'],
2903 'unsafe': True,
2905 'GetUniformfv': {
2906 'type': 'Custom',
2907 'data_transfer_methods': ['shm'],
2908 'result': ['SizedResult<GLfloat>'],
2910 'GetUniformiv': {
2911 'type': 'Custom',
2912 'data_transfer_methods': ['shm'],
2913 'result': ['SizedResult<GLint>'],
2915 'GetUniformuiv': {
2916 'type': 'Custom',
2917 'data_transfer_methods': ['shm'],
2918 'result': ['SizedResult<GLuint>'],
2919 'unsafe': True,
2921 'GetUniformIndices': {
2922 'type': 'Custom',
2923 'data_transfer_methods': ['shm'],
2924 'result': ['SizedResult<GLuint>'],
2925 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2926 'GLuint* indices',
2927 'unsafe': True,
2929 'GetUniformLocation': {
2930 'type': 'Custom',
2931 'data_transfer_methods': ['shm'],
2932 'cmd_args':
2933 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2934 'result': ['GLint'],
2935 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2937 'GetVertexAttribfv': {
2938 'type': 'GETn',
2939 'result': ['SizedResult<GLfloat>'],
2940 'impl_decl': False,
2941 'decoder_func': 'DoGetVertexAttribfv',
2942 'expectation': False,
2943 'client_test': False,
2945 'GetVertexAttribiv': {
2946 'type': 'GETn',
2947 'result': ['SizedResult<GLint>'],
2948 'impl_decl': False,
2949 'decoder_func': 'DoGetVertexAttribiv',
2950 'expectation': False,
2951 'client_test': False,
2953 'GetVertexAttribIiv': {
2954 'type': 'GETn',
2955 'result': ['SizedResult<GLint>'],
2956 'impl_decl': False,
2957 'decoder_func': 'DoGetVertexAttribIiv',
2958 'expectation': False,
2959 'client_test': False,
2960 'unsafe': True,
2962 'GetVertexAttribIuiv': {
2963 'type': 'GETn',
2964 'result': ['SizedResult<GLuint>'],
2965 'impl_decl': False,
2966 'decoder_func': 'DoGetVertexAttribIuiv',
2967 'expectation': False,
2968 'client_test': False,
2969 'unsafe': True,
2971 'GetVertexAttribPointerv': {
2972 'type': 'Custom',
2973 'data_transfer_methods': ['shm'],
2974 'result': ['SizedResult<GLuint>'],
2975 'client_test': False,
2977 'InvalidateFramebuffer': {
2978 'type': 'PUTn',
2979 'count': 1,
2980 'client_test': False,
2981 'unit_test': False,
2982 'unsafe': True,
2984 'InvalidateSubFramebuffer': {
2985 'type': 'PUTn',
2986 'count': 1,
2987 'client_test': False,
2988 'unit_test': False,
2989 'unsafe': True,
2991 'IsBuffer': {
2992 'type': 'Is',
2993 'decoder_func': 'DoIsBuffer',
2994 'expectation': False,
2996 'IsEnabled': {
2997 'type': 'Is',
2998 'decoder_func': 'DoIsEnabled',
2999 'client_test': False,
3000 'impl_func': False,
3001 'expectation': False,
3003 'IsFramebuffer': {
3004 'type': 'Is',
3005 'decoder_func': 'DoIsFramebuffer',
3006 'expectation': False,
3008 'IsProgram': {
3009 'type': 'Is',
3010 'decoder_func': 'DoIsProgram',
3011 'expectation': False,
3013 'IsRenderbuffer': {
3014 'type': 'Is',
3015 'decoder_func': 'DoIsRenderbuffer',
3016 'expectation': False,
3018 'IsShader': {
3019 'type': 'Is',
3020 'decoder_func': 'DoIsShader',
3021 'expectation': False,
3023 'IsSampler': {
3024 'type': 'Is',
3025 'id_mapping': [ 'Sampler' ],
3026 'expectation': False,
3027 'unsafe': True,
3029 'IsSync': {
3030 'type': 'Is',
3031 'id_mapping': [ 'Sync' ],
3032 'cmd_args': 'GLuint sync',
3033 'expectation': False,
3034 'unsafe': True,
3036 'IsTexture': {
3037 'type': 'Is',
3038 'decoder_func': 'DoIsTexture',
3039 'expectation': False,
3041 'IsTransformFeedback': {
3042 'type': 'Is',
3043 'id_mapping': [ 'TransformFeedback' ],
3044 'expectation': False,
3045 'unsafe': True,
3047 'LinkProgram': {
3048 'decoder_func': 'DoLinkProgram',
3049 'impl_func': False,
3050 'trace_level': 1,
3052 'MapBufferCHROMIUM': {
3053 'gen_cmd': False,
3054 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3055 'chromium': True,
3056 'client_test': False,
3057 'trace_level': 1,
3059 'MapBufferSubDataCHROMIUM': {
3060 'gen_cmd': False,
3061 'extension': True,
3062 'chromium': True,
3063 'client_test': False,
3064 'pepper_interface': 'ChromiumMapSub',
3065 'trace_level': 1,
3067 'MapTexSubImage2DCHROMIUM': {
3068 'gen_cmd': False,
3069 'extension': "CHROMIUM_sub_image",
3070 'chromium': True,
3071 'client_test': False,
3072 'pepper_interface': 'ChromiumMapSub',
3073 'trace_level': 1,
3075 'MapBufferRange': {
3076 'type': 'Custom',
3077 'data_transfer_methods': ['shm'],
3078 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3079 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3080 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3081 'uint32_t result_shm_id, uint32_t result_shm_offset',
3082 'unsafe': True,
3083 'result': ['uint32_t'],
3084 'trace_level': 1,
3086 'PauseTransformFeedback': {
3087 'unsafe': True,
3089 'PixelStorei': {'type': 'Manual'},
3090 'PostSubBufferCHROMIUM': {
3091 'type': 'Custom',
3092 'impl_func': False,
3093 'unit_test': False,
3094 'client_test': False,
3095 'extension': True,
3096 'chromium': True,
3098 'ProduceTextureCHROMIUM': {
3099 'decoder_func': 'DoProduceTextureCHROMIUM',
3100 'impl_func': False,
3101 'type': 'PUT',
3102 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3103 'unit_test': False,
3104 'client_test': False,
3105 'extension': "CHROMIUM_texture_mailbox",
3106 'chromium': True,
3107 'trace_level': 1,
3109 'ProduceTextureDirectCHROMIUM': {
3110 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3111 'impl_func': False,
3112 'type': 'PUT',
3113 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3114 'unit_test': False,
3115 'client_test': False,
3116 'extension': "CHROMIUM_texture_mailbox",
3117 'chromium': True,
3118 'trace_level': 1,
3120 'RenderbufferStorage': {
3121 'decoder_func': 'DoRenderbufferStorage',
3122 'gl_test_func': 'glRenderbufferStorageEXT',
3123 'expectation': False,
3124 'trace_level': 1,
3126 'RenderbufferStorageMultisampleCHROMIUM': {
3127 'cmd_comment':
3128 '// GL_CHROMIUM_framebuffer_multisample\n',
3129 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3130 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3131 'expectation': False,
3132 'unit_test': False,
3133 'extension_flag': 'chromium_framebuffer_multisample',
3134 'pepper_interface': 'FramebufferMultisample',
3135 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3136 'trace_level': 1,
3138 'RenderbufferStorageMultisampleEXT': {
3139 'cmd_comment':
3140 '// GL_EXT_multisampled_render_to_texture\n',
3141 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3142 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3143 'expectation': False,
3144 'unit_test': False,
3145 'extension_flag': 'multisampled_render_to_texture',
3146 'trace_level': 1,
3148 'ReadBuffer': {
3149 'unsafe': True,
3150 'trace_level': 1,
3152 'ReadPixels': {
3153 'cmd_comment':
3154 '// ReadPixels has the result separated from the pixel buffer so that\n'
3155 '// it is easier to specify the result going to some specific place\n'
3156 '// that exactly fits the rectangle of pixels.\n',
3157 'type': 'Custom',
3158 'data_transfer_methods': ['shm'],
3159 'impl_func': False,
3160 'client_test': False,
3161 'cmd_args':
3162 'GLint x, GLint y, GLsizei width, GLsizei height, '
3163 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3164 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3165 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3166 'GLboolean async',
3167 'result': ['uint32_t'],
3168 'defer_reads': True,
3169 'trace_level': 1,
3171 'ReleaseShaderCompiler': {
3172 'decoder_func': 'DoReleaseShaderCompiler',
3173 'unit_test': False,
3175 'ResumeTransformFeedback': {
3176 'unsafe': True,
3178 'SamplerParameterf': {
3179 'valid_args': {
3180 '2': 'GL_NEAREST'
3182 'id_mapping': [ 'Sampler' ],
3183 'unsafe': True,
3185 'SamplerParameterfv': {
3186 'type': 'PUT',
3187 'data_value': 'GL_NEAREST',
3188 'count': 1,
3189 'gl_test_func': 'glSamplerParameterf',
3190 'decoder_func': 'DoSamplerParameterfv',
3191 'first_element_only': True,
3192 'id_mapping': [ 'Sampler' ],
3193 'unsafe': True,
3195 'SamplerParameteri': {
3196 'valid_args': {
3197 '2': 'GL_NEAREST'
3199 'id_mapping': [ 'Sampler' ],
3200 'unsafe': True,
3202 'SamplerParameteriv': {
3203 'type': 'PUT',
3204 'data_value': 'GL_NEAREST',
3205 'count': 1,
3206 'gl_test_func': 'glSamplerParameteri',
3207 'decoder_func': 'DoSamplerParameteriv',
3208 'first_element_only': True,
3209 'unsafe': True,
3211 'ShaderBinary': {
3212 'type': 'Custom',
3213 'client_test': False,
3215 'ShaderSource': {
3216 'type': 'PUTSTR',
3217 'decoder_func': 'DoShaderSource',
3218 'expectation': False,
3219 'data_transfer_methods': ['bucket'],
3220 'cmd_args':
3221 'GLuint shader, const char** str',
3222 'pepper_args':
3223 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3225 'StencilMask': {
3226 'type': 'StateSetFrontBack',
3227 'state': 'StencilMask',
3228 'no_gl': True,
3229 'expectation': False,
3231 'StencilMaskSeparate': {
3232 'type': 'StateSetFrontBackSeparate',
3233 'state': 'StencilMask',
3234 'no_gl': True,
3235 'expectation': False,
3237 'SwapBuffers': {
3238 'impl_func': False,
3239 'decoder_func': 'DoSwapBuffers',
3240 'unit_test': False,
3241 'client_test': False,
3242 'extension': True,
3243 'trace_level': 1,
3245 'SwapInterval': {
3246 'impl_func': False,
3247 'decoder_func': 'DoSwapInterval',
3248 'unit_test': False,
3249 'client_test': False,
3250 'extension': True,
3251 'trace_level': 1,
3253 'TexImage2D': {
3254 'type': 'Manual',
3255 'data_transfer_methods': ['shm'],
3256 'client_test': False,
3257 'trace_level': 2,
3259 'TexImage3D': {
3260 'type': 'Manual',
3261 'data_transfer_methods': ['shm'],
3262 'client_test': False,
3263 'unsafe': True,
3264 'trace_level': 2,
3266 'TexParameterf': {
3267 'decoder_func': 'DoTexParameterf',
3268 'valid_args': {
3269 '2': 'GL_NEAREST'
3272 'TexParameteri': {
3273 'decoder_func': 'DoTexParameteri',
3274 'valid_args': {
3275 '2': 'GL_NEAREST'
3278 'TexParameterfv': {
3279 'type': 'PUT',
3280 'data_value': 'GL_NEAREST',
3281 'count': 1,
3282 'decoder_func': 'DoTexParameterfv',
3283 'gl_test_func': 'glTexParameterf',
3284 'first_element_only': True,
3286 'TexParameteriv': {
3287 'type': 'PUT',
3288 'data_value': 'GL_NEAREST',
3289 'count': 1,
3290 'decoder_func': 'DoTexParameteriv',
3291 'gl_test_func': 'glTexParameteri',
3292 'first_element_only': True,
3294 'TexStorage3D': {
3295 'unsafe': True,
3296 'trace_level': 2,
3298 'TexSubImage2D': {
3299 'type': 'Manual',
3300 'data_transfer_methods': ['shm'],
3301 'client_test': False,
3302 'trace_level': 2,
3303 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3304 'GLint xoffset, GLint yoffset, '
3305 'GLsizei width, GLsizei height, '
3306 'GLenumTextureFormat format, GLenumPixelType type, '
3307 'const void* pixels, GLboolean internal'
3309 'TexSubImage3D': {
3310 'type': 'Manual',
3311 'data_transfer_methods': ['shm'],
3312 'client_test': False,
3313 'trace_level': 2,
3314 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3315 'GLint xoffset, GLint yoffset, GLint zoffset, '
3316 'GLsizei width, GLsizei height, GLsizei depth, '
3317 'GLenumTextureFormat format, GLenumPixelType type, '
3318 'const void* pixels, GLboolean internal',
3319 'unsafe': True,
3321 'TransformFeedbackVaryings': {
3322 'type': 'PUTSTR',
3323 'data_transfer_methods': ['bucket'],
3324 'decoder_func': 'DoTransformFeedbackVaryings',
3325 'cmd_args':
3326 'GLuint program, const char** varyings, GLenum buffermode',
3327 'unsafe': True,
3329 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3330 'Uniform1fv': {
3331 'type': 'PUTn',
3332 'count': 1,
3333 'decoder_func': 'DoUniform1fv',
3335 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3336 'Uniform1iv': {
3337 'type': 'PUTn',
3338 'count': 1,
3339 'decoder_func': 'DoUniform1iv',
3340 'unit_test': False,
3342 'Uniform1ui': {
3343 'type': 'PUTXn',
3344 'count': 1,
3345 'unsafe': True,
3347 'Uniform1uiv': {
3348 'type': 'PUTn',
3349 'count': 1,
3350 'unsafe': True,
3352 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3353 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3354 'Uniform2fv': {
3355 'type': 'PUTn',
3356 'count': 2,
3357 'decoder_func': 'DoUniform2fv',
3359 'Uniform2iv': {
3360 'type': 'PUTn',
3361 'count': 2,
3362 'decoder_func': 'DoUniform2iv',
3364 'Uniform2ui': {
3365 'type': 'PUTXn',
3366 'count': 2,
3367 'unsafe': True,
3369 'Uniform2uiv': {
3370 'type': 'PUTn',
3371 'count': 2,
3372 'unsafe': True,
3374 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3375 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3376 'Uniform3fv': {
3377 'type': 'PUTn',
3378 'count': 3,
3379 'decoder_func': 'DoUniform3fv',
3381 'Uniform3iv': {
3382 'type': 'PUTn',
3383 'count': 3,
3384 'decoder_func': 'DoUniform3iv',
3386 'Uniform3ui': {
3387 'type': 'PUTXn',
3388 'count': 3,
3389 'unsafe': True,
3391 'Uniform3uiv': {
3392 'type': 'PUTn',
3393 'count': 3,
3394 'unsafe': True,
3396 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3397 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3398 'Uniform4fv': {
3399 'type': 'PUTn',
3400 'count': 4,
3401 'decoder_func': 'DoUniform4fv',
3403 'Uniform4iv': {
3404 'type': 'PUTn',
3405 'count': 4,
3406 'decoder_func': 'DoUniform4iv',
3408 'Uniform4ui': {
3409 'type': 'PUTXn',
3410 'count': 4,
3411 'unsafe': True,
3413 'Uniform4uiv': {
3414 'type': 'PUTn',
3415 'count': 4,
3416 'unsafe': True,
3418 'UniformMatrix2fv': {
3419 'type': 'PUTn',
3420 'count': 4,
3421 'decoder_func': 'DoUniformMatrix2fv',
3423 'UniformMatrix2x3fv': {
3424 'type': 'PUTn',
3425 'count': 6,
3426 'unsafe': True,
3428 'UniformMatrix2x4fv': {
3429 'type': 'PUTn',
3430 'count': 8,
3431 'unsafe': True,
3433 'UniformMatrix3fv': {
3434 'type': 'PUTn',
3435 'count': 9,
3436 'decoder_func': 'DoUniformMatrix3fv',
3438 'UniformMatrix3x2fv': {
3439 'type': 'PUTn',
3440 'count': 6,
3441 'unsafe': True,
3443 'UniformMatrix3x4fv': {
3444 'type': 'PUTn',
3445 'count': 12,
3446 'unsafe': True,
3448 'UniformMatrix4fv': {
3449 'type': 'PUTn',
3450 'count': 16,
3451 'decoder_func': 'DoUniformMatrix4fv',
3453 'UniformMatrix4x2fv': {
3454 'type': 'PUTn',
3455 'count': 8,
3456 'unsafe': True,
3458 'UniformMatrix4x3fv': {
3459 'type': 'PUTn',
3460 'count': 12,
3461 'unsafe': True,
3463 'UniformBlockBinding': {
3464 'type': 'Custom',
3465 'impl_func': False,
3466 'unsafe': True,
3468 'UnmapBufferCHROMIUM': {
3469 'gen_cmd': False,
3470 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3471 'chromium': True,
3472 'client_test': False,
3473 'trace_level': 1,
3475 'UnmapBufferSubDataCHROMIUM': {
3476 'gen_cmd': False,
3477 'extension': True,
3478 'chromium': True,
3479 'client_test': False,
3480 'pepper_interface': 'ChromiumMapSub',
3481 'trace_level': 1,
3483 'UnmapBuffer': {
3484 'type': 'Custom',
3485 'unsafe': True,
3486 'trace_level': 1,
3488 'UnmapTexSubImage2DCHROMIUM': {
3489 'gen_cmd': False,
3490 'extension': "CHROMIUM_sub_image",
3491 'chromium': True,
3492 'client_test': False,
3493 'pepper_interface': 'ChromiumMapSub',
3494 'trace_level': 1,
3496 'UseProgram': {
3497 'type': 'Bind',
3498 'decoder_func': 'DoUseProgram',
3500 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3501 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3502 'VertexAttrib1fv': {
3503 'type': 'PUT',
3504 'count': 1,
3505 'decoder_func': 'DoVertexAttrib1fv',
3507 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3508 'VertexAttrib2fv': {
3509 'type': 'PUT',
3510 'count': 2,
3511 'decoder_func': 'DoVertexAttrib2fv',
3513 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3514 'VertexAttrib3fv': {
3515 'type': 'PUT',
3516 'count': 3,
3517 'decoder_func': 'DoVertexAttrib3fv',
3519 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3520 'VertexAttrib4fv': {
3521 'type': 'PUT',
3522 'count': 4,
3523 'decoder_func': 'DoVertexAttrib4fv',
3525 'VertexAttribI4i': {
3526 'unsafe': True,
3527 'decoder_func': 'DoVertexAttribI4i',
3529 'VertexAttribI4iv': {
3530 'type': 'PUT',
3531 'count': 4,
3532 'unsafe': True,
3533 'decoder_func': 'DoVertexAttribI4iv',
3535 'VertexAttribI4ui': {
3536 'unsafe': True,
3537 'decoder_func': 'DoVertexAttribI4ui',
3539 'VertexAttribI4uiv': {
3540 'type': 'PUT',
3541 'count': 4,
3542 'unsafe': True,
3543 'decoder_func': 'DoVertexAttribI4uiv',
3545 'VertexAttribIPointer': {
3546 'type': 'Manual',
3547 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3548 'GLenumVertexAttribIType type, GLsizei stride, '
3549 'GLuint offset',
3550 'client_test': False,
3551 'unsafe': True,
3553 'VertexAttribPointer': {
3554 'type': 'Manual',
3555 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3556 'GLenumVertexAttribType type, GLboolean normalized, '
3557 'GLsizei stride, GLuint offset',
3558 'client_test': False,
3560 'WaitSync': {
3561 'type': 'Custom',
3562 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3563 'GLuint timeout_0, GLuint timeout_1',
3564 'impl_func': False,
3565 'client_test': False,
3566 'unsafe': True,
3567 'trace_level': 1,
3569 'Scissor': {
3570 'type': 'StateSet',
3571 'state': 'Scissor',
3573 'Viewport': {
3574 'decoder_func': 'DoViewport',
3576 'ResizeCHROMIUM': {
3577 'type': 'Custom',
3578 'impl_func': False,
3579 'unit_test': False,
3580 'extension': True,
3581 'chromium': True,
3582 'trace_level': 1,
3584 'GetRequestableExtensionsCHROMIUM': {
3585 'type': 'Custom',
3586 'impl_func': False,
3587 'cmd_args': 'uint32_t bucket_id',
3588 'extension': True,
3589 'chromium': True,
3591 'RequestExtensionCHROMIUM': {
3592 'type': 'Custom',
3593 'impl_func': False,
3594 'client_test': False,
3595 'cmd_args': 'uint32_t bucket_id',
3596 'extension': True,
3597 'chromium': True,
3599 'RateLimitOffscreenContextCHROMIUM': {
3600 'gen_cmd': False,
3601 'extension': True,
3602 'chromium': True,
3603 'client_test': False,
3605 'CreateStreamTextureCHROMIUM': {
3606 'type': 'HandWritten',
3607 'impl_func': False,
3608 'gen_cmd': False,
3609 'extension': True,
3610 'chromium': True,
3611 'trace_level': 1,
3613 'TexImageIOSurface2DCHROMIUM': {
3614 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3615 'unit_test': False,
3616 'extension': True,
3617 'chromium': True,
3618 'trace_level': 1,
3620 'CopyTextureCHROMIUM': {
3621 'decoder_func': 'DoCopyTextureCHROMIUM',
3622 'unit_test': False,
3623 'extension': "CHROMIUM_copy_texture",
3624 'chromium': True,
3625 'trace_level': 2,
3627 'CopySubTextureCHROMIUM': {
3628 'decoder_func': 'DoCopySubTextureCHROMIUM',
3629 'unit_test': False,
3630 'extension': "CHROMIUM_copy_texture",
3631 'chromium': True,
3632 'trace_level': 2,
3634 'CompressedCopyTextureCHROMIUM': {
3635 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3636 'unit_test': False,
3637 'extension': True,
3638 'chromium': True,
3640 'TexStorage2DEXT': {
3641 'unit_test': False,
3642 'extension': True,
3643 'decoder_func': 'DoTexStorage2DEXT',
3644 'trace_level': 2,
3646 'DrawArraysInstancedANGLE': {
3647 'type': 'Manual',
3648 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3649 'GLsizei primcount',
3650 'extension': True,
3651 'unit_test': False,
3652 'pepper_interface': 'InstancedArrays',
3653 'defer_draws': True,
3654 'trace_level': 2,
3656 'DrawBuffersEXT': {
3657 'type': 'PUTn',
3658 'decoder_func': 'DoDrawBuffersEXT',
3659 'count': 1,
3660 'client_test': False,
3661 'unit_test': False,
3662 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3663 # work without.
3664 'extension': True,
3665 'pepper_interface': 'DrawBuffers',
3666 'trace_level': 2,
3668 'DrawElementsInstancedANGLE': {
3669 'type': 'Manual',
3670 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3671 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3672 'extension': True,
3673 'unit_test': False,
3674 'client_test': False,
3675 'pepper_interface': 'InstancedArrays',
3676 'defer_draws': True,
3677 'trace_level': 2,
3679 'VertexAttribDivisorANGLE': {
3680 'type': 'Manual',
3681 'cmd_args': 'GLuint index, GLuint divisor',
3682 'extension': True,
3683 'unit_test': False,
3684 'pepper_interface': 'InstancedArrays',
3686 'GenQueriesEXT': {
3687 'type': 'GENn',
3688 'gl_test_func': 'glGenQueriesARB',
3689 'resource_type': 'Query',
3690 'resource_types': 'Queries',
3691 'unit_test': False,
3692 'pepper_interface': 'Query',
3693 'not_shared': 'True',
3694 'extension': "occlusion_query_EXT",
3696 'DeleteQueriesEXT': {
3697 'type': 'DELn',
3698 'gl_test_func': 'glDeleteQueriesARB',
3699 'resource_type': 'Query',
3700 'resource_types': 'Queries',
3701 'unit_test': False,
3702 'pepper_interface': 'Query',
3703 'extension': "occlusion_query_EXT",
3705 'IsQueryEXT': {
3706 'gen_cmd': False,
3707 'client_test': False,
3708 'pepper_interface': 'Query',
3709 'extension': "occlusion_query_EXT",
3711 'BeginQueryEXT': {
3712 'type': 'Manual',
3713 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3714 'data_transfer_methods': ['shm'],
3715 'gl_test_func': 'glBeginQuery',
3716 'pepper_interface': 'Query',
3717 'extension': "occlusion_query_EXT",
3719 'BeginTransformFeedback': {
3720 'unsafe': True,
3722 'EndQueryEXT': {
3723 'type': 'Manual',
3724 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3725 'gl_test_func': 'glEndnQuery',
3726 'client_test': False,
3727 'pepper_interface': 'Query',
3728 'extension': "occlusion_query_EXT",
3730 'EndTransformFeedback': {
3731 'unsafe': True,
3733 'GetQueryivEXT': {
3734 'gen_cmd': False,
3735 'client_test': False,
3736 'gl_test_func': 'glGetQueryiv',
3737 'pepper_interface': 'Query',
3738 'extension': "occlusion_query_EXT",
3740 'GetQueryObjectuivEXT': {
3741 'gen_cmd': False,
3742 'client_test': False,
3743 'gl_test_func': 'glGetQueryObjectuiv',
3744 'pepper_interface': 'Query',
3745 'extension': "occlusion_query_EXT",
3747 'GetQueryObjectui64vEXT': {
3748 'gen_cmd': False,
3749 'client_test': False,
3750 'gl_test_func': 'glGetQueryObjectui64v',
3751 'extension': "disjoint_timer_query_EXT",
3753 'BindUniformLocationCHROMIUM': {
3754 'type': 'GLchar',
3755 'extension': True,
3756 'data_transfer_methods': ['bucket'],
3757 'needs_size': True,
3758 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3760 'InsertEventMarkerEXT': {
3761 'type': 'GLcharN',
3762 'decoder_func': 'DoInsertEventMarkerEXT',
3763 'expectation': False,
3764 'extension': True,
3766 'PushGroupMarkerEXT': {
3767 'type': 'GLcharN',
3768 'decoder_func': 'DoPushGroupMarkerEXT',
3769 'expectation': False,
3770 'extension': True,
3772 'PopGroupMarkerEXT': {
3773 'decoder_func': 'DoPopGroupMarkerEXT',
3774 'expectation': False,
3775 'extension': True,
3776 'impl_func': False,
3779 'GenVertexArraysOES': {
3780 'type': 'GENn',
3781 'extension': True,
3782 'gl_test_func': 'glGenVertexArraysOES',
3783 'resource_type': 'VertexArray',
3784 'resource_types': 'VertexArrays',
3785 'unit_test': False,
3786 'pepper_interface': 'VertexArrayObject',
3788 'BindVertexArrayOES': {
3789 'type': 'Bind',
3790 'extension': True,
3791 'gl_test_func': 'glBindVertexArrayOES',
3792 'decoder_func': 'DoBindVertexArrayOES',
3793 'gen_func': 'GenVertexArraysOES',
3794 'unit_test': False,
3795 'client_test': False,
3796 'pepper_interface': 'VertexArrayObject',
3798 'DeleteVertexArraysOES': {
3799 'type': 'DELn',
3800 'extension': True,
3801 'gl_test_func': 'glDeleteVertexArraysOES',
3802 'resource_type': 'VertexArray',
3803 'resource_types': 'VertexArrays',
3804 'unit_test': False,
3805 'pepper_interface': 'VertexArrayObject',
3807 'IsVertexArrayOES': {
3808 'type': 'Is',
3809 'extension': True,
3810 'gl_test_func': 'glIsVertexArrayOES',
3811 'decoder_func': 'DoIsVertexArrayOES',
3812 'expectation': False,
3813 'unit_test': False,
3814 'pepper_interface': 'VertexArrayObject',
3816 'BindTexImage2DCHROMIUM': {
3817 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3818 'unit_test': False,
3819 'extension': "CHROMIUM_image",
3820 'chromium': True,
3822 'ReleaseTexImage2DCHROMIUM': {
3823 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3824 'unit_test': False,
3825 'extension': "CHROMIUM_image",
3826 'chromium': True,
3828 'ShallowFinishCHROMIUM': {
3829 'impl_func': False,
3830 'gen_cmd': False,
3831 'extension': True,
3832 'chromium': True,
3833 'client_test': False,
3835 'ShallowFlushCHROMIUM': {
3836 'impl_func': False,
3837 'gen_cmd': False,
3838 'extension': "CHROMIUM_miscellaneous",
3839 'chromium': True,
3840 'client_test': False,
3842 'OrderingBarrierCHROMIUM': {
3843 'impl_func': False,
3844 'gen_cmd': False,
3845 'extension': True,
3846 'chromium': True,
3847 'client_test': False,
3849 'TraceBeginCHROMIUM': {
3850 'type': 'Custom',
3851 'impl_func': False,
3852 'client_test': False,
3853 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3854 'extension': True,
3855 'chromium': True,
3857 'TraceEndCHROMIUM': {
3858 'impl_func': False,
3859 'client_test': False,
3860 'decoder_func': 'DoTraceEndCHROMIUM',
3861 'unit_test': False,
3862 'extension': True,
3863 'chromium': True,
3865 'AsyncTexImage2DCHROMIUM': {
3866 'type': 'Manual',
3867 'data_transfer_methods': ['shm'],
3868 'client_test': False,
3869 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3870 'GLintTextureInternalFormat internalformat, '
3871 'GLsizei width, GLsizei height, '
3872 'GLintTextureBorder border, '
3873 'GLenumTextureFormat format, GLenumPixelType type, '
3874 'const void* pixels, '
3875 'uint32_t async_upload_token, '
3876 'void* sync_data',
3877 'extension': True,
3878 'chromium': True,
3879 'trace_level': 2,
3881 'AsyncTexSubImage2DCHROMIUM': {
3882 'type': 'Manual',
3883 'data_transfer_methods': ['shm'],
3884 'client_test': False,
3885 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3886 'GLint xoffset, GLint yoffset, '
3887 'GLsizei width, GLsizei height, '
3888 'GLenumTextureFormat format, GLenumPixelType type, '
3889 'const void* data, '
3890 'uint32_t async_upload_token, '
3891 'void* sync_data',
3892 'extension': True,
3893 'chromium': True,
3894 'trace_level': 2,
3896 'WaitAsyncTexImage2DCHROMIUM': {
3897 'type': 'Manual',
3898 'client_test': False,
3899 'extension': True,
3900 'chromium': True,
3901 'trace_level': 1,
3903 'WaitAllAsyncTexImage2DCHROMIUM': {
3904 'type': 'Manual',
3905 'client_test': False,
3906 'extension': True,
3907 'chromium': True,
3908 'trace_level': 1,
3910 'DiscardFramebufferEXT': {
3911 'type': 'PUTn',
3912 'count': 1,
3913 'decoder_func': 'DoDiscardFramebufferEXT',
3914 'unit_test': False,
3915 'client_test': False,
3916 'extension_flag': 'ext_discard_framebuffer',
3917 'trace_level': 2,
3919 'LoseContextCHROMIUM': {
3920 'decoder_func': 'DoLoseContextCHROMIUM',
3921 'unit_test': False,
3922 'extension': True,
3923 'chromium': True,
3924 'trace_level': 1,
3926 'InsertSyncPointCHROMIUM': {
3927 'type': 'HandWritten',
3928 'impl_func': False,
3929 'extension': "CHROMIUM_sync_point",
3930 'chromium': True,
3931 'trace_level': 1,
3933 'WaitSyncPointCHROMIUM': {
3934 'type': 'Custom',
3935 'impl_func': True,
3936 'extension': "CHROMIUM_sync_point",
3937 'chromium': True,
3938 'trace_level': 1,
3940 'DiscardBackbufferCHROMIUM': {
3941 'type': 'Custom',
3942 'impl_func': True,
3943 'extension': True,
3944 'chromium': True,
3945 'trace_level': 2,
3947 'ScheduleOverlayPlaneCHROMIUM': {
3948 'type': 'Custom',
3949 'impl_func': True,
3950 'unit_test': False,
3951 'client_test': False,
3952 'extension': True,
3953 'chromium': True,
3955 'MatrixLoadfCHROMIUM': {
3956 'type': 'PUT',
3957 'count': 16,
3958 'data_type': 'GLfloat',
3959 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3960 'gl_test_func': 'glMatrixLoadfEXT',
3961 'chromium': True,
3962 'extension': True,
3963 'extension_flag': 'chromium_path_rendering',
3965 'MatrixLoadIdentityCHROMIUM': {
3966 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3967 'gl_test_func': 'glMatrixLoadIdentityEXT',
3968 'chromium': True,
3969 'extension': True,
3970 'extension_flag': 'chromium_path_rendering',
3975 def Grouper(n, iterable, fillvalue=None):
3976 """Collect data into fixed-length chunks or blocks"""
3977 args = [iter(iterable)] * n
3978 return itertools.izip_longest(fillvalue=fillvalue, *args)
3981 def SplitWords(input_string):
3982 """Split by '_' if found, otherwise split at uppercase/numeric chars.
3984 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
3985 "Case"], and "Vector3" into ["Vector", "3"].
3987 if input_string.find('_') > -1:
3988 # 'some_TEXT_' -> 'some TEXT'
3989 return input_string.replace('_', ' ').strip().split()
3990 else:
3991 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
3992 # mixed case.
3993 # look for capitalization to cut input_strings
3994 # 'SomeText' -> 'Some Text'
3995 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
3996 # 'Vector3' -> 'Vector 3'
3997 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
3998 return input_string.split()
4000 def ToUnderscore(input_string):
4001 """converts CamelCase to camel_case."""
4002 words = SplitWords(input_string)
4003 return '_'.join([word.lower() for word in words])
4005 def CachedStateName(item):
4006 if item.get('cached', False):
4007 return 'cached_' + item['name']
4008 return item['name']
4010 def ToGLExtensionString(extension_flag):
4011 """Returns GL-type extension string of a extension flag."""
4012 if extension_flag == "oes_compressed_etc1_rgb8_texture":
4013 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4014 # unfortunate.
4015 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4016 'egl', 'atc', 'etc1', 'angle']
4017 parts = extension_flag.split('_')
4018 return "_".join(
4019 [part.upper() if part in uppercase_words else part for part in parts])
4021 def ToCamelCase(input_string):
4022 """converts ABC_underscore_case to ABCUnderscoreCase."""
4023 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
4025 def GetGLGetTypeConversion(result_type, value_type, value):
4026 """Makes a gl compatible type conversion string for accessing state variables.
4028 Useful when accessing state variables through glGetXXX calls.
4029 glGet documetation (for example, the manual pages):
4030 [...] If glGetIntegerv is called, [...] most floating-point values are
4031 rounded to the nearest integer value. [...]
4033 Args:
4034 result_type: the gl type to be obtained
4035 value_type: the GL type of the state variable
4036 value: the name of the state variable
4038 Returns:
4039 String that converts the state variable to desired GL type according to GL
4040 rules.
4043 if result_type == 'GLint':
4044 if value_type == 'GLfloat':
4045 return 'static_cast<GLint>(round(%s))' % value
4046 return 'static_cast<%s>(%s)' % (result_type, value)
4048 class CWriter(object):
4049 """Writes to a file formatting it for Google's style guidelines."""
4051 def __init__(self, filename):
4052 self.filename = filename
4053 self.content = []
4055 def Write(self, string):
4056 """Writes a string to a file spliting if it's > 80 characters."""
4057 lines = string.splitlines()
4058 num_lines = len(lines)
4059 for ii in range(0, num_lines):
4060 self.content.append(lines[ii])
4061 if ii < (num_lines - 1) or string[-1] == '\n':
4062 self.content.append('\n')
4064 def Close(self):
4065 """Close the file."""
4066 content = "".join(self.content)
4067 write_file = True
4068 if os.path.exists(self.filename):
4069 old_file = open(self.filename, "rb");
4070 old_content = old_file.read()
4071 old_file.close();
4072 if content == old_content:
4073 write_file = False
4074 if write_file:
4075 file = open(self.filename, "wb")
4076 file.write(content)
4077 file.close()
4080 class CHeaderWriter(CWriter):
4081 """Writes a C Header file."""
4083 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
4085 def __init__(self, filename, file_comment = None):
4086 CWriter.__init__(self, filename)
4088 base = os.path.abspath(filename)
4089 while os.path.basename(base) != 'src':
4090 new_base = os.path.dirname(base)
4091 assert new_base != base # Prevent infinite loop.
4092 base = new_base
4094 hpath = os.path.relpath(filename, base)
4095 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
4097 self.Write(_LICENSE)
4098 self.Write(_DO_NOT_EDIT_WARNING)
4099 if not file_comment == None:
4100 self.Write(file_comment)
4101 self.Write("#ifndef %s\n" % self.guard)
4102 self.Write("#define %s\n\n" % self.guard)
4104 def Close(self):
4105 self.Write("#endif // %s\n\n" % self.guard)
4106 CWriter.Close(self)
4108 class TypeHandler(object):
4109 """This class emits code for a particular type of function."""
4111 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
4113 def __init__(self):
4114 pass
4116 def InitFunction(self, func):
4117 """Add or adjust anything type specific for this function."""
4118 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
4119 func.AddCmdArg(DataSizeArgument('data_size'))
4121 def NeedsDataTransferFunction(self, func):
4122 """Overriden from TypeHandler."""
4123 return func.num_pointer_args >= 1
4125 def WriteStruct(self, func, file):
4126 """Writes a structure that matches the arguments to a function."""
4127 comment = func.GetInfo('cmd_comment')
4128 if not comment == None:
4129 file.Write(comment)
4130 file.Write("struct %s {\n" % func.name)
4131 file.Write(" typedef %s ValueType;\n" % func.name)
4132 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
4133 func.WriteCmdArgFlag(file)
4134 func.WriteCmdFlag(file)
4135 file.Write("\n")
4136 result = func.GetInfo('result')
4137 if not result == None:
4138 if len(result) == 1:
4139 file.Write(" typedef %s Result;\n\n" % result[0])
4140 else:
4141 file.Write(" struct Result {\n")
4142 for line in result:
4143 file.Write(" %s;\n" % line)
4144 file.Write(" };\n\n")
4146 func.WriteCmdComputeSize(file)
4147 func.WriteCmdSetHeader(file)
4148 func.WriteCmdInit(file)
4149 func.WriteCmdSet(file)
4151 file.Write(" gpu::CommandHeader header;\n")
4152 args = func.GetCmdArgs()
4153 for arg in args:
4154 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
4156 consts = func.GetCmdConstants()
4157 for const in consts:
4158 file.Write(" static const %s %s = %s;\n" %
4159 (const.cmd_type, const.name, const.GetConstantValue()))
4161 file.Write("};\n")
4162 file.Write("\n")
4164 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
4165 file.Write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
4166 file.Write(" \"size of %s should be %d\");\n" %
4167 (func.name, size))
4168 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
4169 file.Write(" \"offset of %s header should be 0\");\n" %
4170 func.name)
4171 offset = _SIZE_OF_COMMAND_HEADER
4172 for arg in args:
4173 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
4174 (func.name, arg.name, offset))
4175 file.Write(" \"offset of %s %s should be %d\");\n" %
4176 (func.name, arg.name, offset))
4177 offset += _SIZE_OF_UINT32
4178 if not result == None and len(result) > 1:
4179 offset = 0;
4180 for line in result:
4181 parts = line.split()
4182 name = parts[-1]
4183 check = """
4184 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4185 "offset of %(cmd_name)s Result %(field_name)s should be "
4186 "%(offset)d");
4188 file.Write((check.strip() + "\n") % {
4189 'cmd_name': func.name,
4190 'field_name': name,
4191 'offset': offset,
4193 offset += _SIZE_OF_UINT32
4194 file.Write("\n")
4196 def WriteHandlerImplementation(self, func, file):
4197 """Writes the handler implementation for this command."""
4198 if func.IsUnsafe() and func.GetInfo('id_mapping'):
4199 code_no_gen = """ if (!group_->Get%(type)sServiceId(
4200 %(var)s, &%(service_var)s)) {
4201 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4202 return error::kNoError;
4205 code_gen = """ if (!group_->Get%(type)sServiceId(
4206 %(var)s, &%(service_var)s)) {
4207 if (!group_->bind_generates_resource()) {
4208 LOCAL_SET_GL_ERROR(
4209 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4210 return error::kNoError;
4212 GLuint client_id = %(var)s;
4213 gl%(gen_func)s(1, &%(service_var)s);
4214 Create%(type)s(client_id, %(service_var)s);
4217 gen_func = func.GetInfo('gen_func')
4218 for id_type in func.GetInfo('id_mapping'):
4219 service_var = id_type.lower()
4220 if id_type == 'Sync':
4221 service_var = "service_%s" % service_var
4222 file.Write(" GLsync %s = 0;\n" % service_var)
4223 if gen_func and id_type in gen_func:
4224 file.Write(code_gen % { 'type': id_type,
4225 'var': id_type.lower(),
4226 'service_var': service_var,
4227 'func': func.GetGLFunctionName(),
4228 'gen_func': gen_func })
4229 else:
4230 file.Write(code_no_gen % { 'type': id_type,
4231 'var': id_type.lower(),
4232 'service_var': service_var,
4233 'func': func.GetGLFunctionName() })
4234 args = []
4235 for arg in func.GetOriginalArgs():
4236 if arg.type == "GLsync":
4237 args.append("service_%s" % arg.name)
4238 elif arg.name.endswith("size") and arg.type == "GLsizei":
4239 args.append("num_%s" % func.GetLastOriginalArg().name)
4240 elif arg.name == "length":
4241 args.append("nullptr")
4242 else:
4243 args.append(arg.name)
4244 file.Write(" %s(%s);\n" %
4245 (func.GetGLFunctionName(), ", ".join(args)))
4247 def WriteCmdSizeTest(self, func, file):
4248 """Writes the size test for a command."""
4249 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4251 def WriteFormatTest(self, func, file):
4252 """Writes a format test for a command."""
4253 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4254 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4255 (func.name, func.name))
4256 file.Write(" void* next_cmd = cmd.Set(\n")
4257 file.Write(" &cmd")
4258 args = func.GetCmdArgs()
4259 for value, arg in enumerate(args):
4260 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4261 file.Write(");\n")
4262 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4263 func.name)
4264 file.Write(" cmd.header.command);\n")
4265 func.type_handler.WriteCmdSizeTest(func, file)
4266 for value, arg in enumerate(args):
4267 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4268 (arg.type, value + 11, arg.name))
4269 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4270 file.Write(" next_cmd, sizeof(cmd));\n")
4271 file.Write("}\n")
4272 file.Write("\n")
4274 def WriteImmediateFormatTest(self, func, file):
4275 """Writes a format test for an immediate version of a command."""
4276 pass
4278 def WriteBucketFormatTest(self, func, file):
4279 """Writes a format test for a bucket version of a command."""
4280 pass
4282 def WriteGetDataSizeCode(self, func, file):
4283 """Writes the code to set data_size used in validation"""
4284 pass
4286 def WriteImmediateCmdSizeTest(self, func, file):
4287 """Writes a size test for an immediate version of a command."""
4288 file.Write(" // TODO(gman): Compute correct size.\n")
4289 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4291 def __WriteIdMapping(self, func, file):
4292 """Writes client side / service side ID mapping."""
4293 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
4294 return
4295 for id_type in func.GetInfo('id_mapping'):
4296 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
4297 (id_type, id_type.lower(), id_type.lower()))
4299 def WriteImmediateHandlerImplementation (self, func, file):
4300 """Writes the handler impl for the immediate version of a command."""
4301 self.__WriteIdMapping(func, file)
4302 file.Write(" %s(%s);\n" %
4303 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4305 def WriteBucketHandlerImplementation (self, func, file):
4306 """Writes the handler impl for the bucket version of a command."""
4307 self.__WriteIdMapping(func, file)
4308 file.Write(" %s(%s);\n" %
4309 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4311 def WriteServiceHandlerFunctionHeader(self, func, file):
4312 """Writes function header for service implementation handlers."""
4313 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4314 uint32_t immediate_data_size, const void* cmd_data) {
4315 """ % {'name': func.name})
4316 if func.IsUnsafe():
4317 file.Write("""if (!unsafe_es3_apis_enabled())
4318 return error::kUnknownCommand;
4319 """)
4320 file.Write("""const gles2::cmds::%(name)s& c =
4321 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4322 (void)c;
4323 """ % {'name': func.name})
4325 def WriteServiceImplementation(self, func, file):
4326 """Writes the service implementation for a command."""
4327 self.WriteServiceHandlerFunctionHeader(func, file)
4328 self.WriteHandlerExtensionCheck(func, file)
4329 self.WriteHandlerDeferReadWrite(func, file);
4330 if len(func.GetOriginalArgs()) > 0:
4331 last_arg = func.GetLastOriginalArg()
4332 all_but_last_arg = func.GetOriginalArgs()[:-1]
4333 for arg in all_but_last_arg:
4334 arg.WriteGetCode(file)
4335 self.WriteGetDataSizeCode(func, file)
4336 last_arg.WriteGetCode(file)
4337 func.WriteHandlerValidation(file)
4338 func.WriteHandlerImplementation(file)
4339 file.Write(" return error::kNoError;\n")
4340 file.Write("}\n")
4341 file.Write("\n")
4343 def WriteImmediateServiceImplementation(self, func, file):
4344 """Writes the service implementation for an immediate version of command."""
4345 self.WriteServiceHandlerFunctionHeader(func, file)
4346 self.WriteHandlerExtensionCheck(func, file)
4347 self.WriteHandlerDeferReadWrite(func, file);
4348 for arg in func.GetOriginalArgs():
4349 if arg.IsPointer():
4350 self.WriteGetDataSizeCode(func, file)
4351 arg.WriteGetCode(file)
4352 func.WriteHandlerValidation(file)
4353 func.WriteHandlerImplementation(file)
4354 file.Write(" return error::kNoError;\n")
4355 file.Write("}\n")
4356 file.Write("\n")
4358 def WriteBucketServiceImplementation(self, func, file):
4359 """Writes the service implementation for a bucket version of command."""
4360 self.WriteServiceHandlerFunctionHeader(func, file)
4361 self.WriteHandlerExtensionCheck(func, file)
4362 self.WriteHandlerDeferReadWrite(func, file);
4363 for arg in func.GetCmdArgs():
4364 arg.WriteGetCode(file)
4365 func.WriteHandlerValidation(file)
4366 func.WriteHandlerImplementation(file)
4367 file.Write(" return error::kNoError;\n")
4368 file.Write("}\n")
4369 file.Write("\n")
4371 def WriteHandlerExtensionCheck(self, func, file):
4372 if func.GetInfo('extension_flag'):
4373 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
4374 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4375 " \"function not available\");\n" % func.original_name)
4376 file.Write(" return error::kNoError;")
4377 file.Write(" }\n\n")
4379 def WriteHandlerDeferReadWrite(self, func, file):
4380 """Writes the code to handle deferring reads or writes."""
4381 defer_draws = func.GetInfo('defer_draws')
4382 defer_reads = func.GetInfo('defer_reads')
4383 if defer_draws or defer_reads:
4384 file.Write(" error::Error error;\n")
4385 if defer_draws:
4386 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
4387 file.Write(" if (error != error::kNoError)\n")
4388 file.Write(" return error;\n")
4389 if defer_reads:
4390 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
4391 file.Write(" if (error != error::kNoError)\n")
4392 file.Write(" return error;\n")
4394 def WriteValidUnitTest(self, func, file, test, *extras):
4395 """Writes a valid unit test for the service implementation."""
4396 if func.GetInfo('expectation') == False:
4397 test = self._remove_expected_call_re.sub('', test)
4398 name = func.name
4399 arg_strings = [
4400 arg.GetValidArg(func) \
4401 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4403 gl_arg_strings = [
4404 arg.GetValidGLArg(func) \
4405 for arg in func.GetOriginalArgs()
4407 gl_func_name = func.GetGLTestFunctionName()
4408 vars = {
4409 'name':name,
4410 'gl_func_name': gl_func_name,
4411 'args': ", ".join(arg_strings),
4412 'gl_args': ", ".join(gl_arg_strings),
4414 for extra in extras:
4415 vars.update(extra)
4416 old_test = ""
4417 while (old_test != test):
4418 old_test = test
4419 test = test % vars
4420 file.Write(test % vars)
4422 def WriteInvalidUnitTest(self, func, file, test, *extras):
4423 """Writes an invalid unit test for the service implementation."""
4424 if func.IsUnsafe():
4425 return
4426 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4427 # Service implementation does not test constants, as they are not part of
4428 # the call in the service side.
4429 if invalid_arg.IsConstant():
4430 continue
4432 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4433 for value_index in range(0, num_invalid_values):
4434 arg_strings = []
4435 parse_result = "kNoError"
4436 gl_error = None
4437 for arg in func.GetOriginalArgs():
4438 if arg.IsConstant():
4439 continue
4440 if invalid_arg is arg:
4441 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4442 value_index)
4443 else:
4444 arg_string = arg.GetValidArg(func)
4445 arg_strings.append(arg_string)
4446 gl_arg_strings = []
4447 for arg in func.GetOriginalArgs():
4448 gl_arg_strings.append("_")
4449 gl_func_name = func.GetGLTestFunctionName()
4450 gl_error_test = ''
4451 if not gl_error == None:
4452 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4454 vars = {
4455 'name': func.name,
4456 'arg_index': invalid_arg_index,
4457 'value_index': value_index,
4458 'gl_func_name': gl_func_name,
4459 'args': ", ".join(arg_strings),
4460 'all_but_last_args': ", ".join(arg_strings[:-1]),
4461 'gl_args': ", ".join(gl_arg_strings),
4462 'parse_result': parse_result,
4463 'gl_error_test': gl_error_test,
4465 for extra in extras:
4466 vars.update(extra)
4467 file.Write(test % vars)
4469 def WriteServiceUnitTest(self, func, file, *extras):
4470 """Writes the service unit test for a command."""
4472 if func.name == 'Enable':
4473 valid_test = """
4474 TEST_P(%(test_name)s, %(name)sValidArgs) {
4475 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4476 SpecializedSetup<cmds::%(name)s, 0>(true);
4477 cmds::%(name)s cmd;
4478 cmd.Init(%(args)s);"""
4479 elif func.name == 'Disable':
4480 valid_test = """
4481 TEST_P(%(test_name)s, %(name)sValidArgs) {
4482 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4483 SpecializedSetup<cmds::%(name)s, 0>(true);
4484 cmds::%(name)s cmd;
4485 cmd.Init(%(args)s);"""
4486 else:
4487 valid_test = """
4488 TEST_P(%(test_name)s, %(name)sValidArgs) {
4489 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4490 SpecializedSetup<cmds::%(name)s, 0>(true);
4491 cmds::%(name)s cmd;
4492 cmd.Init(%(args)s);"""
4493 if func.IsUnsafe():
4494 valid_test += """
4495 decoder_->set_unsafe_es3_apis_enabled(true);
4496 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4497 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4498 decoder_->set_unsafe_es3_apis_enabled(false);
4499 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4502 else:
4503 valid_test += """
4504 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4505 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4508 self.WriteValidUnitTest(func, file, valid_test, *extras)
4510 if not func.IsUnsafe():
4511 invalid_test = """
4512 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4513 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4514 SpecializedSetup<cmds::%(name)s, 0>(false);
4515 cmds::%(name)s cmd;
4516 cmd.Init(%(args)s);
4517 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4520 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4522 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4523 """Writes the service unit test for an immediate command."""
4524 file.Write("// TODO(gman): %s\n" % func.name)
4526 def WriteImmediateValidationCode(self, func, file):
4527 """Writes the validation code for an immediate version of a command."""
4528 pass
4530 def WriteBucketServiceUnitTest(self, func, file, *extras):
4531 """Writes the service unit test for a bucket command."""
4532 file.Write("// TODO(gman): %s\n" % func.name)
4534 def WriteBucketValidationCode(self, func, file):
4535 """Writes the validation code for a bucket version of a command."""
4536 file.Write("// TODO(gman): %s\n" % func.name)
4538 def WriteGLES2ImplementationDeclaration(self, func, file):
4539 """Writes the GLES2 Implemention declaration."""
4540 impl_decl = func.GetInfo('impl_decl')
4541 if impl_decl == None or impl_decl == True:
4542 file.Write("%s %s(%s) override;\n" %
4543 (func.return_type, func.original_name,
4544 func.MakeTypedOriginalArgString("")))
4545 file.Write("\n")
4547 def WriteGLES2CLibImplementation(self, func, file):
4548 file.Write("%s GLES2%s(%s) {\n" %
4549 (func.return_type, func.name,
4550 func.MakeTypedOriginalArgString("")))
4551 result_string = "return "
4552 if func.return_type == "void":
4553 result_string = ""
4554 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4555 (result_string, func.original_name,
4556 func.MakeOriginalArgString("")))
4557 file.Write("}\n")
4559 def WriteGLES2Header(self, func, file):
4560 """Writes a re-write macro for GLES"""
4561 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4563 def WriteClientGLCallLog(self, func, file):
4564 """Writes a logging macro for the client side code."""
4565 comma = ""
4566 if len(func.GetOriginalArgs()):
4567 comma = " << "
4568 file.Write(
4569 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4570 (func.original_name, comma, func.MakeLogArgString()))
4572 def WriteClientGLReturnLog(self, func, file):
4573 """Writes the return value logging code."""
4574 if func.return_type != "void":
4575 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4577 def WriteGLES2ImplementationHeader(self, func, file):
4578 """Writes the GLES2 Implemention."""
4579 self.WriteGLES2ImplementationDeclaration(func, file)
4581 def WriteGLES2TraceImplementationHeader(self, func, file):
4582 """Writes the GLES2 Trace Implemention header."""
4583 file.Write("%s %s(%s) override;\n" %
4584 (func.return_type, func.original_name,
4585 func.MakeTypedOriginalArgString("")))
4587 def WriteGLES2TraceImplementation(self, func, file):
4588 """Writes the GLES2 Trace Implemention."""
4589 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4590 (func.return_type, func.original_name,
4591 func.MakeTypedOriginalArgString("")))
4592 result_string = "return "
4593 if func.return_type == "void":
4594 result_string = ""
4595 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4596 func.name)
4597 file.Write(" %sgl_->%s(%s);\n" %
4598 (result_string, func.name, func.MakeOriginalArgString("")))
4599 file.Write("}\n")
4600 file.Write("\n")
4602 def WriteGLES2Implementation(self, func, file):
4603 """Writes the GLES2 Implemention."""
4604 impl_func = func.GetInfo('impl_func')
4605 impl_decl = func.GetInfo('impl_decl')
4606 gen_cmd = func.GetInfo('gen_cmd')
4607 if (func.can_auto_generate and
4608 (impl_func == None or impl_func == True) and
4609 (impl_decl == None or impl_decl == True) and
4610 (gen_cmd == None or gen_cmd == True)):
4611 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4612 (func.return_type, func.original_name,
4613 func.MakeTypedOriginalArgString("")))
4614 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4615 self.WriteClientGLCallLog(func, file)
4616 func.WriteDestinationInitalizationValidation(file)
4617 for arg in func.GetOriginalArgs():
4618 arg.WriteClientSideValidationCode(file, func)
4619 file.Write(" helper_->%s(%s);\n" %
4620 (func.name, func.MakeHelperArgString("")))
4621 file.Write(" CheckGLError();\n")
4622 self.WriteClientGLReturnLog(func, file)
4623 file.Write("}\n")
4624 file.Write("\n")
4626 def WriteGLES2InterfaceHeader(self, func, file):
4627 """Writes the GLES2 Interface."""
4628 file.Write("virtual %s %s(%s) = 0;\n" %
4629 (func.return_type, func.original_name,
4630 func.MakeTypedOriginalArgString("")))
4632 def WriteMojoGLES2ImplHeader(self, func, file):
4633 """Writes the Mojo GLES2 implementation header."""
4634 file.Write("%s %s(%s) override;\n" %
4635 (func.return_type, func.original_name,
4636 func.MakeTypedOriginalArgString("")))
4638 def WriteMojoGLES2Impl(self, func, file):
4639 """Writes the Mojo GLES2 implementation."""
4640 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4641 (func.return_type, func.original_name,
4642 func.MakeTypedOriginalArgString("")))
4643 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4644 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4645 "occlusion_query_EXT", "CHROMIUM_image",
4646 "CHROMIUM_copy_texture",
4647 "CHROMIUM_pixel_transfer_buffer_object"]
4648 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4649 file.Write("MojoGLES2MakeCurrent(context_);");
4650 func_return = "gl" + func.original_name + "(" + \
4651 func.MakeOriginalArgString("") + ");"
4652 if func.return_type == "void":
4653 file.Write(func_return);
4654 else:
4655 file.Write("return " + func_return);
4656 else:
4657 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4658 func.original_name);
4659 if func.return_type != "void":
4660 file.Write("return 0;")
4661 file.Write("}")
4663 def WriteGLES2InterfaceStub(self, func, file):
4664 """Writes the GLES2 Interface stub declaration."""
4665 file.Write("%s %s(%s) override;\n" %
4666 (func.return_type, func.original_name,
4667 func.MakeTypedOriginalArgString("")))
4669 def WriteGLES2InterfaceStubImpl(self, func, file):
4670 """Writes the GLES2 Interface stub declaration."""
4671 args = func.GetOriginalArgs()
4672 arg_string = ", ".join(
4673 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4674 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4675 (func.return_type, func.original_name, arg_string))
4676 if func.return_type != "void":
4677 file.Write(" return 0;\n")
4678 file.Write("}\n")
4680 def WriteGLES2ImplementationUnitTest(self, func, file):
4681 """Writes the GLES2 Implemention unit test."""
4682 client_test = func.GetInfo('client_test')
4683 if (func.can_auto_generate and
4684 (client_test == None or client_test == True)):
4685 code = """
4686 TEST_F(GLES2ImplementationTest, %(name)s) {
4687 struct Cmds {
4688 cmds::%(name)s cmd;
4690 Cmds expected;
4691 expected.cmd.Init(%(cmd_args)s);
4693 gl_->%(name)s(%(args)s);
4694 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4697 cmd_arg_strings = [
4698 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4701 gl_arg_strings = [
4702 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4705 file.Write(code % {
4706 'name': func.name,
4707 'args': ", ".join(gl_arg_strings),
4708 'cmd_args': ", ".join(cmd_arg_strings),
4711 # Test constants for invalid values, as they are not tested by the
4712 # service.
4713 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4714 if constants:
4715 code = """
4716 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4717 gl_->%(name)s(%(args)s);
4718 EXPECT_TRUE(NoCommandsWritten());
4719 EXPECT_EQ(%(gl_error)s, CheckError());
4722 for invalid_arg in constants:
4723 gl_arg_strings = []
4724 invalid = invalid_arg.GetInvalidArg(func)
4725 for arg in func.GetOriginalArgs():
4726 if arg is invalid_arg:
4727 gl_arg_strings.append(invalid[0])
4728 else:
4729 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4731 file.Write(code % {
4732 'name': func.name,
4733 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4734 'args': ", ".join(gl_arg_strings),
4735 'gl_error': invalid[2],
4737 else:
4738 if client_test != False:
4739 file.Write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4741 def WriteDestinationInitalizationValidation(self, func, file):
4742 """Writes the client side destintion initialization validation."""
4743 for arg in func.GetOriginalArgs():
4744 arg.WriteDestinationInitalizationValidation(file, func)
4746 def WriteTraceEvent(self, func, file):
4747 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4748 func.original_name)
4750 def WriteImmediateCmdComputeSize(self, func, file):
4751 """Writes the size computation code for the immediate version of a cmd."""
4752 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4753 file.Write(" return static_cast<uint32_t>(\n")
4754 file.Write(" sizeof(ValueType) + // NOLINT\n")
4755 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4756 file.Write(" }\n")
4757 file.Write("\n")
4759 def WriteImmediateCmdSetHeader(self, func, file):
4760 """Writes the SetHeader function for the immediate version of a cmd."""
4761 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4762 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4763 file.Write(" }\n")
4764 file.Write("\n")
4766 def WriteImmediateCmdInit(self, func, file):
4767 """Writes the Init function for the immediate version of a command."""
4768 raise NotImplementedError(func.name)
4770 def WriteImmediateCmdSet(self, func, file):
4771 """Writes the Set function for the immediate version of a command."""
4772 raise NotImplementedError(func.name)
4774 def WriteCmdHelper(self, func, file):
4775 """Writes the cmd helper definition for a cmd."""
4776 code = """ void %(name)s(%(typed_args)s) {
4777 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4778 if (c) {
4779 c->Init(%(args)s);
4784 file.Write(code % {
4785 "name": func.name,
4786 "typed_args": func.MakeTypedCmdArgString(""),
4787 "args": func.MakeCmdArgString(""),
4790 def WriteImmediateCmdHelper(self, func, file):
4791 """Writes the cmd helper definition for the immediate version of a cmd."""
4792 code = """ void %(name)s(%(typed_args)s) {
4793 const uint32_t s = 0; // TODO(gman): compute correct size
4794 gles2::cmds::%(name)s* c =
4795 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4796 if (c) {
4797 c->Init(%(args)s);
4802 file.Write(code % {
4803 "name": func.name,
4804 "typed_args": func.MakeTypedCmdArgString(""),
4805 "args": func.MakeCmdArgString(""),
4809 class StateSetHandler(TypeHandler):
4810 """Handler for commands that simply set state."""
4812 def __init__(self):
4813 TypeHandler.__init__(self)
4815 def WriteHandlerImplementation(self, func, file):
4816 """Overrriden from TypeHandler."""
4817 state_name = func.GetInfo('state')
4818 state = _STATES[state_name]
4819 states = state['states']
4820 args = func.GetOriginalArgs()
4821 for ndx,item in enumerate(states):
4822 code = []
4823 if 'range_checks' in item:
4824 for range_check in item['range_checks']:
4825 code.append("%s %s" % (args[ndx].name, range_check['check']))
4826 if 'nan_check' in item:
4827 # Drivers might generate an INVALID_VALUE error when a value is set
4828 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4829 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4830 # Make this behavior consistent within Chromium, and avoid leaking GL
4831 # errors by generating the error in the command buffer instead of
4832 # letting the GL driver generate it.
4833 code.append("std::isnan(%s)" % args[ndx].name)
4834 if len(code):
4835 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4836 file.Write(
4837 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4838 ' "%s", "%s out of range");\n' %
4839 (func.name, args[ndx].name))
4840 file.Write(" return error::kNoError;\n")
4841 file.Write(" }\n")
4842 code = []
4843 for ndx,item in enumerate(states):
4844 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4845 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4846 for ndx,item in enumerate(states):
4847 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4848 if 'state_flag' in state:
4849 file.Write(" %s = true;\n" % state['state_flag'])
4850 if not func.GetInfo("no_gl"):
4851 for ndx,item in enumerate(states):
4852 if item.get('cached', False):
4853 file.Write(" state_.%s = %s;\n" %
4854 (CachedStateName(item), args[ndx].name))
4855 file.Write(" %s(%s);\n" %
4856 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4857 file.Write(" }\n")
4859 def WriteServiceUnitTest(self, func, file, *extras):
4860 """Overrriden from TypeHandler."""
4861 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
4862 state_name = func.GetInfo('state')
4863 state = _STATES[state_name]
4864 states = state['states']
4865 for ndx,item in enumerate(states):
4866 if 'range_checks' in item:
4867 for check_ndx, range_check in enumerate(item['range_checks']):
4868 valid_test = """
4869 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4870 SpecializedSetup<cmds::%(name)s, 0>(false);
4871 cmds::%(name)s cmd;
4872 cmd.Init(%(args)s);
4873 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4874 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4877 name = func.name
4878 arg_strings = [
4879 arg.GetValidArg(func) \
4880 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4883 arg_strings[ndx] = range_check['test_value']
4884 vars = {
4885 'name': name,
4886 'ndx': ndx,
4887 'check_ndx': check_ndx,
4888 'args': ", ".join(arg_strings),
4890 for extra in extras:
4891 vars.update(extra)
4892 file.Write(valid_test % vars)
4893 if 'nan_check' in item:
4894 valid_test = """
4895 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4896 SpecializedSetup<cmds::%(name)s, 0>(false);
4897 cmds::%(name)s cmd;
4898 cmd.Init(%(args)s);
4899 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4900 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4903 name = func.name
4904 arg_strings = [
4905 arg.GetValidArg(func) \
4906 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4909 arg_strings[ndx] = 'nanf("")'
4910 vars = {
4911 'name': name,
4912 'ndx': ndx,
4913 'args': ", ".join(arg_strings),
4915 for extra in extras:
4916 vars.update(extra)
4917 file.Write(valid_test % vars)
4920 class StateSetRGBAlphaHandler(TypeHandler):
4921 """Handler for commands that simply set state that have rgb/alpha."""
4923 def __init__(self):
4924 TypeHandler.__init__(self)
4926 def WriteHandlerImplementation(self, func, file):
4927 """Overrriden from TypeHandler."""
4928 state_name = func.GetInfo('state')
4929 state = _STATES[state_name]
4930 states = state['states']
4931 args = func.GetOriginalArgs()
4932 num_args = len(args)
4933 code = []
4934 for ndx,item in enumerate(states):
4935 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
4936 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4937 for ndx, item in enumerate(states):
4938 file.Write(" state_.%s = %s;\n" %
4939 (item['name'], args[ndx % num_args].name))
4940 if 'state_flag' in state:
4941 file.Write(" %s = true;\n" % state['state_flag'])
4942 if not func.GetInfo("no_gl"):
4943 file.Write(" %s(%s);\n" %
4944 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4945 file.Write(" }\n")
4948 class StateSetFrontBackSeparateHandler(TypeHandler):
4949 """Handler for commands that simply set state that have front/back."""
4951 def __init__(self):
4952 TypeHandler.__init__(self)
4954 def WriteHandlerImplementation(self, func, file):
4955 """Overrriden from TypeHandler."""
4956 state_name = func.GetInfo('state')
4957 state = _STATES[state_name]
4958 states = state['states']
4959 args = func.GetOriginalArgs()
4960 face = args[0].name
4961 num_args = len(args)
4962 file.Write(" bool changed = false;\n")
4963 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4964 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4965 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4966 code = []
4967 for ndx, item in enumerate(group):
4968 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
4969 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
4970 file.Write(" }\n")
4971 file.Write(" if (changed) {\n")
4972 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4973 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4974 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4975 for ndx, item in enumerate(group):
4976 file.Write(" state_.%s = %s;\n" %
4977 (item['name'], args[ndx + 1].name))
4978 file.Write(" }\n")
4979 if 'state_flag' in state:
4980 file.Write(" %s = true;\n" % state['state_flag'])
4981 if not func.GetInfo("no_gl"):
4982 file.Write(" %s(%s);\n" %
4983 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4984 file.Write(" }\n")
4987 class StateSetFrontBackHandler(TypeHandler):
4988 """Handler for commands that simply set state that set both front/back."""
4990 def __init__(self):
4991 TypeHandler.__init__(self)
4993 def WriteHandlerImplementation(self, func, file):
4994 """Overrriden from TypeHandler."""
4995 state_name = func.GetInfo('state')
4996 state = _STATES[state_name]
4997 states = state['states']
4998 args = func.GetOriginalArgs()
4999 num_args = len(args)
5000 code = []
5001 for group_ndx, group in enumerate(Grouper(num_args, states)):
5002 for ndx, item in enumerate(group):
5003 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5004 file.Write(" if (%s) {\n" % " ||\n ".join(code))
5005 for group_ndx, group in enumerate(Grouper(num_args, states)):
5006 for ndx, item in enumerate(group):
5007 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5008 if 'state_flag' in state:
5009 file.Write(" %s = true;\n" % state['state_flag'])
5010 if not func.GetInfo("no_gl"):
5011 file.Write(" %s(%s);\n" %
5012 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5013 file.Write(" }\n")
5016 class StateSetNamedParameter(TypeHandler):
5017 """Handler for commands that set a state chosen with an enum parameter."""
5019 def __init__(self):
5020 TypeHandler.__init__(self)
5022 def WriteHandlerImplementation(self, func, file):
5023 """Overridden from TypeHandler."""
5024 state_name = func.GetInfo('state')
5025 state = _STATES[state_name]
5026 states = state['states']
5027 args = func.GetOriginalArgs()
5028 num_args = len(args)
5029 assert num_args == 2
5030 file.Write(" switch (%s) {\n" % args[0].name)
5031 for state in states:
5032 file.Write(" case %s:\n" % state['enum'])
5033 file.Write(" if (state_.%s != %s) {\n" %
5034 (state['name'], args[1].name))
5035 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
5036 if not func.GetInfo("no_gl"):
5037 file.Write(" %s(%s);\n" %
5038 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5039 file.Write(" }\n")
5040 file.Write(" break;\n")
5041 file.Write(" default:\n")
5042 file.Write(" NOTREACHED();\n")
5043 file.Write(" }\n")
5046 class CustomHandler(TypeHandler):
5047 """Handler for commands that are auto-generated but require minor tweaks."""
5049 def __init__(self):
5050 TypeHandler.__init__(self)
5052 def WriteServiceImplementation(self, func, file):
5053 """Overrriden from TypeHandler."""
5054 pass
5056 def WriteImmediateServiceImplementation(self, func, file):
5057 """Overrriden from TypeHandler."""
5058 pass
5060 def WriteBucketServiceImplementation(self, func, file):
5061 """Overrriden from TypeHandler."""
5062 pass
5064 def WriteServiceUnitTest(self, func, file, *extras):
5065 """Overrriden from TypeHandler."""
5066 file.Write("// TODO(gman): %s\n\n" % func.name)
5068 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5069 """Overrriden from TypeHandler."""
5070 file.Write("// TODO(gman): %s\n\n" % func.name)
5072 def WriteImmediateCmdGetTotalSize(self, func, file):
5073 """Overrriden from TypeHandler."""
5074 file.Write(
5075 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5077 def WriteImmediateCmdInit(self, func, file):
5078 """Overrriden from TypeHandler."""
5079 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5080 self.WriteImmediateCmdGetTotalSize(func, file)
5081 file.Write(" SetHeader(total_size);\n")
5082 args = func.GetCmdArgs()
5083 for arg in args:
5084 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5085 file.Write(" }\n")
5086 file.Write("\n")
5088 def WriteImmediateCmdSet(self, func, file):
5089 """Overrriden from TypeHandler."""
5090 copy_args = func.MakeCmdArgString("_", False)
5091 file.Write(" void* Set(void* cmd%s) {\n" %
5092 func.MakeTypedCmdArgString("_", True))
5093 self.WriteImmediateCmdGetTotalSize(func, file)
5094 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5095 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5096 "cmd, total_size);\n")
5097 file.Write(" }\n")
5098 file.Write("\n")
5101 class TodoHandler(CustomHandler):
5102 """Handle for commands that are not yet implemented."""
5104 def NeedsDataTransferFunction(self, func):
5105 """Overriden from TypeHandler."""
5106 return False
5108 def WriteImmediateFormatTest(self, func, file):
5109 """Overrriden from TypeHandler."""
5110 pass
5112 def WriteGLES2ImplementationUnitTest(self, func, file):
5113 """Overrriden from TypeHandler."""
5114 pass
5116 def WriteGLES2Implementation(self, func, file):
5117 """Overrriden from TypeHandler."""
5118 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5119 (func.return_type, func.original_name,
5120 func.MakeTypedOriginalArgString("")))
5121 file.Write(" // TODO: for now this is a no-op\n")
5122 file.Write(
5123 " SetGLError("
5124 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5125 func.name)
5126 if func.return_type != "void":
5127 file.Write(" return 0;\n")
5128 file.Write("}\n")
5129 file.Write("\n")
5131 def WriteServiceImplementation(self, func, file):
5132 """Overrriden from TypeHandler."""
5133 self.WriteServiceHandlerFunctionHeader(func, file)
5134 file.Write(" // TODO: for now this is a no-op\n")
5135 file.Write(
5136 " LOCAL_SET_GL_ERROR("
5137 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5138 func.name)
5139 file.Write(" return error::kNoError;\n")
5140 file.Write("}\n")
5141 file.Write("\n")
5144 class HandWrittenHandler(CustomHandler):
5145 """Handler for comands where everything must be written by hand."""
5147 def InitFunction(self, func):
5148 """Add or adjust anything type specific for this function."""
5149 CustomHandler.InitFunction(self, func)
5150 func.can_auto_generate = False
5152 def NeedsDataTransferFunction(self, func):
5153 """Overriden from TypeHandler."""
5154 # If specified explicitly, force the data transfer method.
5155 if func.GetInfo('data_transfer_methods'):
5156 return True
5157 return False
5159 def WriteStruct(self, func, file):
5160 """Overrriden from TypeHandler."""
5161 pass
5163 def WriteDocs(self, func, file):
5164 """Overrriden from TypeHandler."""
5165 pass
5167 def WriteServiceUnitTest(self, func, file, *extras):
5168 """Overrriden from TypeHandler."""
5169 file.Write("// TODO(gman): %s\n\n" % func.name)
5171 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5172 """Overrriden from TypeHandler."""
5173 file.Write("// TODO(gman): %s\n\n" % func.name)
5175 def WriteBucketServiceUnitTest(self, func, file, *extras):
5176 """Overrriden from TypeHandler."""
5177 file.Write("// TODO(gman): %s\n\n" % func.name)
5179 def WriteServiceImplementation(self, func, file):
5180 """Overrriden from TypeHandler."""
5181 pass
5183 def WriteImmediateServiceImplementation(self, func, file):
5184 """Overrriden from TypeHandler."""
5185 pass
5187 def WriteBucketServiceImplementation(self, func, file):
5188 """Overrriden from TypeHandler."""
5189 pass
5191 def WriteImmediateCmdHelper(self, func, file):
5192 """Overrriden from TypeHandler."""
5193 pass
5195 def WriteCmdHelper(self, func, file):
5196 """Overrriden from TypeHandler."""
5197 pass
5199 def WriteFormatTest(self, func, file):
5200 """Overrriden from TypeHandler."""
5201 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5203 def WriteImmediateFormatTest(self, func, file):
5204 """Overrriden from TypeHandler."""
5205 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5207 def WriteBucketFormatTest(self, func, file):
5208 """Overrriden from TypeHandler."""
5209 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5213 class ManualHandler(CustomHandler):
5214 """Handler for commands who's handlers must be written by hand."""
5216 def __init__(self):
5217 CustomHandler.__init__(self)
5219 def InitFunction(self, func):
5220 """Overrriden from TypeHandler."""
5221 if (func.name == 'CompressedTexImage2DBucket' or
5222 func.name == 'CompressedTexImage3DBucket'):
5223 func.cmd_args = func.cmd_args[:-1]
5224 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5225 else:
5226 CustomHandler.InitFunction(self, func)
5228 def WriteServiceImplementation(self, func, file):
5229 """Overrriden from TypeHandler."""
5230 pass
5232 def WriteBucketServiceImplementation(self, func, file):
5233 """Overrriden from TypeHandler."""
5234 pass
5236 def WriteServiceUnitTest(self, func, file, *extras):
5237 """Overrriden from TypeHandler."""
5238 file.Write("// TODO(gman): %s\n\n" % func.name)
5240 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5241 """Overrriden from TypeHandler."""
5242 file.Write("// TODO(gman): %s\n\n" % func.name)
5244 def WriteImmediateServiceImplementation(self, func, file):
5245 """Overrriden from TypeHandler."""
5246 pass
5248 def WriteImmediateFormatTest(self, func, file):
5249 """Overrriden from TypeHandler."""
5250 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
5252 def WriteGLES2Implementation(self, func, file):
5253 """Overrriden from TypeHandler."""
5254 if func.GetInfo('impl_func'):
5255 super(ManualHandler, self).WriteGLES2Implementation(func, file)
5257 def WriteGLES2ImplementationHeader(self, func, file):
5258 """Overrriden from TypeHandler."""
5259 file.Write("%s %s(%s) override;\n" %
5260 (func.return_type, func.original_name,
5261 func.MakeTypedOriginalArgString("")))
5262 file.Write("\n")
5264 def WriteImmediateCmdGetTotalSize(self, func, file):
5265 """Overrriden from TypeHandler."""
5266 # TODO(gman): Move this data to _FUNCTION_INFO?
5267 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
5270 class DataHandler(TypeHandler):
5271 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5272 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5273 def __init__(self):
5274 TypeHandler.__init__(self)
5276 def InitFunction(self, func):
5277 """Overrriden from TypeHandler."""
5278 if (func.name == 'CompressedTexSubImage2DBucket' or
5279 func.name == 'CompressedTexSubImage3DBucket'):
5280 func.cmd_args = func.cmd_args[:-1]
5281 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5283 def WriteGetDataSizeCode(self, func, file):
5284 """Overrriden from TypeHandler."""
5285 # TODO(gman): Move this data to _FUNCTION_INFO?
5286 name = func.name
5287 if name.endswith("Immediate"):
5288 name = name[0:-9]
5289 if name == 'BufferData' or name == 'BufferSubData':
5290 file.Write(" uint32_t data_size = size;\n")
5291 elif (name == 'CompressedTexImage2D' or
5292 name == 'CompressedTexSubImage2D' or
5293 name == 'CompressedTexImage3D' or
5294 name == 'CompressedTexSubImage3D'):
5295 file.Write(" uint32_t data_size = imageSize;\n")
5296 elif (name == 'CompressedTexSubImage2DBucket' or
5297 name == 'CompressedTexSubImage3DBucket'):
5298 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5299 file.Write(" uint32_t data_size = bucket->size();\n")
5300 file.Write(" GLsizei imageSize = data_size;\n")
5301 elif name == 'TexImage2D' or name == 'TexSubImage2D':
5302 code = """ uint32_t data_size;
5303 if (!GLES2Util::ComputeImageDataSize(
5304 width, height, format, type, unpack_alignment_, &data_size)) {
5305 return error::kOutOfBounds;
5308 file.Write(code)
5309 else:
5310 file.Write(
5311 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5313 def WriteImmediateCmdGetTotalSize(self, func, file):
5314 """Overrriden from TypeHandler."""
5315 pass
5317 def WriteImmediateCmdSizeTest(self, func, file):
5318 """Overrriden from TypeHandler."""
5319 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5321 def WriteImmediateCmdInit(self, func, file):
5322 """Overrriden from TypeHandler."""
5323 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5324 self.WriteImmediateCmdGetTotalSize(func, file)
5325 file.Write(" SetHeader(total_size);\n")
5326 args = func.GetCmdArgs()
5327 for arg in args:
5328 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5329 file.Write(" }\n")
5330 file.Write("\n")
5332 def WriteImmediateCmdSet(self, func, file):
5333 """Overrriden from TypeHandler."""
5334 copy_args = func.MakeCmdArgString("_", False)
5335 file.Write(" void* Set(void* cmd%s) {\n" %
5336 func.MakeTypedCmdArgString("_", True))
5337 self.WriteImmediateCmdGetTotalSize(func, file)
5338 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5339 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5340 "cmd, total_size);\n")
5341 file.Write(" }\n")
5342 file.Write("\n")
5344 def WriteImmediateFormatTest(self, func, file):
5345 """Overrriden from TypeHandler."""
5346 # TODO(gman): Remove this exception.
5347 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
5348 return
5350 def WriteServiceUnitTest(self, func, file, *extras):
5351 """Overrriden from TypeHandler."""
5352 file.Write("// TODO(gman): %s\n\n" % func.name)
5354 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5355 """Overrriden from TypeHandler."""
5356 file.Write("// TODO(gman): %s\n\n" % func.name)
5358 def WriteBucketServiceImplementation(self, func, file):
5359 """Overrriden from TypeHandler."""
5360 if ((not func.name == 'CompressedTexSubImage2DBucket') and
5361 (not func.name == 'CompressedTexSubImage3DBucket')):
5362 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
5365 class BindHandler(TypeHandler):
5366 """Handler for glBind___ type functions."""
5368 def __init__(self):
5369 TypeHandler.__init__(self)
5371 def WriteServiceUnitTest(self, func, file, *extras):
5372 """Overrriden from TypeHandler."""
5374 if len(func.GetOriginalArgs()) == 1:
5375 valid_test = """
5376 TEST_P(%(test_name)s, %(name)sValidArgs) {
5377 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5378 SpecializedSetup<cmds::%(name)s, 0>(true);
5379 cmds::%(name)s cmd;
5380 cmd.Init(%(args)s);"""
5381 if func.IsUnsafe():
5382 valid_test += """
5383 decoder_->set_unsafe_es3_apis_enabled(true);
5384 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5385 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5386 decoder_->set_unsafe_es3_apis_enabled(false);
5387 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5390 else:
5391 valid_test += """
5392 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5393 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5396 if func.GetInfo("gen_func"):
5397 valid_test += """
5398 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5399 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5400 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5401 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5402 SpecializedSetup<cmds::%(name)s, 0>(true);
5403 cmds::%(name)s cmd;
5404 cmd.Init(kNewClientId);
5405 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5406 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5407 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5410 self.WriteValidUnitTest(func, file, valid_test, {
5411 'resource_type': func.GetOriginalArgs()[0].resource_type,
5412 'gl_gen_func_name': func.GetInfo("gen_func"),
5413 }, *extras)
5414 else:
5415 valid_test = """
5416 TEST_P(%(test_name)s, %(name)sValidArgs) {
5417 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5418 SpecializedSetup<cmds::%(name)s, 0>(true);
5419 cmds::%(name)s cmd;
5420 cmd.Init(%(args)s);"""
5421 if func.IsUnsafe():
5422 valid_test += """
5423 decoder_->set_unsafe_es3_apis_enabled(true);
5424 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5425 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5426 decoder_->set_unsafe_es3_apis_enabled(false);
5427 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5430 else:
5431 valid_test += """
5432 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5433 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5436 if func.GetInfo("gen_func"):
5437 valid_test += """
5438 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5439 EXPECT_CALL(*gl_,
5440 %(gl_func_name)s(%(gl_args_with_new_id)s));
5441 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5442 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5443 SpecializedSetup<cmds::%(name)s, 0>(true);
5444 cmds::%(name)s cmd;
5445 cmd.Init(%(args_with_new_id)s);"""
5446 if func.IsUnsafe():
5447 valid_test += """
5448 decoder_->set_unsafe_es3_apis_enabled(true);
5449 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5450 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5451 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5452 decoder_->set_unsafe_es3_apis_enabled(false);
5453 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5456 else:
5457 valid_test += """
5458 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5459 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5460 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5464 gl_args_with_new_id = []
5465 args_with_new_id = []
5466 for arg in func.GetOriginalArgs():
5467 if hasattr(arg, 'resource_type'):
5468 gl_args_with_new_id.append('kNewServiceId')
5469 args_with_new_id.append('kNewClientId')
5470 else:
5471 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5472 args_with_new_id.append(arg.GetValidArg(func))
5473 self.WriteValidUnitTest(func, file, valid_test, {
5474 'args_with_new_id': ", ".join(args_with_new_id),
5475 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5476 'resource_type': func.GetResourceIdArg().resource_type,
5477 'gl_gen_func_name': func.GetInfo("gen_func"),
5478 }, *extras)
5480 invalid_test = """
5481 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5482 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5483 SpecializedSetup<cmds::%(name)s, 0>(false);
5484 cmds::%(name)s cmd;
5485 cmd.Init(%(args)s);
5486 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5489 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
5491 def WriteGLES2Implementation(self, func, file):
5492 """Writes the GLES2 Implemention."""
5494 impl_func = func.GetInfo('impl_func')
5495 impl_decl = func.GetInfo('impl_decl')
5497 if (func.can_auto_generate and
5498 (impl_func == None or impl_func == True) and
5499 (impl_decl == None or impl_decl == True)):
5501 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5502 (func.return_type, func.original_name,
5503 func.MakeTypedOriginalArgString("")))
5504 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5505 func.WriteDestinationInitalizationValidation(file)
5506 self.WriteClientGLCallLog(func, file)
5507 for arg in func.GetOriginalArgs():
5508 arg.WriteClientSideValidationCode(file, func)
5510 code = """ if (Is%(type)sReservedId(%(id)s)) {
5511 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5512 return;
5514 %(name)sHelper(%(arg_string)s);
5515 CheckGLError();
5519 name_arg = func.GetResourceIdArg()
5520 file.Write(code % {
5521 'name': func.name,
5522 'arg_string': func.MakeOriginalArgString(""),
5523 'id': name_arg.name,
5524 'type': name_arg.resource_type,
5525 'lc_type': name_arg.resource_type.lower(),
5528 def WriteGLES2ImplementationUnitTest(self, func, file):
5529 """Overrriden from TypeHandler."""
5530 client_test = func.GetInfo('client_test')
5531 if client_test == False:
5532 return
5533 code = """
5534 TEST_F(GLES2ImplementationTest, %(name)s) {
5535 struct Cmds {
5536 cmds::%(name)s cmd;
5538 Cmds expected;
5539 expected.cmd.Init(%(cmd_args)s);
5541 gl_->%(name)s(%(args)s);
5542 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5543 if not func.IsUnsafe():
5544 code += """
5545 ClearCommands();
5546 gl_->%(name)s(%(args)s);
5547 EXPECT_TRUE(NoCommandsWritten());"""
5548 code += """
5551 cmd_arg_strings = [
5552 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5554 gl_arg_strings = [
5555 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5558 file.Write(code % {
5559 'name': func.name,
5560 'args': ", ".join(gl_arg_strings),
5561 'cmd_args': ", ".join(cmd_arg_strings),
5565 class GENnHandler(TypeHandler):
5566 """Handler for glGen___ type functions."""
5568 def __init__(self):
5569 TypeHandler.__init__(self)
5571 def InitFunction(self, func):
5572 """Overrriden from TypeHandler."""
5573 pass
5575 def WriteGetDataSizeCode(self, func, file):
5576 """Overrriden from TypeHandler."""
5577 code = """ uint32_t data_size;
5578 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5579 return error::kOutOfBounds;
5582 file.Write(code)
5584 def WriteHandlerImplementation (self, func, file):
5585 """Overrriden from TypeHandler."""
5586 file.Write(" if (!%sHelper(n, %s)) {\n"
5587 " return error::kInvalidArguments;\n"
5588 " }\n" %
5589 (func.name, func.GetLastOriginalArg().name))
5591 def WriteImmediateHandlerImplementation(self, func, file):
5592 """Overrriden from TypeHandler."""
5593 if func.IsUnsafe():
5594 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5595 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5596 return error::kInvalidArguments;
5599 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5600 gl%(func_name)s(n, service_ids.get());
5601 for (GLsizei ii = 0; ii < n; ++ii) {
5602 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5604 """ % { 'func_name': func.original_name,
5605 'last_arg_name': func.GetLastOriginalArg().name,
5606 'resource_name': func.GetInfo('resource_type') })
5607 else:
5608 file.Write(" if (!%sHelper(n, %s)) {\n"
5609 " return error::kInvalidArguments;\n"
5610 " }\n" %
5611 (func.original_name, func.GetLastOriginalArg().name))
5613 def WriteGLES2Implementation(self, func, file):
5614 """Overrriden from TypeHandler."""
5615 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5616 for (GLsizei i = 0; i < n; ++i) {
5617 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5619 });""" % func.GetOriginalArgs()[1].name)
5620 args = {
5621 'log_code': log_code,
5622 'return_type': func.return_type,
5623 'name': func.original_name,
5624 'typed_args': func.MakeTypedOriginalArgString(""),
5625 'args': func.MakeOriginalArgString(""),
5626 'resource_types': func.GetInfo('resource_types'),
5627 'count_name': func.GetOriginalArgs()[0].name,
5629 file.Write(
5630 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5631 args)
5632 func.WriteDestinationInitalizationValidation(file)
5633 self.WriteClientGLCallLog(func, file)
5634 for arg in func.GetOriginalArgs():
5635 arg.WriteClientSideValidationCode(file, func)
5636 not_shared = func.GetInfo('not_shared')
5637 if not_shared:
5638 alloc_code = (
5640 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5641 for (GLsizei ii = 0; ii < n; ++ii)
5642 %s[ii] = id_allocator->AllocateID();""" %
5643 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5644 else:
5645 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5646 MakeIds(this, 0, %(args)s);""" % args)
5647 args['alloc_code'] = alloc_code
5649 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5650 %(alloc_code)s
5651 %(name)sHelper(%(args)s);
5652 helper_->%(name)sImmediate(%(args)s);
5653 if (share_group_->bind_generates_resource())
5654 helper_->CommandBufferHelper::Flush();
5655 %(log_code)s
5656 CheckGLError();
5660 file.Write(code % args)
5662 def WriteGLES2ImplementationUnitTest(self, func, file):
5663 """Overrriden from TypeHandler."""
5664 code = """
5665 TEST_F(GLES2ImplementationTest, %(name)s) {
5666 GLuint ids[2] = { 0, };
5667 struct Cmds {
5668 cmds::%(name)sImmediate gen;
5669 GLuint data[2];
5671 Cmds expected;
5672 expected.gen.Init(arraysize(ids), &ids[0]);
5673 expected.data[0] = k%(types)sStartId;
5674 expected.data[1] = k%(types)sStartId + 1;
5675 gl_->%(name)s(arraysize(ids), &ids[0]);
5676 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5677 EXPECT_EQ(k%(types)sStartId, ids[0]);
5678 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5681 file.Write(code % {
5682 'name': func.name,
5683 'types': func.GetInfo('resource_types'),
5686 def WriteServiceUnitTest(self, func, file, *extras):
5687 """Overrriden from TypeHandler."""
5688 valid_test = """
5689 TEST_P(%(test_name)s, %(name)sValidArgs) {
5690 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5691 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5692 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5693 SpecializedSetup<cmds::%(name)s, 0>(true);
5694 cmds::%(name)s cmd;
5695 cmd.Init(%(args)s);
5696 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5697 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5698 if func.IsUnsafe():
5699 valid_test += """
5700 GLuint service_id;
5701 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5702 EXPECT_EQ(kNewServiceId, service_id)
5705 else:
5706 valid_test += """
5707 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5710 self.WriteValidUnitTest(func, file, valid_test, {
5711 'resource_name': func.GetInfo('resource_type'),
5712 }, *extras)
5713 invalid_test = """
5714 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5715 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5716 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5717 SpecializedSetup<cmds::%(name)s, 0>(false);
5718 cmds::%(name)s cmd;
5719 cmd.Init(%(args)s);
5720 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5723 self.WriteValidUnitTest(func, file, invalid_test, {
5724 'resource_name': func.GetInfo('resource_type').lower(),
5725 }, *extras)
5727 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5728 """Overrriden from TypeHandler."""
5729 valid_test = """
5730 TEST_P(%(test_name)s, %(name)sValidArgs) {
5731 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5732 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5733 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5734 GLuint temp = kNewClientId;
5735 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5736 if func.IsUnsafe():
5737 valid_test += """
5738 decoder_->set_unsafe_es3_apis_enabled(true);"""
5739 valid_test += """
5740 cmd->Init(1, &temp);
5741 EXPECT_EQ(error::kNoError,
5742 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5743 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5744 if func.IsUnsafe():
5745 valid_test += """
5746 GLuint service_id;
5747 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5748 EXPECT_EQ(kNewServiceId, service_id);
5749 decoder_->set_unsafe_es3_apis_enabled(false);
5750 EXPECT_EQ(error::kUnknownCommand,
5751 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5754 else:
5755 valid_test += """
5756 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5759 self.WriteValidUnitTest(func, file, valid_test, {
5760 'resource_name': func.GetInfo('resource_type'),
5761 }, *extras)
5762 invalid_test = """
5763 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5764 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5765 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5766 SpecializedSetup<cmds::%(name)s, 0>(false);
5767 cmd->Init(1, &client_%(resource_name)s_id_);"""
5768 if func.IsUnsafe():
5769 invalid_test += """
5770 decoder_->set_unsafe_es3_apis_enabled(true);
5771 EXPECT_EQ(error::kInvalidArguments,
5772 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5773 decoder_->set_unsafe_es3_apis_enabled(false);
5776 else:
5777 invalid_test += """
5778 EXPECT_EQ(error::kInvalidArguments,
5779 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5782 self.WriteValidUnitTest(func, file, invalid_test, {
5783 'resource_name': func.GetInfo('resource_type').lower(),
5784 }, *extras)
5786 def WriteImmediateCmdComputeSize(self, func, file):
5787 """Overrriden from TypeHandler."""
5788 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5789 file.Write(
5790 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5791 file.Write(" }\n")
5792 file.Write("\n")
5793 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5794 file.Write(" return static_cast<uint32_t>(\n")
5795 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5796 file.Write(" }\n")
5797 file.Write("\n")
5799 def WriteImmediateCmdSetHeader(self, func, file):
5800 """Overrriden from TypeHandler."""
5801 file.Write(" void SetHeader(GLsizei n) {\n")
5802 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5803 file.Write(" }\n")
5804 file.Write("\n")
5806 def WriteImmediateCmdInit(self, func, file):
5807 """Overrriden from TypeHandler."""
5808 last_arg = func.GetLastOriginalArg()
5809 file.Write(" void Init(%s, %s _%s) {\n" %
5810 (func.MakeTypedCmdArgString("_"),
5811 last_arg.type, last_arg.name))
5812 file.Write(" SetHeader(_n);\n")
5813 args = func.GetCmdArgs()
5814 for arg in args:
5815 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5816 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5817 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5818 file.Write(" }\n")
5819 file.Write("\n")
5821 def WriteImmediateCmdSet(self, func, file):
5822 """Overrriden from TypeHandler."""
5823 last_arg = func.GetLastOriginalArg()
5824 copy_args = func.MakeCmdArgString("_", False)
5825 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5826 (func.MakeTypedCmdArgString("_", True),
5827 last_arg.type, last_arg.name))
5828 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5829 (copy_args, last_arg.name))
5830 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5831 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5832 "cmd, size);\n")
5833 file.Write(" }\n")
5834 file.Write("\n")
5836 def WriteImmediateCmdHelper(self, func, file):
5837 """Overrriden from TypeHandler."""
5838 code = """ void %(name)s(%(typed_args)s) {
5839 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5840 gles2::cmds::%(name)s* c =
5841 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5842 if (c) {
5843 c->Init(%(args)s);
5848 file.Write(code % {
5849 "name": func.name,
5850 "typed_args": func.MakeTypedOriginalArgString(""),
5851 "args": func.MakeOriginalArgString(""),
5854 def WriteImmediateFormatTest(self, func, file):
5855 """Overrriden from TypeHandler."""
5856 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5857 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5858 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5859 (func.name, func.name))
5860 file.Write(" void* next_cmd = cmd.Set(\n")
5861 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5862 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5863 func.name)
5864 file.Write(" cmd.header.command);\n")
5865 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5866 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5867 file.Write(" cmd.header.size * 4u);\n")
5868 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5869 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5870 file.Write(" next_cmd, sizeof(cmd) +\n")
5871 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5872 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5873 file.Write("}\n")
5874 file.Write("\n")
5877 class CreateHandler(TypeHandler):
5878 """Handler for glCreate___ type functions."""
5880 def __init__(self):
5881 TypeHandler.__init__(self)
5883 def InitFunction(self, func):
5884 """Overrriden from TypeHandler."""
5885 func.AddCmdArg(Argument("client_id", 'uint32_t'))
5887 def __GetResourceType(self, func):
5888 if func.return_type == "GLsync":
5889 return "Sync"
5890 else:
5891 return func.name[6:] # Create*
5893 def WriteServiceUnitTest(self, func, file, *extras):
5894 """Overrriden from TypeHandler."""
5895 valid_test = """
5896 TEST_P(%(test_name)s, %(name)sValidArgs) {
5897 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5898 .WillOnce(Return(%(const_service_id)s));
5899 SpecializedSetup<cmds::%(name)s, 0>(true);
5900 cmds::%(name)s cmd;
5901 cmd.Init(%(args)s%(comma)skNewClientId);"""
5902 if func.IsUnsafe():
5903 valid_test += """
5904 decoder_->set_unsafe_es3_apis_enabled(true);"""
5905 valid_test += """
5906 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5907 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5908 if func.IsUnsafe():
5909 valid_test += """
5910 %(return_type)s service_id = 0;
5911 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5912 EXPECT_EQ(%(const_service_id)s, service_id);
5913 decoder_->set_unsafe_es3_apis_enabled(false);
5914 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5917 else:
5918 valid_test += """
5919 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5922 comma = ""
5923 cmd_arg_count = 0
5924 for arg in func.GetOriginalArgs():
5925 if not arg.IsConstant():
5926 cmd_arg_count += 1
5927 if cmd_arg_count:
5928 comma = ", "
5929 if func.return_type == 'GLsync':
5930 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5931 "<GLsync>(kNewServiceId);\n ")
5932 const_service_id = "kNewServiceIdGLuint"
5933 else:
5934 id_type_cast = ""
5935 const_service_id = "kNewServiceId"
5936 self.WriteValidUnitTest(func, file, valid_test, {
5937 'comma': comma,
5938 'resource_type': self.__GetResourceType(func),
5939 'return_type': func.return_type,
5940 'id_type_cast': id_type_cast,
5941 'const_service_id': const_service_id,
5942 }, *extras)
5943 invalid_test = """
5944 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5945 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5946 SpecializedSetup<cmds::%(name)s, 0>(false);
5947 cmds::%(name)s cmd;
5948 cmd.Init(%(args)s%(comma)skNewClientId);
5949 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5952 self.WriteInvalidUnitTest(func, file, invalid_test, {
5953 'comma': comma,
5954 }, *extras)
5956 def WriteHandlerImplementation (self, func, file):
5957 """Overrriden from TypeHandler."""
5958 if func.IsUnsafe():
5959 code = """ uint32_t client_id = c.client_id;
5960 %(return_type)s service_id = 0;
5961 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5962 return error::kInvalidArguments;
5964 service_id = %(gl_func_name)s(%(gl_args)s);
5965 if (service_id) {
5966 group_->Add%(resource_name)sId(client_id, service_id);
5969 else:
5970 code = """ uint32_t client_id = c.client_id;
5971 if (Get%(resource_name)s(client_id)) {
5972 return error::kInvalidArguments;
5974 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5975 if (service_id) {
5976 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5979 file.Write(code % {
5980 'resource_name': self.__GetResourceType(func),
5981 'return_type': func.return_type,
5982 'gl_func_name': func.GetGLFunctionName(),
5983 'gl_args': func.MakeOriginalArgString(""),
5984 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
5986 def WriteGLES2Implementation(self, func, file):
5987 """Overrriden from TypeHandler."""
5988 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5989 (func.return_type, func.original_name,
5990 func.MakeTypedOriginalArgString("")))
5991 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5992 func.WriteDestinationInitalizationValidation(file)
5993 self.WriteClientGLCallLog(func, file)
5994 for arg in func.GetOriginalArgs():
5995 arg.WriteClientSideValidationCode(file, func)
5996 file.Write(" GLuint client_id;\n")
5997 if func.return_type == "GLsync":
5998 file.Write(
5999 " GetIdHandler(id_namespaces::kSyncs)->\n")
6000 else:
6001 file.Write(
6002 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6003 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
6004 file.Write(" helper_->%s(%s);\n" %
6005 (func.name, func.MakeCmdArgString("")))
6006 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6007 file.Write(" CheckGLError();\n")
6008 if func.return_type == "GLsync":
6009 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
6010 else:
6011 file.Write(" return client_id;\n")
6012 file.Write("}\n")
6013 file.Write("\n")
6016 class DeleteHandler(TypeHandler):
6017 """Handler for glDelete___ single resource type functions."""
6019 def __init__(self):
6020 TypeHandler.__init__(self)
6022 def WriteServiceImplementation(self, func, file):
6023 """Overrriden from TypeHandler."""
6024 if func.IsUnsafe():
6025 TypeHandler.WriteServiceImplementation(self, func, file)
6026 # HandleDeleteShader and HandleDeleteProgram are manually written.
6027 pass
6029 def WriteGLES2Implementation(self, func, file):
6030 """Overrriden from TypeHandler."""
6031 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6032 (func.return_type, func.original_name,
6033 func.MakeTypedOriginalArgString("")))
6034 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6035 func.WriteDestinationInitalizationValidation(file)
6036 self.WriteClientGLCallLog(func, file)
6037 for arg in func.GetOriginalArgs():
6038 arg.WriteClientSideValidationCode(file, func)
6039 file.Write(
6040 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
6041 file.Write(" %sHelper(%s);\n" %
6042 (func.original_name, func.GetOriginalArgs()[-1].name))
6043 file.Write(" CheckGLError();\n")
6044 file.Write("}\n")
6045 file.Write("\n")
6047 def WriteHandlerImplementation (self, func, file):
6048 """Overrriden from TypeHandler."""
6049 assert len(func.GetOriginalArgs()) == 1
6050 arg = func.GetOriginalArgs()[0]
6051 if func.IsUnsafe():
6052 file.Write(""" %(arg_type)s service_id = 0;
6053 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6054 glDelete%(resource_type)s(service_id);
6055 group_->Remove%(resource_type)sId(%(arg_name)s);
6056 } else {
6057 LOCAL_SET_GL_ERROR(
6058 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6060 """ % { 'resource_type': func.GetInfo('resource_type'),
6061 'arg_name': arg.name,
6062 'arg_type': arg.type,
6063 'func_name': func.original_name })
6064 else:
6065 file.Write(" %sHelper(%s);\n" % (func.original_name, arg.name))
6067 class DELnHandler(TypeHandler):
6068 """Handler for glDelete___ type functions."""
6070 def __init__(self):
6071 TypeHandler.__init__(self)
6073 def WriteGetDataSizeCode(self, func, file):
6074 """Overrriden from TypeHandler."""
6075 code = """ uint32_t data_size;
6076 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6077 return error::kOutOfBounds;
6080 file.Write(code)
6082 def WriteGLES2ImplementationUnitTest(self, func, file):
6083 """Overrriden from TypeHandler."""
6084 code = """
6085 TEST_F(GLES2ImplementationTest, %(name)s) {
6086 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6087 struct Cmds {
6088 cmds::%(name)sImmediate del;
6089 GLuint data[2];
6091 Cmds expected;
6092 expected.del.Init(arraysize(ids), &ids[0]);
6093 expected.data[0] = k%(types)sStartId;
6094 expected.data[1] = k%(types)sStartId + 1;
6095 gl_->%(name)s(arraysize(ids), &ids[0]);
6096 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6099 file.Write(code % {
6100 'name': func.name,
6101 'types': func.GetInfo('resource_types'),
6104 def WriteServiceUnitTest(self, func, file, *extras):
6105 """Overrriden from TypeHandler."""
6106 valid_test = """
6107 TEST_P(%(test_name)s, %(name)sValidArgs) {
6108 EXPECT_CALL(
6109 *gl_,
6110 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6111 .Times(1);
6112 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6113 SpecializedSetup<cmds::%(name)s, 0>(true);
6114 cmds::%(name)s cmd;
6115 cmd.Init(%(args)s);
6116 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6117 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6118 EXPECT_TRUE(
6119 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6122 self.WriteValidUnitTest(func, file, valid_test, {
6123 'resource_name': func.GetInfo('resource_type').lower(),
6124 'upper_resource_name': func.GetInfo('resource_type'),
6125 }, *extras)
6126 invalid_test = """
6127 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6128 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6129 SpecializedSetup<cmds::%(name)s, 0>(false);
6130 cmds::%(name)s cmd;
6131 cmd.Init(%(args)s);
6132 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6135 self.WriteValidUnitTest(func, file, invalid_test, *extras)
6137 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6138 """Overrriden from TypeHandler."""
6139 valid_test = """
6140 TEST_P(%(test_name)s, %(name)sValidArgs) {
6141 EXPECT_CALL(
6142 *gl_,
6143 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6144 .Times(1);
6145 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6146 SpecializedSetup<cmds::%(name)s, 0>(true);
6147 cmd.Init(1, &client_%(resource_name)s_id_);"""
6148 if func.IsUnsafe():
6149 valid_test += """
6150 decoder_->set_unsafe_es3_apis_enabled(true);"""
6151 valid_test += """
6152 EXPECT_EQ(error::kNoError,
6153 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6154 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6155 if func.IsUnsafe():
6156 valid_test += """
6157 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6158 client_%(resource_name)s_id_, NULL));
6159 decoder_->set_unsafe_es3_apis_enabled(false);
6160 EXPECT_EQ(error::kUnknownCommand,
6161 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6164 else:
6165 valid_test += """
6166 EXPECT_TRUE(
6167 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6170 self.WriteValidUnitTest(func, file, valid_test, {
6171 'resource_name': func.GetInfo('resource_type').lower(),
6172 'upper_resource_name': func.GetInfo('resource_type'),
6173 }, *extras)
6174 invalid_test = """
6175 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6176 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6177 SpecializedSetup<cmds::%(name)s, 0>(false);
6178 GLuint temp = kInvalidClientId;
6179 cmd.Init(1, &temp);"""
6180 if func.IsUnsafe():
6181 invalid_test += """
6182 decoder_->set_unsafe_es3_apis_enabled(true);
6183 EXPECT_EQ(error::kNoError,
6184 ExecuteImmediateCmd(cmd, sizeof(temp)));
6185 decoder_->set_unsafe_es3_apis_enabled(false);
6186 EXPECT_EQ(error::kUnknownCommand,
6187 ExecuteImmediateCmd(cmd, sizeof(temp)));
6190 else:
6191 invalid_test += """
6192 EXPECT_EQ(error::kNoError,
6193 ExecuteImmediateCmd(cmd, sizeof(temp)));
6196 self.WriteValidUnitTest(func, file, invalid_test, *extras)
6198 def WriteHandlerImplementation (self, func, file):
6199 """Overrriden from TypeHandler."""
6200 file.Write(" %sHelper(n, %s);\n" %
6201 (func.name, func.GetLastOriginalArg().name))
6203 def WriteImmediateHandlerImplementation (self, func, file):
6204 """Overrriden from TypeHandler."""
6205 if func.IsUnsafe():
6206 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6207 GLuint service_id = 0;
6208 if (group_->Get%(resource_type)sServiceId(
6209 %(last_arg_name)s[ii], &service_id)) {
6210 glDelete%(resource_type)ss(1, &service_id);
6211 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6214 """ % { 'resource_type': func.GetInfo('resource_type'),
6215 'last_arg_name': func.GetLastOriginalArg().name })
6216 else:
6217 file.Write(" %sHelper(n, %s);\n" %
6218 (func.original_name, func.GetLastOriginalArg().name))
6220 def WriteGLES2Implementation(self, func, file):
6221 """Overrriden from TypeHandler."""
6222 impl_decl = func.GetInfo('impl_decl')
6223 if impl_decl == None or impl_decl == True:
6224 args = {
6225 'return_type': func.return_type,
6226 'name': func.original_name,
6227 'typed_args': func.MakeTypedOriginalArgString(""),
6228 'args': func.MakeOriginalArgString(""),
6229 'resource_type': func.GetInfo('resource_type').lower(),
6230 'count_name': func.GetOriginalArgs()[0].name,
6232 file.Write(
6233 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6234 args)
6235 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6236 func.WriteDestinationInitalizationValidation(file)
6237 self.WriteClientGLCallLog(func, file)
6238 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6239 for (GLsizei i = 0; i < n; ++i) {
6240 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6243 """ % func.GetOriginalArgs()[1].name)
6244 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6245 for (GLsizei i = 0; i < n; ++i) {
6246 DCHECK(%s[i] != 0);
6249 """ % func.GetOriginalArgs()[1].name)
6250 for arg in func.GetOriginalArgs():
6251 arg.WriteClientSideValidationCode(file, func)
6252 code = """ %(name)sHelper(%(args)s);
6253 CheckGLError();
6257 file.Write(code % args)
6259 def WriteImmediateCmdComputeSize(self, func, file):
6260 """Overrriden from TypeHandler."""
6261 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6262 file.Write(
6263 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6264 file.Write(" }\n")
6265 file.Write("\n")
6266 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
6267 file.Write(" return static_cast<uint32_t>(\n")
6268 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6269 file.Write(" }\n")
6270 file.Write("\n")
6272 def WriteImmediateCmdSetHeader(self, func, file):
6273 """Overrriden from TypeHandler."""
6274 file.Write(" void SetHeader(GLsizei n) {\n")
6275 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6276 file.Write(" }\n")
6277 file.Write("\n")
6279 def WriteImmediateCmdInit(self, func, file):
6280 """Overrriden from TypeHandler."""
6281 last_arg = func.GetLastOriginalArg()
6282 file.Write(" void Init(%s, %s _%s) {\n" %
6283 (func.MakeTypedCmdArgString("_"),
6284 last_arg.type, last_arg.name))
6285 file.Write(" SetHeader(_n);\n")
6286 args = func.GetCmdArgs()
6287 for arg in args:
6288 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6289 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6290 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
6291 file.Write(" }\n")
6292 file.Write("\n")
6294 def WriteImmediateCmdSet(self, func, file):
6295 """Overrriden from TypeHandler."""
6296 last_arg = func.GetLastOriginalArg()
6297 copy_args = func.MakeCmdArgString("_", False)
6298 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6299 (func.MakeTypedCmdArgString("_", True),
6300 last_arg.type, last_arg.name))
6301 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6302 (copy_args, last_arg.name))
6303 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6304 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6305 "cmd, size);\n")
6306 file.Write(" }\n")
6307 file.Write("\n")
6309 def WriteImmediateCmdHelper(self, func, file):
6310 """Overrriden from TypeHandler."""
6311 code = """ void %(name)s(%(typed_args)s) {
6312 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6313 gles2::cmds::%(name)s* c =
6314 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6315 if (c) {
6316 c->Init(%(args)s);
6321 file.Write(code % {
6322 "name": func.name,
6323 "typed_args": func.MakeTypedOriginalArgString(""),
6324 "args": func.MakeOriginalArgString(""),
6327 def WriteImmediateFormatTest(self, func, file):
6328 """Overrriden from TypeHandler."""
6329 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6330 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6331 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6332 (func.name, func.name))
6333 file.Write(" void* next_cmd = cmd.Set(\n")
6334 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6335 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6336 func.name)
6337 file.Write(" cmd.header.command);\n")
6338 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6339 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6340 file.Write(" cmd.header.size * 4u);\n")
6341 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6342 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6343 file.Write(" next_cmd, sizeof(cmd) +\n")
6344 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6345 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6346 file.Write("}\n")
6347 file.Write("\n")
6350 class GETnHandler(TypeHandler):
6351 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6353 def __init__(self):
6354 TypeHandler.__init__(self)
6356 def NeedsDataTransferFunction(self, func):
6357 """Overriden from TypeHandler."""
6358 return False
6360 def WriteServiceImplementation(self, func, file):
6361 """Overrriden from TypeHandler."""
6362 self.WriteServiceHandlerFunctionHeader(func, file)
6363 last_arg = func.GetLastOriginalArg()
6364 # All except shm_id and shm_offset.
6365 all_but_last_args = func.GetCmdArgs()[:-2]
6366 for arg in all_but_last_args:
6367 arg.WriteGetCode(file)
6369 code = """ typedef cmds::%(func_name)s::Result Result;
6370 GLsizei num_values = 0;
6371 GetNumValuesReturnedForGLGet(pname, &num_values);
6372 Result* result = GetSharedMemoryAs<Result*>(
6373 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6374 Result::ComputeSize(num_values));
6375 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6377 file.Write(code % {
6378 'last_arg_type': last_arg.type,
6379 'last_arg_name': last_arg.name,
6380 'func_name': func.name,
6382 func.WriteHandlerValidation(file)
6383 code = """ // Check that the client initialized the result.
6384 if (result->size != 0) {
6385 return error::kInvalidArguments;
6388 shadowed = func.GetInfo('shadowed')
6389 if not shadowed:
6390 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
6391 file.Write(code)
6392 func.WriteHandlerImplementation(file)
6393 if shadowed:
6394 code = """ result->SetNumResults(num_values);
6395 return error::kNoError;
6398 else:
6399 code = """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6400 if (error == GL_NO_ERROR) {
6401 result->SetNumResults(num_values);
6403 return error::kNoError;
6407 file.Write(code % {'func_name': func.name})
6409 def WriteGLES2Implementation(self, func, file):
6410 """Overrriden from TypeHandler."""
6411 impl_decl = func.GetInfo('impl_decl')
6412 if impl_decl == None or impl_decl == True:
6413 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6414 (func.return_type, func.original_name,
6415 func.MakeTypedOriginalArgString("")))
6416 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6417 func.WriteDestinationInitalizationValidation(file)
6418 self.WriteClientGLCallLog(func, file)
6419 for arg in func.GetOriginalArgs():
6420 arg.WriteClientSideValidationCode(file, func)
6421 all_but_last_args = func.GetOriginalArgs()[:-1]
6422 args = []
6423 has_length_arg = False
6424 for arg in all_but_last_args:
6425 if arg.type == 'GLsync':
6426 args.append('ToGLuint(%s)' % arg.name)
6427 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6428 continue
6429 elif arg.name == 'length':
6430 has_length_arg = True
6431 continue
6432 else:
6433 args.append(arg.name)
6434 arg_string = ", ".join(args)
6435 all_arg_string = (
6436 ", ".join([
6437 "%s" % arg.name
6438 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6439 self.WriteTraceEvent(func, file)
6440 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6441 return;
6443 typedef cmds::%(func_name)s::Result Result;
6444 Result* result = GetResultAs<Result*>();
6445 if (!result) {
6446 return;
6448 result->SetNumResults(0);
6449 helper_->%(func_name)s(%(arg_string)s,
6450 GetResultShmId(), GetResultShmOffset());
6451 WaitForCmd();
6452 result->CopyResult(%(last_arg_name)s);
6453 GPU_CLIENT_LOG_CODE_BLOCK({
6454 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6455 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6457 });"""
6458 if has_length_arg:
6459 code += """
6460 if (length) {
6461 *length = result->GetNumResults();
6462 }"""
6463 code += """
6464 CheckGLError();
6467 file.Write(code % {
6468 'func_name': func.name,
6469 'arg_string': arg_string,
6470 'all_arg_string': all_arg_string,
6471 'last_arg_name': func.GetLastOriginalArg().name,
6474 def WriteGLES2ImplementationUnitTest(self, func, file):
6475 """Writes the GLES2 Implemention unit test."""
6476 code = """
6477 TEST_F(GLES2ImplementationTest, %(name)s) {
6478 struct Cmds {
6479 cmds::%(name)s cmd;
6481 typedef cmds::%(name)s::Result::Type ResultType;
6482 ResultType result = 0;
6483 Cmds expected;
6484 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6485 sizeof(uint32_t) + sizeof(ResultType));
6486 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6487 EXPECT_CALL(*command_buffer(), OnFlush())
6488 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6489 .RetiresOnSaturation();
6490 gl_->%(name)s(%(args)s, &result);
6491 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6492 EXPECT_EQ(static_cast<ResultType>(1), result);
6495 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6496 if not first_cmd_arg:
6497 return
6499 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6500 func)
6502 cmd_arg_strings = [first_cmd_arg]
6503 for arg in func.GetCmdArgs()[1:-2]:
6504 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6505 gl_arg_strings = [first_gl_arg]
6506 for arg in func.GetOriginalArgs()[1:-1]:
6507 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6509 file.Write(code % {
6510 'name': func.name,
6511 'args': ", ".join(gl_arg_strings),
6512 'cmd_args': ", ".join(cmd_arg_strings),
6515 def WriteServiceUnitTest(self, func, file, *extras):
6516 """Overrriden from TypeHandler."""
6517 valid_test = """
6518 TEST_P(%(test_name)s, %(name)sValidArgs) {
6519 EXPECT_CALL(*gl_, GetError())
6520 .WillOnce(Return(GL_NO_ERROR))
6521 .WillOnce(Return(GL_NO_ERROR))
6522 .RetiresOnSaturation();
6523 SpecializedSetup<cmds::%(name)s, 0>(true);
6524 typedef cmds::%(name)s::Result Result;
6525 Result* result = static_cast<Result*>(shared_memory_address_);
6526 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6527 result->size = 0;
6528 cmds::%(name)s cmd;
6529 cmd.Init(%(cmd_args)s);"""
6530 if func.IsUnsafe():
6531 valid_test += """
6532 decoder_->set_unsafe_es3_apis_enabled(true);"""
6533 valid_test += """
6534 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6535 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6536 %(valid_pname)s),
6537 result->GetNumResults());
6538 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6539 if func.IsUnsafe():
6540 valid_test += """
6541 decoder_->set_unsafe_es3_apis_enabled(false);
6542 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6543 valid_test += """
6546 gl_arg_strings = []
6547 cmd_arg_strings = []
6548 valid_pname = ''
6549 for arg in func.GetOriginalArgs()[:-1]:
6550 if arg.name == 'length':
6551 gl_arg_value = 'nullptr'
6552 elif arg.name.endswith('size'):
6553 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6554 valid_pname)
6555 elif arg.type == 'GLsync':
6556 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6557 else:
6558 gl_arg_value = arg.GetValidGLArg(func)
6559 gl_arg_strings.append(gl_arg_value)
6560 if arg.name == 'pname':
6561 valid_pname = gl_arg_value
6562 if arg.name.endswith('size') or arg.name == 'length':
6563 continue
6564 if arg.type == 'GLsync':
6565 arg_value = 'client_sync_id_'
6566 else:
6567 arg_value = arg.GetValidArg(func)
6568 cmd_arg_strings.append(arg_value)
6569 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6570 gl_arg_strings.append("_")
6571 else:
6572 gl_arg_strings.append("result->GetData()")
6573 cmd_arg_strings.append("shared_memory_id_")
6574 cmd_arg_strings.append("shared_memory_offset_")
6576 self.WriteValidUnitTest(func, file, valid_test, {
6577 'local_gl_args': ", ".join(gl_arg_strings),
6578 'cmd_args': ", ".join(cmd_arg_strings),
6579 'valid_pname': valid_pname,
6580 }, *extras)
6582 if not func.IsUnsafe():
6583 invalid_test = """
6584 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6585 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6586 SpecializedSetup<cmds::%(name)s, 0>(false);
6587 cmds::%(name)s::Result* result =
6588 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6589 result->size = 0;
6590 cmds::%(name)s cmd;
6591 cmd.Init(%(args)s);
6592 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6593 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6596 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
6598 class ArrayArgTypeHandler(TypeHandler):
6599 """Base class for type handlers that handle args that are arrays"""
6601 def __init__(self):
6602 TypeHandler.__init__(self)
6604 def GetArrayType(self, func):
6605 """Returns the type of the element in the element array being PUT to."""
6606 for arg in func.GetOriginalArgs():
6607 if arg.IsPointer():
6608 element_type = arg.GetPointedType()
6609 return element_type
6611 # Special case: array type handler is used for a function that is forwarded
6612 # to the actual array type implementation
6613 element_type = func.GetOriginalArgs()[-1].type
6614 assert all(arg.type == element_type \
6615 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6616 return element_type
6618 def GetArrayCount(self, func):
6619 """Returns the count of the elements in the array being PUT to."""
6620 return func.GetInfo('count')
6622 class PUTHandler(ArrayArgTypeHandler):
6623 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6625 def __init__(self):
6626 ArrayArgTypeHandler.__init__(self)
6628 def WriteServiceUnitTest(self, func, file, *extras):
6629 """Writes the service unit test for a command."""
6630 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6631 if func.GetInfo("first_element_only"):
6632 gl_arg_strings = [
6633 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6635 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6636 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6637 ", ".join(gl_arg_strings))
6638 valid_test = """
6639 TEST_P(%(test_name)s, %(name)sValidArgs) {
6640 SpecializedSetup<cmds::%(name)s, 0>(true);
6641 cmds::%(name)s cmd;
6642 cmd.Init(%(args)s);
6643 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6644 %(expected_call)s
6645 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6646 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6649 extra = {
6650 'data_type': self.GetArrayType(func),
6651 'data_value': func.GetInfo('data_value') or '0',
6652 'expected_call': expected_call,
6654 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6656 invalid_test = """
6657 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6658 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6659 SpecializedSetup<cmds::%(name)s, 0>(false);
6660 cmds::%(name)s cmd;
6661 cmd.Init(%(args)s);
6662 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6663 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6666 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6668 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6669 """Writes the service unit test for a command."""
6670 valid_test = """
6671 TEST_P(%(test_name)s, %(name)sValidArgs) {
6672 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6673 SpecializedSetup<cmds::%(name)s, 0>(true);
6674 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6675 cmd.Init(%(gl_args)s, &temp[0]);
6676 EXPECT_CALL(
6677 *gl_,
6678 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6679 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6680 if func.IsUnsafe():
6681 valid_test += """
6682 decoder_->set_unsafe_es3_apis_enabled(true);"""
6683 valid_test += """
6684 EXPECT_EQ(error::kNoError,
6685 ExecuteImmediateCmd(cmd, sizeof(temp)));
6686 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6687 if func.IsUnsafe():
6688 valid_test += """
6689 decoder_->set_unsafe_es3_apis_enabled(false);
6690 EXPECT_EQ(error::kUnknownCommand,
6691 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6692 valid_test += """
6695 gl_arg_strings = [
6696 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6698 gl_any_strings = ["_"] * len(gl_arg_strings)
6700 extra = {
6701 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6702 'data_type': self.GetArrayType(func),
6703 'data_count': self.GetArrayCount(func),
6704 'data_value': func.GetInfo('data_value') or '0',
6705 'gl_args': ", ".join(gl_arg_strings),
6706 'gl_any_args': ", ".join(gl_any_strings),
6708 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6710 invalid_test = """
6711 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6712 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6713 if func.IsUnsafe():
6714 invalid_test += """
6715 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6717 else:
6718 invalid_test += """
6719 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6721 invalid_test += """
6722 SpecializedSetup<cmds::%(name)s, 0>(false);
6723 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6724 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6725 if func.IsUnsafe():
6726 invalid_test += """
6727 decoder_->set_unsafe_es3_apis_enabled(true);
6728 EXPECT_EQ(error::%(parse_result)s,
6729 ExecuteImmediateCmd(cmd, sizeof(temp)));
6730 decoder_->set_unsafe_es3_apis_enabled(false);
6733 else:
6734 invalid_test += """
6735 EXPECT_EQ(error::%(parse_result)s,
6736 ExecuteImmediateCmd(cmd, sizeof(temp)));
6737 %(gl_error_test)s
6740 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6742 def WriteGetDataSizeCode(self, func, file):
6743 """Overrriden from TypeHandler."""
6744 code = """ uint32_t data_size;
6745 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6746 return error::kOutOfBounds;
6749 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6750 if func.IsImmediate():
6751 file.Write(" if (data_size > immediate_data_size) {\n")
6752 file.Write(" return error::kOutOfBounds;\n")
6753 file.Write(" }\n")
6755 def __NeedsToCalcDataCount(self, func):
6756 use_count_func = func.GetInfo('use_count_func')
6757 return use_count_func != None and use_count_func != False
6759 def WriteGLES2Implementation(self, func, file):
6760 """Overrriden from TypeHandler."""
6761 impl_func = func.GetInfo('impl_func')
6762 if (impl_func != None and impl_func != True):
6763 return;
6764 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6765 (func.return_type, func.original_name,
6766 func.MakeTypedOriginalArgString("")))
6767 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6768 func.WriteDestinationInitalizationValidation(file)
6769 self.WriteClientGLCallLog(func, file)
6771 if self.__NeedsToCalcDataCount(func):
6772 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6773 (func.name, func.GetOriginalArgs()[0].name))
6774 file.Write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6775 else:
6776 file.Write(" size_t count = %d;" % self.GetArrayCount(func))
6777 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6778 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6779 func.GetLastOriginalArg().name)
6780 for arg in func.GetOriginalArgs():
6781 arg.WriteClientSideValidationCode(file, func)
6782 file.Write(" helper_->%sImmediate(%s);\n" %
6783 (func.name, func.MakeOriginalArgString("")))
6784 file.Write(" CheckGLError();\n")
6785 file.Write("}\n")
6786 file.Write("\n")
6788 def WriteGLES2ImplementationUnitTest(self, func, file):
6789 """Writes the GLES2 Implemention unit test."""
6790 client_test = func.GetInfo('client_test')
6791 if (client_test != None and client_test != True):
6792 return;
6793 code = """
6794 TEST_F(GLES2ImplementationTest, %(name)s) {
6795 %(type)s data[%(count)d] = {0};
6796 struct Cmds {
6797 cmds::%(name)sImmediate cmd;
6798 %(type)s data[%(count)d];
6801 for (int jj = 0; jj < %(count)d; ++jj) {
6802 data[jj] = static_cast<%(type)s>(jj);
6804 Cmds expected;
6805 expected.cmd.Init(%(cmd_args)s, &data[0]);
6806 gl_->%(name)s(%(args)s, &data[0]);
6807 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6810 cmd_arg_strings = [
6811 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6813 gl_arg_strings = [
6814 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6817 file.Write(code % {
6818 'name': func.name,
6819 'type': self.GetArrayType(func),
6820 'count': self.GetArrayCount(func),
6821 'args': ", ".join(gl_arg_strings),
6822 'cmd_args': ", ".join(cmd_arg_strings),
6825 def WriteImmediateCmdComputeSize(self, func, file):
6826 """Overrriden from TypeHandler."""
6827 file.Write(" static uint32_t ComputeDataSize() {\n")
6828 file.Write(" return static_cast<uint32_t>(\n")
6829 file.Write(" sizeof(%s) * %d);\n" %
6830 (self.GetArrayType(func), self.GetArrayCount(func)))
6831 file.Write(" }\n")
6832 file.Write("\n")
6833 if self.__NeedsToCalcDataCount(func):
6834 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6835 (func.GetOriginalArgs()[0].type,
6836 func.GetOriginalArgs()[0].name))
6837 file.Write(" return static_cast<uint32_t>(\n")
6838 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6839 (self.GetArrayType(func), func.original_name,
6840 func.GetOriginalArgs()[0].name))
6841 file.Write(" }\n")
6842 file.Write("\n")
6843 file.Write(" static uint32_t ComputeSize() {\n")
6844 file.Write(" return static_cast<uint32_t>(\n")
6845 file.Write(
6846 " sizeof(ValueType) + ComputeDataSize());\n")
6847 file.Write(" }\n")
6848 file.Write("\n")
6850 def WriteImmediateCmdSetHeader(self, func, file):
6851 """Overrriden from TypeHandler."""
6852 file.Write(" void SetHeader() {\n")
6853 file.Write(
6854 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6855 file.Write(" }\n")
6856 file.Write("\n")
6858 def WriteImmediateCmdInit(self, func, file):
6859 """Overrriden from TypeHandler."""
6860 last_arg = func.GetLastOriginalArg()
6861 file.Write(" void Init(%s, %s _%s) {\n" %
6862 (func.MakeTypedCmdArgString("_"),
6863 last_arg.type, last_arg.name))
6864 file.Write(" SetHeader();\n")
6865 args = func.GetCmdArgs()
6866 for arg in args:
6867 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6868 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6869 if self.__NeedsToCalcDataCount(func):
6870 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6871 (last_arg.name, func.GetOriginalArgs()[0].name))
6872 file.Write("""
6873 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6874 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6875 ComputeEffectiveDataSize(%(arg)s);
6876 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6877 """ % { 'arg': func.GetOriginalArgs()[0].name, })
6878 else:
6879 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
6880 file.Write(" }\n")
6881 file.Write("\n")
6883 def WriteImmediateCmdSet(self, func, file):
6884 """Overrriden from TypeHandler."""
6885 last_arg = func.GetLastOriginalArg()
6886 copy_args = func.MakeCmdArgString("_", False)
6887 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6888 (func.MakeTypedCmdArgString("_", True),
6889 last_arg.type, last_arg.name))
6890 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6891 (copy_args, last_arg.name))
6892 file.Write(" const uint32_t size = ComputeSize();\n")
6893 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6894 "cmd, size);\n")
6895 file.Write(" }\n")
6896 file.Write("\n")
6898 def WriteImmediateCmdHelper(self, func, file):
6899 """Overrriden from TypeHandler."""
6900 code = """ void %(name)s(%(typed_args)s) {
6901 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6902 gles2::cmds::%(name)s* c =
6903 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6904 if (c) {
6905 c->Init(%(args)s);
6910 file.Write(code % {
6911 "name": func.name,
6912 "typed_args": func.MakeTypedOriginalArgString(""),
6913 "args": func.MakeOriginalArgString(""),
6916 def WriteImmediateFormatTest(self, func, file):
6917 """Overrriden from TypeHandler."""
6918 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6919 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6920 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6921 for v in range(0, self.GetArrayCount(func)):
6922 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6923 (self.GetArrayType(func), v))
6924 file.Write(" };\n")
6925 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6926 (func.name, func.name))
6927 file.Write(" void* next_cmd = cmd.Set(\n")
6928 file.Write(" &cmd")
6929 args = func.GetCmdArgs()
6930 for value, arg in enumerate(args):
6931 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
6932 file.Write(",\n data);\n")
6933 args = func.GetCmdArgs()
6934 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6935 % func.name)
6936 file.Write(" cmd.header.command);\n")
6937 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6938 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6939 file.Write(" cmd.header.size * 4u);\n")
6940 for value, arg in enumerate(args):
6941 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6942 (arg.type, value + 11, arg.name))
6943 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6944 file.Write(" next_cmd, sizeof(cmd) +\n")
6945 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6946 file.Write(" // TODO(gman): Check that data was inserted;\n")
6947 file.Write("}\n")
6948 file.Write("\n")
6951 class PUTnHandler(ArrayArgTypeHandler):
6952 """Handler for PUTn 'glUniform__v' type functions."""
6954 def __init__(self):
6955 ArrayArgTypeHandler.__init__(self)
6957 def WriteServiceUnitTest(self, func, file, *extras):
6958 """Overridden from TypeHandler."""
6959 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
6961 valid_test = """
6962 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6963 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6964 SpecializedSetup<cmds::%(name)s, 0>(true);
6965 cmds::%(name)s cmd;
6966 cmd.Init(%(args)s);
6967 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6968 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6971 gl_arg_strings = []
6972 arg_strings = []
6973 for count, arg in enumerate(func.GetOriginalArgs()):
6974 # hardcoded to match unit tests.
6975 if count == 0:
6976 # the location of the second element of the 2nd uniform.
6977 # defined in GLES2DecoderBase::SetupShaderForUniform
6978 gl_arg_strings.append("3")
6979 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
6980 elif count == 1:
6981 # the number of elements that gl will be called with.
6982 gl_arg_strings.append("3")
6983 # the number of elements requested in the command.
6984 arg_strings.append("5")
6985 else:
6986 gl_arg_strings.append(arg.GetValidGLArg(func))
6987 if not arg.IsConstant():
6988 arg_strings.append(arg.GetValidArg(func))
6989 extra = {
6990 'gl_args': ", ".join(gl_arg_strings),
6991 'args': ", ".join(arg_strings),
6993 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6995 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6996 """Overridden from TypeHandler."""
6997 valid_test = """
6998 TEST_P(%(test_name)s, %(name)sValidArgs) {
6999 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7000 EXPECT_CALL(
7001 *gl_,
7002 %(gl_func_name)s(%(gl_args)s,
7003 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7004 SpecializedSetup<cmds::%(name)s, 0>(true);
7005 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7006 cmd.Init(%(args)s, &temp[0]);"""
7007 if func.IsUnsafe():
7008 valid_test += """
7009 decoder_->set_unsafe_es3_apis_enabled(true);"""
7010 valid_test += """
7011 EXPECT_EQ(error::kNoError,
7012 ExecuteImmediateCmd(cmd, sizeof(temp)));
7013 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7014 if func.IsUnsafe():
7015 valid_test += """
7016 decoder_->set_unsafe_es3_apis_enabled(false);
7017 EXPECT_EQ(error::kUnknownCommand,
7018 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7019 valid_test += """
7022 gl_arg_strings = []
7023 gl_any_strings = []
7024 arg_strings = []
7025 for arg in func.GetOriginalArgs()[0:-1]:
7026 gl_arg_strings.append(arg.GetValidGLArg(func))
7027 gl_any_strings.append("_")
7028 if not arg.IsConstant():
7029 arg_strings.append(arg.GetValidArg(func))
7030 extra = {
7031 'data_type': self.GetArrayType(func),
7032 'data_count': self.GetArrayCount(func),
7033 'args': ", ".join(arg_strings),
7034 'gl_args': ", ".join(gl_arg_strings),
7035 'gl_any_args': ", ".join(gl_any_strings),
7037 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
7039 invalid_test = """
7040 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7041 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7042 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7043 SpecializedSetup<cmds::%(name)s, 0>(false);
7044 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7045 cmd.Init(%(all_but_last_args)s, &temp[0]);
7046 EXPECT_EQ(error::%(parse_result)s,
7047 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7050 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
7052 def WriteGetDataSizeCode(self, func, file):
7053 """Overrriden from TypeHandler."""
7054 code = """ uint32_t data_size;
7055 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7056 return error::kOutOfBounds;
7059 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
7060 if func.IsImmediate():
7061 file.Write(" if (data_size > immediate_data_size) {\n")
7062 file.Write(" return error::kOutOfBounds;\n")
7063 file.Write(" }\n")
7065 def WriteGLES2Implementation(self, func, file):
7066 """Overrriden from TypeHandler."""
7067 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7068 (func.return_type, func.original_name,
7069 func.MakeTypedOriginalArgString("")))
7070 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7071 func.WriteDestinationInitalizationValidation(file)
7072 self.WriteClientGLCallLog(func, file)
7073 last_pointer_name = func.GetLastOriginalPointerArg().name
7074 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7075 for (GLsizei i = 0; i < count; ++i) {
7076 """)
7077 values_str = ' << ", " << '.join(
7078 ["%s[%d + i * %d]" % (
7079 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
7080 0, self.GetArrayCount(func))])
7081 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
7082 file.Write(" }\n });\n")
7083 for arg in func.GetOriginalArgs():
7084 arg.WriteClientSideValidationCode(file, func)
7085 file.Write(" helper_->%sImmediate(%s);\n" %
7086 (func.name, func.MakeInitString("")))
7087 file.Write(" CheckGLError();\n")
7088 file.Write("}\n")
7089 file.Write("\n")
7091 def WriteGLES2ImplementationUnitTest(self, func, file):
7092 """Writes the GLES2 Implemention unit test."""
7093 code = """
7094 TEST_F(GLES2ImplementationTest, %(name)s) {
7095 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7096 struct Cmds {
7097 cmds::%(name)sImmediate cmd;
7098 %(type)s data[%(count_param)d][%(count)d];
7101 Cmds expected;
7102 for (int ii = 0; ii < %(count_param)d; ++ii) {
7103 for (int jj = 0; jj < %(count)d; ++jj) {
7104 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7107 expected.cmd.Init(%(cmd_args)s);
7108 gl_->%(name)s(%(args)s);
7109 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7112 cmd_arg_strings = []
7113 for arg in func.GetCmdArgs():
7114 if arg.name.endswith("_shm_id"):
7115 cmd_arg_strings.append("&data[0][0]")
7116 elif arg.name.endswith("_shm_offset"):
7117 continue
7118 else:
7119 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
7120 gl_arg_strings = []
7121 count_param = 0
7122 for arg in func.GetOriginalArgs():
7123 if arg.IsPointer():
7124 valid_value = "&data[0][0]"
7125 else:
7126 valid_value = arg.GetValidClientSideArg(func)
7127 gl_arg_strings.append(valid_value)
7128 if arg.name == "count":
7129 count_param = int(valid_value)
7130 file.Write(code % {
7131 'name': func.name,
7132 'type': self.GetArrayType(func),
7133 'count': self.GetArrayCount(func),
7134 'args': ", ".join(gl_arg_strings),
7135 'cmd_args': ", ".join(cmd_arg_strings),
7136 'count_param': count_param,
7139 # Test constants for invalid values, as they are not tested by the
7140 # service.
7141 constants = [
7142 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
7144 if not constants:
7145 return
7147 code = """
7148 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7149 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7150 for (int ii = 0; ii < %(count_param)d; ++ii) {
7151 for (int jj = 0; jj < %(count)d; ++jj) {
7152 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7155 gl_->%(name)s(%(args)s);
7156 EXPECT_TRUE(NoCommandsWritten());
7157 EXPECT_EQ(%(gl_error)s, CheckError());
7160 for invalid_arg in constants:
7161 gl_arg_strings = []
7162 invalid = invalid_arg.GetInvalidArg(func)
7163 for arg in func.GetOriginalArgs():
7164 if arg is invalid_arg:
7165 gl_arg_strings.append(invalid[0])
7166 elif arg.IsPointer():
7167 gl_arg_strings.append("&data[0][0]")
7168 else:
7169 valid_value = arg.GetValidClientSideArg(func)
7170 gl_arg_strings.append(valid_value)
7171 if arg.name == "count":
7172 count_param = int(valid_value)
7174 file.Write(code % {
7175 'name': func.name,
7176 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
7177 'type': self.GetArrayType(func),
7178 'count': self.GetArrayCount(func),
7179 'args': ", ".join(gl_arg_strings),
7180 'gl_error': invalid[2],
7181 'count_param': count_param,
7185 def WriteImmediateCmdComputeSize(self, func, file):
7186 """Overrriden from TypeHandler."""
7187 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7188 file.Write(" return static_cast<uint32_t>(\n")
7189 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
7190 (self.GetArrayType(func), self.GetArrayCount(func)))
7191 file.Write(" }\n")
7192 file.Write("\n")
7193 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
7194 file.Write(" return static_cast<uint32_t>(\n")
7195 file.Write(
7196 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7197 file.Write(" }\n")
7198 file.Write("\n")
7200 def WriteImmediateCmdSetHeader(self, func, file):
7201 """Overrriden from TypeHandler."""
7202 file.Write(" void SetHeader(GLsizei count) {\n")
7203 file.Write(
7204 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7205 file.Write(" }\n")
7206 file.Write("\n")
7208 def WriteImmediateCmdInit(self, func, file):
7209 """Overrriden from TypeHandler."""
7210 file.Write(" void Init(%s) {\n" %
7211 func.MakeTypedInitString("_"))
7212 file.Write(" SetHeader(_count);\n")
7213 args = func.GetCmdArgs()
7214 for arg in args:
7215 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
7216 file.Write(" memcpy(ImmediateDataAddress(this),\n")
7217 pointer_arg = func.GetLastOriginalPointerArg()
7218 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
7219 file.Write(" }\n")
7220 file.Write("\n")
7222 def WriteImmediateCmdSet(self, func, file):
7223 """Overrriden from TypeHandler."""
7224 file.Write(" void* Set(void* cmd%s) {\n" %
7225 func.MakeTypedInitString("_", True))
7226 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7227 func.MakeInitString("_"))
7228 file.Write(" const uint32_t size = ComputeSize(_count);\n")
7229 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7230 "cmd, size);\n")
7231 file.Write(" }\n")
7232 file.Write("\n")
7234 def WriteImmediateCmdHelper(self, func, file):
7235 """Overrriden from TypeHandler."""
7236 code = """ void %(name)s(%(typed_args)s) {
7237 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7238 gles2::cmds::%(name)s* c =
7239 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7240 if (c) {
7241 c->Init(%(args)s);
7246 file.Write(code % {
7247 "name": func.name,
7248 "typed_args": func.MakeTypedInitString(""),
7249 "args": func.MakeInitString("")
7252 def WriteImmediateFormatTest(self, func, file):
7253 """Overrriden from TypeHandler."""
7254 args = func.GetOriginalArgs()
7255 count_param = 0
7256 for arg in args:
7257 if arg.name == "count":
7258 count_param = int(arg.GetValidClientSideCmdArg(func))
7259 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7260 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
7261 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
7262 for v in range(0, self.GetArrayCount(func) * count_param):
7263 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7264 (self.GetArrayType(func), v))
7265 file.Write(" };\n")
7266 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7267 (func.name, func.name))
7268 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
7269 file.Write(" const size_t kExpectedCmdSize =\n")
7270 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7271 (self.GetArrayType(func), self.GetArrayCount(func)))
7272 file.Write(" void* next_cmd = cmd.Set(\n")
7273 file.Write(" &cmd")
7274 for value, arg in enumerate(args):
7275 if arg.IsPointer():
7276 file.Write(",\n data")
7277 elif arg.IsConstant():
7278 continue
7279 else:
7280 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
7281 file.Write(");\n")
7282 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7283 func.name)
7284 file.Write(" cmd.header.command);\n")
7285 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7286 for value, arg in enumerate(args):
7287 if arg.IsPointer() or arg.IsConstant():
7288 continue
7289 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7290 (arg.type, value + 1, arg.name))
7291 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7292 file.Write(" next_cmd, sizeof(cmd) +\n")
7293 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7294 file.Write(" // TODO(gman): Check that data was inserted;\n")
7295 file.Write("}\n")
7296 file.Write("\n")
7298 class PUTSTRHandler(ArrayArgTypeHandler):
7299 """Handler for functions that pass a string array."""
7301 def __init__(self):
7302 ArrayArgTypeHandler.__init__(self)
7304 def __GetDataArg(self, func):
7305 """Return the argument that points to the 2D char arrays"""
7306 for arg in func.GetOriginalArgs():
7307 if arg.IsPointer2D():
7308 return arg
7309 return None
7311 def __GetLengthArg(self, func):
7312 """Return the argument that holds length for each char array"""
7313 for arg in func.GetOriginalArgs():
7314 if arg.IsPointer() and not arg.IsPointer2D():
7315 return arg
7316 return None
7318 def WriteGLES2Implementation(self, func, file):
7319 """Overrriden from TypeHandler."""
7320 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7321 (func.return_type, func.original_name,
7322 func.MakeTypedOriginalArgString("")))
7323 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7324 func.WriteDestinationInitalizationValidation(file)
7325 self.WriteClientGLCallLog(func, file)
7326 data_arg = self.__GetDataArg(func)
7327 length_arg = self.__GetLengthArg(func)
7328 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
7329 for (GLsizei ii = 0; ii < count; ++ii) {
7330 if (%(data)s[ii]) {"""
7331 if length_arg == None:
7332 log_code_block += """
7333 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7334 else:
7335 log_code_block += """
7336 if (%(length)s && %(length)s[ii] >= 0) {
7337 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7338 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7339 } else {
7340 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7341 }"""
7342 log_code_block += """
7343 } else {
7344 GPU_CLIENT_LOG(" " << ii << ": NULL");
7349 file.Write(log_code_block % {
7350 'data': data_arg.name,
7351 'length': length_arg.name if not length_arg == None else ''
7353 for arg in func.GetOriginalArgs():
7354 arg.WriteClientSideValidationCode(file, func)
7356 bucket_args = []
7357 for arg in func.GetOriginalArgs():
7358 if arg.name == 'count' or arg == self.__GetLengthArg(func):
7359 continue
7360 if arg == self.__GetDataArg(func):
7361 bucket_args.append('kResultBucketId')
7362 else:
7363 bucket_args.append(arg.name)
7364 code_block = """
7365 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7366 return;
7368 helper_->%(func_name)sBucket(%(bucket_args)s);
7369 helper_->SetBucketSize(kResultBucketId, 0);
7370 CheckGLError();
7374 file.Write(code_block % {
7375 'data': data_arg.name,
7376 'length': length_arg.name if not length_arg == None else 'NULL',
7377 'func_name': func.name,
7378 'bucket_args': ', '.join(bucket_args),
7381 def WriteGLES2ImplementationUnitTest(self, func, file):
7382 """Overrriden from TypeHandler."""
7383 code = """
7384 TEST_F(GLES2ImplementationTest, %(name)s) {
7385 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7386 const char* kString1 = "happy";
7387 const char* kString2 = "ending";
7388 const size_t kString1Size = ::strlen(kString1) + 1;
7389 const size_t kString2Size = ::strlen(kString2) + 1;
7390 const size_t kHeaderSize = sizeof(GLint) * 3;
7391 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7392 const size_t kPaddedHeaderSize =
7393 transfer_buffer_->RoundToAlignment(kHeaderSize);
7394 const size_t kPaddedString1Size =
7395 transfer_buffer_->RoundToAlignment(kString1Size);
7396 const size_t kPaddedString2Size =
7397 transfer_buffer_->RoundToAlignment(kString2Size);
7398 struct Cmds {
7399 cmd::SetBucketSize set_bucket_size;
7400 cmd::SetBucketData set_bucket_header;
7401 cmd::SetToken set_token1;
7402 cmd::SetBucketData set_bucket_data1;
7403 cmd::SetToken set_token2;
7404 cmd::SetBucketData set_bucket_data2;
7405 cmd::SetToken set_token3;
7406 cmds::%(name)sBucket cmd_bucket;
7407 cmd::SetBucketSize clear_bucket_size;
7410 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7411 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7412 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7414 Cmds expected;
7415 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7416 expected.set_bucket_header.Init(
7417 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7418 expected.set_token1.Init(GetNextToken());
7419 expected.set_bucket_data1.Init(
7420 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7421 expected.set_token2.Init(GetNextToken());
7422 expected.set_bucket_data2.Init(
7423 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7424 mem2.offset);
7425 expected.set_token3.Init(GetNextToken());
7426 expected.cmd_bucket.Init(%(bucket_args)s);
7427 expected.clear_bucket_size.Init(kBucketId, 0);
7428 const char* kStrings[] = { kString1, kString2 };
7429 gl_->%(name)s(%(gl_args)s);
7430 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7433 gl_args = []
7434 bucket_args = []
7435 for arg in func.GetOriginalArgs():
7436 if arg == self.__GetDataArg(func):
7437 gl_args.append('kStrings')
7438 bucket_args.append('kBucketId')
7439 elif arg == self.__GetLengthArg(func):
7440 gl_args.append('NULL')
7441 elif arg.name == 'count':
7442 gl_args.append('2')
7443 else:
7444 gl_args.append(arg.GetValidClientSideArg(func))
7445 bucket_args.append(arg.GetValidClientSideArg(func))
7446 file.Write(code % {
7447 'name': func.name,
7448 'gl_args': ", ".join(gl_args),
7449 'bucket_args': ", ".join(bucket_args),
7452 if self.__GetLengthArg(func) == None:
7453 return
7454 code = """
7455 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7456 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7457 const char* kString = "foobar******";
7458 const size_t kStringSize = 6; // We only need "foobar".
7459 const size_t kHeaderSize = sizeof(GLint) * 2;
7460 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7461 const size_t kPaddedHeaderSize =
7462 transfer_buffer_->RoundToAlignment(kHeaderSize);
7463 const size_t kPaddedStringSize =
7464 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7465 struct Cmds {
7466 cmd::SetBucketSize set_bucket_size;
7467 cmd::SetBucketData set_bucket_header;
7468 cmd::SetToken set_token1;
7469 cmd::SetBucketData set_bucket_data;
7470 cmd::SetToken set_token2;
7471 cmds::ShaderSourceBucket shader_source_bucket;
7472 cmd::SetBucketSize clear_bucket_size;
7475 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7476 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7478 Cmds expected;
7479 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7480 expected.set_bucket_header.Init(
7481 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7482 expected.set_token1.Init(GetNextToken());
7483 expected.set_bucket_data.Init(
7484 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7485 expected.set_token2.Init(GetNextToken());
7486 expected.shader_source_bucket.Init(%(bucket_args)s);
7487 expected.clear_bucket_size.Init(kBucketId, 0);
7488 const char* kStrings[] = { kString };
7489 const GLint kLength[] = { kStringSize };
7490 gl_->%(name)s(%(gl_args)s);
7491 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7494 gl_args = []
7495 for arg in func.GetOriginalArgs():
7496 if arg == self.__GetDataArg(func):
7497 gl_args.append('kStrings')
7498 elif arg == self.__GetLengthArg(func):
7499 gl_args.append('kLength')
7500 elif arg.name == 'count':
7501 gl_args.append('1')
7502 else:
7503 gl_args.append(arg.GetValidClientSideArg(func))
7504 file.Write(code % {
7505 'name': func.name,
7506 'gl_args': ", ".join(gl_args),
7507 'bucket_args': ", ".join(bucket_args),
7510 def WriteBucketServiceUnitTest(self, func, file, *extras):
7511 """Overrriden from TypeHandler."""
7512 cmd_args = []
7513 cmd_args_with_invalid_id = []
7514 gl_args = []
7515 for index, arg in enumerate(func.GetOriginalArgs()):
7516 if arg == self.__GetLengthArg(func):
7517 gl_args.append('_')
7518 elif arg.name == 'count':
7519 gl_args.append('1')
7520 elif arg == self.__GetDataArg(func):
7521 cmd_args.append('kBucketId')
7522 cmd_args_with_invalid_id.append('kBucketId')
7523 gl_args.append('_')
7524 elif index == 0: # Resource ID arg
7525 cmd_args.append(arg.GetValidArg(func))
7526 cmd_args_with_invalid_id.append('kInvalidClientId')
7527 gl_args.append(arg.GetValidGLArg(func))
7528 else:
7529 cmd_args.append(arg.GetValidArg(func))
7530 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7531 gl_args.append(arg.GetValidGLArg(func))
7533 test = """
7534 TEST_P(%(test_name)s, %(name)sValidArgs) {
7535 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7536 const uint32 kBucketId = 123;
7537 const char kSource0[] = "hello";
7538 const char* kSource[] = { kSource0 };
7539 const char kValidStrEnd = 0;
7540 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7541 cmds::%(name)s cmd;
7542 cmd.Init(%(cmd_args)s);
7543 decoder_->set_unsafe_es3_apis_enabled(true);
7544 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7545 if func.IsUnsafe():
7546 test += """
7547 decoder_->set_unsafe_es3_apis_enabled(false);
7548 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7550 test += """
7553 self.WriteValidUnitTest(func, file, test, {
7554 'cmd_args': ", ".join(cmd_args),
7555 'gl_args': ", ".join(gl_args),
7556 }, *extras)
7558 test = """
7559 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7560 const uint32 kBucketId = 123;
7561 const char kSource0[] = "hello";
7562 const char* kSource[] = { kSource0 };
7563 const char kValidStrEnd = 0;
7564 decoder_->set_unsafe_es3_apis_enabled(true);
7565 cmds::%(name)s cmd;
7566 // Test no bucket.
7567 cmd.Init(%(cmd_args)s);
7568 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7569 // Test invalid client.
7570 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7571 cmd.Init(%(cmd_args_with_invalid_id)s);
7572 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7573 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7576 self.WriteValidUnitTest(func, file, test, {
7577 'cmd_args': ", ".join(cmd_args),
7578 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7579 }, *extras)
7581 test = """
7582 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7583 const uint32 kBucketId = 123;
7584 const char kSource0[] = "hello";
7585 const char* kSource[] = { kSource0 };
7586 const char kValidStrEnd = 0;
7587 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7588 const GLsizei kTests[] = {
7589 kCount + 1,
7591 std::numeric_limits<GLsizei>::max(),
7594 decoder_->set_unsafe_es3_apis_enabled(true);
7595 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7596 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7597 cmds::%(name)s cmd;
7598 cmd.Init(%(cmd_args)s);
7599 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7603 self.WriteValidUnitTest(func, file, test, {
7604 'cmd_args': ", ".join(cmd_args),
7605 }, *extras)
7607 test = """
7608 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7609 const uint32 kBucketId = 123;
7610 const char kSource0[] = "hello";
7611 const char* kSource[] = { kSource0 };
7612 const char kInvalidStrEnd = '*';
7613 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7614 cmds::%(name)s cmd;
7615 cmd.Init(%(cmd_args)s);
7616 decoder_->set_unsafe_es3_apis_enabled(true);
7617 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7620 self.WriteValidUnitTest(func, file, test, {
7621 'cmd_args': ", ".join(cmd_args),
7622 }, *extras)
7625 class PUTXnHandler(ArrayArgTypeHandler):
7626 """Handler for glUniform?f functions."""
7627 def __init__(self):
7628 ArrayArgTypeHandler.__init__(self)
7630 def WriteHandlerImplementation(self, func, file):
7631 """Overrriden from TypeHandler."""
7632 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7633 if func.IsUnsafe():
7634 code += """
7635 gl%(name)sv(%(location)s, 1, &temp[0]);
7637 else:
7638 code += """
7639 Do%(name)sv(%(location)s, 1, &temp[0]);
7641 values = ""
7642 args = func.GetOriginalArgs()
7643 count = int(self.GetArrayCount(func))
7644 num_args = len(args)
7645 for ii in range(count):
7646 values += "%s, " % args[len(args) - count + ii].name
7648 file.Write(code % {
7649 'name': func.name,
7650 'count': self.GetArrayCount(func),
7651 'type': self.GetArrayType(func),
7652 'location': args[0].name,
7653 'args': func.MakeOriginalArgString(""),
7654 'values': values,
7657 def WriteServiceUnitTest(self, func, file, *extras):
7658 """Overrriden from TypeHandler."""
7659 valid_test = """
7660 TEST_P(%(test_name)s, %(name)sValidArgs) {
7661 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7662 SpecializedSetup<cmds::%(name)s, 0>(true);
7663 cmds::%(name)s cmd;
7664 cmd.Init(%(args)s);"""
7665 if func.IsUnsafe():
7666 valid_test += """
7667 decoder_->set_unsafe_es3_apis_enabled(true);"""
7668 valid_test += """
7669 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7670 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7671 if func.IsUnsafe():
7672 valid_test += """
7673 decoder_->set_unsafe_es3_apis_enabled(false);
7674 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7675 valid_test += """
7678 args = func.GetOriginalArgs()
7679 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7680 self.WriteValidUnitTest(func, file, valid_test, {
7681 'name': func.name,
7682 'count': self.GetArrayCount(func),
7683 'local_args': local_args,
7684 }, *extras)
7686 invalid_test = """
7687 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7688 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7689 SpecializedSetup<cmds::%(name)s, 0>(false);
7690 cmds::%(name)s cmd;
7691 cmd.Init(%(args)s);
7692 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7695 self.WriteInvalidUnitTest(func, file, invalid_test, {
7696 'name': func.GetInfo('name'),
7697 'count': self.GetArrayCount(func),
7701 class GLcharHandler(CustomHandler):
7702 """Handler for functions that pass a single string ."""
7704 def __init__(self):
7705 CustomHandler.__init__(self)
7707 def WriteImmediateCmdComputeSize(self, func, file):
7708 """Overrriden from TypeHandler."""
7709 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7710 file.Write(" return static_cast<uint32_t>(\n")
7711 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7712 file.Write(" }\n")
7714 def WriteImmediateCmdSetHeader(self, func, file):
7715 """Overrriden from TypeHandler."""
7716 code = """
7717 void SetHeader(uint32_t data_size) {
7718 header.SetCmdBySize<ValueType>(data_size);
7721 file.Write(code)
7723 def WriteImmediateCmdInit(self, func, file):
7724 """Overrriden from TypeHandler."""
7725 last_arg = func.GetLastOriginalArg()
7726 args = func.GetCmdArgs()
7727 set_code = []
7728 for arg in args:
7729 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7730 code = """
7731 void Init(%(typed_args)s, uint32_t _data_size) {
7732 SetHeader(_data_size);
7733 %(set_code)s
7734 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7738 file.Write(code % {
7739 "typed_args": func.MakeTypedArgString("_"),
7740 "set_code": "\n".join(set_code),
7741 "last_arg": last_arg.name
7744 def WriteImmediateCmdSet(self, func, file):
7745 """Overrriden from TypeHandler."""
7746 last_arg = func.GetLastOriginalArg()
7747 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7748 func.MakeTypedCmdArgString("_", True))
7749 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7750 func.MakeCmdArgString("_"))
7751 file.Write(" return NextImmediateCmdAddress<ValueType>("
7752 "cmd, _data_size);\n")
7753 file.Write(" }\n")
7754 file.Write("\n")
7756 def WriteImmediateCmdHelper(self, func, file):
7757 """Overrriden from TypeHandler."""
7758 code = """ void %(name)s(%(typed_args)s) {
7759 const uint32_t data_size = strlen(name);
7760 gles2::cmds::%(name)s* c =
7761 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7762 if (c) {
7763 c->Init(%(args)s, data_size);
7768 file.Write(code % {
7769 "name": func.name,
7770 "typed_args": func.MakeTypedOriginalArgString(""),
7771 "args": func.MakeOriginalArgString(""),
7775 def WriteImmediateFormatTest(self, func, file):
7776 """Overrriden from TypeHandler."""
7777 init_code = []
7778 check_code = []
7779 all_but_last_arg = func.GetCmdArgs()[:-1]
7780 for value, arg in enumerate(all_but_last_arg):
7781 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7782 for value, arg in enumerate(all_but_last_arg):
7783 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7784 (arg.type, value + 11, arg.name))
7785 code = """
7786 TEST_F(GLES2FormatTest, %(func_name)s) {
7787 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7788 static const char* const test_str = \"test string\";
7789 void* next_cmd = cmd.Set(
7790 &cmd,
7791 %(init_code)s
7792 test_str,
7793 strlen(test_str));
7794 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7795 cmd.header.command);
7796 EXPECT_EQ(sizeof(cmd) +
7797 RoundSizeToMultipleOfEntries(strlen(test_str)),
7798 cmd.header.size * 4u);
7799 EXPECT_EQ(static_cast<char*>(next_cmd),
7800 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7801 RoundSizeToMultipleOfEntries(strlen(test_str)));
7802 %(check_code)s
7803 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7804 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7805 CheckBytesWritten(
7806 next_cmd,
7807 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7808 sizeof(cmd) + strlen(test_str));
7812 file.Write(code % {
7813 'func_name': func.name,
7814 'init_code': "\n".join(init_code),
7815 'check_code': "\n".join(check_code),
7819 class GLcharNHandler(CustomHandler):
7820 """Handler for functions that pass a single string with an optional len."""
7822 def __init__(self):
7823 CustomHandler.__init__(self)
7825 def InitFunction(self, func):
7826 """Overrriden from TypeHandler."""
7827 func.cmd_args = []
7828 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7830 def NeedsDataTransferFunction(self, func):
7831 """Overriden from TypeHandler."""
7832 return False
7834 def AddBucketFunction(self, generator, func):
7835 """Overrriden from TypeHandler."""
7836 pass
7838 def WriteServiceImplementation(self, func, file):
7839 """Overrriden from TypeHandler."""
7840 self.WriteServiceHandlerFunctionHeader(func, file)
7841 file.Write("""
7842 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7843 Bucket* bucket = GetBucket(bucket_id);
7844 if (!bucket || bucket->size() == 0) {
7845 return error::kInvalidArguments;
7847 std::string str;
7848 if (!bucket->GetAsString(&str)) {
7849 return error::kInvalidArguments;
7851 %(gl_func_name)s(0, str.c_str());
7852 return error::kNoError;
7855 """ % {
7856 'name': func.name,
7857 'gl_func_name': func.GetGLFunctionName(),
7858 'bucket_id': func.cmd_args[0].name,
7862 class IsHandler(TypeHandler):
7863 """Handler for glIs____ type and glGetError functions."""
7865 def __init__(self):
7866 TypeHandler.__init__(self)
7868 def InitFunction(self, func):
7869 """Overrriden from TypeHandler."""
7870 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7871 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7872 if func.GetInfo('result') == None:
7873 func.AddInfo('result', ['uint32_t'])
7875 def WriteServiceUnitTest(self, func, file, *extras):
7876 """Overrriden from TypeHandler."""
7877 valid_test = """
7878 TEST_P(%(test_name)s, %(name)sValidArgs) {
7879 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7880 SpecializedSetup<cmds::%(name)s, 0>(true);
7881 cmds::%(name)s cmd;
7882 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7883 if func.IsUnsafe():
7884 valid_test += """
7885 decoder_->set_unsafe_es3_apis_enabled(true);"""
7886 valid_test += """
7887 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7888 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7889 if func.IsUnsafe():
7890 valid_test += """
7891 decoder_->set_unsafe_es3_apis_enabled(false);
7892 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7893 valid_test += """
7896 comma = ""
7897 if len(func.GetOriginalArgs()):
7898 comma =", "
7899 self.WriteValidUnitTest(func, file, valid_test, {
7900 'comma': comma,
7901 }, *extras)
7903 invalid_test = """
7904 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7905 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7906 SpecializedSetup<cmds::%(name)s, 0>(false);
7907 cmds::%(name)s cmd;
7908 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7909 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7912 self.WriteInvalidUnitTest(func, file, invalid_test, {
7913 'comma': comma,
7914 }, *extras)
7916 invalid_test = """
7917 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7918 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7919 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7920 if func.IsUnsafe():
7921 invalid_test += """
7922 decoder_->set_unsafe_es3_apis_enabled(true);"""
7923 invalid_test += """
7924 cmds::%(name)s cmd;
7925 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7926 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7927 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7928 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7929 if func.IsUnsafe():
7930 invalid_test += """
7931 decoder_->set_unsafe_es3_apis_enabled(true);"""
7932 invalid_test += """
7935 self.WriteValidUnitTest(func, file, invalid_test, {
7936 'comma': comma,
7937 }, *extras)
7939 def WriteServiceImplementation(self, func, file):
7940 """Overrriden from TypeHandler."""
7941 self.WriteServiceHandlerFunctionHeader(func, file)
7942 args = func.GetOriginalArgs()
7943 for arg in args:
7944 arg.WriteGetCode(file)
7946 code = """ typedef cmds::%(func_name)s::Result Result;
7947 Result* result_dst = GetSharedMemoryAs<Result*>(
7948 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7949 if (!result_dst) {
7950 return error::kOutOfBounds;
7953 file.Write(code % {'func_name': func.name})
7954 func.WriteHandlerValidation(file)
7955 if func.IsUnsafe():
7956 assert func.GetInfo('id_mapping')
7957 assert len(func.GetInfo('id_mapping')) == 1
7958 assert len(args) == 1
7959 id_type = func.GetInfo('id_mapping')[0]
7960 file.Write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
7961 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7962 (id_type, id_type.lower(), id_type.lower()))
7963 else:
7964 file.Write(" *result_dst = %s(%s);\n" %
7965 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
7966 file.Write(" return error::kNoError;\n")
7967 file.Write("}\n")
7968 file.Write("\n")
7970 def WriteGLES2Implementation(self, func, file):
7971 """Overrriden from TypeHandler."""
7972 impl_func = func.GetInfo('impl_func')
7973 if impl_func == None or impl_func == True:
7974 error_value = func.GetInfo("error_value") or "GL_FALSE"
7975 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7976 (func.return_type, func.original_name,
7977 func.MakeTypedOriginalArgString("")))
7978 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7979 self.WriteTraceEvent(func, file)
7980 func.WriteDestinationInitalizationValidation(file)
7981 self.WriteClientGLCallLog(func, file)
7982 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
7983 file.Write(" Result* result = GetResultAs<Result*>();\n")
7984 file.Write(" if (!result) {\n")
7985 file.Write(" return %s;\n" % error_value)
7986 file.Write(" }\n")
7987 file.Write(" *result = 0;\n")
7988 assert len(func.GetOriginalArgs()) == 1
7989 id_arg = func.GetOriginalArgs()[0]
7990 if id_arg.type == 'GLsync':
7991 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
7992 else:
7993 arg_string = func.MakeOriginalArgString("")
7994 file.Write(
7995 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7996 (func.name, arg_string))
7997 file.Write(" WaitForCmd();\n")
7998 file.Write(" %s result_value = *result" % func.return_type)
7999 if func.return_type == "GLboolean":
8000 file.Write(" != 0")
8001 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8002 file.Write(" CheckGLError();\n")
8003 file.Write(" return result_value;\n")
8004 file.Write("}\n")
8005 file.Write("\n")
8007 def WriteGLES2ImplementationUnitTest(self, func, file):
8008 """Overrriden from TypeHandler."""
8009 client_test = func.GetInfo('client_test')
8010 if client_test == None or client_test == True:
8011 code = """
8012 TEST_F(GLES2ImplementationTest, %(name)s) {
8013 struct Cmds {
8014 cmds::%(name)s cmd;
8017 Cmds expected;
8018 ExpectedMemoryInfo result1 =
8019 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8020 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8022 EXPECT_CALL(*command_buffer(), OnFlush())
8023 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8024 .RetiresOnSaturation();
8026 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8027 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8028 EXPECT_TRUE(result);
8031 args = func.GetOriginalArgs()
8032 assert len(args) == 1
8033 file.Write(code % {
8034 'name': func.name,
8035 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
8036 'gl_id_value': args[0].GetValidClientSideArg(func) })
8039 class STRnHandler(TypeHandler):
8040 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8041 GetTranslatedShaderSourceANGLE."""
8043 def __init__(self):
8044 TypeHandler.__init__(self)
8046 def InitFunction(self, func):
8047 """Overrriden from TypeHandler."""
8048 # remove all but the first cmd args.
8049 cmd_args = func.GetCmdArgs()
8050 func.ClearCmdArgs()
8051 func.AddCmdArg(cmd_args[0])
8052 # add on a bucket id.
8053 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8055 def WriteGLES2Implementation(self, func, file):
8056 """Overrriden from TypeHandler."""
8057 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8058 GPU_CLIENT_SINGLE_THREAD_CHECK();
8060 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8061 << "] gl%(func_name)s" << "("
8062 << %(arg0)s << ", "
8063 << %(arg1)s << ", "
8064 << static_cast<void*>(%(arg2)s) << ", "
8065 << static_cast<void*>(%(arg3)s) << ")");
8066 helper_->SetBucketSize(kResultBucketId, 0);
8067 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8068 std::string str;
8069 GLsizei max_size = 0;
8070 if (GetBucketAsString(kResultBucketId, &str)) {
8071 if (bufsize > 0) {
8072 max_size =
8073 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8074 memcpy(%(dest_name)s, str.c_str(), max_size);
8075 %(dest_name)s[max_size] = '\\0';
8076 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8079 if (%(length_name)s != NULL) {
8080 *%(length_name)s = max_size;
8082 CheckGLError();
8085 args = func.GetOriginalArgs()
8086 str_args = {
8087 'return_type': func.return_type,
8088 'func_name': func.original_name,
8089 'args': func.MakeTypedOriginalArgString(""),
8090 'id_name': args[0].name,
8091 'bufsize_name': args[1].name,
8092 'length_name': args[2].name,
8093 'dest_name': args[3].name,
8094 'arg0': args[0].name,
8095 'arg1': args[1].name,
8096 'arg2': args[2].name,
8097 'arg3': args[3].name,
8099 file.Write(code_1 % str_args)
8100 func.WriteDestinationInitalizationValidation(file)
8101 file.Write(code_2 % str_args)
8103 def WriteServiceUnitTest(self, func, file, *extras):
8104 """Overrriden from TypeHandler."""
8105 valid_test = """
8106 TEST_P(%(test_name)s, %(name)sValidArgs) {
8107 const char* kInfo = "hello";
8108 const uint32_t kBucketId = 123;
8109 SpecializedSetup<cmds::%(name)s, 0>(true);
8110 %(expect_len_code)s
8111 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8112 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8113 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8114 cmds::%(name)s cmd;
8115 cmd.Init(%(args)s);
8116 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8117 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8118 ASSERT_TRUE(bucket != NULL);
8119 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8120 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8121 bucket->size()));
8122 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8125 args = func.GetOriginalArgs()
8126 id_name = args[0].GetValidGLArg(func)
8127 get_len_func = func.GetInfo('get_len_func')
8128 get_len_enum = func.GetInfo('get_len_enum')
8129 sub = {
8130 'id_name': id_name,
8131 'get_len_func': get_len_func,
8132 'get_len_enum': get_len_enum,
8133 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8134 args[0].GetValidGLArg(func),
8135 'args': '%s, kBucketId' % args[0].GetValidArg(func),
8136 'expect_len_code': '',
8138 if get_len_func and get_len_func[0:2] == 'gl':
8139 sub['expect_len_code'] = (
8140 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8141 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8142 get_len_func[2:], id_name, get_len_enum)
8143 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
8145 invalid_test = """
8146 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8147 const uint32_t kBucketId = 123;
8148 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8149 .Times(0);
8150 cmds::%(name)s cmd;
8151 cmd.Init(kInvalidClientId, kBucketId);
8152 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8153 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8156 self.WriteValidUnitTest(func, file, invalid_test, *extras)
8158 def WriteServiceImplementation(self, func, file):
8159 """Overrriden from TypeHandler."""
8160 pass
8162 class NamedType(object):
8163 """A class that represents a type of an argument in a client function.
8165 A type of an argument that is to be passed through in the command buffer
8166 command. Currently used only for the arguments that are specificly named in
8167 the 'cmd_buffer_functions.txt' file, mostly enums.
8170 def __init__(self, info):
8171 assert not 'is_complete' in info or info['is_complete'] == True
8172 self.info = info
8173 self.valid = info['valid']
8174 if 'invalid' in info:
8175 self.invalid = info['invalid']
8176 else:
8177 self.invalid = []
8178 if 'valid_es3' in info:
8179 self.valid_es3 = info['valid_es3']
8180 else:
8181 self.valid_es3 = []
8182 if 'deprecated_es3' in info:
8183 self.deprecated_es3 = info['deprecated_es3']
8184 else:
8185 self.deprecated_es3 = []
8187 def GetType(self):
8188 return self.info['type']
8190 def GetInvalidValues(self):
8191 return self.invalid
8193 def GetValidValues(self):
8194 return self.valid
8196 def GetValidValuesES3(self):
8197 return self.valid_es3
8199 def GetDeprecatedValuesES3(self):
8200 return self.deprecated_es3
8202 def IsConstant(self):
8203 if not 'is_complete' in self.info:
8204 return False
8206 return len(self.GetValidValues()) == 1
8208 def GetConstantValue(self):
8209 return self.GetValidValues()[0]
8211 class Argument(object):
8212 """A class that represents a function argument."""
8214 cmd_type_map_ = {
8215 'GLenum': 'uint32_t',
8216 'GLint': 'int32_t',
8217 'GLintptr': 'int32_t',
8218 'GLsizei': 'int32_t',
8219 'GLsizeiptr': 'int32_t',
8220 'GLfloat': 'float',
8221 'GLclampf': 'float',
8223 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8225 def __init__(self, name, type):
8226 self.name = name
8227 self.optional = type.endswith("Optional*")
8228 if self.optional:
8229 type = type[:-9] + "*"
8230 self.type = type
8232 if type in self.cmd_type_map_:
8233 self.cmd_type = self.cmd_type_map_[type]
8234 else:
8235 self.cmd_type = 'uint32_t'
8237 def IsPointer(self):
8238 """Returns true if argument is a pointer."""
8239 return False
8241 def IsPointer2D(self):
8242 """Returns true if argument is a 2D pointer."""
8243 return False
8245 def IsConstant(self):
8246 """Returns true if the argument has only one valid value."""
8247 return False
8249 def AddCmdArgs(self, args):
8250 """Adds command arguments for this argument to the given list."""
8251 if not self.IsConstant():
8252 return args.append(self)
8254 def AddInitArgs(self, args):
8255 """Adds init arguments for this argument to the given list."""
8256 if not self.IsConstant():
8257 return args.append(self)
8259 def GetValidArg(self, func):
8260 """Gets a valid value for this argument."""
8261 valid_arg = func.GetValidArg(self)
8262 if valid_arg != None:
8263 return valid_arg
8265 index = func.GetOriginalArgs().index(self)
8266 return str(index + 1)
8268 def GetValidClientSideArg(self, func):
8269 """Gets a valid value for this argument."""
8270 valid_arg = func.GetValidArg(self)
8271 if valid_arg != None:
8272 return valid_arg
8274 if self.IsPointer():
8275 return 'nullptr'
8276 index = func.GetOriginalArgs().index(self)
8277 if self.type == 'GLsync':
8278 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
8279 return str(index + 1)
8281 def GetValidClientSideCmdArg(self, func):
8282 """Gets a valid value for this argument."""
8283 valid_arg = func.GetValidArg(self)
8284 if valid_arg != None:
8285 return valid_arg
8286 try:
8287 index = func.GetOriginalArgs().index(self)
8288 return str(index + 1)
8289 except ValueError:
8290 pass
8291 index = func.GetCmdArgs().index(self)
8292 return str(index + 1)
8294 def GetValidGLArg(self, func):
8295 """Gets a valid GL value for this argument."""
8296 value = self.GetValidArg(func)
8297 if self.type == 'GLsync':
8298 return ("reinterpret_cast<GLsync>(%s)" % value)
8299 return value
8301 def GetValidNonCachedClientSideArg(self, func):
8302 """Returns a valid value for this argument in a GL call.
8303 Using the value will produce a command buffer service invocation.
8304 Returns None if there is no such value."""
8305 value = '123'
8306 if self.type == 'GLsync':
8307 return ("reinterpret_cast<GLsync>(%s)" % value)
8308 return value
8310 def GetValidNonCachedClientSideCmdArg(self, func):
8311 """Returns a valid value for this argument in a command buffer command.
8312 Calling the GL function with the value returned by
8313 GetValidNonCachedClientSideArg will result in a command buffer command
8314 that contains the value returned by this function. """
8315 return '123'
8317 def GetNumInvalidValues(self, func):
8318 """returns the number of invalid values to be tested."""
8319 return 0
8321 def GetInvalidArg(self, index):
8322 """returns an invalid value and expected parse result by index."""
8323 return ("---ERROR0---", "---ERROR2---", None)
8325 def GetLogArg(self):
8326 """Get argument appropriate for LOG macro."""
8327 if self.type == 'GLboolean':
8328 return 'GLES2Util::GetStringBool(%s)' % self.name
8329 if self.type == 'GLenum':
8330 return 'GLES2Util::GetStringEnum(%s)' % self.name
8331 return self.name
8333 def WriteGetCode(self, file):
8334 """Writes the code to get an argument from a command structure."""
8335 if self.type == 'GLsync':
8336 my_type = 'GLuint'
8337 else:
8338 my_type = self.type
8339 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
8340 (my_type, self.name, my_type, self.name))
8342 def WriteValidationCode(self, file, func):
8343 """Writes the validation code for an argument."""
8344 pass
8346 def WriteClientSideValidationCode(self, file, func):
8347 """Writes the validation code for an argument."""
8348 pass
8350 def WriteDestinationInitalizationValidation(self, file, func):
8351 """Writes the client side destintion initialization validation."""
8352 pass
8354 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
8355 """Writes the client side destintion initialization validation if needed."""
8356 parts = self.type.split(" ")
8357 if len(parts) > 1:
8358 return
8359 if parts[0] in self.need_validation_:
8360 file.Write(
8361 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8362 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
8365 def WriteGetAddress(self, file):
8366 """Writes the code to get the address this argument refers to."""
8367 pass
8369 def GetImmediateVersion(self):
8370 """Gets the immediate version of this argument."""
8371 return self
8373 def GetBucketVersion(self):
8374 """Gets the bucket version of this argument."""
8375 return self
8378 class BoolArgument(Argument):
8379 """class for GLboolean"""
8381 def __init__(self, name, type):
8382 Argument.__init__(self, name, 'GLboolean')
8384 def GetValidArg(self, func):
8385 """Gets a valid value for this argument."""
8386 return 'true'
8388 def GetValidClientSideArg(self, func):
8389 """Gets a valid value for this argument."""
8390 return 'true'
8392 def GetValidClientSideCmdArg(self, func):
8393 """Gets a valid value for this argument."""
8394 return 'true'
8396 def GetValidGLArg(self, func):
8397 """Gets a valid GL value for this argument."""
8398 return 'true'
8401 class UniformLocationArgument(Argument):
8402 """class for uniform locations."""
8404 def __init__(self, name):
8405 Argument.__init__(self, name, "GLint")
8407 def WriteGetCode(self, file):
8408 """Writes the code to get an argument from a command structure."""
8409 code = """ %s %s = static_cast<%s>(c.%s);
8411 file.Write(code % (self.type, self.name, self.type, self.name))
8413 class DataSizeArgument(Argument):
8414 """class for data_size which Bucket commands do not need."""
8416 def __init__(self, name):
8417 Argument.__init__(self, name, "uint32_t")
8419 def GetBucketVersion(self):
8420 return None
8423 class SizeArgument(Argument):
8424 """class for GLsizei and GLsizeiptr."""
8426 def __init__(self, name, type):
8427 Argument.__init__(self, name, type)
8429 def GetNumInvalidValues(self, func):
8430 """overridden from Argument."""
8431 if func.IsImmediate():
8432 return 0
8433 return 1
8435 def GetInvalidArg(self, index):
8436 """overridden from Argument."""
8437 return ("-1", "kNoError", "GL_INVALID_VALUE")
8439 def WriteValidationCode(self, file, func):
8440 """overridden from Argument."""
8441 if func.IsUnsafe():
8442 return
8443 code = """ if (%(var_name)s < 0) {
8444 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8445 return error::kNoError;
8448 file.Write(code % {
8449 "var_name": self.name,
8450 "func_name": func.original_name,
8453 def WriteClientSideValidationCode(self, file, func):
8454 """overridden from Argument."""
8455 code = """ if (%(var_name)s < 0) {
8456 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8457 return;
8460 file.Write(code % {
8461 "var_name": self.name,
8462 "func_name": func.original_name,
8466 class SizeNotNegativeArgument(SizeArgument):
8467 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8469 def __init__(self, name, type, gl_type):
8470 SizeArgument.__init__(self, name, gl_type)
8472 def GetInvalidArg(self, index):
8473 """overridden from SizeArgument."""
8474 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8476 def WriteValidationCode(self, file, func):
8477 """overridden from SizeArgument."""
8478 pass
8481 class EnumBaseArgument(Argument):
8482 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8483 ValidatedBoolArgument."""
8485 def __init__(self, name, gl_type, type, gl_error):
8486 Argument.__init__(self, name, gl_type)
8488 self.local_type = type
8489 self.gl_error = gl_error
8490 name = type[len(gl_type):]
8491 self.type_name = name
8492 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8494 def IsConstant(self):
8495 return self.named_type.IsConstant()
8497 def GetConstantValue(self):
8498 return self.named_type.GetConstantValue()
8500 def WriteValidationCode(self, file, func):
8501 if func.IsUnsafe():
8502 return
8503 if self.named_type.IsConstant():
8504 return
8505 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8506 (ToUnderscore(self.type_name), self.name))
8507 if self.gl_error == "GL_INVALID_ENUM":
8508 file.Write(
8509 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8510 (func.original_name, self.name, self.name))
8511 else:
8512 file.Write(
8513 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8514 (self.gl_error, func.original_name, self.name, self.gl_error))
8515 file.Write(" return error::kNoError;\n")
8516 file.Write(" }\n")
8518 def WriteClientSideValidationCode(self, file, func):
8519 if not self.named_type.IsConstant():
8520 return
8521 file.Write(" if (%s != %s) {" % (self.name,
8522 self.GetConstantValue()))
8523 file.Write(
8524 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8525 (self.gl_error, func.original_name, self.name, self.gl_error))
8526 if func.return_type == "void":
8527 file.Write(" return;\n")
8528 else:
8529 file.Write(" return %s;\n" % func.GetErrorReturnString())
8530 file.Write(" }\n")
8532 def GetValidArg(self, func):
8533 valid_arg = func.GetValidArg(self)
8534 if valid_arg != None:
8535 return valid_arg
8536 valid = self.named_type.GetValidValues()
8537 if valid:
8538 num_valid = len(valid)
8539 return valid[0]
8541 index = func.GetOriginalArgs().index(self)
8542 return str(index + 1)
8544 def GetValidClientSideArg(self, func):
8545 """Gets a valid value for this argument."""
8546 return self.GetValidArg(func)
8548 def GetValidClientSideCmdArg(self, func):
8549 """Gets a valid value for this argument."""
8550 valid_arg = func.GetValidArg(self)
8551 if valid_arg != None:
8552 return valid_arg
8554 valid = self.named_type.GetValidValues()
8555 if valid:
8556 num_valid = len(valid)
8557 return valid[0]
8559 try:
8560 index = func.GetOriginalArgs().index(self)
8561 return str(index + 1)
8562 except ValueError:
8563 pass
8564 index = func.GetCmdArgs().index(self)
8565 return str(index + 1)
8567 def GetValidGLArg(self, func):
8568 """Gets a valid value for this argument."""
8569 return self.GetValidArg(func)
8571 def GetNumInvalidValues(self, func):
8572 """returns the number of invalid values to be tested."""
8573 return len(self.named_type.GetInvalidValues())
8575 def GetInvalidArg(self, index):
8576 """returns an invalid value by index."""
8577 invalid = self.named_type.GetInvalidValues()
8578 if invalid:
8579 num_invalid = len(invalid)
8580 if index >= num_invalid:
8581 index = num_invalid - 1
8582 return (invalid[index], "kNoError", self.gl_error)
8583 return ("---ERROR1---", "kNoError", self.gl_error)
8586 class EnumArgument(EnumBaseArgument):
8587 """A class that represents a GLenum argument"""
8589 def __init__(self, name, type):
8590 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8592 def GetLogArg(self):
8593 """Overridden from Argument."""
8594 return ("GLES2Util::GetString%s(%s)" %
8595 (self.type_name, self.name))
8598 class IntArgument(EnumBaseArgument):
8599 """A class for a GLint argument that can only accept specific values.
8601 For example glTexImage2D takes a GLint for its internalformat
8602 argument instead of a GLenum.
8605 def __init__(self, name, type):
8606 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8609 class ValidatedBoolArgument(EnumBaseArgument):
8610 """A class for a GLboolean argument that can only accept specific values.
8612 For example glUniformMatrix takes a GLboolean for it's transpose but it
8613 must be false.
8616 def __init__(self, name, type):
8617 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8619 def GetLogArg(self):
8620 """Overridden from Argument."""
8621 return 'GLES2Util::GetStringBool(%s)' % self.name
8624 class BitFieldArgument(EnumBaseArgument):
8625 """A class for a GLbitfield argument that can only accept specific values.
8627 For example glFenceSync takes a GLbitfield for its flags argument bit it
8628 must be 0.
8631 def __init__(self, name, type):
8632 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8633 "GL_INVALID_VALUE")
8636 class ImmediatePointerArgument(Argument):
8637 """A class that represents an immediate argument to a function.
8639 An immediate argument is one where the data follows the command.
8642 def __init__(self, name, type):
8643 Argument.__init__(self, name, type)
8645 def IsPointer(self):
8646 return True
8648 def GetPointedType(self):
8649 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8650 assert match
8651 return match.groupdict()['element_type']
8653 def AddCmdArgs(self, args):
8654 """Overridden from Argument."""
8655 pass
8657 def WriteGetCode(self, file):
8658 """Overridden from Argument."""
8659 file.Write(
8660 " %s %s = GetImmediateDataAs<%s>(\n" %
8661 (self.type, self.name, self.type))
8662 file.Write(" c, data_size, immediate_data_size);\n")
8664 def WriteValidationCode(self, file, func):
8665 """Overridden from Argument."""
8666 if self.optional:
8667 return
8668 file.Write(" if (%s == NULL) {\n" % self.name)
8669 file.Write(" return error::kOutOfBounds;\n")
8670 file.Write(" }\n")
8672 def GetImmediateVersion(self):
8673 """Overridden from Argument."""
8674 return None
8676 def WriteDestinationInitalizationValidation(self, file, func):
8677 """Overridden from Argument."""
8678 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8680 def GetLogArg(self):
8681 """Overridden from Argument."""
8682 return "static_cast<const void*>(%s)" % self.name
8685 class PointerArgument(Argument):
8686 """A class that represents a pointer argument to a function."""
8688 def __init__(self, name, type):
8689 Argument.__init__(self, name, type)
8691 def IsPointer(self):
8692 """Overridden from Argument."""
8693 return True
8695 def IsPointer2D(self):
8696 """Overridden from Argument."""
8697 return self.type.count('*') == 2
8699 def GetPointedType(self):
8700 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8701 assert match
8702 return match.groupdict()['element_type']
8704 def GetValidArg(self, func):
8705 """Overridden from Argument."""
8706 return "shared_memory_id_, shared_memory_offset_"
8708 def GetValidGLArg(self, func):
8709 """Overridden from Argument."""
8710 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8712 def GetNumInvalidValues(self, func):
8713 """Overridden from Argument."""
8714 return 2
8716 def GetInvalidArg(self, index):
8717 """Overridden from Argument."""
8718 if index == 0:
8719 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8720 else:
8721 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8722 "kOutOfBounds", None)
8724 def GetLogArg(self):
8725 """Overridden from Argument."""
8726 return "static_cast<const void*>(%s)" % self.name
8728 def AddCmdArgs(self, args):
8729 """Overridden from Argument."""
8730 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8731 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8733 def WriteGetCode(self, file):
8734 """Overridden from Argument."""
8735 file.Write(
8736 " %s %s = GetSharedMemoryAs<%s>(\n" %
8737 (self.type, self.name, self.type))
8738 file.Write(
8739 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8740 (self.name, self.name))
8742 def WriteGetAddress(self, file):
8743 """Overridden from Argument."""
8744 file.Write(
8745 " %s %s = GetSharedMemoryAs<%s>(\n" %
8746 (self.type, self.name, self.type))
8747 file.Write(
8748 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8749 (self.name, self.name, self.name))
8751 def WriteValidationCode(self, file, func):
8752 """Overridden from Argument."""
8753 if self.optional:
8754 return
8755 file.Write(" if (%s == NULL) {\n" % self.name)
8756 file.Write(" return error::kOutOfBounds;\n")
8757 file.Write(" }\n")
8759 def GetImmediateVersion(self):
8760 """Overridden from Argument."""
8761 return ImmediatePointerArgument(self.name, self.type)
8763 def GetBucketVersion(self):
8764 """Overridden from Argument."""
8765 if self.type.find('char') >= 0:
8766 if self.IsPointer2D():
8767 return InputStringArrayBucketArgument(self.name, self.type)
8768 return InputStringBucketArgument(self.name, self.type)
8769 return BucketPointerArgument(self.name, self.type)
8771 def WriteDestinationInitalizationValidation(self, file, func):
8772 """Overridden from Argument."""
8773 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8776 class BucketPointerArgument(PointerArgument):
8777 """A class that represents an bucket argument to a function."""
8779 def __init__(self, name, type):
8780 Argument.__init__(self, name, type)
8782 def AddCmdArgs(self, args):
8783 """Overridden from Argument."""
8784 pass
8786 def WriteGetCode(self, file):
8787 """Overridden from Argument."""
8788 file.Write(
8789 " %s %s = bucket->GetData(0, data_size);\n" %
8790 (self.type, self.name))
8792 def WriteValidationCode(self, file, func):
8793 """Overridden from Argument."""
8794 pass
8796 def GetImmediateVersion(self):
8797 """Overridden from Argument."""
8798 return None
8800 def WriteDestinationInitalizationValidation(self, file, func):
8801 """Overridden from Argument."""
8802 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8804 def GetLogArg(self):
8805 """Overridden from Argument."""
8806 return "static_cast<const void*>(%s)" % self.name
8809 class InputStringBucketArgument(Argument):
8810 """A string input argument where the string is passed in a bucket."""
8812 def __init__(self, name, type):
8813 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8815 def IsPointer(self):
8816 """Overridden from Argument."""
8817 return True
8819 def IsPointer2D(self):
8820 """Overridden from Argument."""
8821 return False
8824 class InputStringArrayBucketArgument(Argument):
8825 """A string array input argument where the strings are passed in a bucket."""
8827 def __init__(self, name, type):
8828 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8829 self._original_name = name
8831 def WriteGetCode(self, file):
8832 """Overridden from Argument."""
8833 code = """
8834 Bucket* bucket = GetBucket(c.%(name)s);
8835 if (!bucket) {
8836 return error::kInvalidArguments;
8838 GLsizei count = 0;
8839 std::vector<char*> strs;
8840 std::vector<GLint> len;
8841 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8842 return error::kInvalidArguments;
8844 const char** %(original_name)s =
8845 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8846 const GLint* length =
8847 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8848 (void)length;
8850 file.Write(code % {
8851 'name': self.name,
8852 'original_name': self._original_name,
8855 def GetValidArg(self, func):
8856 return "kNameBucketId"
8858 def GetValidGLArg(self, func):
8859 return "_"
8861 def IsPointer(self):
8862 """Overridden from Argument."""
8863 return True
8865 def IsPointer2D(self):
8866 """Overridden from Argument."""
8867 return True
8870 class ResourceIdArgument(Argument):
8871 """A class that represents a resource id argument to a function."""
8873 def __init__(self, name, type):
8874 match = re.match("(GLid\w+)", type)
8875 self.resource_type = match.group(1)[4:]
8876 if self.resource_type == "Sync":
8877 type = type.replace(match.group(1), "GLsync")
8878 else:
8879 type = type.replace(match.group(1), "GLuint")
8880 Argument.__init__(self, name, type)
8882 def WriteGetCode(self, file):
8883 """Overridden from Argument."""
8884 if self.type == "GLsync":
8885 my_type = "GLuint"
8886 else:
8887 my_type = self.type
8888 file.Write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8890 def GetValidArg(self, func):
8891 return "client_%s_id_" % self.resource_type.lower()
8893 def GetValidGLArg(self, func):
8894 if self.resource_type == "Sync":
8895 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8896 return "kService%sId" % self.resource_type
8899 class ResourceIdBindArgument(Argument):
8900 """Represents a resource id argument to a bind function."""
8902 def __init__(self, name, type):
8903 match = re.match("(GLidBind\w+)", type)
8904 self.resource_type = match.group(1)[8:]
8905 type = type.replace(match.group(1), "GLuint")
8906 Argument.__init__(self, name, type)
8908 def WriteGetCode(self, file):
8909 """Overridden from Argument."""
8910 code = """ %(type)s %(name)s = c.%(name)s;
8912 file.Write(code % {'type': self.type, 'name': self.name})
8914 def GetValidArg(self, func):
8915 return "client_%s_id_" % self.resource_type.lower()
8917 def GetValidGLArg(self, func):
8918 return "kService%sId" % self.resource_type
8921 class ResourceIdZeroArgument(Argument):
8922 """Represents a resource id argument to a function that can be zero."""
8924 def __init__(self, name, type):
8925 match = re.match("(GLidZero\w+)", type)
8926 self.resource_type = match.group(1)[8:]
8927 type = type.replace(match.group(1), "GLuint")
8928 Argument.__init__(self, name, type)
8930 def WriteGetCode(self, file):
8931 """Overridden from Argument."""
8932 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
8934 def GetValidArg(self, func):
8935 return "client_%s_id_" % self.resource_type.lower()
8937 def GetValidGLArg(self, func):
8938 return "kService%sId" % self.resource_type
8940 def GetNumInvalidValues(self, func):
8941 """returns the number of invalid values to be tested."""
8942 return 1
8944 def GetInvalidArg(self, index):
8945 """returns an invalid value by index."""
8946 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8949 class Function(object):
8950 """A class that represents a function."""
8952 type_handlers = {
8953 '': TypeHandler(),
8954 'Bind': BindHandler(),
8955 'Create': CreateHandler(),
8956 'Custom': CustomHandler(),
8957 'Data': DataHandler(),
8958 'Delete': DeleteHandler(),
8959 'DELn': DELnHandler(),
8960 'GENn': GENnHandler(),
8961 'GETn': GETnHandler(),
8962 'GLchar': GLcharHandler(),
8963 'GLcharN': GLcharNHandler(),
8964 'HandWritten': HandWrittenHandler(),
8965 'Is': IsHandler(),
8966 'Manual': ManualHandler(),
8967 'PUT': PUTHandler(),
8968 'PUTn': PUTnHandler(),
8969 'PUTSTR': PUTSTRHandler(),
8970 'PUTXn': PUTXnHandler(),
8971 'StateSet': StateSetHandler(),
8972 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8973 'StateSetFrontBack': StateSetFrontBackHandler(),
8974 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8975 'StateSetNamedParameter': StateSetNamedParameter(),
8976 'STRn': STRnHandler(),
8977 'Todo': TodoHandler(),
8980 def __init__(self, name, info):
8981 self.name = name
8982 self.original_name = info['original_name']
8984 self.original_args = self.ParseArgs(info['original_args'])
8986 if 'cmd_args' in info:
8987 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
8988 else:
8989 self.args_for_cmds = self.original_args[:]
8991 self.return_type = info['return_type']
8992 if self.return_type != 'void':
8993 self.return_arg = CreateArg(info['return_type'] + " result")
8994 else:
8995 self.return_arg = None
8997 self.num_pointer_args = sum(
8998 [1 for arg in self.args_for_cmds if arg.IsPointer()])
8999 if self.num_pointer_args > 0:
9000 for arg in reversed(self.original_args):
9001 if arg.IsPointer():
9002 self.last_original_pointer_arg = arg
9003 break
9004 else:
9005 self.last_original_pointer_arg = None
9006 self.info = info
9007 self.type_handler = self.type_handlers[info['type']]
9008 self.can_auto_generate = (self.num_pointer_args == 0 and
9009 info['return_type'] == "void")
9010 self.InitFunction()
9012 def ParseArgs(self, arg_string):
9013 """Parses a function arg string."""
9014 args = []
9015 parts = arg_string.split(',')
9016 for arg_string in parts:
9017 arg = CreateArg(arg_string)
9018 if arg:
9019 args.append(arg)
9020 return args
9022 def IsType(self, type_name):
9023 """Returns true if function is a certain type."""
9024 return self.info['type'] == type_name
9026 def InitFunction(self):
9027 """Creates command args and calls the init function for the type handler.
9029 Creates argument lists for command buffer commands, eg. self.cmd_args and
9030 self.init_args.
9031 Calls the type function initialization.
9032 Override to create different kind of command buffer command argument lists.
9034 self.cmd_args = []
9035 for arg in self.args_for_cmds:
9036 arg.AddCmdArgs(self.cmd_args)
9038 self.init_args = []
9039 for arg in self.args_for_cmds:
9040 arg.AddInitArgs(self.init_args)
9042 if self.return_arg:
9043 self.init_args.append(self.return_arg)
9045 self.type_handler.InitFunction(self)
9047 def IsImmediate(self):
9048 """Returns whether the function is immediate data function or not."""
9049 return False
9051 def IsUnsafe(self):
9052 """Returns whether the function has service side validation or not."""
9053 return self.GetInfo('unsafe', False)
9055 def GetInfo(self, name, default = None):
9056 """Returns a value from the function info for this function."""
9057 if name in self.info:
9058 return self.info[name]
9059 return default
9061 def GetValidArg(self, arg):
9062 """Gets a valid argument value for the parameter arg from the function info
9063 if one exists."""
9064 try:
9065 index = self.GetOriginalArgs().index(arg)
9066 except ValueError:
9067 return None
9069 valid_args = self.GetInfo('valid_args')
9070 if valid_args and str(index) in valid_args:
9071 return valid_args[str(index)]
9072 return None
9074 def AddInfo(self, name, value):
9075 """Adds an info."""
9076 self.info[name] = value
9078 def IsExtension(self):
9079 return self.GetInfo('extension') or self.GetInfo('extension_flag')
9081 def IsCoreGLFunction(self):
9082 return (not self.IsExtension() and
9083 not self.GetInfo('pepper_interface') and
9084 not self.IsUnsafe())
9086 def InPepperInterface(self, interface):
9087 ext = self.GetInfo('pepper_interface')
9088 if not interface.GetName():
9089 return self.IsCoreGLFunction()
9090 return ext == interface.GetName()
9092 def InAnyPepperExtension(self):
9093 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
9095 def GetErrorReturnString(self):
9096 if self.GetInfo("error_return"):
9097 return self.GetInfo("error_return")
9098 elif self.return_type == "GLboolean":
9099 return "GL_FALSE"
9100 elif "*" in self.return_type:
9101 return "NULL"
9102 return "0"
9104 def GetGLFunctionName(self):
9105 """Gets the function to call to execute GL for this command."""
9106 if self.GetInfo('decoder_func'):
9107 return self.GetInfo('decoder_func')
9108 return "gl%s" % self.original_name
9110 def GetGLTestFunctionName(self):
9111 gl_func_name = self.GetInfo('gl_test_func')
9112 if gl_func_name == None:
9113 gl_func_name = self.GetGLFunctionName()
9114 if gl_func_name.startswith("gl"):
9115 gl_func_name = gl_func_name[2:]
9116 else:
9117 gl_func_name = self.original_name
9118 return gl_func_name
9120 def GetDataTransferMethods(self):
9121 return self.GetInfo('data_transfer_methods',
9122 ['immediate' if self.num_pointer_args == 1 else 'shm'])
9124 def AddCmdArg(self, arg):
9125 """Adds a cmd argument to this function."""
9126 self.cmd_args.append(arg)
9128 def GetCmdArgs(self):
9129 """Gets the command args for this function."""
9130 return self.cmd_args
9132 def ClearCmdArgs(self):
9133 """Clears the command args for this function."""
9134 self.cmd_args = []
9136 def GetCmdConstants(self):
9137 """Gets the constants for this function."""
9138 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
9140 def GetInitArgs(self):
9141 """Gets the init args for this function."""
9142 return self.init_args
9144 def GetOriginalArgs(self):
9145 """Gets the original arguments to this function."""
9146 return self.original_args
9148 def GetLastOriginalArg(self):
9149 """Gets the last original argument to this function."""
9150 return self.original_args[len(self.original_args) - 1]
9152 def GetLastOriginalPointerArg(self):
9153 return self.last_original_pointer_arg
9155 def GetResourceIdArg(self):
9156 for arg in self.original_args:
9157 if hasattr(arg, 'resource_type'):
9158 return arg
9159 return None
9161 def _MaybePrependComma(self, arg_string, add_comma):
9162 """Adds a comma if arg_string is not empty and add_comma is true."""
9163 comma = ""
9164 if add_comma and len(arg_string):
9165 comma = ", "
9166 return "%s%s" % (comma, arg_string)
9168 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
9169 """Gets a list of arguments as they are in GL."""
9170 args = self.GetOriginalArgs()
9171 arg_string = ", ".join(
9172 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9173 return self._MaybePrependComma(arg_string, add_comma)
9175 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9176 """Gets the list of arguments as they are in GL."""
9177 args = self.GetOriginalArgs()
9178 arg_string = separator.join(
9179 ["%s%s" % (prefix, arg.name) for arg in args])
9180 return self._MaybePrependComma(arg_string, add_comma)
9182 def MakeTypedHelperArgString(self, prefix, add_comma = False):
9183 """Gets a list of typed GL arguments after removing unneeded arguments."""
9184 args = self.GetOriginalArgs()
9185 arg_string = ", ".join(
9186 ["%s %s%s" % (
9187 arg.type,
9188 prefix,
9189 arg.name,
9190 ) for arg in args if not arg.IsConstant()])
9191 return self._MaybePrependComma(arg_string, add_comma)
9193 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
9194 """Gets a list of GL arguments after removing unneeded arguments."""
9195 args = self.GetOriginalArgs()
9196 arg_string = separator.join(
9197 ["%s%s" % (prefix, arg.name)
9198 for arg in args if not arg.IsConstant()])
9199 return self._MaybePrependComma(arg_string, add_comma)
9201 def MakeTypedPepperArgString(self, prefix):
9202 """Gets a list of arguments as they need to be for Pepper."""
9203 if self.GetInfo("pepper_args"):
9204 return self.GetInfo("pepper_args")
9205 else:
9206 return self.MakeTypedOriginalArgString(prefix, False)
9208 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
9209 """Converts a C type name to the corresponding Pepper IDL type."""
9210 idltype = {
9211 'char*': '[out] str_t',
9212 'const GLchar* const*': '[out] cstr_t',
9213 'const char*': 'cstr_t',
9214 'const void*': 'mem_t',
9215 'void*': '[out] mem_t',
9216 'void**': '[out] mem_ptr_t',
9217 }.get(ctype, ctype)
9218 # We use "GLxxx_ptr_t" for "GLxxx*".
9219 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
9220 if matched:
9221 idltype = matched.group(2) + '_ptr_t'
9222 if not matched.group(1):
9223 idltype = '[out] ' + idltype
9224 # If an in/out specifier is not specified yet, prepend [in].
9225 if idltype[0] != '[':
9226 idltype = '[in] ' + idltype
9227 # Strip the in/out specifier for a return type.
9228 if is_for_return_type:
9229 idltype = re.sub(r'\[\w+\] ', '', idltype)
9230 return idltype
9232 def MakeTypedPepperIdlArgStrings(self):
9233 """Gets a list of arguments as they need to be for Pepper IDL."""
9234 args = self.GetOriginalArgs()
9235 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
9236 for arg in args]
9238 def GetPepperName(self):
9239 if self.GetInfo("pepper_name"):
9240 return self.GetInfo("pepper_name")
9241 return self.name
9243 def MakeTypedCmdArgString(self, prefix, add_comma = False):
9244 """Gets a typed list of arguments as they need to be for command buffers."""
9245 args = self.GetCmdArgs()
9246 arg_string = ", ".join(
9247 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9248 return self._MaybePrependComma(arg_string, add_comma)
9250 def MakeCmdArgString(self, prefix, add_comma = False):
9251 """Gets the list of arguments as they need to be for command buffers."""
9252 args = self.GetCmdArgs()
9253 arg_string = ", ".join(
9254 ["%s%s" % (prefix, arg.name) for arg in args])
9255 return self._MaybePrependComma(arg_string, add_comma)
9257 def MakeTypedInitString(self, prefix, add_comma = False):
9258 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9259 args = self.GetInitArgs()
9260 arg_string = ", ".join(
9261 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9262 return self._MaybePrependComma(arg_string, add_comma)
9264 def MakeInitString(self, prefix, add_comma = False):
9265 """Gets the list of arguments as they need to be for cmd Init/Set."""
9266 args = self.GetInitArgs()
9267 arg_string = ", ".join(
9268 ["%s%s" % (prefix, arg.name) for arg in args])
9269 return self._MaybePrependComma(arg_string, add_comma)
9271 def MakeLogArgString(self):
9272 """Makes a string of the arguments for the LOG macros"""
9273 args = self.GetOriginalArgs()
9274 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
9276 def WriteCommandDescription(self, file):
9277 """Writes a description of the command."""
9278 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
9280 def WriteHandlerValidation(self, file):
9281 """Writes validation code for the function."""
9282 for arg in self.GetOriginalArgs():
9283 arg.WriteValidationCode(file, self)
9284 self.WriteValidationCode(file)
9286 def WriteHandlerImplementation(self, file):
9287 """Writes the handler implementation for this command."""
9288 self.type_handler.WriteHandlerImplementation(self, file)
9290 def WriteValidationCode(self, file):
9291 """Writes the validation code for a command."""
9292 pass
9294 def WriteCmdFlag(self, file):
9295 """Writes the cmd cmd_flags constant."""
9296 flags = []
9297 # By default trace only at the highest level 3.
9298 trace_level = int(self.GetInfo('trace_level', default = 3))
9299 if trace_level not in xrange(0, 4):
9300 raise KeyError("Unhandled trace_level: %d" % trace_level)
9302 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
9304 if len(flags) > 0:
9305 cmd_flags = ' | '.join(flags)
9306 else:
9307 cmd_flags = 0
9309 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
9312 def WriteCmdArgFlag(self, file):
9313 """Writes the cmd kArgFlags constant."""
9314 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9316 def WriteCmdComputeSize(self, file):
9317 """Writes the ComputeSize function for the command."""
9318 file.Write(" static uint32_t ComputeSize() {\n")
9319 file.Write(
9320 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9321 file.Write(" }\n")
9322 file.Write("\n")
9324 def WriteCmdSetHeader(self, file):
9325 """Writes the cmd's SetHeader function."""
9326 file.Write(" void SetHeader() {\n")
9327 file.Write(" header.SetCmd<ValueType>();\n")
9328 file.Write(" }\n")
9329 file.Write("\n")
9331 def WriteCmdInit(self, file):
9332 """Writes the cmd's Init function."""
9333 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
9334 file.Write(" SetHeader();\n")
9335 args = self.GetCmdArgs()
9336 for arg in args:
9337 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
9338 file.Write(" }\n")
9339 file.Write("\n")
9341 def WriteCmdSet(self, file):
9342 """Writes the cmd's Set function."""
9343 copy_args = self.MakeCmdArgString("_", False)
9344 file.Write(" void* Set(void* cmd%s) {\n" %
9345 self.MakeTypedCmdArgString("_", True))
9346 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
9347 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
9348 file.Write(" }\n")
9349 file.Write("\n")
9351 def WriteStruct(self, file):
9352 self.type_handler.WriteStruct(self, file)
9354 def WriteDocs(self, file):
9355 self.type_handler.WriteDocs(self, file)
9357 def WriteCmdHelper(self, file):
9358 """Writes the cmd's helper."""
9359 self.type_handler.WriteCmdHelper(self, file)
9361 def WriteServiceImplementation(self, file):
9362 """Writes the service implementation for a command."""
9363 self.type_handler.WriteServiceImplementation(self, file)
9365 def WriteServiceUnitTest(self, file, *extras):
9366 """Writes the service implementation for a command."""
9367 self.type_handler.WriteServiceUnitTest(self, file, *extras)
9369 def WriteGLES2CLibImplementation(self, file):
9370 """Writes the GLES2 C Lib Implemention."""
9371 self.type_handler.WriteGLES2CLibImplementation(self, file)
9373 def WriteGLES2InterfaceHeader(self, file):
9374 """Writes the GLES2 Interface declaration."""
9375 self.type_handler.WriteGLES2InterfaceHeader(self, file)
9377 def WriteMojoGLES2ImplHeader(self, file):
9378 """Writes the Mojo GLES2 implementation header declaration."""
9379 self.type_handler.WriteMojoGLES2ImplHeader(self, file)
9381 def WriteMojoGLES2Impl(self, file):
9382 """Writes the Mojo GLES2 implementation declaration."""
9383 self.type_handler.WriteMojoGLES2Impl(self, file)
9385 def WriteGLES2InterfaceStub(self, file):
9386 """Writes the GLES2 Interface Stub declaration."""
9387 self.type_handler.WriteGLES2InterfaceStub(self, file)
9389 def WriteGLES2InterfaceStubImpl(self, file):
9390 """Writes the GLES2 Interface Stub declaration."""
9391 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
9393 def WriteGLES2ImplementationHeader(self, file):
9394 """Writes the GLES2 Implemention declaration."""
9395 self.type_handler.WriteGLES2ImplementationHeader(self, file)
9397 def WriteGLES2Implementation(self, file):
9398 """Writes the GLES2 Implemention definition."""
9399 self.type_handler.WriteGLES2Implementation(self, file)
9401 def WriteGLES2TraceImplementationHeader(self, file):
9402 """Writes the GLES2 Trace Implemention declaration."""
9403 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
9405 def WriteGLES2TraceImplementation(self, file):
9406 """Writes the GLES2 Trace Implemention definition."""
9407 self.type_handler.WriteGLES2TraceImplementation(self, file)
9409 def WriteGLES2Header(self, file):
9410 """Writes the GLES2 Implemention unit test."""
9411 self.type_handler.WriteGLES2Header(self, file)
9413 def WriteGLES2ImplementationUnitTest(self, file):
9414 """Writes the GLES2 Implemention unit test."""
9415 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
9417 def WriteDestinationInitalizationValidation(self, file):
9418 """Writes the client side destintion initialization validation."""
9419 self.type_handler.WriteDestinationInitalizationValidation(self, file)
9421 def WriteFormatTest(self, file):
9422 """Writes the cmd's format test."""
9423 self.type_handler.WriteFormatTest(self, file)
9426 class PepperInterface(object):
9427 """A class that represents a function."""
9429 def __init__(self, info):
9430 self.name = info["name"]
9431 self.dev = info["dev"]
9433 def GetName(self):
9434 return self.name
9436 def GetInterfaceName(self):
9437 upperint = ""
9438 dev = ""
9439 if self.name:
9440 upperint = "_" + self.name.upper()
9441 if self.dev:
9442 dev = "_DEV"
9443 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9445 def GetInterfaceString(self):
9446 dev = ""
9447 if self.dev:
9448 dev = "(Dev)"
9449 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9451 def GetStructName(self):
9452 dev = ""
9453 if self.dev:
9454 dev = "_Dev"
9455 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9458 class ImmediateFunction(Function):
9459 """A class that represnets an immediate function command."""
9461 def __init__(self, func):
9462 Function.__init__(
9463 self,
9464 "%sImmediate" % func.name,
9465 func.info)
9467 def InitFunction(self):
9468 # Override args in original_args and args_for_cmds with immediate versions
9469 # of the args.
9471 new_original_args = []
9472 for arg in self.original_args:
9473 new_arg = arg.GetImmediateVersion()
9474 if new_arg:
9475 new_original_args.append(new_arg)
9476 self.original_args = new_original_args
9478 new_args_for_cmds = []
9479 for arg in self.args_for_cmds:
9480 new_arg = arg.GetImmediateVersion()
9481 if new_arg:
9482 new_args_for_cmds.append(new_arg)
9484 self.args_for_cmds = new_args_for_cmds
9486 Function.InitFunction(self)
9488 def IsImmediate(self):
9489 return True
9491 def WriteCommandDescription(self, file):
9492 """Overridden from Function"""
9493 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9494 self.original_name)
9496 def WriteServiceImplementation(self, file):
9497 """Overridden from Function"""
9498 self.type_handler.WriteImmediateServiceImplementation(self, file)
9500 def WriteHandlerImplementation(self, file):
9501 """Overridden from Function"""
9502 self.type_handler.WriteImmediateHandlerImplementation(self, file)
9504 def WriteServiceUnitTest(self, file, *extras):
9505 """Writes the service implementation for a command."""
9506 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
9508 def WriteValidationCode(self, file):
9509 """Overridden from Function"""
9510 self.type_handler.WriteImmediateValidationCode(self, file)
9512 def WriteCmdArgFlag(self, file):
9513 """Overridden from Function"""
9514 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9516 def WriteCmdComputeSize(self, file):
9517 """Overridden from Function"""
9518 self.type_handler.WriteImmediateCmdComputeSize(self, file)
9520 def WriteCmdSetHeader(self, file):
9521 """Overridden from Function"""
9522 self.type_handler.WriteImmediateCmdSetHeader(self, file)
9524 def WriteCmdInit(self, file):
9525 """Overridden from Function"""
9526 self.type_handler.WriteImmediateCmdInit(self, file)
9528 def WriteCmdSet(self, file):
9529 """Overridden from Function"""
9530 self.type_handler.WriteImmediateCmdSet(self, file)
9532 def WriteCmdHelper(self, file):
9533 """Overridden from Function"""
9534 self.type_handler.WriteImmediateCmdHelper(self, file)
9536 def WriteFormatTest(self, file):
9537 """Overridden from Function"""
9538 self.type_handler.WriteImmediateFormatTest(self, file)
9541 class BucketFunction(Function):
9542 """A class that represnets a bucket version of a function command."""
9544 def __init__(self, func):
9545 Function.__init__(
9546 self,
9547 "%sBucket" % func.name,
9548 func.info)
9550 def InitFunction(self):
9551 # Override args in original_args and args_for_cmds with bucket versions
9552 # of the args.
9554 new_original_args = []
9555 for arg in self.original_args:
9556 new_arg = arg.GetBucketVersion()
9557 if new_arg:
9558 new_original_args.append(new_arg)
9559 self.original_args = new_original_args
9561 new_args_for_cmds = []
9562 for arg in self.args_for_cmds:
9563 new_arg = arg.GetBucketVersion()
9564 if new_arg:
9565 new_args_for_cmds.append(new_arg)
9567 self.args_for_cmds = new_args_for_cmds
9569 Function.InitFunction(self)
9571 def WriteCommandDescription(self, file):
9572 """Overridden from Function"""
9573 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9574 self.original_name)
9576 def WriteServiceImplementation(self, file):
9577 """Overridden from Function"""
9578 self.type_handler.WriteBucketServiceImplementation(self, file)
9580 def WriteHandlerImplementation(self, file):
9581 """Overridden from Function"""
9582 self.type_handler.WriteBucketHandlerImplementation(self, file)
9584 def WriteServiceUnitTest(self, file, *extras):
9585 """Overridden from Function"""
9586 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
9588 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9589 """Overridden from Function"""
9590 args = self.GetOriginalArgs()
9591 arg_string = separator.join(
9592 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9593 else arg.name) for arg in args])
9594 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9597 def CreateArg(arg_string):
9598 """Creates an Argument."""
9599 arg_parts = arg_string.split()
9600 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9601 return None
9602 # Is this a pointer argument?
9603 elif arg_string.find('*') >= 0:
9604 return PointerArgument(
9605 arg_parts[-1],
9606 " ".join(arg_parts[0:-1]))
9607 # Is this a resource argument? Must come after pointer check.
9608 elif arg_parts[0].startswith('GLidBind'):
9609 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9610 elif arg_parts[0].startswith('GLidZero'):
9611 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9612 elif arg_parts[0].startswith('GLid'):
9613 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9614 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9615 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9616 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9617 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9618 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9619 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9620 elif arg_parts[0].startswith('GLboolean'):
9621 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9622 elif arg_parts[0].startswith('GLintUniformLocation'):
9623 return UniformLocationArgument(arg_parts[-1])
9624 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9625 not arg_parts[0].startswith('GLintptr')):
9626 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9627 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9628 arg_parts[0].startswith('GLintptrNotNegative')):
9629 return SizeNotNegativeArgument(arg_parts[-1],
9630 " ".join(arg_parts[0:-1]),
9631 arg_parts[0][0:-11])
9632 elif arg_parts[0].startswith('GLsize'):
9633 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9634 else:
9635 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9638 class GLGenerator(object):
9639 """A class to generate GL command buffers."""
9641 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9643 def __init__(self, verbose):
9644 self.original_functions = []
9645 self.functions = []
9646 self.verbose = verbose
9647 self.errors = 0
9648 self.pepper_interfaces = []
9649 self.interface_info = {}
9650 self.generated_cpp_filenames = []
9652 for interface in _PEPPER_INTERFACES:
9653 interface = PepperInterface(interface)
9654 self.pepper_interfaces.append(interface)
9655 self.interface_info[interface.GetName()] = interface
9657 def AddFunction(self, func):
9658 """Adds a function."""
9659 self.functions.append(func)
9661 def GetFunctionInfo(self, name):
9662 """Gets a type info for the given function name."""
9663 if name in _FUNCTION_INFO:
9664 func_info = _FUNCTION_INFO[name].copy()
9665 else:
9666 func_info = {}
9668 if not 'type' in func_info:
9669 func_info['type'] = ''
9671 return func_info
9673 def Log(self, msg):
9674 """Prints something if verbose is true."""
9675 if self.verbose:
9676 print msg
9678 def Error(self, msg):
9679 """Prints an error."""
9680 print "Error: %s" % msg
9681 self.errors += 1
9683 def WriteLicense(self, file):
9684 """Writes the license."""
9685 file.Write(_LICENSE)
9687 def WriteNamespaceOpen(self, file):
9688 """Writes the code for the namespace."""
9689 file.Write("namespace gpu {\n")
9690 file.Write("namespace gles2 {\n")
9691 file.Write("\n")
9693 def WriteNamespaceClose(self, file):
9694 """Writes the code to close the namespace."""
9695 file.Write("} // namespace gles2\n")
9696 file.Write("} // namespace gpu\n")
9697 file.Write("\n")
9699 def ParseGLH(self, filename):
9700 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9701 f = open(filename, "r")
9702 functions = f.read()
9703 f.close()
9704 for line in functions.splitlines():
9705 match = self._function_re.match(line)
9706 if match:
9707 func_name = match.group(2)[2:]
9708 func_info = self.GetFunctionInfo(func_name)
9709 if func_info['type'] == 'Noop':
9710 continue
9712 parsed_func_info = {
9713 'original_name': func_name,
9714 'original_args': match.group(3),
9715 'return_type': match.group(1).strip(),
9718 for k in parsed_func_info.keys():
9719 if not k in func_info:
9720 func_info[k] = parsed_func_info[k]
9722 f = Function(func_name, func_info)
9723 self.original_functions.append(f)
9725 #for arg in f.GetOriginalArgs():
9726 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9727 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9729 gen_cmd = f.GetInfo('gen_cmd')
9730 if gen_cmd == True or gen_cmd == None:
9731 if f.type_handler.NeedsDataTransferFunction(f):
9732 methods = f.GetDataTransferMethods()
9733 if 'immediate' in methods:
9734 self.AddFunction(ImmediateFunction(f))
9735 if 'bucket' in methods:
9736 self.AddFunction(BucketFunction(f))
9737 if 'shm' in methods:
9738 self.AddFunction(f)
9739 else:
9740 self.AddFunction(f)
9742 self.Log("Auto Generated Functions : %d" %
9743 len([f for f in self.functions if f.can_auto_generate or
9744 (not f.IsType('') and not f.IsType('Custom') and
9745 not f.IsType('Todo'))]))
9747 funcs = [f for f in self.functions if not f.can_auto_generate and
9748 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9749 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9751 for f in funcs:
9752 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9754 def WriteCommandIds(self, filename):
9755 """Writes the command buffer format"""
9756 file = CHeaderWriter(filename)
9757 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9758 id = 256
9759 for func in self.functions:
9760 file.Write(" %-60s /* %d */ \\\n" %
9761 ("OP(%s)" % func.name, id))
9762 id += 1
9763 file.Write("\n")
9765 file.Write("enum CommandId {\n")
9766 file.Write(" kStartPoint = cmd::kLastCommonId, "
9767 "// All GLES2 commands start after this.\n")
9768 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9769 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9770 file.Write("#undef GLES2_CMD_OP\n")
9771 file.Write(" kNumCommands\n")
9772 file.Write("};\n")
9773 file.Write("\n")
9774 file.Close()
9775 self.generated_cpp_filenames.append(file.filename)
9777 def WriteFormat(self, filename):
9778 """Writes the command buffer format"""
9779 file = CHeaderWriter(filename)
9780 # Forward declaration of a few enums used in constant argument
9781 # to avoid including GL header files.
9782 enum_defines = {
9783 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9784 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9786 file.Write('\n')
9787 for enum in enum_defines:
9788 file.Write("#define %s %s\n" % (enum, enum_defines[enum]))
9789 file.Write('\n')
9790 for func in self.functions:
9791 if True:
9792 #gen_cmd = func.GetInfo('gen_cmd')
9793 #if gen_cmd == True or gen_cmd == None:
9794 func.WriteStruct(file)
9795 file.Write("\n")
9796 file.Close()
9797 self.generated_cpp_filenames.append(file.filename)
9799 def WriteDocs(self, filename):
9800 """Writes the command buffer doc version of the commands"""
9801 file = CWriter(filename)
9802 for func in self.functions:
9803 if True:
9804 #gen_cmd = func.GetInfo('gen_cmd')
9805 #if gen_cmd == True or gen_cmd == None:
9806 func.WriteDocs(file)
9807 file.Write("\n")
9808 file.Close()
9809 self.generated_cpp_filenames.append(file.filename)
9811 def WriteFormatTest(self, filename):
9812 """Writes the command buffer format test."""
9813 file = CHeaderWriter(
9814 filename,
9815 "// This file contains unit tests for gles2 commmands\n"
9816 "// It is included by gles2_cmd_format_test.cc\n"
9817 "\n")
9819 for func in self.functions:
9820 if True:
9821 #gen_cmd = func.GetInfo('gen_cmd')
9822 #if gen_cmd == True or gen_cmd == None:
9823 func.WriteFormatTest(file)
9825 file.Close()
9826 self.generated_cpp_filenames.append(file.filename)
9828 def WriteCmdHelperHeader(self, filename):
9829 """Writes the gles2 command helper."""
9830 file = CHeaderWriter(filename)
9832 for func in self.functions:
9833 if True:
9834 #gen_cmd = func.GetInfo('gen_cmd')
9835 #if gen_cmd == True or gen_cmd == None:
9836 func.WriteCmdHelper(file)
9838 file.Close()
9839 self.generated_cpp_filenames.append(file.filename)
9841 def WriteServiceContextStateHeader(self, filename):
9842 """Writes the service context state header."""
9843 file = CHeaderWriter(
9844 filename,
9845 "// It is included by context_state.h\n")
9846 file.Write("struct EnableFlags {\n")
9847 file.Write(" EnableFlags();\n")
9848 for capability in _CAPABILITY_FLAGS:
9849 file.Write(" bool %s;\n" % capability['name'])
9850 file.Write(" bool cached_%s;\n" % capability['name'])
9851 file.Write("};\n\n")
9853 for state_name in sorted(_STATES.keys()):
9854 state = _STATES[state_name]
9855 for item in state['states']:
9856 if isinstance(item['default'], list):
9857 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
9858 len(item['default'])))
9859 else:
9860 file.Write("%s %s;\n" % (item['type'], item['name']))
9862 if item.get('cached', False):
9863 if isinstance(item['default'], list):
9864 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9865 len(item['default'])))
9866 else:
9867 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
9869 file.Write("\n")
9871 file.Write("""
9872 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9873 switch (cap) {
9874 """)
9875 for capability in _CAPABILITY_FLAGS:
9876 file.Write("""\
9877 case GL_%s:
9878 """ % capability['name'].upper())
9879 file.Write("""\
9880 if (enable_flags.cached_%(name)s == enable &&
9881 !ignore_cached_state)
9882 return;
9883 enable_flags.cached_%(name)s = enable;
9884 break;
9885 """ % capability)
9887 file.Write("""\
9888 default:
9889 NOTREACHED();
9890 return;
9892 if (enable)
9893 glEnable(cap);
9894 else
9895 glDisable(cap);
9897 """)
9899 file.Close()
9900 self.generated_cpp_filenames.append(file.filename)
9902 def WriteClientContextStateHeader(self, filename):
9903 """Writes the client context state header."""
9904 file = CHeaderWriter(
9905 filename,
9906 "// It is included by client_context_state.h\n")
9907 file.Write("struct EnableFlags {\n")
9908 file.Write(" EnableFlags();\n")
9909 for capability in _CAPABILITY_FLAGS:
9910 file.Write(" bool %s;\n" % capability['name'])
9911 file.Write("};\n\n")
9913 file.Close()
9914 self.generated_cpp_filenames.append(file.filename)
9916 def WriteContextStateGetters(self, file, class_name):
9917 """Writes the state getters."""
9918 for gl_type in ["GLint", "GLfloat"]:
9919 file.Write("""
9920 bool %s::GetStateAs%s(
9921 GLenum pname, %s* params, GLsizei* num_written) const {
9922 switch (pname) {
9923 """ % (class_name, gl_type, gl_type))
9924 for state_name in sorted(_STATES.keys()):
9925 state = _STATES[state_name]
9926 if 'enum' in state:
9927 file.Write(" case %s:\n" % state['enum'])
9928 file.Write(" *num_written = %d;\n" % len(state['states']))
9929 file.Write(" if (params) {\n")
9930 for ndx,item in enumerate(state['states']):
9931 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9932 (ndx, gl_type, item['name']))
9933 file.Write(" }\n")
9934 file.Write(" return true;\n")
9935 else:
9936 for item in state['states']:
9937 file.Write(" case %s:\n" % item['enum'])
9938 if isinstance(item['default'], list):
9939 item_len = len(item['default'])
9940 file.Write(" *num_written = %d;\n" % item_len)
9941 file.Write(" if (params) {\n")
9942 if item['type'] == gl_type:
9943 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9944 (item['name'], item['type'], item_len))
9945 else:
9946 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9947 item_len)
9948 file.Write(" params[i] = %s;\n" %
9949 (GetGLGetTypeConversion(gl_type, item['type'],
9950 "%s[i]" % item['name'])))
9951 file.Write(" }\n");
9952 else:
9953 file.Write(" *num_written = 1;\n")
9954 file.Write(" if (params) {\n")
9955 file.Write(" params[0] = %s;\n" %
9956 (GetGLGetTypeConversion(gl_type, item['type'],
9957 item['name'])))
9958 file.Write(" }\n")
9959 file.Write(" return true;\n")
9960 for capability in _CAPABILITY_FLAGS:
9961 file.Write(" case GL_%s:\n" % capability['name'].upper())
9962 file.Write(" *num_written = 1;\n")
9963 file.Write(" if (params) {\n")
9964 file.Write(
9965 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9966 (gl_type, capability['name']))
9967 file.Write(" }\n")
9968 file.Write(" return true;\n")
9969 file.Write(""" default:
9970 return false;
9973 """)
9975 def WriteServiceContextStateImpl(self, filename):
9976 """Writes the context state service implementation."""
9977 file = CHeaderWriter(
9978 filename,
9979 "// It is included by context_state.cc\n")
9980 code = []
9981 for capability in _CAPABILITY_FLAGS:
9982 code.append("%s(%s)" %
9983 (capability['name'],
9984 ('false', 'true')['default' in capability]))
9985 code.append("cached_%s(%s)" %
9986 (capability['name'],
9987 ('false', 'true')['default' in capability]))
9988 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9989 ",\n ".join(code))
9990 file.Write("\n")
9992 file.Write("void ContextState::Initialize() {\n")
9993 for state_name in sorted(_STATES.keys()):
9994 state = _STATES[state_name]
9995 for item in state['states']:
9996 if isinstance(item['default'], list):
9997 for ndx, value in enumerate(item['default']):
9998 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
9999 else:
10000 file.Write(" %s = %s;\n" % (item['name'], item['default']))
10001 if item.get('cached', False):
10002 if isinstance(item['default'], list):
10003 for ndx, value in enumerate(item['default']):
10004 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
10005 else:
10006 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
10007 file.Write("}\n")
10009 file.Write("""
10010 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10011 """)
10012 def WriteCapabilities(test_prev, es3_caps):
10013 for capability in _CAPABILITY_FLAGS:
10014 capability_name = capability['name']
10015 capability_es3 = 'es3' in capability and capability['es3'] == True
10016 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
10017 continue
10018 if test_prev:
10019 file.Write(""" if (prev_state->enable_flags.cached_%s !=
10020 enable_flags.cached_%s) {\n""" %
10021 (capability_name, capability_name))
10022 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10023 (capability_name.upper(), capability_name))
10024 if test_prev:
10025 file.Write(" }")
10027 file.Write(" if (prev_state) {")
10028 WriteCapabilities(True, False)
10029 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10030 WriteCapabilities(True, True)
10031 file.Write(" }\n")
10032 file.Write(" } else {")
10033 WriteCapabilities(False, False)
10034 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10035 WriteCapabilities(False, True)
10036 file.Write(" }\n")
10037 file.Write(" }")
10039 file.Write("""}
10041 void ContextState::InitState(const ContextState *prev_state) const {
10042 """)
10044 def WriteStates(test_prev):
10045 # We need to sort the keys so the expectations match
10046 for state_name in sorted(_STATES.keys()):
10047 state = _STATES[state_name]
10048 if state['type'] == 'FrontBack':
10049 num_states = len(state['states'])
10050 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10051 if test_prev:
10052 file.Write(" if (")
10053 args = []
10054 for place, item in enumerate(group):
10055 item_name = CachedStateName(item)
10056 args.append('%s' % item_name)
10057 if test_prev:
10058 if place > 0:
10059 file.Write(' ||\n')
10060 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
10061 if test_prev:
10062 file.Write(")\n")
10063 file.Write(
10064 " gl%s(%s, %s);\n" %
10065 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10066 elif state['type'] == 'NamedParameter':
10067 for item in state['states']:
10068 item_name = CachedStateName(item)
10070 if 'extension_flag' in item:
10071 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
10072 item['extension_flag'])
10073 if test_prev:
10074 if isinstance(item['default'], list):
10075 file.Write(" if (memcmp(prev_state->%s, %s, "
10076 "sizeof(%s) * %d)) {\n" %
10077 (item_name, item_name, item['type'],
10078 len(item['default'])))
10079 else:
10080 file.Write(" if (prev_state->%s != %s) {\n " %
10081 (item_name, item_name))
10082 if 'gl_version_flag' in item:
10083 item_name = item['gl_version_flag']
10084 inverted = ''
10085 if item_name[0] == '!':
10086 inverted = '!'
10087 item_name = item_name[1:]
10088 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10089 (inverted, item_name))
10090 file.Write(" gl%s(%s, %s);\n" %
10091 (state['func'],
10092 (item['enum_set']
10093 if 'enum_set' in item else item['enum']),
10094 item['name']))
10095 if 'gl_version_flag' in item:
10096 file.Write(" }\n")
10097 if test_prev:
10098 if 'extension_flag' in item:
10099 file.Write(" ")
10100 file.Write(" }")
10101 if 'extension_flag' in item:
10102 file.Write(" }")
10103 else:
10104 if 'extension_flag' in state:
10105 file.Write(" if (feature_info_->feature_flags().%s)\n " %
10106 state['extension_flag'])
10107 if test_prev:
10108 file.Write(" if (")
10109 args = []
10110 for place, item in enumerate(state['states']):
10111 item_name = CachedStateName(item)
10112 args.append('%s' % item_name)
10113 if test_prev:
10114 if place > 0:
10115 file.Write(' ||\n')
10116 file.Write("(%s != prev_state->%s)" %
10117 (item_name, item_name))
10118 if test_prev:
10119 file.Write(" )\n")
10120 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
10122 file.Write(" if (prev_state) {")
10123 WriteStates(True)
10124 file.Write(" } else {")
10125 WriteStates(False)
10126 file.Write(" }")
10127 file.Write("}\n")
10129 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
10130 switch (cap) {
10131 """)
10132 for capability in _CAPABILITY_FLAGS:
10133 file.Write(" case GL_%s:\n" % capability['name'].upper())
10134 file.Write(" return enable_flags.%s;\n" % capability['name'])
10135 file.Write(""" default:
10136 NOTREACHED();
10137 return false;
10140 """)
10142 self.WriteContextStateGetters(file, "ContextState")
10143 file.Close()
10144 self.generated_cpp_filenames.append(file.filename)
10146 def WriteClientContextStateImpl(self, filename):
10147 """Writes the context state client side implementation."""
10148 file = CHeaderWriter(
10149 filename,
10150 "// It is included by client_context_state.cc\n")
10151 code = []
10152 for capability in _CAPABILITY_FLAGS:
10153 code.append("%s(%s)" %
10154 (capability['name'],
10155 ('false', 'true')['default' in capability]))
10156 file.Write(
10157 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10158 ",\n ".join(code))
10159 file.Write("\n")
10161 file.Write("""
10162 bool ClientContextState::SetCapabilityState(
10163 GLenum cap, bool enabled, bool* changed) {
10164 *changed = false;
10165 switch (cap) {
10166 """)
10167 for capability in _CAPABILITY_FLAGS:
10168 file.Write(" case GL_%s:\n" % capability['name'].upper())
10169 file.Write(""" if (enable_flags.%(name)s != enabled) {
10170 *changed = true;
10171 enable_flags.%(name)s = enabled;
10173 return true;
10174 """ % capability)
10175 file.Write(""" default:
10176 return false;
10179 """)
10180 file.Write("""bool ClientContextState::GetEnabled(
10181 GLenum cap, bool* enabled) const {
10182 switch (cap) {
10183 """)
10184 for capability in _CAPABILITY_FLAGS:
10185 file.Write(" case GL_%s:\n" % capability['name'].upper())
10186 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
10187 file.Write(" return true;\n")
10188 file.Write(""" default:
10189 return false;
10192 """)
10193 file.Close()
10194 self.generated_cpp_filenames.append(file.filename)
10196 def WriteServiceImplementation(self, filename):
10197 """Writes the service decorder implementation."""
10198 file = CHeaderWriter(
10199 filename,
10200 "// It is included by gles2_cmd_decoder.cc\n")
10202 for func in self.functions:
10203 if True:
10204 #gen_cmd = func.GetInfo('gen_cmd')
10205 #if gen_cmd == True or gen_cmd == None:
10206 func.WriteServiceImplementation(file)
10208 file.Write("""
10209 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10210 switch (cap) {
10211 """)
10212 for capability in _CAPABILITY_FLAGS:
10213 file.Write(" case GL_%s:\n" % capability['name'].upper())
10214 if 'state_flag' in capability:
10216 file.Write("""\
10217 state_.enable_flags.%(name)s = enabled;
10218 if (state_.enable_flags.cached_%(name)s != enabled
10219 || state_.ignore_cached_state) {
10220 %(state_flag)s = true;
10222 return false;
10223 """ % capability)
10224 else:
10225 file.Write("""\
10226 state_.enable_flags.%(name)s = enabled;
10227 if (state_.enable_flags.cached_%(name)s != enabled
10228 || state_.ignore_cached_state) {
10229 state_.enable_flags.cached_%(name)s = enabled;
10230 return true;
10232 return false;
10233 """ % capability)
10234 file.Write(""" default:
10235 NOTREACHED();
10236 return false;
10239 """)
10240 file.Close()
10241 self.generated_cpp_filenames.append(file.filename)
10243 def WriteServiceUnitTests(self, filename):
10244 """Writes the service decorder unit tests."""
10245 num_tests = len(self.functions)
10246 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
10247 count = 0
10248 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
10249 count += 1
10250 name = filename % count
10251 file = CHeaderWriter(
10252 name,
10253 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
10254 test_name = 'GLES2DecoderTest%d' % count
10255 end = test_num + FUNCTIONS_PER_FILE
10256 if end > num_tests:
10257 end = num_tests
10258 for idx in range(test_num, end):
10259 func = self.functions[idx]
10261 # Do any filtering of the functions here, so that the functions
10262 # will not move between the numbered files if filtering properties
10263 # are changed.
10264 if func.GetInfo('extension_flag'):
10265 continue
10267 if True:
10268 #gen_cmd = func.GetInfo('gen_cmd')
10269 #if gen_cmd == True or gen_cmd == None:
10270 if func.GetInfo('unit_test') == False:
10271 file.Write("// TODO(gman): %s\n" % func.name)
10272 else:
10273 func.WriteServiceUnitTest(file, {
10274 'test_name': test_name
10276 file.Close()
10277 self.generated_cpp_filenames.append(file.filename)
10278 file = CHeaderWriter(
10279 filename % 0,
10280 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
10281 file.Write(
10282 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10283 bool es3_capable) {""")
10284 for capability in _CAPABILITY_FLAGS:
10285 capability_es3 = 'es3' in capability and capability['es3'] == True
10286 if not capability_es3:
10287 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10288 (capability['name'].upper(),
10289 ('false', 'true')['default' in capability]))
10291 file.Write(" if (es3_capable) {")
10292 for capability in _CAPABILITY_FLAGS:
10293 capability_es3 = 'es3' in capability and capability['es3'] == True
10294 if capability_es3:
10295 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10296 (capability['name'].upper(),
10297 ('false', 'true')['default' in capability]))
10298 file.Write(""" }
10301 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10302 """)
10304 # We need to sort the keys so the expectations match
10305 for state_name in sorted(_STATES.keys()):
10306 state = _STATES[state_name]
10307 if state['type'] == 'FrontBack':
10308 num_states = len(state['states'])
10309 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10310 args = []
10311 for item in group:
10312 if 'expected' in item:
10313 args.append(item['expected'])
10314 else:
10315 args.append(item['default'])
10316 file.Write(
10317 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10318 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10319 file.Write(" .Times(1)\n")
10320 file.Write(" .RetiresOnSaturation();\n")
10321 elif state['type'] == 'NamedParameter':
10322 for item in state['states']:
10323 if 'extension_flag' in item:
10324 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10325 item['extension_flag'])
10326 file.Write(" ")
10327 expect_value = item['default']
10328 if isinstance(expect_value, list):
10329 # TODO: Currently we do not check array values.
10330 expect_value = "_"
10332 file.Write(
10333 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10334 (state['func'],
10335 (item['enum_set']
10336 if 'enum_set' in item else item['enum']),
10337 expect_value))
10338 file.Write(" .Times(1)\n")
10339 file.Write(" .RetiresOnSaturation();\n")
10340 if 'extension_flag' in item:
10341 file.Write(" }\n")
10342 else:
10343 if 'extension_flag' in state:
10344 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10345 state['extension_flag'])
10346 file.Write(" ")
10347 args = []
10348 for item in state['states']:
10349 if 'expected' in item:
10350 args.append(item['expected'])
10351 else:
10352 args.append(item['default'])
10353 # TODO: Currently we do not check array values.
10354 args = ["_" if isinstance(arg, list) else arg for arg in args]
10355 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10356 (state['func'], ", ".join(args)))
10357 file.Write(" .Times(1)\n")
10358 file.Write(" .RetiresOnSaturation();\n")
10359 if 'extension_flag' in state:
10360 file.Write(" }\n")
10361 file.Write("""}
10362 """)
10363 file.Close()
10364 self.generated_cpp_filenames.append(file.filename)
10366 def WriteServiceUnitTestsForExtensions(self, filename):
10367 """Writes the service decorder unit tests for functions with extension_flag.
10369 The functions are special in that they need a specific unit test
10370 baseclass to turn on the extension.
10372 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
10373 file = CHeaderWriter(
10374 filename,
10375 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
10376 for func in functions:
10377 if True:
10378 if func.GetInfo('unit_test') == False:
10379 file.Write("// TODO(gman): %s\n" % func.name)
10380 else:
10381 extension = ToCamelCase(
10382 ToGLExtensionString(func.GetInfo('extension_flag')))
10383 func.WriteServiceUnitTest(file, {
10384 'test_name': 'GLES2DecoderTestWith%s' % extension
10387 file.Close()
10388 self.generated_cpp_filenames.append(file.filename)
10390 def WriteGLES2Header(self, filename):
10391 """Writes the GLES2 header."""
10392 file = CHeaderWriter(
10393 filename,
10394 "// This file contains Chromium-specific GLES2 declarations.\n\n")
10396 for func in self.original_functions:
10397 func.WriteGLES2Header(file)
10399 file.Write("\n")
10400 file.Close()
10401 self.generated_cpp_filenames.append(file.filename)
10403 def WriteGLES2CLibImplementation(self, filename):
10404 """Writes the GLES2 c lib implementation."""
10405 file = CHeaderWriter(
10406 filename,
10407 "// These functions emulate GLES2 over command buffers.\n")
10409 for func in self.original_functions:
10410 func.WriteGLES2CLibImplementation(file)
10412 file.Write("""
10413 namespace gles2 {
10415 extern const NameToFunc g_gles2_function_table[] = {
10416 """)
10417 for func in self.original_functions:
10418 file.Write(
10419 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10420 (func.name, func.name))
10421 file.Write(""" { NULL, NULL, },
10424 } // namespace gles2
10425 """)
10426 file.Close()
10427 self.generated_cpp_filenames.append(file.filename)
10429 def WriteGLES2InterfaceHeader(self, filename):
10430 """Writes the GLES2 interface header."""
10431 file = CHeaderWriter(
10432 filename,
10433 "// This file is included by gles2_interface.h to declare the\n"
10434 "// GL api functions.\n")
10435 for func in self.original_functions:
10436 func.WriteGLES2InterfaceHeader(file)
10437 file.Close()
10438 self.generated_cpp_filenames.append(file.filename)
10440 def WriteMojoGLES2ImplHeader(self, filename):
10441 """Writes the Mojo GLES2 implementation header."""
10442 file = CHeaderWriter(
10443 filename,
10444 "// This file is included by gles2_interface.h to declare the\n"
10445 "// GL api functions.\n")
10447 code = """
10448 #include "gpu/command_buffer/client/gles2_interface.h"
10449 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10451 namespace mojo {
10453 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10454 public:
10455 explicit MojoGLES2Impl(MojoGLES2Context context) {
10456 context_ = context;
10458 ~MojoGLES2Impl() override {}
10460 file.Write(code);
10461 for func in self.original_functions:
10462 func.WriteMojoGLES2ImplHeader(file)
10463 code = """
10464 private:
10465 MojoGLES2Context context_;
10468 } // namespace mojo
10470 file.Write(code);
10471 file.Close()
10472 self.generated_cpp_filenames.append(file.filename)
10474 def WriteMojoGLES2Impl(self, filename):
10475 """Writes the Mojo GLES2 implementation."""
10476 file = CWriter(filename)
10477 file.Write(_LICENSE)
10478 file.Write(_DO_NOT_EDIT_WARNING)
10480 code = """
10481 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10483 #include "base/logging.h"
10484 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10485 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10486 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10487 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10488 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10489 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10490 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10491 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10492 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10494 namespace mojo {
10497 file.Write(code);
10498 for func in self.original_functions:
10499 func.WriteMojoGLES2Impl(file)
10500 code = """
10502 } // namespace mojo
10504 file.Write(code);
10505 file.Close()
10506 self.generated_cpp_filenames.append(file.filename)
10508 def WriteGLES2InterfaceStub(self, filename):
10509 """Writes the GLES2 interface stub header."""
10510 file = CHeaderWriter(
10511 filename,
10512 "// This file is included by gles2_interface_stub.h.\n")
10513 for func in self.original_functions:
10514 func.WriteGLES2InterfaceStub(file)
10515 file.Close()
10516 self.generated_cpp_filenames.append(file.filename)
10518 def WriteGLES2InterfaceStubImpl(self, filename):
10519 """Writes the GLES2 interface header."""
10520 file = CHeaderWriter(
10521 filename,
10522 "// This file is included by gles2_interface_stub.cc.\n")
10523 for func in self.original_functions:
10524 func.WriteGLES2InterfaceStubImpl(file)
10525 file.Close()
10526 self.generated_cpp_filenames.append(file.filename)
10528 def WriteGLES2ImplementationHeader(self, filename):
10529 """Writes the GLES2 Implementation header."""
10530 file = CHeaderWriter(
10531 filename,
10532 "// This file is included by gles2_implementation.h to declare the\n"
10533 "// GL api functions.\n")
10534 for func in self.original_functions:
10535 func.WriteGLES2ImplementationHeader(file)
10536 file.Close()
10537 self.generated_cpp_filenames.append(file.filename)
10539 def WriteGLES2Implementation(self, filename):
10540 """Writes the GLES2 Implementation."""
10541 file = CHeaderWriter(
10542 filename,
10543 "// This file is included by gles2_implementation.cc to define the\n"
10544 "// GL api functions.\n")
10545 for func in self.original_functions:
10546 func.WriteGLES2Implementation(file)
10547 file.Close()
10548 self.generated_cpp_filenames.append(file.filename)
10550 def WriteGLES2TraceImplementationHeader(self, filename):
10551 """Writes the GLES2 Trace Implementation header."""
10552 file = CHeaderWriter(
10553 filename,
10554 "// This file is included by gles2_trace_implementation.h\n")
10555 for func in self.original_functions:
10556 func.WriteGLES2TraceImplementationHeader(file)
10557 file.Close()
10558 self.generated_cpp_filenames.append(file.filename)
10560 def WriteGLES2TraceImplementation(self, filename):
10561 """Writes the GLES2 Trace Implementation."""
10562 file = CHeaderWriter(
10563 filename,
10564 "// This file is included by gles2_trace_implementation.cc\n")
10565 for func in self.original_functions:
10566 func.WriteGLES2TraceImplementation(file)
10567 file.Close()
10568 self.generated_cpp_filenames.append(file.filename)
10570 def WriteGLES2ImplementationUnitTests(self, filename):
10571 """Writes the GLES2 helper header."""
10572 file = CHeaderWriter(
10573 filename,
10574 "// This file is included by gles2_implementation.h to declare the\n"
10575 "// GL api functions.\n")
10576 for func in self.original_functions:
10577 func.WriteGLES2ImplementationUnitTest(file)
10578 file.Close()
10579 self.generated_cpp_filenames.append(file.filename)
10581 def WriteServiceUtilsHeader(self, filename):
10582 """Writes the gles2 auto generated utility header."""
10583 file = CHeaderWriter(filename)
10584 for name in sorted(_NAMED_TYPE_INFO.keys()):
10585 named_type = NamedType(_NAMED_TYPE_INFO[name])
10586 if named_type.IsConstant():
10587 continue
10588 file.Write("ValueValidator<%s> %s;\n" %
10589 (named_type.GetType(), ToUnderscore(name)))
10590 file.Write("\n")
10591 file.Close()
10592 self.generated_cpp_filenames.append(file.filename)
10594 def WriteServiceUtilsImplementation(self, filename):
10595 """Writes the gles2 auto generated utility implementation."""
10596 file = CHeaderWriter(filename)
10597 names = sorted(_NAMED_TYPE_INFO.keys())
10598 for name in names:
10599 named_type = NamedType(_NAMED_TYPE_INFO[name])
10600 if named_type.IsConstant():
10601 continue
10602 if named_type.GetValidValues():
10603 file.Write("static const %s valid_%s_table[] = {\n" %
10604 (named_type.GetType(), ToUnderscore(name)))
10605 for value in named_type.GetValidValues():
10606 file.Write(" %s,\n" % value)
10607 file.Write("};\n")
10608 file.Write("\n")
10609 if named_type.GetValidValuesES3():
10610 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10611 (named_type.GetType(), ToUnderscore(name)))
10612 for value in named_type.GetValidValuesES3():
10613 file.Write(" %s,\n" % value)
10614 file.Write("};\n")
10615 file.Write("\n")
10616 if named_type.GetDeprecatedValuesES3():
10617 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10618 (named_type.GetType(), ToUnderscore(name)))
10619 for value in named_type.GetDeprecatedValuesES3():
10620 file.Write(" %s,\n" % value)
10621 file.Write("};\n")
10622 file.Write("\n")
10623 file.Write("Validators::Validators()")
10624 pre = ' : '
10625 for count, name in enumerate(names):
10626 named_type = NamedType(_NAMED_TYPE_INFO[name])
10627 if named_type.IsConstant():
10628 continue
10629 if named_type.GetValidValues():
10630 code = """%(pre)s%(name)s(
10631 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10632 else:
10633 code = "%(pre)s%(name)s()"
10634 file.Write(code % {
10635 'name': ToUnderscore(name),
10636 'pre': pre,
10638 pre = ',\n '
10639 file.Write(" {\n");
10640 file.Write("}\n\n");
10642 file.Write("void Validators::UpdateValuesES3() {\n")
10643 for name in names:
10644 named_type = NamedType(_NAMED_TYPE_INFO[name])
10645 if named_type.GetDeprecatedValuesES3():
10646 code = """ %(name)s.RemoveValues(
10647 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10649 file.Write(code % {
10650 'name': ToUnderscore(name),
10652 if named_type.GetValidValuesES3():
10653 code = """ %(name)s.AddValues(
10654 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10656 file.Write(code % {
10657 'name': ToUnderscore(name),
10659 file.Write("}\n\n");
10660 file.Close()
10661 self.generated_cpp_filenames.append(file.filename)
10663 def WriteCommonUtilsHeader(self, filename):
10664 """Writes the gles2 common utility header."""
10665 file = CHeaderWriter(filename)
10666 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10667 for type_info in type_infos:
10668 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10669 file.Write("static std::string GetString%s(uint32_t value);\n" %
10670 type_info)
10671 file.Write("\n")
10672 file.Close()
10673 self.generated_cpp_filenames.append(file.filename)
10675 def WriteCommonUtilsImpl(self, filename):
10676 """Writes the gles2 common utility header."""
10677 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10678 dict = {}
10679 for fname in ['third_party/khronos/GLES2/gl2.h',
10680 'third_party/khronos/GLES2/gl2ext.h',
10681 'third_party/khronos/GLES3/gl3.h',
10682 'gpu/GLES2/gl2chromium.h',
10683 'gpu/GLES2/gl2extchromium.h']:
10684 lines = open(fname).readlines()
10685 for line in lines:
10686 m = enum_re.match(line)
10687 if m:
10688 name = m.group(1)
10689 value = m.group(2)
10690 if len(value) <= 10:
10691 if not value in dict:
10692 dict[value] = name
10693 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10694 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10695 dict[value].endswith('_CHROMIUM')):
10696 self.Error("code collision: %s and %s have the same code %s" %
10697 (dict[value], name, value))
10699 file = CHeaderWriter(filename)
10700 file.Write("static const GLES2Util::EnumToString "
10701 "enum_to_string_table[] = {\n")
10702 for value in dict:
10703 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
10704 file.Write("""};
10706 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10707 enum_to_string_table;
10708 const size_t GLES2Util::enum_to_string_table_len_ =
10709 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10711 """)
10713 enums = sorted(_NAMED_TYPE_INFO.keys())
10714 for enum in enums:
10715 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10716 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10717 enum)
10718 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10719 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10720 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10721 assert len(valid_list) == len(set(valid_list))
10722 if len(valid_list) > 0:
10723 file.Write(" static const EnumToString string_table[] = {\n")
10724 for value in valid_list:
10725 file.Write(' { %s, "%s" },\n' % (value, value))
10726 file.Write(""" };
10727 return GLES2Util::GetQualifiedEnumString(
10728 string_table, arraysize(string_table), value);
10731 """)
10732 else:
10733 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10734 NULL, 0, value);
10737 """)
10738 file.Close()
10739 self.generated_cpp_filenames.append(file.filename)
10741 def WritePepperGLES2Interface(self, filename, dev):
10742 """Writes the Pepper OpenGLES interface definition."""
10743 file = CWriter(filename)
10744 file.Write(_LICENSE)
10745 file.Write(_DO_NOT_EDIT_WARNING)
10747 file.Write("label Chrome {\n")
10748 file.Write(" M39 = 1.0\n")
10749 file.Write("};\n\n")
10751 if not dev:
10752 # Declare GL types.
10753 file.Write("[version=1.0]\n")
10754 file.Write("describe {\n")
10755 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10756 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10757 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10758 'GLubyte', 'GLuint', 'GLushort']:
10759 file.Write(" %s;\n" % gltype)
10760 file.Write(" %s_ptr_t;\n" % gltype)
10761 file.Write("};\n\n")
10763 # C level typedefs.
10764 file.Write("#inline c\n")
10765 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10766 if dev:
10767 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10768 else:
10769 file.Write("\n#ifndef __gl2_h_\n")
10770 for (k, v) in _GL_TYPES.iteritems():
10771 file.Write("typedef %s %s;\n" % (v, k))
10772 file.Write("#ifdef _WIN64\n")
10773 for (k, v) in _GL_TYPES_64.iteritems():
10774 file.Write("typedef %s %s;\n" % (v, k))
10775 file.Write("#else\n")
10776 for (k, v) in _GL_TYPES_32.iteritems():
10777 file.Write("typedef %s %s;\n" % (v, k))
10778 file.Write("#endif // _WIN64\n")
10779 file.Write("#endif // __gl2_h_\n\n")
10780 file.Write("#endinl\n")
10782 for interface in self.pepper_interfaces:
10783 if interface.dev != dev:
10784 continue
10785 # Historically, we provide OpenGLES2 interfaces with struct
10786 # namespace. Not to break code which uses the interface as
10787 # "struct OpenGLES2", we put it in struct namespace.
10788 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10789 interface.GetInterfaceName())
10790 file.Write("interface %s {\n" % interface.GetStructName())
10791 for func in self.original_functions:
10792 if not func.InPepperInterface(interface):
10793 continue
10795 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10796 is_for_return_type=True)
10797 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10798 file.Write(func_prefix)
10799 file.Write("[in] PP_Resource context")
10800 for arg in func.MakeTypedPepperIdlArgStrings():
10801 file.Write(",\n" + " " * len(func_prefix) + arg)
10802 file.Write(");\n")
10803 file.Write("};\n\n")
10806 file.Close()
10808 def WritePepperGLES2Implementation(self, filename):
10809 """Writes the Pepper OpenGLES interface implementation."""
10811 file = CWriter(filename)
10812 file.Write(_LICENSE)
10813 file.Write(_DO_NOT_EDIT_WARNING)
10815 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10816 file.Write("#include \"base/logging.h\"\n")
10817 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10818 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10819 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10821 file.Write("namespace ppapi {\n\n")
10822 file.Write("namespace {\n\n")
10824 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10825 " Enter3D;\n\n")
10827 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10828 " enter) {\n")
10829 file.Write(" DCHECK(enter);\n")
10830 file.Write(" DCHECK(enter->succeeded());\n")
10831 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10832 "gles2_impl();\n");
10833 file.Write("}\n\n");
10835 for func in self.original_functions:
10836 if not func.InAnyPepperExtension():
10837 continue
10839 original_arg = func.MakeTypedPepperArgString("")
10840 context_arg = "PP_Resource context_id"
10841 if len(original_arg):
10842 arg = context_arg + ", " + original_arg
10843 else:
10844 arg = context_arg
10845 file.Write("%s %s(%s) {\n" %
10846 (func.return_type, func.GetPepperName(), arg))
10847 file.Write(" Enter3D enter(context_id, true);\n")
10848 file.Write(" if (enter.succeeded()) {\n")
10850 return_str = "" if func.return_type == "void" else "return "
10851 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10852 (return_str, func.original_name,
10853 func.MakeOriginalArgString("")))
10854 file.Write(" }")
10855 if func.return_type == "void":
10856 file.Write("\n")
10857 else:
10858 file.Write(" else {\n")
10859 file.Write(" return %s;\n" % func.GetErrorReturnString())
10860 file.Write(" }\n")
10861 file.Write("}\n\n")
10863 file.Write("} // namespace\n")
10865 for interface in self.pepper_interfaces:
10866 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10867 (interface.GetStructName(), interface.GetName()))
10868 file.Write(" static const struct %s "
10869 "ppb_opengles2 = {\n" % interface.GetStructName())
10870 file.Write(" &")
10871 file.Write(",\n &".join(
10872 f.GetPepperName() for f in self.original_functions
10873 if f.InPepperInterface(interface)))
10874 file.Write("\n")
10876 file.Write(" };\n")
10877 file.Write(" return &ppb_opengles2;\n")
10878 file.Write("}\n")
10880 file.Write("} // namespace ppapi\n")
10881 file.Close()
10882 self.generated_cpp_filenames.append(file.filename)
10884 def WriteGLES2ToPPAPIBridge(self, filename):
10885 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10887 file = CWriter(filename)
10888 file.Write(_LICENSE)
10889 file.Write(_DO_NOT_EDIT_WARNING)
10891 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10892 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10893 file.Write("#endif\n")
10894 file.Write("#include <GLES2/gl2.h>\n")
10895 file.Write("#include <GLES2/gl2ext.h>\n")
10896 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10898 for func in self.original_functions:
10899 if not func.InAnyPepperExtension():
10900 continue
10902 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10904 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10905 (func.return_type, func.GetPepperName(),
10906 func.MakeTypedPepperArgString("")))
10907 return_str = "" if func.return_type == "void" else "return "
10908 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10909 original_arg = func.MakeOriginalArgString("")
10910 context_arg = "glGetCurrentContextPPAPI()"
10911 if len(original_arg):
10912 arg = context_arg + ", " + original_arg
10913 else:
10914 arg = context_arg
10915 if interface.GetName():
10916 file.Write(" const struct %s* ext = %s;\n" %
10917 (interface.GetStructName(), interface_str))
10918 file.Write(" if (ext)\n")
10919 file.Write(" %sext->%s(%s);\n" %
10920 (return_str, func.GetPepperName(), arg))
10921 if return_str:
10922 file.Write(" %s0;\n" % return_str)
10923 else:
10924 file.Write(" %s%s->%s(%s);\n" %
10925 (return_str, interface_str, func.GetPepperName(), arg))
10926 file.Write("}\n\n")
10927 file.Close()
10928 self.generated_cpp_filenames.append(file.filename)
10930 def WriteMojoGLCallVisitor(self, filename):
10931 """Provides the GL implementation for mojo"""
10932 file = CWriter(filename)
10933 file.Write(_LICENSE)
10934 file.Write(_DO_NOT_EDIT_WARNING)
10936 for func in self.original_functions:
10937 if not func.IsCoreGLFunction():
10938 continue
10939 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10940 (func.name, func.return_type,
10941 func.MakeTypedOriginalArgString(""),
10942 func.MakeOriginalArgString("")))
10944 file.Close()
10945 self.generated_cpp_filenames.append(file.filename)
10947 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10948 """Provides the GL implementation for mojo for a particular extension"""
10949 file = CWriter(filename)
10950 file.Write(_LICENSE)
10951 file.Write(_DO_NOT_EDIT_WARNING)
10953 for func in self.original_functions:
10954 if func.GetInfo("extension") != extension:
10955 continue
10956 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10957 (func.name, func.return_type,
10958 func.MakeTypedOriginalArgString(""),
10959 func.MakeOriginalArgString("")))
10961 file.Close()
10962 self.generated_cpp_filenames.append(file.filename)
10964 def Format(generated_files):
10965 formatter = "clang-format"
10966 if platform.system() == "Windows":
10967 formatter += ".bat"
10968 for filename in generated_files:
10969 call([formatter, "-i", "-style=chromium", filename])
10971 def main(argv):
10972 """This is the main function."""
10973 parser = OptionParser()
10974 parser.add_option(
10975 "--output-dir",
10976 help="base directory for resulting files, under chrome/src. default is "
10977 "empty. Use this if you want the result stored under gen.")
10978 parser.add_option(
10979 "-v", "--verbose", action="store_true",
10980 help="prints more output.")
10982 (options, args) = parser.parse_args(args=argv)
10984 # Add in states and capabilites to GLState
10985 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10986 for state_name in sorted(_STATES.keys()):
10987 state = _STATES[state_name]
10988 if 'extension_flag' in state:
10989 continue
10990 if 'enum' in state:
10991 if not state['enum'] in gl_state_valid:
10992 gl_state_valid.append(state['enum'])
10993 else:
10994 for item in state['states']:
10995 if 'extension_flag' in item:
10996 continue
10997 if not item['enum'] in gl_state_valid:
10998 gl_state_valid.append(item['enum'])
10999 for capability in _CAPABILITY_FLAGS:
11000 valid_value = "GL_%s" % capability['name'].upper()
11001 if not valid_value in gl_state_valid:
11002 gl_state_valid.append(valid_value)
11004 # This script lives under gpu/command_buffer, cd to base directory.
11005 os.chdir(os.path.dirname(__file__) + "/../..")
11006 base_dir = os.getcwd()
11007 gen = GLGenerator(options.verbose)
11008 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
11010 # Support generating files under gen/
11011 if options.output_dir != None:
11012 os.chdir(options.output_dir)
11014 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
11015 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
11016 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
11017 gen.WritePepperGLES2Implementation(
11018 "ppapi/shared_impl/ppb_opengles2_shared.cc")
11019 os.chdir(base_dir)
11020 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
11021 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
11022 gen.WriteFormatTest(
11023 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
11024 gen.WriteGLES2InterfaceHeader(
11025 "gpu/command_buffer/client/gles2_interface_autogen.h")
11026 gen.WriteMojoGLES2ImplHeader(
11027 "mojo/gpu/mojo_gles2_impl_autogen.h")
11028 gen.WriteMojoGLES2Impl(
11029 "mojo/gpu/mojo_gles2_impl_autogen.cc")
11030 gen.WriteGLES2InterfaceStub(
11031 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
11032 gen.WriteGLES2InterfaceStubImpl(
11033 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
11034 gen.WriteGLES2ImplementationHeader(
11035 "gpu/command_buffer/client/gles2_implementation_autogen.h")
11036 gen.WriteGLES2Implementation(
11037 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
11038 gen.WriteGLES2ImplementationUnitTests(
11039 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
11040 gen.WriteGLES2TraceImplementationHeader(
11041 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
11042 gen.WriteGLES2TraceImplementation(
11043 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
11044 gen.WriteGLES2CLibImplementation(
11045 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
11046 gen.WriteCmdHelperHeader(
11047 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
11048 gen.WriteServiceImplementation(
11049 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
11050 gen.WriteServiceContextStateHeader(
11051 "gpu/command_buffer/service/context_state_autogen.h")
11052 gen.WriteServiceContextStateImpl(
11053 "gpu/command_buffer/service/context_state_impl_autogen.h")
11054 gen.WriteClientContextStateHeader(
11055 "gpu/command_buffer/client/client_context_state_autogen.h")
11056 gen.WriteClientContextStateImpl(
11057 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
11058 gen.WriteServiceUnitTests(
11059 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
11060 gen.WriteServiceUnitTestsForExtensions(
11061 "gpu/command_buffer/service/"
11062 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11063 gen.WriteServiceUtilsHeader(
11064 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11065 gen.WriteServiceUtilsImplementation(
11066 "gpu/command_buffer/service/"
11067 "gles2_cmd_validation_implementation_autogen.h")
11068 gen.WriteCommonUtilsHeader(
11069 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11070 gen.WriteCommonUtilsImpl(
11071 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11072 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11073 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
11074 "gles2_call_visitor")
11075 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
11076 gen.WriteMojoGLCallVisitorForExtension(
11077 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
11078 "CHROMIUM_texture_mailbox")
11079 gen.WriteMojoGLCallVisitorForExtension(
11080 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
11081 "CHROMIUM_sync_point")
11082 gen.WriteMojoGLCallVisitorForExtension(
11083 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
11084 "CHROMIUM_sub_image")
11085 gen.WriteMojoGLCallVisitorForExtension(
11086 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
11087 "CHROMIUM_miscellaneous")
11088 gen.WriteMojoGLCallVisitorForExtension(
11089 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
11090 "occlusion_query_EXT")
11091 gen.WriteMojoGLCallVisitorForExtension(
11092 mojo_gles2_prefix + "_chromium_image_autogen.h",
11093 "CHROMIUM_image")
11094 gen.WriteMojoGLCallVisitorForExtension(
11095 mojo_gles2_prefix + "_chromium_copy_texture_autogen.h",
11096 "CHROMIUM_copy_texture")
11097 gen.WriteMojoGLCallVisitorForExtension(
11098 mojo_gles2_prefix + "_chromium_pixel_transfer_buffer_object_autogen.h",
11099 "CHROMIUM_pixel_transfer_buffer_object")
11101 Format(gen.generated_cpp_filenames)
11103 if gen.errors > 0:
11104 print "%d errors" % gen.errors
11105 return 1
11106 return 0
11109 if __name__ == '__main__':
11110 sys.exit(main(sys.argv[1:]))