Reland "Non-SFI mode: Switch to newlib. (patchset #4 id:60001 of https://codereview...
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blobb4ad241fddc3368ae5721467a1dc5dc6654c56e1
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_UNPACK_FLIP_Y_CHROMIUM',
765 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
766 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
767 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
768 # we can add this because we emulate it if the driver does not support it.
769 'GL_VERTEX_ARRAY_BINDING_OES',
770 'GL_VIEWPORT',
772 'valid_es3': [
773 'GL_COPY_READ_BUFFER_BINDING',
774 'GL_COPY_WRITE_BUFFER_BINDING',
775 'GL_DRAW_BUFFER0',
776 'GL_DRAW_BUFFER1',
777 'GL_DRAW_BUFFER2',
778 'GL_DRAW_BUFFER3',
779 'GL_DRAW_BUFFER4',
780 'GL_DRAW_BUFFER5',
781 'GL_DRAW_BUFFER6',
782 'GL_DRAW_BUFFER7',
783 'GL_DRAW_BUFFER8',
784 'GL_DRAW_BUFFER9',
785 'GL_DRAW_BUFFER10',
786 'GL_DRAW_BUFFER11',
787 'GL_DRAW_BUFFER12',
788 'GL_DRAW_BUFFER13',
789 'GL_DRAW_BUFFER14',
790 'GL_DRAW_BUFFER15',
791 'GL_DRAW_FRAMEBUFFER_BINDING',
792 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
793 'GL_MAJOR_VERSION',
794 'GL_MAX_3D_TEXTURE_SIZE',
795 'GL_MAX_ARRAY_TEXTURE_LAYERS',
796 'GL_MAX_COLOR_ATTACHMENTS',
797 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
798 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
799 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
800 'GL_MAX_DRAW_BUFFERS',
801 'GL_MAX_ELEMENT_INDEX',
802 'GL_MAX_ELEMENTS_INDICES',
803 'GL_MAX_ELEMENTS_VERTICES',
804 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
805 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
806 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
807 'GL_MAX_PROGRAM_TEXEL_OFFSET',
808 'GL_MAX_SAMPLES',
809 'GL_MAX_SERVER_WAIT_TIMEOUT',
810 'GL_MAX_TEXTURE_LOD_BIAS',
811 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
812 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
813 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
814 'GL_MAX_UNIFORM_BLOCK_SIZE',
815 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
816 'GL_MAX_VARYING_COMPONENTS',
817 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
818 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
819 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
820 'GL_MIN_PROGRAM_TEXEL_OFFSET',
821 'GL_MINOR_VERSION',
822 'GL_NUM_EXTENSIONS',
823 'GL_NUM_PROGRAM_BINARY_FORMATS',
824 'GL_PACK_ROW_LENGTH',
825 'GL_PACK_SKIP_PIXELS',
826 'GL_PACK_SKIP_ROWS',
827 'GL_PIXEL_PACK_BUFFER_BINDING',
828 'GL_PIXEL_UNPACK_BUFFER_BINDING',
829 'GL_PROGRAM_BINARY_FORMATS',
830 'GL_READ_BUFFER',
831 'GL_READ_FRAMEBUFFER_BINDING',
832 'GL_SAMPLER_BINDING',
833 'GL_TEXTURE_BINDING_2D_ARRAY',
834 'GL_TEXTURE_BINDING_3D',
835 'GL_TRANSFORM_FEEDBACK_BINDING',
836 'GL_TRANSFORM_FEEDBACK_ACTIVE',
837 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
838 'GL_TRANSFORM_FEEDBACK_PAUSED',
839 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
840 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
841 'GL_UNIFORM_BUFFER_BINDING',
842 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
843 'GL_UNIFORM_BUFFER_SIZE',
844 'GL_UNIFORM_BUFFER_START',
845 'GL_UNPACK_IMAGE_HEIGHT',
846 'GL_UNPACK_ROW_LENGTH',
847 'GL_UNPACK_SKIP_IMAGES',
848 'GL_UNPACK_SKIP_PIXELS',
849 'GL_UNPACK_SKIP_ROWS',
850 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
851 # 'GL_VERTEX_ARRAY_BINDING',
853 'invalid': [
854 'GL_FOG_HINT',
857 'IndexedGLState': {
858 'type': 'GLenum',
859 'valid': [
860 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
862 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
863 'GL_UNIFORM_BUFFER_BINDING',
864 'GL_UNIFORM_BUFFER_SIZE',
865 'GL_UNIFORM_BUFFER_START',
867 'invalid': [
868 'GL_FOG_HINT',
871 'GetTexParamTarget': {
872 'type': 'GLenum',
873 'valid': [
874 'GL_TEXTURE_2D',
875 'GL_TEXTURE_CUBE_MAP',
877 'valid_es3': [
878 'GL_TEXTURE_2D_ARRAY',
879 'GL_TEXTURE_3D',
881 'invalid': [
882 'GL_PROXY_TEXTURE_CUBE_MAP',
885 'TextureTarget': {
886 'type': 'GLenum',
887 'valid': [
888 'GL_TEXTURE_2D',
889 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
890 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
891 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
892 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
893 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
894 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
896 'invalid': [
897 'GL_PROXY_TEXTURE_CUBE_MAP',
900 'Texture3DTarget': {
901 'type': 'GLenum',
902 'valid': [
903 'GL_TEXTURE_3D',
904 'GL_TEXTURE_2D_ARRAY',
906 'invalid': [
907 'GL_TEXTURE_2D',
910 'TextureBindTarget': {
911 'type': 'GLenum',
912 'valid': [
913 'GL_TEXTURE_2D',
914 'GL_TEXTURE_CUBE_MAP',
916 'valid_es3': [
917 'GL_TEXTURE_3D',
918 'GL_TEXTURE_2D_ARRAY',
920 'invalid': [
921 'GL_TEXTURE_1D',
922 'GL_TEXTURE_3D',
925 'TransformFeedbackBindTarget': {
926 'type': 'GLenum',
927 'valid': [
928 'GL_TRANSFORM_FEEDBACK',
930 'invalid': [
931 'GL_TEXTURE_2D',
934 'TransformFeedbackPrimitiveMode': {
935 'type': 'GLenum',
936 'valid': [
937 'GL_POINTS',
938 'GL_LINES',
939 'GL_TRIANGLES',
941 'invalid': [
942 'GL_LINE_LOOP',
945 'ShaderType': {
946 'type': 'GLenum',
947 'valid': [
948 'GL_VERTEX_SHADER',
949 'GL_FRAGMENT_SHADER',
951 'invalid': [
952 'GL_GEOMETRY_SHADER',
955 'FaceType': {
956 'type': 'GLenum',
957 'valid': [
958 'GL_FRONT',
959 'GL_BACK',
960 'GL_FRONT_AND_BACK',
963 'FaceMode': {
964 'type': 'GLenum',
965 'valid': [
966 'GL_CW',
967 'GL_CCW',
970 'CmpFunction': {
971 'type': 'GLenum',
972 'valid': [
973 'GL_NEVER',
974 'GL_LESS',
975 'GL_EQUAL',
976 'GL_LEQUAL',
977 'GL_GREATER',
978 'GL_NOTEQUAL',
979 'GL_GEQUAL',
980 'GL_ALWAYS',
983 'Equation': {
984 'type': 'GLenum',
985 'valid': [
986 'GL_FUNC_ADD',
987 'GL_FUNC_SUBTRACT',
988 'GL_FUNC_REVERSE_SUBTRACT',
990 'valid_es3': [
991 'GL_MIN',
992 'GL_MAX',
994 'invalid': [
995 'GL_NONE',
998 'SrcBlendFactor': {
999 'type': 'GLenum',
1000 'valid': [
1001 'GL_ZERO',
1002 'GL_ONE',
1003 'GL_SRC_COLOR',
1004 'GL_ONE_MINUS_SRC_COLOR',
1005 'GL_DST_COLOR',
1006 'GL_ONE_MINUS_DST_COLOR',
1007 'GL_SRC_ALPHA',
1008 'GL_ONE_MINUS_SRC_ALPHA',
1009 'GL_DST_ALPHA',
1010 'GL_ONE_MINUS_DST_ALPHA',
1011 'GL_CONSTANT_COLOR',
1012 'GL_ONE_MINUS_CONSTANT_COLOR',
1013 'GL_CONSTANT_ALPHA',
1014 'GL_ONE_MINUS_CONSTANT_ALPHA',
1015 'GL_SRC_ALPHA_SATURATE',
1018 'DstBlendFactor': {
1019 'type': 'GLenum',
1020 'valid': [
1021 'GL_ZERO',
1022 'GL_ONE',
1023 'GL_SRC_COLOR',
1024 'GL_ONE_MINUS_SRC_COLOR',
1025 'GL_DST_COLOR',
1026 'GL_ONE_MINUS_DST_COLOR',
1027 'GL_SRC_ALPHA',
1028 'GL_ONE_MINUS_SRC_ALPHA',
1029 'GL_DST_ALPHA',
1030 'GL_ONE_MINUS_DST_ALPHA',
1031 'GL_CONSTANT_COLOR',
1032 'GL_ONE_MINUS_CONSTANT_COLOR',
1033 'GL_CONSTANT_ALPHA',
1034 'GL_ONE_MINUS_CONSTANT_ALPHA',
1037 'Capability': {
1038 'type': 'GLenum',
1039 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1040 if 'es3' not in cap or cap['es3'] != True],
1041 'valid_es3': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1042 if 'es3' in cap and cap['es3'] == True],
1043 'invalid': [
1044 'GL_CLIP_PLANE0',
1045 'GL_POINT_SPRITE',
1048 'DrawMode': {
1049 'type': 'GLenum',
1050 'valid': [
1051 'GL_POINTS',
1052 'GL_LINE_STRIP',
1053 'GL_LINE_LOOP',
1054 'GL_LINES',
1055 'GL_TRIANGLE_STRIP',
1056 'GL_TRIANGLE_FAN',
1057 'GL_TRIANGLES',
1059 'invalid': [
1060 'GL_QUADS',
1061 'GL_POLYGON',
1064 'IndexType': {
1065 'type': 'GLenum',
1066 'valid': [
1067 'GL_UNSIGNED_BYTE',
1068 'GL_UNSIGNED_SHORT',
1070 'valid_es3': [
1071 'GL_UNSIGNED_INT',
1073 'invalid': [
1074 'GL_INT',
1077 'GetMaxIndexType': {
1078 'type': 'GLenum',
1079 'valid': [
1080 'GL_UNSIGNED_BYTE',
1081 'GL_UNSIGNED_SHORT',
1082 'GL_UNSIGNED_INT',
1084 'invalid': [
1085 'GL_INT',
1088 'Attachment': {
1089 'type': 'GLenum',
1090 'valid': [
1091 'GL_COLOR_ATTACHMENT0',
1092 'GL_DEPTH_ATTACHMENT',
1093 'GL_STENCIL_ATTACHMENT',
1095 'valid_es3': [
1096 'GL_DEPTH_STENCIL_ATTACHMENT',
1099 'BackbufferAttachment': {
1100 'type': 'GLenum',
1101 'valid': [
1102 'GL_COLOR_EXT',
1103 'GL_DEPTH_EXT',
1104 'GL_STENCIL_EXT',
1107 'BufferParameter': {
1108 'type': 'GLenum',
1109 'valid': [
1110 'GL_BUFFER_SIZE',
1111 'GL_BUFFER_USAGE',
1113 'valid_es3': [
1114 'GL_BUFFER_ACCESS_FLAGS',
1115 'GL_BUFFER_MAPPED',
1116 'GL_BUFFER_MAP_LENGTH',
1117 'GL_BUFFER_MAP_OFFSET',
1119 'invalid': [
1120 'GL_PIXEL_PACK_BUFFER',
1123 'BufferMode': {
1124 'type': 'GLenum',
1125 'valid': [
1126 'GL_INTERLEAVED_ATTRIBS',
1127 'GL_SEPARATE_ATTRIBS',
1129 'invalid': [
1130 'GL_PIXEL_PACK_BUFFER',
1133 'FrameBufferParameter': {
1134 'type': 'GLenum',
1135 'valid': [
1136 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1137 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1138 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1139 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1141 'valid_es3': [
1142 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1143 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1144 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1145 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1146 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1147 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1148 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1149 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1150 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1153 'MatrixMode': {
1154 'type': 'GLenum',
1155 'valid': [
1156 'GL_PATH_PROJECTION_CHROMIUM',
1157 'GL_PATH_MODELVIEW_CHROMIUM',
1160 'ProgramParameter': {
1161 'type': 'GLenum',
1162 'valid': [
1163 'GL_DELETE_STATUS',
1164 'GL_LINK_STATUS',
1165 'GL_VALIDATE_STATUS',
1166 'GL_INFO_LOG_LENGTH',
1167 'GL_ATTACHED_SHADERS',
1168 'GL_ACTIVE_ATTRIBUTES',
1169 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1170 'GL_ACTIVE_UNIFORMS',
1171 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1173 'valid_es3': [
1174 'GL_ACTIVE_UNIFORM_BLOCKS',
1175 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1176 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1177 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1178 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1180 'invalid': [
1181 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1184 'QueryObjectParameter': {
1185 'type': 'GLenum',
1186 'valid': [
1187 'GL_QUERY_RESULT_EXT',
1188 'GL_QUERY_RESULT_AVAILABLE_EXT',
1191 'QueryParameter': {
1192 'type': 'GLenum',
1193 'valid': [
1194 'GL_CURRENT_QUERY_EXT',
1197 'QueryTarget': {
1198 'type': 'GLenum',
1199 'valid': [
1200 'GL_ANY_SAMPLES_PASSED_EXT',
1201 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1202 'GL_COMMANDS_ISSUED_CHROMIUM',
1203 'GL_LATENCY_QUERY_CHROMIUM',
1204 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1205 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1206 'GL_COMMANDS_COMPLETED_CHROMIUM',
1209 'RenderBufferParameter': {
1210 'type': 'GLenum',
1211 'valid': [
1212 'GL_RENDERBUFFER_RED_SIZE',
1213 'GL_RENDERBUFFER_GREEN_SIZE',
1214 'GL_RENDERBUFFER_BLUE_SIZE',
1215 'GL_RENDERBUFFER_ALPHA_SIZE',
1216 'GL_RENDERBUFFER_DEPTH_SIZE',
1217 'GL_RENDERBUFFER_STENCIL_SIZE',
1218 'GL_RENDERBUFFER_WIDTH',
1219 'GL_RENDERBUFFER_HEIGHT',
1220 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1222 'valid_es3': [
1223 'GL_RENDERBUFFER_SAMPLES',
1226 'InternalFormatParameter': {
1227 'type': 'GLenum',
1228 'valid': [
1229 'GL_NUM_SAMPLE_COUNTS',
1230 'GL_SAMPLES',
1233 'SamplerParameter': {
1234 'type': 'GLenum',
1235 'valid': [
1236 'GL_TEXTURE_MAG_FILTER',
1237 'GL_TEXTURE_MIN_FILTER',
1238 'GL_TEXTURE_MIN_LOD',
1239 'GL_TEXTURE_MAX_LOD',
1240 'GL_TEXTURE_WRAP_S',
1241 'GL_TEXTURE_WRAP_T',
1242 'GL_TEXTURE_WRAP_R',
1243 'GL_TEXTURE_COMPARE_MODE',
1244 'GL_TEXTURE_COMPARE_FUNC',
1246 'invalid': [
1247 'GL_GENERATE_MIPMAP',
1250 'ShaderParameter': {
1251 'type': 'GLenum',
1252 'valid': [
1253 'GL_SHADER_TYPE',
1254 'GL_DELETE_STATUS',
1255 'GL_COMPILE_STATUS',
1256 'GL_INFO_LOG_LENGTH',
1257 'GL_SHADER_SOURCE_LENGTH',
1258 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1261 'ShaderPrecision': {
1262 'type': 'GLenum',
1263 'valid': [
1264 'GL_LOW_FLOAT',
1265 'GL_MEDIUM_FLOAT',
1266 'GL_HIGH_FLOAT',
1267 'GL_LOW_INT',
1268 'GL_MEDIUM_INT',
1269 'GL_HIGH_INT',
1272 'StringType': {
1273 'type': 'GLenum',
1274 'valid': [
1275 'GL_VENDOR',
1276 'GL_RENDERER',
1277 'GL_VERSION',
1278 'GL_SHADING_LANGUAGE_VERSION',
1279 'GL_EXTENSIONS',
1282 'TextureParameter': {
1283 'type': 'GLenum',
1284 'valid': [
1285 'GL_TEXTURE_MAG_FILTER',
1286 'GL_TEXTURE_MIN_FILTER',
1287 'GL_TEXTURE_POOL_CHROMIUM',
1288 'GL_TEXTURE_WRAP_S',
1289 'GL_TEXTURE_WRAP_T',
1291 'valid_es3': [
1292 'GL_TEXTURE_BASE_LEVEL',
1293 'GL_TEXTURE_COMPARE_FUNC',
1294 'GL_TEXTURE_COMPARE_MODE',
1295 'GL_TEXTURE_IMMUTABLE_FORMAT',
1296 'GL_TEXTURE_IMMUTABLE_LEVELS',
1297 'GL_TEXTURE_MAX_LEVEL',
1298 'GL_TEXTURE_MAX_LOD',
1299 'GL_TEXTURE_MIN_LOD',
1300 'GL_TEXTURE_WRAP_R',
1302 'invalid': [
1303 'GL_GENERATE_MIPMAP',
1306 'TexturePool': {
1307 'type': 'GLenum',
1308 'valid': [
1309 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1310 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1313 'TextureWrapMode': {
1314 'type': 'GLenum',
1315 'valid': [
1316 'GL_CLAMP_TO_EDGE',
1317 'GL_MIRRORED_REPEAT',
1318 'GL_REPEAT',
1321 'TextureMinFilterMode': {
1322 'type': 'GLenum',
1323 'valid': [
1324 'GL_NEAREST',
1325 'GL_LINEAR',
1326 'GL_NEAREST_MIPMAP_NEAREST',
1327 'GL_LINEAR_MIPMAP_NEAREST',
1328 'GL_NEAREST_MIPMAP_LINEAR',
1329 'GL_LINEAR_MIPMAP_LINEAR',
1332 'TextureMagFilterMode': {
1333 'type': 'GLenum',
1334 'valid': [
1335 'GL_NEAREST',
1336 'GL_LINEAR',
1339 'TextureCompareFunc': {
1340 'type': 'GLenum',
1341 'valid': [
1342 'GL_LEQUAL',
1343 'GL_GEQUAL',
1344 'GL_LESS',
1345 'GL_GREATER',
1346 'GL_EQUAL',
1347 'GL_NOTEQUAL',
1348 'GL_ALWAYS',
1349 'GL_NEVER',
1352 'TextureCompareMode': {
1353 'type': 'GLenum',
1354 'valid': [
1355 'GL_NONE',
1356 'GL_COMPARE_REF_TO_TEXTURE',
1359 'TextureUsage': {
1360 'type': 'GLenum',
1361 'valid': [
1362 'GL_NONE',
1363 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1366 'VertexAttribute': {
1367 'type': 'GLenum',
1368 'valid': [
1369 # some enum that the decoder actually passes through to GL needs
1370 # to be the first listed here since it's used in unit tests.
1371 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1372 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1373 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1374 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1375 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1376 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1377 'GL_CURRENT_VERTEX_ATTRIB',
1379 'valid_es3': [
1380 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1381 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1384 'VertexPointer': {
1385 'type': 'GLenum',
1386 'valid': [
1387 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1390 'HintTarget': {
1391 'type': 'GLenum',
1392 'valid': [
1393 'GL_GENERATE_MIPMAP_HINT',
1395 'valid_es3': [
1396 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1398 'invalid': [
1399 'GL_PERSPECTIVE_CORRECTION_HINT',
1402 'HintMode': {
1403 'type': 'GLenum',
1404 'valid': [
1405 'GL_FASTEST',
1406 'GL_NICEST',
1407 'GL_DONT_CARE',
1410 'PixelStore': {
1411 'type': 'GLenum',
1412 'valid': [
1413 'GL_PACK_ALIGNMENT',
1414 'GL_UNPACK_ALIGNMENT',
1415 'GL_UNPACK_FLIP_Y_CHROMIUM',
1416 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1417 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1419 'valid_es3': [
1420 'GL_PACK_ROW_LENGTH',
1421 'GL_PACK_SKIP_PIXELS',
1422 'GL_PACK_SKIP_ROWS',
1423 'GL_UNPACK_ROW_LENGTH',
1424 'GL_UNPACK_IMAGE_HEIGHT',
1425 'GL_UNPACK_SKIP_PIXELS',
1426 'GL_UNPACK_SKIP_ROWS',
1427 'GL_UNPACK_SKIP_IMAGES',
1429 'invalid': [
1430 'GL_PACK_SWAP_BYTES',
1431 'GL_UNPACK_SWAP_BYTES',
1434 'PixelStoreAlignment': {
1435 'type': 'GLint',
1436 'valid': [
1437 '1',
1438 '2',
1439 '4',
1440 '8',
1442 'invalid': [
1443 '3',
1444 '9',
1447 'ReadPixelFormat': {
1448 'type': 'GLenum',
1449 'valid': [
1450 'GL_ALPHA',
1451 'GL_RGB',
1452 'GL_RGBA',
1454 'valid_es3': [
1455 'GL_RGBA_INTEGER',
1457 'deprecated_es3': [
1458 'GL_ALPHA',
1459 'GL_RGB',
1462 'PixelType': {
1463 'type': 'GLenum',
1464 'valid': [
1465 'GL_UNSIGNED_BYTE',
1466 'GL_UNSIGNED_SHORT_5_6_5',
1467 'GL_UNSIGNED_SHORT_4_4_4_4',
1468 'GL_UNSIGNED_SHORT_5_5_5_1',
1470 'valid_es3': [
1471 'GL_BYTE',
1472 'GL_UNSIGNED_SHORT',
1473 'GL_SHORT',
1474 'GL_UNSIGNED_INT',
1475 'GL_INT',
1476 'GL_HALF_FLOAT',
1477 'GL_FLOAT',
1478 'GL_UNSIGNED_INT_2_10_10_10_REV',
1479 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1480 'GL_UNSIGNED_INT_5_9_9_9_REV',
1481 'GL_UNSIGNED_INT_24_8',
1482 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1484 'invalid': [
1485 'GL_UNSIGNED_BYTE_3_3_2',
1488 'ReadPixelType': {
1489 'type': 'GLenum',
1490 'valid': [
1491 'GL_UNSIGNED_BYTE',
1492 'GL_UNSIGNED_SHORT_5_6_5',
1493 'GL_UNSIGNED_SHORT_4_4_4_4',
1494 'GL_UNSIGNED_SHORT_5_5_5_1',
1496 'invalid': [
1497 'GL_SHORT',
1499 'valid_es3': [
1500 'GL_UNSIGNED_INT',
1501 'GL_INT',
1502 'GL_FLOAT',
1504 'deprecated_es3': [
1505 'GL_UNSIGNED_SHORT_5_6_5',
1506 'GL_UNSIGNED_SHORT_4_4_4_4',
1507 'GL_UNSIGNED_SHORT_5_5_5_1',
1510 'RenderBufferFormat': {
1511 'type': 'GLenum',
1512 'valid': [
1513 'GL_RGBA4',
1514 'GL_RGB565',
1515 'GL_RGB5_A1',
1516 'GL_DEPTH_COMPONENT16',
1517 'GL_STENCIL_INDEX8',
1519 'valid_es3': [
1520 'GL_R8',
1521 'GL_R8UI',
1522 'GL_R8I',
1523 'GL_R16UI',
1524 'GL_R16I',
1525 'GL_R32UI',
1526 'GL_R32I',
1527 'GL_RG8',
1528 'GL_RG8UI',
1529 'GL_RG8I',
1530 'GL_RG16UI',
1531 'GL_RG16I',
1532 'GL_RG32UI',
1533 'GL_RG32I',
1534 'GL_RGB8',
1535 'GL_RGBA8',
1536 'GL_SRGB8_ALPHA8',
1537 'GL_RGB10_A2',
1538 'GL_RGBA8UI',
1539 'GL_RGBA8I',
1540 'GL_RGB10_A2UI',
1541 'GL_RGBA16UI',
1542 'GL_RGBA16I',
1543 'GL_RGBA32UI',
1544 'GL_RGBA32I',
1545 'GL_DEPTH_COMPONENT24',
1546 'GL_DEPTH_COMPONENT32F',
1547 'GL_DEPTH24_STENCIL8',
1548 'GL_DEPTH32F_STENCIL8',
1551 'ShaderBinaryFormat': {
1552 'type': 'GLenum',
1553 'valid': [
1556 'StencilOp': {
1557 'type': 'GLenum',
1558 'valid': [
1559 'GL_KEEP',
1560 'GL_ZERO',
1561 'GL_REPLACE',
1562 'GL_INCR',
1563 'GL_INCR_WRAP',
1564 'GL_DECR',
1565 'GL_DECR_WRAP',
1566 'GL_INVERT',
1569 'TextureFormat': {
1570 'type': 'GLenum',
1571 'valid': [
1572 'GL_ALPHA',
1573 'GL_LUMINANCE',
1574 'GL_LUMINANCE_ALPHA',
1575 'GL_RGB',
1576 'GL_RGBA',
1578 'valid_es3': [
1579 'GL_RED',
1580 'GL_RED_INTEGER',
1581 'GL_RG',
1582 'GL_RG_INTEGER',
1583 'GL_RGB_INTEGER',
1584 'GL_RGBA_INTEGER',
1585 'GL_DEPTH_COMPONENT',
1586 'GL_DEPTH_STENCIL',
1588 'invalid': [
1589 'GL_BGRA',
1590 'GL_BGR',
1593 'TextureInternalFormat': {
1594 'type': 'GLenum',
1595 'valid': [
1596 'GL_ALPHA',
1597 'GL_LUMINANCE',
1598 'GL_LUMINANCE_ALPHA',
1599 'GL_RGB',
1600 'GL_RGBA',
1602 'valid_es3': [
1603 'GL_R8',
1604 'GL_R8_SNORM',
1605 'GL_R16F',
1606 'GL_R32F',
1607 'GL_R8UI',
1608 'GL_R8I',
1609 'GL_R16UI',
1610 'GL_R16I',
1611 'GL_R32UI',
1612 'GL_R32I',
1613 'GL_RG8',
1614 'GL_RG8_SNORM',
1615 'GL_RG16F',
1616 'GL_RG32F',
1617 'GL_RG8UI',
1618 'GL_RG8I',
1619 'GL_RG16UI',
1620 'GL_RG16I',
1621 'GL_RG32UI',
1622 'GL_RG32I',
1623 'GL_RGB8',
1624 'GL_SRGB8',
1625 'GL_RGB565',
1626 'GL_RGB8_SNORM',
1627 'GL_R11F_G11F_B10F',
1628 'GL_RGB9_E5',
1629 'GL_RGB16F',
1630 'GL_RGB32F',
1631 'GL_RGB8UI',
1632 'GL_RGB8I',
1633 'GL_RGB16UI',
1634 'GL_RGB16I',
1635 'GL_RGB32UI',
1636 'GL_RGB32I',
1637 'GL_RGBA8',
1638 'GL_SRGB8_ALPHA8',
1639 'GL_RGBA8_SNORM',
1640 'GL_RGB5_A1',
1641 'GL_RGBA4',
1642 'GL_RGB10_A2',
1643 'GL_RGBA16F',
1644 'GL_RGBA32F',
1645 'GL_RGBA8UI',
1646 'GL_RGBA8I',
1647 'GL_RGB10_A2UI',
1648 'GL_RGBA16UI',
1649 'GL_RGBA16I',
1650 'GL_RGBA32UI',
1651 'GL_RGBA32I',
1652 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1653 # We will reject them dynamically in GPU command buffer.
1654 'GL_DEPTH_COMPONENT16',
1655 'GL_DEPTH_COMPONENT24',
1656 'GL_DEPTH_COMPONENT32F',
1657 'GL_DEPTH24_STENCIL8',
1658 'GL_DEPTH32F_STENCIL8',
1660 'invalid': [
1661 'GL_BGRA',
1662 'GL_BGR',
1665 'TextureInternalFormatStorage': {
1666 'type': 'GLenum',
1667 'valid': [
1668 'GL_RGB565',
1669 'GL_RGBA4',
1670 'GL_RGB5_A1',
1671 'GL_ALPHA8_EXT',
1672 'GL_LUMINANCE8_EXT',
1673 'GL_LUMINANCE8_ALPHA8_EXT',
1674 'GL_RGB8_OES',
1675 'GL_RGBA8_OES',
1677 'valid_es3': [
1678 'GL_R8',
1679 'GL_R8_SNORM',
1680 'GL_R16F',
1681 'GL_R32F',
1682 'GL_R8UI',
1683 'GL_R8I',
1684 'GL_R16UI',
1685 'GL_R16I',
1686 'GL_R32UI',
1687 'GL_R32I',
1688 'GL_RG8',
1689 'GL_RG8_SNORM',
1690 'GL_RG16F',
1691 'GL_RG32F',
1692 'GL_RG8UI',
1693 'GL_RG8I',
1694 'GL_RG16UI',
1695 'GL_RG16I',
1696 'GL_RG32UI',
1697 'GL_RG32I',
1698 'GL_SRGB8',
1699 'GL_RGB8_SNORM',
1700 'GL_R11F_G11F_B10F',
1701 'GL_RGB9_E5',
1702 'GL_RGB16F',
1703 'GL_RGB32F',
1704 'GL_RGB8UI',
1705 'GL_RGB8I',
1706 'GL_RGB16UI',
1707 'GL_RGB16I',
1708 'GL_RGB32UI',
1709 'GL_RGB32I',
1710 'GL_SRGB8_ALPHA8',
1711 'GL_RGBA8_SNORM',
1712 'GL_RGB10_A2',
1713 'GL_RGBA16F',
1714 'GL_RGBA32F',
1715 'GL_RGBA8UI',
1716 'GL_RGBA8I',
1717 'GL_RGB10_A2UI',
1718 'GL_RGBA16UI',
1719 'GL_RGBA16I',
1720 'GL_RGBA32UI',
1721 'GL_RGBA32I',
1722 'GL_DEPTH_COMPONENT16',
1723 'GL_DEPTH_COMPONENT24',
1724 'GL_DEPTH_COMPONENT32F',
1725 'GL_DEPTH24_STENCIL8',
1726 'GL_DEPTH32F_STENCIL8',
1727 'GL_COMPRESSED_R11_EAC',
1728 'GL_COMPRESSED_SIGNED_R11_EAC',
1729 'GL_COMPRESSED_RG11_EAC',
1730 'GL_COMPRESSED_SIGNED_RG11_EAC',
1731 'GL_COMPRESSED_RGB8_ETC2',
1732 'GL_COMPRESSED_SRGB8_ETC2',
1733 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1734 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1735 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1736 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1738 'deprecated_es3': [
1739 'GL_ALPHA8_EXT',
1740 'GL_LUMINANCE8_EXT',
1741 'GL_LUMINANCE8_ALPHA8_EXT',
1742 'GL_ALPHA16F_EXT',
1743 'GL_LUMINANCE16F_EXT',
1744 'GL_LUMINANCE_ALPHA16F_EXT',
1745 'GL_ALPHA32F_EXT',
1746 'GL_LUMINANCE32F_EXT',
1747 'GL_LUMINANCE_ALPHA32F_EXT',
1750 'ImageInternalFormat': {
1751 'type': 'GLenum',
1752 'valid': [
1753 'GL_RGB',
1754 'GL_RGB_YUV_420_CHROMIUM',
1755 'GL_RGBA',
1758 'ImageUsage': {
1759 'type': 'GLenum',
1760 'valid': [
1761 'GL_MAP_CHROMIUM',
1762 'GL_SCANOUT_CHROMIUM'
1765 'ValueBufferTarget': {
1766 'type': 'GLenum',
1767 'valid': [
1768 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1771 'SubscriptionTarget': {
1772 'type': 'GLenum',
1773 'valid': [
1774 'GL_MOUSE_POSITION_CHROMIUM',
1777 'UniformParameter': {
1778 'type': 'GLenum',
1779 'valid': [
1780 'GL_UNIFORM_SIZE',
1781 'GL_UNIFORM_TYPE',
1782 'GL_UNIFORM_NAME_LENGTH',
1783 'GL_UNIFORM_BLOCK_INDEX',
1784 'GL_UNIFORM_OFFSET',
1785 'GL_UNIFORM_ARRAY_STRIDE',
1786 'GL_UNIFORM_MATRIX_STRIDE',
1787 'GL_UNIFORM_IS_ROW_MAJOR',
1789 'invalid': [
1790 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1793 'UniformBlockParameter': {
1794 'type': 'GLenum',
1795 'valid': [
1796 'GL_UNIFORM_BLOCK_BINDING',
1797 'GL_UNIFORM_BLOCK_DATA_SIZE',
1798 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1799 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1800 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1801 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1802 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1804 'invalid': [
1805 'GL_NEAREST',
1808 'VertexAttribType': {
1809 'type': 'GLenum',
1810 'valid': [
1811 'GL_BYTE',
1812 'GL_UNSIGNED_BYTE',
1813 'GL_SHORT',
1814 'GL_UNSIGNED_SHORT',
1815 # 'GL_FIXED', // This is not available on Desktop GL.
1816 'GL_FLOAT',
1818 'valid_es3': [
1819 'GL_INT',
1820 'GL_UNSIGNED_INT',
1821 'GL_HALF_FLOAT',
1822 'GL_INT_2_10_10_10_REV',
1823 'GL_UNSIGNED_INT_2_10_10_10_REV',
1825 'invalid': [
1826 'GL_DOUBLE',
1829 'VertexAttribIType': {
1830 'type': 'GLenum',
1831 'valid': [
1832 'GL_BYTE',
1833 'GL_UNSIGNED_BYTE',
1834 'GL_SHORT',
1835 'GL_UNSIGNED_SHORT',
1836 'GL_INT',
1837 'GL_UNSIGNED_INT',
1839 'invalid': [
1840 'GL_FLOAT',
1841 'GL_DOUBLE',
1844 'TextureBorder': {
1845 'type': 'GLint',
1846 'is_complete': True,
1847 'valid': [
1848 '0',
1850 'invalid': [
1851 '1',
1854 'VertexAttribSize': {
1855 'type': 'GLint',
1856 'valid': [
1857 '1',
1858 '2',
1859 '3',
1860 '4',
1862 'invalid': [
1863 '0',
1864 '5',
1867 'ZeroOnly': {
1868 'type': 'GLint',
1869 'is_complete': True,
1870 'valid': [
1871 '0',
1873 'invalid': [
1874 '1',
1877 'FalseOnly': {
1878 'type': 'GLboolean',
1879 'is_complete': True,
1880 'valid': [
1881 'false',
1883 'invalid': [
1884 'true',
1887 'ResetStatus': {
1888 'type': 'GLenum',
1889 'valid': [
1890 'GL_GUILTY_CONTEXT_RESET_ARB',
1891 'GL_INNOCENT_CONTEXT_RESET_ARB',
1892 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1895 'SyncCondition': {
1896 'type': 'GLenum',
1897 'is_complete': True,
1898 'valid': [
1899 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1901 'invalid': [
1902 '0',
1905 'SyncFlags': {
1906 'type': 'GLbitfield',
1907 'is_complete': True,
1908 'valid': [
1909 '0',
1911 'invalid': [
1912 '1',
1915 'SyncFlushFlags': {
1916 'type': 'GLbitfield',
1917 'valid': [
1918 'GL_SYNC_FLUSH_COMMANDS_BIT',
1919 '0',
1921 'invalid': [
1922 '0xFFFFFFFF',
1925 'SyncParameter': {
1926 'type': 'GLenum',
1927 'valid': [
1928 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1929 'GL_OBJECT_TYPE',
1930 'GL_SYNC_CONDITION',
1931 'GL_SYNC_FLAGS',
1933 'invalid': [
1934 'GL_SYNC_FENCE',
1939 # This table specifies the different pepper interfaces that are supported for
1940 # GL commands. 'dev' is true if it's a dev interface.
1941 _PEPPER_INTERFACES = [
1942 {'name': '', 'dev': False},
1943 {'name': 'InstancedArrays', 'dev': False},
1944 {'name': 'FramebufferBlit', 'dev': False},
1945 {'name': 'FramebufferMultisample', 'dev': False},
1946 {'name': 'ChromiumEnableFeature', 'dev': False},
1947 {'name': 'ChromiumMapSub', 'dev': False},
1948 {'name': 'Query', 'dev': False},
1949 {'name': 'VertexArrayObject', 'dev': False},
1950 {'name': 'DrawBuffers', 'dev': True},
1953 # A function info object specifies the type and other special data for the
1954 # command that will be generated. A base function info object is generated by
1955 # parsing the "cmd_buffer_functions.txt", one for each function in the
1956 # file. These function info objects can be augmented and their values can be
1957 # overridden by adding an object to the table below.
1959 # Must match function names specified in "cmd_buffer_functions.txt".
1961 # cmd_comment: A comment added to the cmd format.
1962 # type: defines which handler will be used to generate code.
1963 # decoder_func: defines which function to call in the decoder to execute the
1964 # corresponding GL command. If not specified the GL command will
1965 # be called directly.
1966 # gl_test_func: GL function that is expected to be called when testing.
1967 # cmd_args: The arguments to use for the command. This overrides generating
1968 # them based on the GL function arguments.
1969 # gen_cmd: Whether or not this function geneates a command. Default = True.
1970 # data_transfer_methods: Array of methods that are used for transfering the
1971 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1972 # The default is 'immediate' if the command has one pointer
1973 # argument, otherwise 'shm'. One command is generated for each
1974 # transfer method. Affects only commands which are not of type
1975 # 'HandWritten', 'GETn' or 'GLcharN'.
1976 # Note: the command arguments that affect this are the final args,
1977 # taking cmd_args override into consideration.
1978 # impl_func: Whether or not to generate the GLES2Implementation part of this
1979 # command.
1980 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1981 # for this command.
1982 # needs_size: If True a data_size field is added to the command.
1983 # count: The number of units per element. For PUTn or PUT types.
1984 # use_count_func: If True the actual data count needs to be computed; the count
1985 # argument specifies the maximum count.
1986 # unit_test: If False no service side unit test will be generated.
1987 # client_test: If False no client side unit test will be generated.
1988 # expectation: If False the unit test will have no expected calls.
1989 # gen_func: Name of function that generates GL resource for corresponding
1990 # bind function.
1991 # states: array of states that get set by this function corresponding to
1992 # the given arguments
1993 # state_flag: name of flag that is set to true when function is called.
1994 # no_gl: no GL function is called.
1995 # valid_args: A dictionary of argument indices to args to use in unit tests
1996 # when they can not be automatically determined.
1997 # pepper_interface: The pepper interface that is used for this extension
1998 # pepper_name: The name of the function as exposed to pepper.
1999 # pepper_args: A string representing the argument list (what would appear in
2000 # C/C++ between the parentheses for the function declaration)
2001 # that the Pepper API expects for this function. Use this only if
2002 # the stable Pepper API differs from the GLES2 argument list.
2003 # invalid_test: False if no invalid test needed.
2004 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2005 # first_element_only: For PUT types, True if only the first element of an
2006 # array is used and we end up calling the single value
2007 # corresponding function. eg. TexParameteriv -> TexParameteri
2008 # extension: Function is an extension to GL and should not be exposed to
2009 # pepper unless pepper_interface is defined.
2010 # extension_flag: Function is an extension and should be enabled only when
2011 # the corresponding feature info flag is enabled. Implies
2012 # 'extension': True.
2013 # not_shared: For GENn types, True if objects can't be shared between contexts
2014 # unsafe: True = no validation is implemented on the service side and the
2015 # command is only available with --enable-unsafe-es3-apis.
2016 # id_mapping: A list of resource type names whose client side IDs need to be
2017 # mapped to service side IDs. This is only used for unsafe APIs.
2019 _FUNCTION_INFO = {
2020 'ActiveTexture': {
2021 'decoder_func': 'DoActiveTexture',
2022 'unit_test': False,
2023 'impl_func': False,
2024 'client_test': False,
2026 'AttachShader': {'decoder_func': 'DoAttachShader'},
2027 'BindAttribLocation': {
2028 'type': 'GLchar',
2029 'data_transfer_methods': ['bucket'],
2030 'needs_size': True,
2032 'BindBuffer': {
2033 'type': 'Bind',
2034 'decoder_func': 'DoBindBuffer',
2035 'gen_func': 'GenBuffersARB',
2037 'BindBufferBase': {
2038 'type': 'Bind',
2039 'id_mapping': [ 'Buffer' ],
2040 'gen_func': 'GenBuffersARB',
2041 'unsafe': True,
2043 'BindBufferRange': {
2044 'type': 'Bind',
2045 'id_mapping': [ 'Buffer' ],
2046 'gen_func': 'GenBuffersARB',
2047 'valid_args': {
2048 '3': '4',
2049 '4': '4'
2051 'unsafe': True,
2053 'BindFramebuffer': {
2054 'type': 'Bind',
2055 'decoder_func': 'DoBindFramebuffer',
2056 'gl_test_func': 'glBindFramebufferEXT',
2057 'gen_func': 'GenFramebuffersEXT',
2058 'trace_level': 1,
2060 'BindRenderbuffer': {
2061 'type': 'Bind',
2062 'decoder_func': 'DoBindRenderbuffer',
2063 'gl_test_func': 'glBindRenderbufferEXT',
2064 'gen_func': 'GenRenderbuffersEXT',
2066 'BindSampler': {
2067 'type': 'Bind',
2068 'id_mapping': [ 'Sampler' ],
2069 'unsafe': True,
2071 'BindTexture': {
2072 'type': 'Bind',
2073 'decoder_func': 'DoBindTexture',
2074 'gen_func': 'GenTextures',
2075 # TODO(gman): remove this once client side caching works.
2076 'client_test': False,
2077 'trace_level': 2,
2079 'BindTransformFeedback': {
2080 'type': 'Bind',
2081 'id_mapping': [ 'TransformFeedback' ],
2082 'unsafe': True,
2084 'BlitFramebufferCHROMIUM': {
2085 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2086 'unit_test': False,
2087 'extension_flag': 'chromium_framebuffer_multisample',
2088 'pepper_interface': 'FramebufferBlit',
2089 'pepper_name': 'BlitFramebufferEXT',
2090 'defer_reads': True,
2091 'defer_draws': True,
2092 'trace_level': 1,
2094 'BufferData': {
2095 'type': 'Manual',
2096 'data_transfer_methods': ['shm'],
2097 'client_test': False,
2098 'trace_level': 2,
2100 'BufferSubData': {
2101 'type': 'Data',
2102 'client_test': False,
2103 'decoder_func': 'DoBufferSubData',
2104 'data_transfer_methods': ['shm'],
2105 'trace_level': 2,
2107 'CheckFramebufferStatus': {
2108 'type': 'Is',
2109 'decoder_func': 'DoCheckFramebufferStatus',
2110 'gl_test_func': 'glCheckFramebufferStatusEXT',
2111 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2112 'result': ['GLenum'],
2114 'Clear': {
2115 'decoder_func': 'DoClear',
2116 'defer_draws': True,
2117 'trace_level': 2,
2119 'ClearBufferiv': {
2120 'type': 'PUT',
2121 'use_count_func': True,
2122 'count': 4,
2123 'unsafe': True,
2124 'trace_level': 2,
2126 'ClearBufferuiv': {
2127 'type': 'PUT',
2128 'count': 4,
2129 'unsafe': True,
2130 'trace_level': 2,
2132 'ClearBufferfv': {
2133 'type': 'PUT',
2134 'use_count_func': True,
2135 'count': 4,
2136 'unsafe': True,
2137 'trace_level': 2,
2139 'ClearBufferfi': {
2140 'unsafe': True,
2141 'trace_level': 2,
2143 'ClearColor': {
2144 'type': 'StateSet',
2145 'state': 'ClearColor',
2147 'ClearDepthf': {
2148 'type': 'StateSet',
2149 'state': 'ClearDepthf',
2150 'decoder_func': 'glClearDepth',
2151 'gl_test_func': 'glClearDepth',
2152 'valid_args': {
2153 '0': '0.5f'
2156 'ClientWaitSync': {
2157 'type': 'Custom',
2158 'data_transfer_methods': ['shm'],
2159 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2160 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2161 'unsafe': True,
2162 'result': ['GLenum'],
2163 'trace_level': 2,
2165 'ColorMask': {
2166 'type': 'StateSet',
2167 'state': 'ColorMask',
2168 'no_gl': True,
2169 'expectation': False,
2171 'ConsumeTextureCHROMIUM': {
2172 'decoder_func': 'DoConsumeTextureCHROMIUM',
2173 'impl_func': False,
2174 'type': 'PUT',
2175 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2176 'unit_test': False,
2177 'client_test': False,
2178 'extension': "CHROMIUM_texture_mailbox",
2179 'chromium': True,
2180 'trace_level': 2,
2182 'CopyBufferSubData': {
2183 'unsafe': True,
2185 'CreateAndConsumeTextureCHROMIUM': {
2186 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2187 'impl_func': False,
2188 'type': 'HandWritten',
2189 'data_transfer_methods': ['immediate'],
2190 'unit_test': False,
2191 'client_test': False,
2192 'extension': "CHROMIUM_texture_mailbox",
2193 'chromium': True,
2194 'trace_level': 2,
2196 'GenValuebuffersCHROMIUM': {
2197 'type': 'GENn',
2198 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2199 'resource_type': 'Valuebuffer',
2200 'resource_types': 'Valuebuffers',
2201 'unit_test': False,
2202 'extension': True,
2203 'chromium': True,
2205 'DeleteValuebuffersCHROMIUM': {
2206 'type': 'DELn',
2207 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2208 'resource_type': 'Valuebuffer',
2209 'resource_types': 'Valuebuffers',
2210 'unit_test': False,
2211 'extension': True,
2212 'chromium': True,
2214 'IsValuebufferCHROMIUM': {
2215 'type': 'Is',
2216 'decoder_func': 'DoIsValuebufferCHROMIUM',
2217 'expectation': False,
2218 'extension': True,
2219 'chromium': True,
2221 'BindValuebufferCHROMIUM': {
2222 'type': 'Bind',
2223 'decoder_func': 'DoBindValueBufferCHROMIUM',
2224 'gen_func': 'GenValueBuffersCHROMIUM',
2225 'unit_test': False,
2226 'extension': True,
2227 'chromium': True,
2229 'SubscribeValueCHROMIUM': {
2230 'decoder_func': 'DoSubscribeValueCHROMIUM',
2231 'unit_test': False,
2232 'extension': True,
2233 'chromium': True,
2235 'PopulateSubscribedValuesCHROMIUM': {
2236 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2237 'unit_test': False,
2238 'extension': True,
2239 'chromium': True,
2241 'UniformValuebufferCHROMIUM': {
2242 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2243 'unit_test': False,
2244 'extension': True,
2245 'chromium': True,
2247 'ClearStencil': {
2248 'type': 'StateSet',
2249 'state': 'ClearStencil',
2251 'EnableFeatureCHROMIUM': {
2252 'type': 'Custom',
2253 'data_transfer_methods': ['shm'],
2254 'decoder_func': 'DoEnableFeatureCHROMIUM',
2255 'expectation': False,
2256 'cmd_args': 'GLuint bucket_id, GLint* result',
2257 'result': ['GLint'],
2258 'extension': True,
2259 'chromium': True,
2260 'pepper_interface': 'ChromiumEnableFeature',
2262 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2263 'CompressedTexImage2D': {
2264 'type': 'Manual',
2265 'data_transfer_methods': ['bucket', 'shm'],
2266 'trace_level': 1,
2268 'CompressedTexSubImage2D': {
2269 'type': 'Data',
2270 'data_transfer_methods': ['bucket', 'shm'],
2271 'decoder_func': 'DoCompressedTexSubImage2D',
2272 'trace_level': 1,
2274 'CopyTexImage2D': {
2275 'decoder_func': 'DoCopyTexImage2D',
2276 'unit_test': False,
2277 'defer_reads': True,
2278 'trace_level': 1,
2280 'CopyTexSubImage2D': {
2281 'decoder_func': 'DoCopyTexSubImage2D',
2282 'defer_reads': True,
2283 'trace_level': 1,
2285 'CompressedTexImage3D': {
2286 'type': 'Manual',
2287 'data_transfer_methods': ['bucket', 'shm'],
2288 'unsafe': True,
2289 'trace_level': 1,
2291 'CompressedTexSubImage3D': {
2292 'type': 'Data',
2293 'data_transfer_methods': ['bucket', 'shm'],
2294 'decoder_func': 'DoCompressedTexSubImage3D',
2295 'unsafe': True,
2296 'trace_level': 1,
2298 'CopyTexSubImage3D': {
2299 'defer_reads': True,
2300 'unsafe': True,
2301 'trace_level': 1,
2303 'CreateImageCHROMIUM': {
2304 'type': 'Manual',
2305 'cmd_args':
2306 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2307 'GLenum internalformat',
2308 'result': ['GLuint'],
2309 'client_test': False,
2310 'gen_cmd': False,
2311 'expectation': False,
2312 'extension': "CHROMIUM_image",
2313 'chromium': True,
2314 'trace_level': 1,
2316 'DestroyImageCHROMIUM': {
2317 'type': 'Manual',
2318 'client_test': False,
2319 'gen_cmd': False,
2320 'extension': "CHROMIUM_image",
2321 'chromium': True,
2322 'trace_level': 1,
2324 'CreateGpuMemoryBufferImageCHROMIUM': {
2325 'type': 'Manual',
2326 'cmd_args':
2327 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2328 'result': ['GLuint'],
2329 'client_test': False,
2330 'gen_cmd': False,
2331 'expectation': False,
2332 'extension': "CHROMIUM_image",
2333 'chromium': True,
2334 'trace_level': 1,
2336 'CreateProgram': {
2337 'type': 'Create',
2338 'client_test': False,
2340 'CreateShader': {
2341 'type': 'Create',
2342 'client_test': False,
2344 'BlendColor': {
2345 'type': 'StateSet',
2346 'state': 'BlendColor',
2348 'BlendEquation': {
2349 'type': 'StateSetRGBAlpha',
2350 'state': 'BlendEquation',
2351 'valid_args': {
2352 '0': 'GL_FUNC_SUBTRACT'
2355 'BlendEquationSeparate': {
2356 'type': 'StateSet',
2357 'state': 'BlendEquation',
2358 'valid_args': {
2359 '0': 'GL_FUNC_SUBTRACT'
2362 'BlendFunc': {
2363 'type': 'StateSetRGBAlpha',
2364 'state': 'BlendFunc',
2366 'BlendFuncSeparate': {
2367 'type': 'StateSet',
2368 'state': 'BlendFunc',
2370 'BlendBarrierKHR': {
2371 'gl_test_func': 'glBlendBarrierKHR',
2372 'extension': True,
2373 'extension_flag': 'blend_equation_advanced',
2374 'client_test': False,
2376 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2377 'StencilFunc': {
2378 'type': 'StateSetFrontBack',
2379 'state': 'StencilFunc',
2381 'StencilFuncSeparate': {
2382 'type': 'StateSetFrontBackSeparate',
2383 'state': 'StencilFunc',
2385 'StencilOp': {
2386 'type': 'StateSetFrontBack',
2387 'state': 'StencilOp',
2388 'valid_args': {
2389 '1': 'GL_INCR'
2392 'StencilOpSeparate': {
2393 'type': 'StateSetFrontBackSeparate',
2394 'state': 'StencilOp',
2395 'valid_args': {
2396 '1': 'GL_INCR'
2399 'Hint': {
2400 'type': 'StateSetNamedParameter',
2401 'state': 'Hint',
2403 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2404 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2405 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2406 'LineWidth': {
2407 'type': 'StateSet',
2408 'state': 'LineWidth',
2409 'valid_args': {
2410 '0': '0.5f'
2413 'PolygonOffset': {
2414 'type': 'StateSet',
2415 'state': 'PolygonOffset',
2417 'DeleteBuffers': {
2418 'type': 'DELn',
2419 'gl_test_func': 'glDeleteBuffersARB',
2420 'resource_type': 'Buffer',
2421 'resource_types': 'Buffers',
2423 'DeleteFramebuffers': {
2424 'type': 'DELn',
2425 'gl_test_func': 'glDeleteFramebuffersEXT',
2426 'resource_type': 'Framebuffer',
2427 'resource_types': 'Framebuffers',
2428 'trace_level': 2,
2430 'DeleteProgram': { 'type': 'Delete' },
2431 'DeleteRenderbuffers': {
2432 'type': 'DELn',
2433 'gl_test_func': 'glDeleteRenderbuffersEXT',
2434 'resource_type': 'Renderbuffer',
2435 'resource_types': 'Renderbuffers',
2436 'trace_level': 2,
2438 'DeleteSamplers': {
2439 'type': 'DELn',
2440 'resource_type': 'Sampler',
2441 'resource_types': 'Samplers',
2442 'unsafe': True,
2444 'DeleteShader': { 'type': 'Delete' },
2445 'DeleteSync': {
2446 'type': 'Delete',
2447 'cmd_args': 'GLuint sync',
2448 'resource_type': 'Sync',
2449 'unsafe': True,
2451 'DeleteTextures': {
2452 'type': 'DELn',
2453 'resource_type': 'Texture',
2454 'resource_types': 'Textures',
2456 'DeleteTransformFeedbacks': {
2457 'type': 'DELn',
2458 'resource_type': 'TransformFeedback',
2459 'resource_types': 'TransformFeedbacks',
2460 'unsafe': True,
2462 'DepthRangef': {
2463 'decoder_func': 'DoDepthRangef',
2464 'gl_test_func': 'glDepthRange',
2466 'DepthMask': {
2467 'type': 'StateSet',
2468 'state': 'DepthMask',
2469 'no_gl': True,
2470 'expectation': False,
2472 'DetachShader': {'decoder_func': 'DoDetachShader'},
2473 'Disable': {
2474 'decoder_func': 'DoDisable',
2475 'impl_func': False,
2476 'client_test': False,
2478 'DisableVertexAttribArray': {
2479 'decoder_func': 'DoDisableVertexAttribArray',
2480 'impl_decl': False,
2482 'DrawArrays': {
2483 'type': 'Manual',
2484 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2485 'defer_draws': True,
2486 'trace_level': 2,
2488 'DrawElements': {
2489 'type': 'Manual',
2490 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2491 'GLenumIndexType type, GLuint index_offset',
2492 'client_test': False,
2493 'defer_draws': True,
2494 'trace_level': 2,
2496 'DrawRangeElements': {
2497 'type': 'Manual',
2498 'gen_cmd': 'False',
2499 'unsafe': True,
2501 'Enable': {
2502 'decoder_func': 'DoEnable',
2503 'impl_func': False,
2504 'client_test': False,
2506 'EnableVertexAttribArray': {
2507 'decoder_func': 'DoEnableVertexAttribArray',
2508 'impl_decl': False,
2510 'FenceSync': {
2511 'type': 'Create',
2512 'client_test': False,
2513 'unsafe': True,
2514 'trace_level': 1,
2516 'Finish': {
2517 'impl_func': False,
2518 'client_test': False,
2519 'decoder_func': 'DoFinish',
2520 'defer_reads': True,
2521 'trace_level': 1,
2523 'Flush': {
2524 'impl_func': False,
2525 'decoder_func': 'DoFlush',
2526 'trace_level': 1,
2528 'FramebufferRenderbuffer': {
2529 'decoder_func': 'DoFramebufferRenderbuffer',
2530 'gl_test_func': 'glFramebufferRenderbufferEXT',
2531 'trace_level': 1,
2533 'FramebufferTexture2D': {
2534 'decoder_func': 'DoFramebufferTexture2D',
2535 'gl_test_func': 'glFramebufferTexture2DEXT',
2536 'trace_level': 1,
2538 'FramebufferTexture2DMultisampleEXT': {
2539 'decoder_func': 'DoFramebufferTexture2DMultisample',
2540 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2541 'expectation': False,
2542 'unit_test': False,
2543 'extension_flag': 'multisampled_render_to_texture',
2544 'trace_level': 1,
2546 'FramebufferTextureLayer': {
2547 'decoder_func': 'DoFramebufferTextureLayer',
2548 'unsafe': True,
2549 'trace_level': 1,
2551 'GenerateMipmap': {
2552 'decoder_func': 'DoGenerateMipmap',
2553 'gl_test_func': 'glGenerateMipmapEXT',
2554 'trace_level': 1,
2556 'GenBuffers': {
2557 'type': 'GENn',
2558 'gl_test_func': 'glGenBuffersARB',
2559 'resource_type': 'Buffer',
2560 'resource_types': 'Buffers',
2562 'GenMailboxCHROMIUM': {
2563 'type': 'HandWritten',
2564 'impl_func': False,
2565 'extension': "CHROMIUM_texture_mailbox",
2566 'chromium': True,
2568 'GenFramebuffers': {
2569 'type': 'GENn',
2570 'gl_test_func': 'glGenFramebuffersEXT',
2571 'resource_type': 'Framebuffer',
2572 'resource_types': 'Framebuffers',
2574 'GenRenderbuffers': {
2575 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2576 'resource_type': 'Renderbuffer',
2577 'resource_types': 'Renderbuffers',
2579 'GenSamplers': {
2580 'type': 'GENn',
2581 'gl_test_func': 'glGenSamplers',
2582 'resource_type': 'Sampler',
2583 'resource_types': 'Samplers',
2584 'unsafe': True,
2586 'GenTextures': {
2587 'type': 'GENn',
2588 'gl_test_func': 'glGenTextures',
2589 'resource_type': 'Texture',
2590 'resource_types': 'Textures',
2592 'GenTransformFeedbacks': {
2593 'type': 'GENn',
2594 'gl_test_func': 'glGenTransformFeedbacks',
2595 'resource_type': 'TransformFeedback',
2596 'resource_types': 'TransformFeedbacks',
2597 'unsafe': True,
2599 'GetActiveAttrib': {
2600 'type': 'Custom',
2601 'data_transfer_methods': ['shm'],
2602 'cmd_args':
2603 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2604 'void* result',
2605 'result': [
2606 'int32_t success',
2607 'int32_t size',
2608 'uint32_t type',
2611 'GetActiveUniform': {
2612 'type': 'Custom',
2613 'data_transfer_methods': ['shm'],
2614 'cmd_args':
2615 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2616 'void* result',
2617 'result': [
2618 'int32_t success',
2619 'int32_t size',
2620 'uint32_t type',
2623 'GetActiveUniformBlockiv': {
2624 'type': 'Custom',
2625 'data_transfer_methods': ['shm'],
2626 'result': ['SizedResult<GLint>'],
2627 'unsafe': True,
2629 'GetActiveUniformBlockName': {
2630 'type': 'Custom',
2631 'data_transfer_methods': ['shm'],
2632 'cmd_args':
2633 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2634 'void* result',
2635 'result': ['int32_t'],
2636 'unsafe': True,
2638 'GetActiveUniformsiv': {
2639 'type': 'Custom',
2640 'data_transfer_methods': ['shm'],
2641 'cmd_args':
2642 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2643 'GLint* params',
2644 'result': ['SizedResult<GLint>'],
2645 'unsafe': True,
2647 'GetAttachedShaders': {
2648 'type': 'Custom',
2649 'data_transfer_methods': ['shm'],
2650 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2651 'result': ['SizedResult<GLuint>'],
2653 'GetAttribLocation': {
2654 'type': 'Custom',
2655 'data_transfer_methods': ['shm'],
2656 'cmd_args':
2657 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2658 'result': ['GLint'],
2659 'error_return': -1,
2661 'GetFragDataLocation': {
2662 'type': 'Custom',
2663 'data_transfer_methods': ['shm'],
2664 'cmd_args':
2665 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2666 'result': ['GLint'],
2667 'error_return': -1,
2668 'unsafe': True,
2670 'GetBooleanv': {
2671 'type': 'GETn',
2672 'result': ['SizedResult<GLboolean>'],
2673 'decoder_func': 'DoGetBooleanv',
2674 'gl_test_func': 'glGetBooleanv',
2676 'GetBufferParameteriv': {
2677 'type': 'GETn',
2678 'result': ['SizedResult<GLint>'],
2679 'decoder_func': 'DoGetBufferParameteriv',
2680 'expectation': False,
2681 'shadowed': True,
2683 'GetError': {
2684 'type': 'Is',
2685 'decoder_func': 'GetErrorState()->GetGLError',
2686 'impl_func': False,
2687 'result': ['GLenum'],
2688 'client_test': False,
2690 'GetFloatv': {
2691 'type': 'GETn',
2692 'result': ['SizedResult<GLfloat>'],
2693 'decoder_func': 'DoGetFloatv',
2694 'gl_test_func': 'glGetFloatv',
2696 'GetFramebufferAttachmentParameteriv': {
2697 'type': 'GETn',
2698 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2699 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2700 'result': ['SizedResult<GLint>'],
2702 'GetGraphicsResetStatusKHR': {
2703 'extension': True,
2704 'client_test': False,
2705 'gen_cmd': False,
2706 'trace_level': 1,
2708 'GetInteger64v': {
2709 'type': 'GETn',
2710 'result': ['SizedResult<GLint64>'],
2711 'client_test': False,
2712 'decoder_func': 'DoGetInteger64v',
2713 'unsafe': True
2715 'GetIntegerv': {
2716 'type': 'GETn',
2717 'result': ['SizedResult<GLint>'],
2718 'decoder_func': 'DoGetIntegerv',
2719 'client_test': False,
2721 'GetInteger64i_v': {
2722 'type': 'GETn',
2723 'result': ['SizedResult<GLint64>'],
2724 'client_test': False,
2725 'unsafe': True
2727 'GetIntegeri_v': {
2728 'type': 'GETn',
2729 'result': ['SizedResult<GLint>'],
2730 'client_test': False,
2731 'unsafe': True
2733 'GetInternalformativ': {
2734 'type': 'Custom',
2735 'data_transfer_methods': ['shm'],
2736 'result': ['SizedResult<GLint>'],
2737 'cmd_args':
2738 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2739 'GLenumInternalFormatParameter pname, GLint* params',
2740 'unsafe': True,
2742 'GetMaxValueInBufferCHROMIUM': {
2743 'type': 'Is',
2744 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2745 'result': ['GLuint'],
2746 'unit_test': False,
2747 'client_test': False,
2748 'extension': True,
2749 'chromium': True,
2750 'impl_func': False,
2752 'GetProgramiv': {
2753 'type': 'GETn',
2754 'decoder_func': 'DoGetProgramiv',
2755 'result': ['SizedResult<GLint>'],
2756 'expectation': False,
2758 'GetProgramInfoCHROMIUM': {
2759 'type': 'Custom',
2760 'expectation': False,
2761 'impl_func': False,
2762 'extension': True,
2763 'chromium': True,
2764 'client_test': False,
2765 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2766 'result': [
2767 'uint32_t link_status',
2768 'uint32_t num_attribs',
2769 'uint32_t num_uniforms',
2772 'GetProgramInfoLog': {
2773 'type': 'STRn',
2774 'expectation': False,
2776 'GetRenderbufferParameteriv': {
2777 'type': 'GETn',
2778 'decoder_func': 'DoGetRenderbufferParameteriv',
2779 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2780 'result': ['SizedResult<GLint>'],
2782 'GetSamplerParameterfv': {
2783 'type': 'GETn',
2784 'result': ['SizedResult<GLfloat>'],
2785 'id_mapping': [ 'Sampler' ],
2786 'unsafe': True,
2788 'GetSamplerParameteriv': {
2789 'type': 'GETn',
2790 'result': ['SizedResult<GLint>'],
2791 'id_mapping': [ 'Sampler' ],
2792 'unsafe': True,
2794 'GetShaderiv': {
2795 'type': 'GETn',
2796 'decoder_func': 'DoGetShaderiv',
2797 'result': ['SizedResult<GLint>'],
2799 'GetShaderInfoLog': {
2800 'type': 'STRn',
2801 'get_len_func': 'glGetShaderiv',
2802 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2803 'unit_test': False,
2805 'GetShaderPrecisionFormat': {
2806 'type': 'Custom',
2807 'data_transfer_methods': ['shm'],
2808 'cmd_args':
2809 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2810 'void* result',
2811 'result': [
2812 'int32_t success',
2813 'int32_t min_range',
2814 'int32_t max_range',
2815 'int32_t precision',
2818 'GetShaderSource': {
2819 'type': 'STRn',
2820 'get_len_func': 'DoGetShaderiv',
2821 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2822 'unit_test': False,
2823 'client_test': False,
2825 'GetString': {
2826 'type': 'Custom',
2827 'client_test': False,
2828 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2830 'GetSynciv': {
2831 'type': 'GETn',
2832 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2833 'result': ['SizedResult<GLint>'],
2834 'id_mapping': ['Sync'],
2835 'unsafe': True,
2837 'GetTexParameterfv': {
2838 'type': 'GETn',
2839 'decoder_func': 'DoGetTexParameterfv',
2840 'result': ['SizedResult<GLfloat>']
2842 'GetTexParameteriv': {
2843 'type': 'GETn',
2844 'decoder_func': 'DoGetTexParameteriv',
2845 'result': ['SizedResult<GLint>']
2847 'GetTranslatedShaderSourceANGLE': {
2848 'type': 'STRn',
2849 'get_len_func': 'DoGetShaderiv',
2850 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2851 'unit_test': False,
2852 'extension': True,
2854 'GetUniformBlockIndex': {
2855 'type': 'Custom',
2856 'data_transfer_methods': ['shm'],
2857 'cmd_args':
2858 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2859 'result': ['GLuint'],
2860 'error_return': 'GL_INVALID_INDEX',
2861 'unsafe': True,
2863 'GetUniformBlocksCHROMIUM': {
2864 'type': 'Custom',
2865 'expectation': False,
2866 'impl_func': False,
2867 'extension': True,
2868 'chromium': True,
2869 'client_test': False,
2870 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2871 'result': ['uint32_t'],
2872 'unsafe': True,
2874 'GetUniformsES3CHROMIUM': {
2875 'type': 'Custom',
2876 'expectation': False,
2877 'impl_func': False,
2878 'extension': True,
2879 'chromium': True,
2880 'client_test': False,
2881 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2882 'result': ['uint32_t'],
2883 'unsafe': True,
2885 'GetTransformFeedbackVarying': {
2886 'type': 'Custom',
2887 'data_transfer_methods': ['shm'],
2888 'cmd_args':
2889 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2890 'void* result',
2891 'result': [
2892 'int32_t success',
2893 'int32_t size',
2894 'uint32_t type',
2896 'unsafe': True,
2898 'GetTransformFeedbackVaryingsCHROMIUM': {
2899 'type': 'Custom',
2900 'expectation': False,
2901 'impl_func': False,
2902 'extension': True,
2903 'chromium': True,
2904 'client_test': False,
2905 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2906 'result': ['uint32_t'],
2907 'unsafe': True,
2909 'GetUniformfv': {
2910 'type': 'Custom',
2911 'data_transfer_methods': ['shm'],
2912 'result': ['SizedResult<GLfloat>'],
2914 'GetUniformiv': {
2915 'type': 'Custom',
2916 'data_transfer_methods': ['shm'],
2917 'result': ['SizedResult<GLint>'],
2919 'GetUniformuiv': {
2920 'type': 'Custom',
2921 'data_transfer_methods': ['shm'],
2922 'result': ['SizedResult<GLuint>'],
2923 'unsafe': True,
2925 'GetUniformIndices': {
2926 'type': 'Custom',
2927 'data_transfer_methods': ['shm'],
2928 'result': ['SizedResult<GLuint>'],
2929 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2930 'GLuint* indices',
2931 'unsafe': True,
2933 'GetUniformLocation': {
2934 'type': 'Custom',
2935 'data_transfer_methods': ['shm'],
2936 'cmd_args':
2937 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2938 'result': ['GLint'],
2939 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2941 'GetVertexAttribfv': {
2942 'type': 'GETn',
2943 'result': ['SizedResult<GLfloat>'],
2944 'impl_decl': False,
2945 'decoder_func': 'DoGetVertexAttribfv',
2946 'expectation': False,
2947 'client_test': False,
2949 'GetVertexAttribiv': {
2950 'type': 'GETn',
2951 'result': ['SizedResult<GLint>'],
2952 'impl_decl': False,
2953 'decoder_func': 'DoGetVertexAttribiv',
2954 'expectation': False,
2955 'client_test': False,
2957 'GetVertexAttribIiv': {
2958 'type': 'GETn',
2959 'result': ['SizedResult<GLint>'],
2960 'impl_decl': False,
2961 'decoder_func': 'DoGetVertexAttribIiv',
2962 'expectation': False,
2963 'client_test': False,
2964 'unsafe': True,
2966 'GetVertexAttribIuiv': {
2967 'type': 'GETn',
2968 'result': ['SizedResult<GLuint>'],
2969 'impl_decl': False,
2970 'decoder_func': 'DoGetVertexAttribIuiv',
2971 'expectation': False,
2972 'client_test': False,
2973 'unsafe': True,
2975 'GetVertexAttribPointerv': {
2976 'type': 'Custom',
2977 'data_transfer_methods': ['shm'],
2978 'result': ['SizedResult<GLuint>'],
2979 'client_test': False,
2981 'InvalidateFramebuffer': {
2982 'type': 'PUTn',
2983 'count': 1,
2984 'client_test': False,
2985 'unit_test': False,
2986 'unsafe': True,
2988 'InvalidateSubFramebuffer': {
2989 'type': 'PUTn',
2990 'count': 1,
2991 'client_test': False,
2992 'unit_test': False,
2993 'unsafe': True,
2995 'IsBuffer': {
2996 'type': 'Is',
2997 'decoder_func': 'DoIsBuffer',
2998 'expectation': False,
3000 'IsEnabled': {
3001 'type': 'Is',
3002 'decoder_func': 'DoIsEnabled',
3003 'client_test': False,
3004 'impl_func': False,
3005 'expectation': False,
3007 'IsFramebuffer': {
3008 'type': 'Is',
3009 'decoder_func': 'DoIsFramebuffer',
3010 'expectation': False,
3012 'IsProgram': {
3013 'type': 'Is',
3014 'decoder_func': 'DoIsProgram',
3015 'expectation': False,
3017 'IsRenderbuffer': {
3018 'type': 'Is',
3019 'decoder_func': 'DoIsRenderbuffer',
3020 'expectation': False,
3022 'IsShader': {
3023 'type': 'Is',
3024 'decoder_func': 'DoIsShader',
3025 'expectation': False,
3027 'IsSampler': {
3028 'type': 'Is',
3029 'id_mapping': [ 'Sampler' ],
3030 'expectation': False,
3031 'unsafe': True,
3033 'IsSync': {
3034 'type': 'Is',
3035 'id_mapping': [ 'Sync' ],
3036 'cmd_args': 'GLuint sync',
3037 'expectation': False,
3038 'unsafe': True,
3040 'IsTexture': {
3041 'type': 'Is',
3042 'decoder_func': 'DoIsTexture',
3043 'expectation': False,
3045 'IsTransformFeedback': {
3046 'type': 'Is',
3047 'id_mapping': [ 'TransformFeedback' ],
3048 'expectation': False,
3049 'unsafe': True,
3051 'LinkProgram': {
3052 'decoder_func': 'DoLinkProgram',
3053 'impl_func': False,
3054 'trace_level': 1,
3056 'MapBufferCHROMIUM': {
3057 'gen_cmd': False,
3058 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3059 'chromium': True,
3060 'client_test': False,
3061 'trace_level': 1,
3063 'MapBufferSubDataCHROMIUM': {
3064 'gen_cmd': False,
3065 'extension': True,
3066 'chromium': True,
3067 'client_test': False,
3068 'pepper_interface': 'ChromiumMapSub',
3069 'trace_level': 1,
3071 'MapTexSubImage2DCHROMIUM': {
3072 'gen_cmd': False,
3073 'extension': "CHROMIUM_sub_image",
3074 'chromium': True,
3075 'client_test': False,
3076 'pepper_interface': 'ChromiumMapSub',
3077 'trace_level': 1,
3079 'MapBufferRange': {
3080 'type': 'Custom',
3081 'data_transfer_methods': ['shm'],
3082 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3083 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3084 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3085 'uint32_t result_shm_id, uint32_t result_shm_offset',
3086 'unsafe': True,
3087 'result': ['uint32_t'],
3088 'trace_level': 1,
3090 'PauseTransformFeedback': {
3091 'unsafe': True,
3093 'PixelStorei': {'type': 'Manual'},
3094 'PostSubBufferCHROMIUM': {
3095 'type': 'Custom',
3096 'impl_func': False,
3097 'unit_test': False,
3098 'client_test': False,
3099 'extension': True,
3100 'chromium': True,
3102 'ProduceTextureCHROMIUM': {
3103 'decoder_func': 'DoProduceTextureCHROMIUM',
3104 'impl_func': False,
3105 'type': 'PUT',
3106 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3107 'unit_test': False,
3108 'client_test': False,
3109 'extension': "CHROMIUM_texture_mailbox",
3110 'chromium': True,
3111 'trace_level': 1,
3113 'ProduceTextureDirectCHROMIUM': {
3114 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3115 'impl_func': False,
3116 'type': 'PUT',
3117 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3118 'unit_test': False,
3119 'client_test': False,
3120 'extension': "CHROMIUM_texture_mailbox",
3121 'chromium': True,
3122 'trace_level': 1,
3124 'RenderbufferStorage': {
3125 'decoder_func': 'DoRenderbufferStorage',
3126 'gl_test_func': 'glRenderbufferStorageEXT',
3127 'expectation': False,
3128 'trace_level': 1,
3130 'RenderbufferStorageMultisampleCHROMIUM': {
3131 'cmd_comment':
3132 '// GL_CHROMIUM_framebuffer_multisample\n',
3133 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3134 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3135 'expectation': False,
3136 'unit_test': False,
3137 'extension_flag': 'chromium_framebuffer_multisample',
3138 'pepper_interface': 'FramebufferMultisample',
3139 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3140 'trace_level': 1,
3142 'RenderbufferStorageMultisampleEXT': {
3143 'cmd_comment':
3144 '// GL_EXT_multisampled_render_to_texture\n',
3145 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3146 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3147 'expectation': False,
3148 'unit_test': False,
3149 'extension_flag': 'multisampled_render_to_texture',
3150 'trace_level': 1,
3152 'ReadBuffer': {
3153 'unsafe': True,
3154 'trace_level': 1,
3156 'ReadPixels': {
3157 'cmd_comment':
3158 '// ReadPixels has the result separated from the pixel buffer so that\n'
3159 '// it is easier to specify the result going to some specific place\n'
3160 '// that exactly fits the rectangle of pixels.\n',
3161 'type': 'Custom',
3162 'data_transfer_methods': ['shm'],
3163 'impl_func': False,
3164 'client_test': False,
3165 'cmd_args':
3166 'GLint x, GLint y, GLsizei width, GLsizei height, '
3167 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3168 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3169 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3170 'GLboolean async',
3171 'result': ['uint32_t'],
3172 'defer_reads': True,
3173 'trace_level': 1,
3175 'ReleaseShaderCompiler': {
3176 'decoder_func': 'DoReleaseShaderCompiler',
3177 'unit_test': False,
3179 'ResumeTransformFeedback': {
3180 'unsafe': True,
3182 'SamplerParameterf': {
3183 'valid_args': {
3184 '2': 'GL_NEAREST'
3186 'id_mapping': [ 'Sampler' ],
3187 'unsafe': True,
3189 'SamplerParameterfv': {
3190 'type': 'PUT',
3191 'data_value': 'GL_NEAREST',
3192 'count': 1,
3193 'gl_test_func': 'glSamplerParameterf',
3194 'decoder_func': 'DoSamplerParameterfv',
3195 'first_element_only': True,
3196 'id_mapping': [ 'Sampler' ],
3197 'unsafe': True,
3199 'SamplerParameteri': {
3200 'valid_args': {
3201 '2': 'GL_NEAREST'
3203 'id_mapping': [ 'Sampler' ],
3204 'unsafe': True,
3206 'SamplerParameteriv': {
3207 'type': 'PUT',
3208 'data_value': 'GL_NEAREST',
3209 'count': 1,
3210 'gl_test_func': 'glSamplerParameteri',
3211 'decoder_func': 'DoSamplerParameteriv',
3212 'first_element_only': True,
3213 'unsafe': True,
3215 'ShaderBinary': {
3216 'type': 'Custom',
3217 'client_test': False,
3219 'ShaderSource': {
3220 'type': 'PUTSTR',
3221 'decoder_func': 'DoShaderSource',
3222 'expectation': False,
3223 'data_transfer_methods': ['bucket'],
3224 'cmd_args':
3225 'GLuint shader, const char** str',
3226 'pepper_args':
3227 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3229 'StencilMask': {
3230 'type': 'StateSetFrontBack',
3231 'state': 'StencilMask',
3232 'no_gl': True,
3233 'expectation': False,
3235 'StencilMaskSeparate': {
3236 'type': 'StateSetFrontBackSeparate',
3237 'state': 'StencilMask',
3238 'no_gl': True,
3239 'expectation': False,
3241 'SwapBuffers': {
3242 'impl_func': False,
3243 'decoder_func': 'DoSwapBuffers',
3244 'unit_test': False,
3245 'client_test': False,
3246 'extension': True,
3247 'trace_level': 1,
3249 'SwapInterval': {
3250 'impl_func': False,
3251 'decoder_func': 'DoSwapInterval',
3252 'unit_test': False,
3253 'client_test': False,
3254 'extension': True,
3255 'trace_level': 1,
3257 'TexImage2D': {
3258 'type': 'Manual',
3259 'data_transfer_methods': ['shm'],
3260 'client_test': False,
3261 'trace_level': 2,
3263 'TexImage3D': {
3264 'type': 'Manual',
3265 'data_transfer_methods': ['shm'],
3266 'client_test': False,
3267 'unsafe': True,
3268 'trace_level': 2,
3270 'TexParameterf': {
3271 'decoder_func': 'DoTexParameterf',
3272 'valid_args': {
3273 '2': 'GL_NEAREST'
3276 'TexParameteri': {
3277 'decoder_func': 'DoTexParameteri',
3278 'valid_args': {
3279 '2': 'GL_NEAREST'
3282 'TexParameterfv': {
3283 'type': 'PUT',
3284 'data_value': 'GL_NEAREST',
3285 'count': 1,
3286 'decoder_func': 'DoTexParameterfv',
3287 'gl_test_func': 'glTexParameterf',
3288 'first_element_only': True,
3290 'TexParameteriv': {
3291 'type': 'PUT',
3292 'data_value': 'GL_NEAREST',
3293 'count': 1,
3294 'decoder_func': 'DoTexParameteriv',
3295 'gl_test_func': 'glTexParameteri',
3296 'first_element_only': True,
3298 'TexStorage3D': {
3299 'unsafe': True,
3300 'trace_level': 2,
3302 'TexSubImage2D': {
3303 'type': 'Manual',
3304 'data_transfer_methods': ['shm'],
3305 'client_test': False,
3306 'trace_level': 2,
3307 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3308 'GLint xoffset, GLint yoffset, '
3309 'GLsizei width, GLsizei height, '
3310 'GLenumTextureFormat format, GLenumPixelType type, '
3311 'const void* pixels, GLboolean internal'
3313 'TexSubImage3D': {
3314 'type': 'Manual',
3315 'data_transfer_methods': ['shm'],
3316 'client_test': False,
3317 'trace_level': 2,
3318 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3319 'GLint xoffset, GLint yoffset, GLint zoffset, '
3320 'GLsizei width, GLsizei height, GLsizei depth, '
3321 'GLenumTextureFormat format, GLenumPixelType type, '
3322 'const void* pixels, GLboolean internal',
3323 'unsafe': True,
3325 'TransformFeedbackVaryings': {
3326 'type': 'PUTSTR',
3327 'data_transfer_methods': ['bucket'],
3328 'decoder_func': 'DoTransformFeedbackVaryings',
3329 'cmd_args':
3330 'GLuint program, const char** varyings, GLenum buffermode',
3331 'unsafe': True,
3333 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3334 'Uniform1fv': {
3335 'type': 'PUTn',
3336 'count': 1,
3337 'decoder_func': 'DoUniform1fv',
3339 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3340 'Uniform1iv': {
3341 'type': 'PUTn',
3342 'count': 1,
3343 'decoder_func': 'DoUniform1iv',
3344 'unit_test': False,
3346 'Uniform1ui': {
3347 'type': 'PUTXn',
3348 'count': 1,
3349 'unsafe': True,
3351 'Uniform1uiv': {
3352 'type': 'PUTn',
3353 'count': 1,
3354 'unsafe': True,
3356 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3357 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3358 'Uniform2fv': {
3359 'type': 'PUTn',
3360 'count': 2,
3361 'decoder_func': 'DoUniform2fv',
3363 'Uniform2iv': {
3364 'type': 'PUTn',
3365 'count': 2,
3366 'decoder_func': 'DoUniform2iv',
3368 'Uniform2ui': {
3369 'type': 'PUTXn',
3370 'count': 2,
3371 'unsafe': True,
3373 'Uniform2uiv': {
3374 'type': 'PUTn',
3375 'count': 2,
3376 'unsafe': True,
3378 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3379 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3380 'Uniform3fv': {
3381 'type': 'PUTn',
3382 'count': 3,
3383 'decoder_func': 'DoUniform3fv',
3385 'Uniform3iv': {
3386 'type': 'PUTn',
3387 'count': 3,
3388 'decoder_func': 'DoUniform3iv',
3390 'Uniform3ui': {
3391 'type': 'PUTXn',
3392 'count': 3,
3393 'unsafe': True,
3395 'Uniform3uiv': {
3396 'type': 'PUTn',
3397 'count': 3,
3398 'unsafe': True,
3400 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3401 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3402 'Uniform4fv': {
3403 'type': 'PUTn',
3404 'count': 4,
3405 'decoder_func': 'DoUniform4fv',
3407 'Uniform4iv': {
3408 'type': 'PUTn',
3409 'count': 4,
3410 'decoder_func': 'DoUniform4iv',
3412 'Uniform4ui': {
3413 'type': 'PUTXn',
3414 'count': 4,
3415 'unsafe': True,
3417 'Uniform4uiv': {
3418 'type': 'PUTn',
3419 'count': 4,
3420 'unsafe': True,
3422 'UniformMatrix2fv': {
3423 'type': 'PUTn',
3424 'count': 4,
3425 'decoder_func': 'DoUniformMatrix2fv',
3427 'UniformMatrix2x3fv': {
3428 'type': 'PUTn',
3429 'count': 6,
3430 'unsafe': True,
3432 'UniformMatrix2x4fv': {
3433 'type': 'PUTn',
3434 'count': 8,
3435 'unsafe': True,
3437 'UniformMatrix3fv': {
3438 'type': 'PUTn',
3439 'count': 9,
3440 'decoder_func': 'DoUniformMatrix3fv',
3442 'UniformMatrix3x2fv': {
3443 'type': 'PUTn',
3444 'count': 6,
3445 'unsafe': True,
3447 'UniformMatrix3x4fv': {
3448 'type': 'PUTn',
3449 'count': 12,
3450 'unsafe': True,
3452 'UniformMatrix4fv': {
3453 'type': 'PUTn',
3454 'count': 16,
3455 'decoder_func': 'DoUniformMatrix4fv',
3457 'UniformMatrix4x2fv': {
3458 'type': 'PUTn',
3459 'count': 8,
3460 'unsafe': True,
3462 'UniformMatrix4x3fv': {
3463 'type': 'PUTn',
3464 'count': 12,
3465 'unsafe': True,
3467 'UniformBlockBinding': {
3468 'type': 'Custom',
3469 'impl_func': False,
3470 'unsafe': True,
3472 'UnmapBufferCHROMIUM': {
3473 'gen_cmd': False,
3474 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3475 'chromium': True,
3476 'client_test': False,
3477 'trace_level': 1,
3479 'UnmapBufferSubDataCHROMIUM': {
3480 'gen_cmd': False,
3481 'extension': True,
3482 'chromium': True,
3483 'client_test': False,
3484 'pepper_interface': 'ChromiumMapSub',
3485 'trace_level': 1,
3487 'UnmapBuffer': {
3488 'type': 'Custom',
3489 'unsafe': True,
3490 'trace_level': 1,
3492 'UnmapTexSubImage2DCHROMIUM': {
3493 'gen_cmd': False,
3494 'extension': "CHROMIUM_sub_image",
3495 'chromium': True,
3496 'client_test': False,
3497 'pepper_interface': 'ChromiumMapSub',
3498 'trace_level': 1,
3500 'UseProgram': {
3501 'type': 'Bind',
3502 'decoder_func': 'DoUseProgram',
3504 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3505 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3506 'VertexAttrib1fv': {
3507 'type': 'PUT',
3508 'count': 1,
3509 'decoder_func': 'DoVertexAttrib1fv',
3511 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3512 'VertexAttrib2fv': {
3513 'type': 'PUT',
3514 'count': 2,
3515 'decoder_func': 'DoVertexAttrib2fv',
3517 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3518 'VertexAttrib3fv': {
3519 'type': 'PUT',
3520 'count': 3,
3521 'decoder_func': 'DoVertexAttrib3fv',
3523 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3524 'VertexAttrib4fv': {
3525 'type': 'PUT',
3526 'count': 4,
3527 'decoder_func': 'DoVertexAttrib4fv',
3529 'VertexAttribI4i': {
3530 'unsafe': True,
3531 'decoder_func': 'DoVertexAttribI4i',
3533 'VertexAttribI4iv': {
3534 'type': 'PUT',
3535 'count': 4,
3536 'unsafe': True,
3537 'decoder_func': 'DoVertexAttribI4iv',
3539 'VertexAttribI4ui': {
3540 'unsafe': True,
3541 'decoder_func': 'DoVertexAttribI4ui',
3543 'VertexAttribI4uiv': {
3544 'type': 'PUT',
3545 'count': 4,
3546 'unsafe': True,
3547 'decoder_func': 'DoVertexAttribI4uiv',
3549 'VertexAttribIPointer': {
3550 'type': 'Manual',
3551 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3552 'GLenumVertexAttribIType type, GLsizei stride, '
3553 'GLuint offset',
3554 'client_test': False,
3555 'unsafe': True,
3557 'VertexAttribPointer': {
3558 'type': 'Manual',
3559 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3560 'GLenumVertexAttribType type, GLboolean normalized, '
3561 'GLsizei stride, GLuint offset',
3562 'client_test': False,
3564 'WaitSync': {
3565 'type': 'Custom',
3566 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3567 'GLuint timeout_0, GLuint timeout_1',
3568 'impl_func': False,
3569 'client_test': False,
3570 'unsafe': True,
3571 'trace_level': 1,
3573 'Scissor': {
3574 'type': 'StateSet',
3575 'state': 'Scissor',
3577 'Viewport': {
3578 'decoder_func': 'DoViewport',
3580 'ResizeCHROMIUM': {
3581 'type': 'Custom',
3582 'impl_func': False,
3583 'unit_test': False,
3584 'extension': True,
3585 'chromium': True,
3586 'trace_level': 1,
3588 'GetRequestableExtensionsCHROMIUM': {
3589 'type': 'Custom',
3590 'impl_func': False,
3591 'cmd_args': 'uint32_t bucket_id',
3592 'extension': True,
3593 'chromium': True,
3595 'RequestExtensionCHROMIUM': {
3596 'type': 'Custom',
3597 'impl_func': False,
3598 'client_test': False,
3599 'cmd_args': 'uint32_t bucket_id',
3600 'extension': True,
3601 'chromium': True,
3603 'RateLimitOffscreenContextCHROMIUM': {
3604 'gen_cmd': False,
3605 'extension': True,
3606 'chromium': True,
3607 'client_test': False,
3609 'CreateStreamTextureCHROMIUM': {
3610 'type': 'HandWritten',
3611 'impl_func': False,
3612 'gen_cmd': False,
3613 'extension': True,
3614 'chromium': True,
3615 'trace_level': 1,
3617 'TexImageIOSurface2DCHROMIUM': {
3618 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3619 'unit_test': False,
3620 'extension': True,
3621 'chromium': True,
3622 'trace_level': 1,
3624 'CopyTextureCHROMIUM': {
3625 'decoder_func': 'DoCopyTextureCHROMIUM',
3626 'unit_test': False,
3627 'extension': "CHROMIUM_copy_texture",
3628 'chromium': True,
3629 'trace_level': 2,
3631 'CopySubTextureCHROMIUM': {
3632 'decoder_func': 'DoCopySubTextureCHROMIUM',
3633 'unit_test': False,
3634 'extension': "CHROMIUM_copy_texture",
3635 'chromium': True,
3636 'trace_level': 2,
3638 'CompressedCopyTextureCHROMIUM': {
3639 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3640 'unit_test': False,
3641 'extension': True,
3642 'chromium': True,
3644 'TexStorage2DEXT': {
3645 'unit_test': False,
3646 'extension': True,
3647 'decoder_func': 'DoTexStorage2DEXT',
3648 'trace_level': 2,
3650 'DrawArraysInstancedANGLE': {
3651 'type': 'Manual',
3652 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3653 'GLsizei primcount',
3654 'extension': True,
3655 'unit_test': False,
3656 'pepper_interface': 'InstancedArrays',
3657 'defer_draws': True,
3658 'trace_level': 2,
3660 'DrawBuffersEXT': {
3661 'type': 'PUTn',
3662 'decoder_func': 'DoDrawBuffersEXT',
3663 'count': 1,
3664 'client_test': False,
3665 'unit_test': False,
3666 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3667 # work without.
3668 'extension': True,
3669 'pepper_interface': 'DrawBuffers',
3670 'trace_level': 2,
3672 'DrawElementsInstancedANGLE': {
3673 'type': 'Manual',
3674 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3675 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3676 'extension': True,
3677 'unit_test': False,
3678 'client_test': False,
3679 'pepper_interface': 'InstancedArrays',
3680 'defer_draws': True,
3681 'trace_level': 2,
3683 'VertexAttribDivisorANGLE': {
3684 'type': 'Manual',
3685 'cmd_args': 'GLuint index, GLuint divisor',
3686 'extension': True,
3687 'unit_test': False,
3688 'pepper_interface': 'InstancedArrays',
3690 'GenQueriesEXT': {
3691 'type': 'GENn',
3692 'gl_test_func': 'glGenQueriesARB',
3693 'resource_type': 'Query',
3694 'resource_types': 'Queries',
3695 'unit_test': False,
3696 'pepper_interface': 'Query',
3697 'not_shared': 'True',
3698 'extension': "occlusion_query_EXT",
3700 'DeleteQueriesEXT': {
3701 'type': 'DELn',
3702 'gl_test_func': 'glDeleteQueriesARB',
3703 'resource_type': 'Query',
3704 'resource_types': 'Queries',
3705 'unit_test': False,
3706 'pepper_interface': 'Query',
3707 'extension': "occlusion_query_EXT",
3709 'IsQueryEXT': {
3710 'gen_cmd': False,
3711 'client_test': False,
3712 'pepper_interface': 'Query',
3713 'extension': "occlusion_query_EXT",
3715 'BeginQueryEXT': {
3716 'type': 'Manual',
3717 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3718 'data_transfer_methods': ['shm'],
3719 'gl_test_func': 'glBeginQuery',
3720 'pepper_interface': 'Query',
3721 'extension': "occlusion_query_EXT",
3723 'BeginTransformFeedback': {
3724 'unsafe': True,
3726 'EndQueryEXT': {
3727 'type': 'Manual',
3728 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3729 'gl_test_func': 'glEndnQuery',
3730 'client_test': False,
3731 'pepper_interface': 'Query',
3732 'extension': "occlusion_query_EXT",
3734 'EndTransformFeedback': {
3735 'unsafe': True,
3737 'GetQueryivEXT': {
3738 'gen_cmd': False,
3739 'client_test': False,
3740 'gl_test_func': 'glGetQueryiv',
3741 'pepper_interface': 'Query',
3742 'extension': "occlusion_query_EXT",
3744 'GetQueryObjectuivEXT': {
3745 'gen_cmd': False,
3746 'client_test': False,
3747 'gl_test_func': 'glGetQueryObjectuiv',
3748 'pepper_interface': 'Query',
3749 'extension': "occlusion_query_EXT",
3751 'BindUniformLocationCHROMIUM': {
3752 'type': 'GLchar',
3753 'extension': True,
3754 'data_transfer_methods': ['bucket'],
3755 'needs_size': True,
3756 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3758 'InsertEventMarkerEXT': {
3759 'type': 'GLcharN',
3760 'decoder_func': 'DoInsertEventMarkerEXT',
3761 'expectation': False,
3762 'extension': True,
3764 'PushGroupMarkerEXT': {
3765 'type': 'GLcharN',
3766 'decoder_func': 'DoPushGroupMarkerEXT',
3767 'expectation': False,
3768 'extension': True,
3770 'PopGroupMarkerEXT': {
3771 'decoder_func': 'DoPopGroupMarkerEXT',
3772 'expectation': False,
3773 'extension': True,
3774 'impl_func': False,
3777 'GenVertexArraysOES': {
3778 'type': 'GENn',
3779 'extension': True,
3780 'gl_test_func': 'glGenVertexArraysOES',
3781 'resource_type': 'VertexArray',
3782 'resource_types': 'VertexArrays',
3783 'unit_test': False,
3784 'pepper_interface': 'VertexArrayObject',
3786 'BindVertexArrayOES': {
3787 'type': 'Bind',
3788 'extension': True,
3789 'gl_test_func': 'glBindVertexArrayOES',
3790 'decoder_func': 'DoBindVertexArrayOES',
3791 'gen_func': 'GenVertexArraysOES',
3792 'unit_test': False,
3793 'client_test': False,
3794 'pepper_interface': 'VertexArrayObject',
3796 'DeleteVertexArraysOES': {
3797 'type': 'DELn',
3798 'extension': True,
3799 'gl_test_func': 'glDeleteVertexArraysOES',
3800 'resource_type': 'VertexArray',
3801 'resource_types': 'VertexArrays',
3802 'unit_test': False,
3803 'pepper_interface': 'VertexArrayObject',
3805 'IsVertexArrayOES': {
3806 'type': 'Is',
3807 'extension': True,
3808 'gl_test_func': 'glIsVertexArrayOES',
3809 'decoder_func': 'DoIsVertexArrayOES',
3810 'expectation': False,
3811 'unit_test': False,
3812 'pepper_interface': 'VertexArrayObject',
3814 'BindTexImage2DCHROMIUM': {
3815 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3816 'unit_test': False,
3817 'extension': "CHROMIUM_image",
3818 'chromium': True,
3820 'ReleaseTexImage2DCHROMIUM': {
3821 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3822 'unit_test': False,
3823 'extension': "CHROMIUM_image",
3824 'chromium': True,
3826 'ShallowFinishCHROMIUM': {
3827 'impl_func': False,
3828 'gen_cmd': False,
3829 'extension': True,
3830 'chromium': True,
3831 'client_test': False,
3833 'ShallowFlushCHROMIUM': {
3834 'impl_func': False,
3835 'gen_cmd': False,
3836 'extension': "CHROMIUM_miscellaneous",
3837 'chromium': True,
3838 'client_test': False,
3840 'OrderingBarrierCHROMIUM': {
3841 'impl_func': False,
3842 'gen_cmd': False,
3843 'extension': True,
3844 'chromium': True,
3845 'client_test': False,
3847 'TraceBeginCHROMIUM': {
3848 'type': 'Custom',
3849 'impl_func': False,
3850 'client_test': False,
3851 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3852 'extension': True,
3853 'chromium': True,
3855 'TraceEndCHROMIUM': {
3856 'impl_func': False,
3857 'client_test': False,
3858 'decoder_func': 'DoTraceEndCHROMIUM',
3859 'unit_test': False,
3860 'extension': True,
3861 'chromium': True,
3863 'AsyncTexImage2DCHROMIUM': {
3864 'type': 'Manual',
3865 'data_transfer_methods': ['shm'],
3866 'client_test': False,
3867 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3868 'GLintTextureInternalFormat internalformat, '
3869 'GLsizei width, GLsizei height, '
3870 'GLintTextureBorder border, '
3871 'GLenumTextureFormat format, GLenumPixelType type, '
3872 'const void* pixels, '
3873 'uint32_t async_upload_token, '
3874 'void* sync_data',
3875 'extension': True,
3876 'chromium': True,
3877 'trace_level': 2,
3879 'AsyncTexSubImage2DCHROMIUM': {
3880 'type': 'Manual',
3881 'data_transfer_methods': ['shm'],
3882 'client_test': False,
3883 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3884 'GLint xoffset, GLint yoffset, '
3885 'GLsizei width, GLsizei height, '
3886 'GLenumTextureFormat format, GLenumPixelType type, '
3887 'const void* data, '
3888 'uint32_t async_upload_token, '
3889 'void* sync_data',
3890 'extension': True,
3891 'chromium': True,
3892 'trace_level': 2,
3894 'WaitAsyncTexImage2DCHROMIUM': {
3895 'type': 'Manual',
3896 'client_test': False,
3897 'extension': True,
3898 'chromium': True,
3899 'trace_level': 1,
3901 'WaitAllAsyncTexImage2DCHROMIUM': {
3902 'type': 'Manual',
3903 'client_test': False,
3904 'extension': True,
3905 'chromium': True,
3906 'trace_level': 1,
3908 'DiscardFramebufferEXT': {
3909 'type': 'PUTn',
3910 'count': 1,
3911 'decoder_func': 'DoDiscardFramebufferEXT',
3912 'unit_test': False,
3913 'client_test': False,
3914 'extension_flag': 'ext_discard_framebuffer',
3915 'trace_level': 2,
3917 'LoseContextCHROMIUM': {
3918 'decoder_func': 'DoLoseContextCHROMIUM',
3919 'unit_test': False,
3920 'extension': True,
3921 'chromium': True,
3922 'trace_level': 1,
3924 'InsertSyncPointCHROMIUM': {
3925 'type': 'HandWritten',
3926 'impl_func': False,
3927 'extension': "CHROMIUM_sync_point",
3928 'chromium': True,
3929 'trace_level': 1,
3931 'WaitSyncPointCHROMIUM': {
3932 'type': 'Custom',
3933 'impl_func': True,
3934 'extension': "CHROMIUM_sync_point",
3935 'chromium': True,
3936 'trace_level': 1,
3938 'DiscardBackbufferCHROMIUM': {
3939 'type': 'Custom',
3940 'impl_func': True,
3941 'extension': True,
3942 'chromium': True,
3943 'trace_level': 2,
3945 'ScheduleOverlayPlaneCHROMIUM': {
3946 'type': 'Custom',
3947 'impl_func': True,
3948 'unit_test': False,
3949 'client_test': False,
3950 'extension': True,
3951 'chromium': True,
3953 'MatrixLoadfCHROMIUM': {
3954 'type': 'PUT',
3955 'count': 16,
3956 'data_type': 'GLfloat',
3957 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3958 'gl_test_func': 'glMatrixLoadfEXT',
3959 'chromium': True,
3960 'extension': True,
3961 'extension_flag': 'chromium_path_rendering',
3963 'MatrixLoadIdentityCHROMIUM': {
3964 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3965 'gl_test_func': 'glMatrixLoadIdentityEXT',
3966 'chromium': True,
3967 'extension': True,
3968 'extension_flag': 'chromium_path_rendering',
3973 def Grouper(n, iterable, fillvalue=None):
3974 """Collect data into fixed-length chunks or blocks"""
3975 args = [iter(iterable)] * n
3976 return itertools.izip_longest(fillvalue=fillvalue, *args)
3979 def SplitWords(input_string):
3980 """Split by '_' if found, otherwise split at uppercase/numeric chars.
3982 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
3983 "Case"], and "Vector3" into ["Vector", "3"].
3985 if input_string.find('_') > -1:
3986 # 'some_TEXT_' -> 'some TEXT'
3987 return input_string.replace('_', ' ').strip().split()
3988 else:
3989 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
3990 # mixed case.
3991 # look for capitalization to cut input_strings
3992 # 'SomeText' -> 'Some Text'
3993 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
3994 # 'Vector3' -> 'Vector 3'
3995 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
3996 return input_string.split()
3998 def ToUnderscore(input_string):
3999 """converts CamelCase to camel_case."""
4000 words = SplitWords(input_string)
4001 return '_'.join([word.lower() for word in words])
4003 def CachedStateName(item):
4004 if item.get('cached', False):
4005 return 'cached_' + item['name']
4006 return item['name']
4008 def ToGLExtensionString(extension_flag):
4009 """Returns GL-type extension string of a extension flag."""
4010 if extension_flag == "oes_compressed_etc1_rgb8_texture":
4011 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4012 # unfortunate.
4013 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4014 'egl', 'atc', 'etc1', 'angle']
4015 parts = extension_flag.split('_')
4016 return "_".join(
4017 [part.upper() if part in uppercase_words else part for part in parts])
4019 def ToCamelCase(input_string):
4020 """converts ABC_underscore_case to ABCUnderscoreCase."""
4021 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
4023 def GetGLGetTypeConversion(result_type, value_type, value):
4024 """Makes a gl compatible type conversion string for accessing state variables.
4026 Useful when accessing state variables through glGetXXX calls.
4027 glGet documetation (for example, the manual pages):
4028 [...] If glGetIntegerv is called, [...] most floating-point values are
4029 rounded to the nearest integer value. [...]
4031 Args:
4032 result_type: the gl type to be obtained
4033 value_type: the GL type of the state variable
4034 value: the name of the state variable
4036 Returns:
4037 String that converts the state variable to desired GL type according to GL
4038 rules.
4041 if result_type == 'GLint':
4042 if value_type == 'GLfloat':
4043 return 'static_cast<GLint>(round(%s))' % value
4044 return 'static_cast<%s>(%s)' % (result_type, value)
4046 class CWriter(object):
4047 """Writes to a file formatting it for Google's style guidelines."""
4049 def __init__(self, filename):
4050 self.filename = filename
4051 self.content = []
4053 def Write(self, string):
4054 """Writes a string to a file spliting if it's > 80 characters."""
4055 lines = string.splitlines()
4056 num_lines = len(lines)
4057 for ii in range(0, num_lines):
4058 self.content.append(lines[ii])
4059 if ii < (num_lines - 1) or string[-1] == '\n':
4060 self.content.append('\n')
4062 def Close(self):
4063 """Close the file."""
4064 content = "".join(self.content)
4065 write_file = True
4066 if os.path.exists(self.filename):
4067 old_file = open(self.filename, "rb");
4068 old_content = old_file.read()
4069 old_file.close();
4070 if content == old_content:
4071 write_file = False
4072 if write_file:
4073 file = open(self.filename, "wb")
4074 file.write(content)
4075 file.close()
4078 class CHeaderWriter(CWriter):
4079 """Writes a C Header file."""
4081 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
4083 def __init__(self, filename, file_comment = None):
4084 CWriter.__init__(self, filename)
4086 base = os.path.abspath(filename)
4087 while os.path.basename(base) != 'src':
4088 new_base = os.path.dirname(base)
4089 assert new_base != base # Prevent infinite loop.
4090 base = new_base
4092 hpath = os.path.relpath(filename, base)
4093 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
4095 self.Write(_LICENSE)
4096 self.Write(_DO_NOT_EDIT_WARNING)
4097 if not file_comment == None:
4098 self.Write(file_comment)
4099 self.Write("#ifndef %s\n" % self.guard)
4100 self.Write("#define %s\n\n" % self.guard)
4102 def Close(self):
4103 self.Write("#endif // %s\n\n" % self.guard)
4104 CWriter.Close(self)
4106 class TypeHandler(object):
4107 """This class emits code for a particular type of function."""
4109 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
4111 def __init__(self):
4112 pass
4114 def InitFunction(self, func):
4115 """Add or adjust anything type specific for this function."""
4116 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
4117 func.AddCmdArg(DataSizeArgument('data_size'))
4119 def NeedsDataTransferFunction(self, func):
4120 """Overriden from TypeHandler."""
4121 return func.num_pointer_args >= 1
4123 def WriteStruct(self, func, file):
4124 """Writes a structure that matches the arguments to a function."""
4125 comment = func.GetInfo('cmd_comment')
4126 if not comment == None:
4127 file.Write(comment)
4128 file.Write("struct %s {\n" % func.name)
4129 file.Write(" typedef %s ValueType;\n" % func.name)
4130 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
4131 func.WriteCmdArgFlag(file)
4132 func.WriteCmdFlag(file)
4133 file.Write("\n")
4134 result = func.GetInfo('result')
4135 if not result == None:
4136 if len(result) == 1:
4137 file.Write(" typedef %s Result;\n\n" % result[0])
4138 else:
4139 file.Write(" struct Result {\n")
4140 for line in result:
4141 file.Write(" %s;\n" % line)
4142 file.Write(" };\n\n")
4144 func.WriteCmdComputeSize(file)
4145 func.WriteCmdSetHeader(file)
4146 func.WriteCmdInit(file)
4147 func.WriteCmdSet(file)
4149 file.Write(" gpu::CommandHeader header;\n")
4150 args = func.GetCmdArgs()
4151 for arg in args:
4152 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
4154 consts = func.GetCmdConstants()
4155 for const in consts:
4156 file.Write(" static const %s %s = %s;\n" %
4157 (const.cmd_type, const.name, const.GetConstantValue()))
4159 file.Write("};\n")
4160 file.Write("\n")
4162 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
4163 file.Write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
4164 file.Write(" \"size of %s should be %d\");\n" %
4165 (func.name, size))
4166 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
4167 file.Write(" \"offset of %s header should be 0\");\n" %
4168 func.name)
4169 offset = _SIZE_OF_COMMAND_HEADER
4170 for arg in args:
4171 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
4172 (func.name, arg.name, offset))
4173 file.Write(" \"offset of %s %s should be %d\");\n" %
4174 (func.name, arg.name, offset))
4175 offset += _SIZE_OF_UINT32
4176 if not result == None and len(result) > 1:
4177 offset = 0;
4178 for line in result:
4179 parts = line.split()
4180 name = parts[-1]
4181 check = """
4182 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4183 "offset of %(cmd_name)s Result %(field_name)s should be "
4184 "%(offset)d");
4186 file.Write((check.strip() + "\n") % {
4187 'cmd_name': func.name,
4188 'field_name': name,
4189 'offset': offset,
4191 offset += _SIZE_OF_UINT32
4192 file.Write("\n")
4194 def WriteHandlerImplementation(self, func, file):
4195 """Writes the handler implementation for this command."""
4196 if func.IsUnsafe() and func.GetInfo('id_mapping'):
4197 code_no_gen = """ if (!group_->Get%(type)sServiceId(
4198 %(var)s, &%(service_var)s)) {
4199 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4200 return error::kNoError;
4203 code_gen = """ if (!group_->Get%(type)sServiceId(
4204 %(var)s, &%(service_var)s)) {
4205 if (!group_->bind_generates_resource()) {
4206 LOCAL_SET_GL_ERROR(
4207 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4208 return error::kNoError;
4210 GLuint client_id = %(var)s;
4211 gl%(gen_func)s(1, &%(service_var)s);
4212 Create%(type)s(client_id, %(service_var)s);
4215 gen_func = func.GetInfo('gen_func')
4216 for id_type in func.GetInfo('id_mapping'):
4217 service_var = id_type.lower()
4218 if id_type == 'Sync':
4219 service_var = "service_%s" % service_var
4220 file.Write(" GLsync %s = 0;\n" % service_var)
4221 if gen_func and id_type in gen_func:
4222 file.Write(code_gen % { 'type': id_type,
4223 'var': id_type.lower(),
4224 'service_var': service_var,
4225 'func': func.GetGLFunctionName(),
4226 'gen_func': gen_func })
4227 else:
4228 file.Write(code_no_gen % { 'type': id_type,
4229 'var': id_type.lower(),
4230 'service_var': service_var,
4231 'func': func.GetGLFunctionName() })
4232 args = []
4233 for arg in func.GetOriginalArgs():
4234 if arg.type == "GLsync":
4235 args.append("service_%s" % arg.name)
4236 elif arg.name.endswith("size") and arg.type == "GLsizei":
4237 args.append("num_%s" % func.GetLastOriginalArg().name)
4238 elif arg.name == "length":
4239 args.append("nullptr")
4240 else:
4241 args.append(arg.name)
4242 file.Write(" %s(%s);\n" %
4243 (func.GetGLFunctionName(), ", ".join(args)))
4245 def WriteCmdSizeTest(self, func, file):
4246 """Writes the size test for a command."""
4247 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4249 def WriteFormatTest(self, func, file):
4250 """Writes a format test for a command."""
4251 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4252 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4253 (func.name, func.name))
4254 file.Write(" void* next_cmd = cmd.Set(\n")
4255 file.Write(" &cmd")
4256 args = func.GetCmdArgs()
4257 for value, arg in enumerate(args):
4258 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4259 file.Write(");\n")
4260 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4261 func.name)
4262 file.Write(" cmd.header.command);\n")
4263 func.type_handler.WriteCmdSizeTest(func, file)
4264 for value, arg in enumerate(args):
4265 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4266 (arg.type, value + 11, arg.name))
4267 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4268 file.Write(" next_cmd, sizeof(cmd));\n")
4269 file.Write("}\n")
4270 file.Write("\n")
4272 def WriteImmediateFormatTest(self, func, file):
4273 """Writes a format test for an immediate version of a command."""
4274 pass
4276 def WriteBucketFormatTest(self, func, file):
4277 """Writes a format test for a bucket version of a command."""
4278 pass
4280 def WriteGetDataSizeCode(self, func, file):
4281 """Writes the code to set data_size used in validation"""
4282 pass
4284 def WriteImmediateCmdSizeTest(self, func, file):
4285 """Writes a size test for an immediate version of a command."""
4286 file.Write(" // TODO(gman): Compute correct size.\n")
4287 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4289 def __WriteIdMapping(self, func, file):
4290 """Writes client side / service side ID mapping."""
4291 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
4292 return
4293 for id_type in func.GetInfo('id_mapping'):
4294 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
4295 (id_type, id_type.lower(), id_type.lower()))
4297 def WriteImmediateHandlerImplementation (self, func, file):
4298 """Writes the handler impl for the immediate version of a command."""
4299 self.__WriteIdMapping(func, file)
4300 file.Write(" %s(%s);\n" %
4301 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4303 def WriteBucketHandlerImplementation (self, func, file):
4304 """Writes the handler impl for the bucket version of a command."""
4305 self.__WriteIdMapping(func, file)
4306 file.Write(" %s(%s);\n" %
4307 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4309 def WriteServiceHandlerFunctionHeader(self, func, file):
4310 """Writes function header for service implementation handlers."""
4311 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4312 uint32_t immediate_data_size, const void* cmd_data) {
4313 """ % {'name': func.name})
4314 if func.IsUnsafe():
4315 file.Write("""if (!unsafe_es3_apis_enabled())
4316 return error::kUnknownCommand;
4317 """)
4318 file.Write("""const gles2::cmds::%(name)s& c =
4319 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4320 (void)c;
4321 """ % {'name': func.name})
4323 def WriteServiceImplementation(self, func, file):
4324 """Writes the service implementation for a command."""
4325 self.WriteServiceHandlerFunctionHeader(func, file)
4326 self.WriteHandlerExtensionCheck(func, file)
4327 self.WriteHandlerDeferReadWrite(func, file);
4328 if len(func.GetOriginalArgs()) > 0:
4329 last_arg = func.GetLastOriginalArg()
4330 all_but_last_arg = func.GetOriginalArgs()[:-1]
4331 for arg in all_but_last_arg:
4332 arg.WriteGetCode(file)
4333 self.WriteGetDataSizeCode(func, file)
4334 last_arg.WriteGetCode(file)
4335 func.WriteHandlerValidation(file)
4336 func.WriteHandlerImplementation(file)
4337 file.Write(" return error::kNoError;\n")
4338 file.Write("}\n")
4339 file.Write("\n")
4341 def WriteImmediateServiceImplementation(self, func, file):
4342 """Writes the service implementation for an immediate version of command."""
4343 self.WriteServiceHandlerFunctionHeader(func, file)
4344 self.WriteHandlerExtensionCheck(func, file)
4345 self.WriteHandlerDeferReadWrite(func, file);
4346 for arg in func.GetOriginalArgs():
4347 if arg.IsPointer():
4348 self.WriteGetDataSizeCode(func, file)
4349 arg.WriteGetCode(file)
4350 func.WriteHandlerValidation(file)
4351 func.WriteHandlerImplementation(file)
4352 file.Write(" return error::kNoError;\n")
4353 file.Write("}\n")
4354 file.Write("\n")
4356 def WriteBucketServiceImplementation(self, func, file):
4357 """Writes the service implementation for a bucket version of command."""
4358 self.WriteServiceHandlerFunctionHeader(func, file)
4359 self.WriteHandlerExtensionCheck(func, file)
4360 self.WriteHandlerDeferReadWrite(func, file);
4361 for arg in func.GetCmdArgs():
4362 arg.WriteGetCode(file)
4363 func.WriteHandlerValidation(file)
4364 func.WriteHandlerImplementation(file)
4365 file.Write(" return error::kNoError;\n")
4366 file.Write("}\n")
4367 file.Write("\n")
4369 def WriteHandlerExtensionCheck(self, func, file):
4370 if func.GetInfo('extension_flag'):
4371 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
4372 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4373 " \"function not available\");\n" % func.original_name)
4374 file.Write(" return error::kNoError;")
4375 file.Write(" }\n\n")
4377 def WriteHandlerDeferReadWrite(self, func, file):
4378 """Writes the code to handle deferring reads or writes."""
4379 defer_draws = func.GetInfo('defer_draws')
4380 defer_reads = func.GetInfo('defer_reads')
4381 if defer_draws or defer_reads:
4382 file.Write(" error::Error error;\n")
4383 if defer_draws:
4384 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
4385 file.Write(" if (error != error::kNoError)\n")
4386 file.Write(" return error;\n")
4387 if defer_reads:
4388 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
4389 file.Write(" if (error != error::kNoError)\n")
4390 file.Write(" return error;\n")
4392 def WriteValidUnitTest(self, func, file, test, *extras):
4393 """Writes a valid unit test for the service implementation."""
4394 if func.GetInfo('expectation') == False:
4395 test = self._remove_expected_call_re.sub('', test)
4396 name = func.name
4397 arg_strings = [
4398 arg.GetValidArg(func) \
4399 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4401 gl_arg_strings = [
4402 arg.GetValidGLArg(func) \
4403 for arg in func.GetOriginalArgs()
4405 gl_func_name = func.GetGLTestFunctionName()
4406 vars = {
4407 'name':name,
4408 'gl_func_name': gl_func_name,
4409 'args': ", ".join(arg_strings),
4410 'gl_args': ", ".join(gl_arg_strings),
4412 for extra in extras:
4413 vars.update(extra)
4414 old_test = ""
4415 while (old_test != test):
4416 old_test = test
4417 test = test % vars
4418 file.Write(test % vars)
4420 def WriteInvalidUnitTest(self, func, file, test, *extras):
4421 """Writes an invalid unit test for the service implementation."""
4422 if func.IsUnsafe():
4423 return
4424 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4425 # Service implementation does not test constants, as they are not part of
4426 # the call in the service side.
4427 if invalid_arg.IsConstant():
4428 continue
4430 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4431 for value_index in range(0, num_invalid_values):
4432 arg_strings = []
4433 parse_result = "kNoError"
4434 gl_error = None
4435 for arg in func.GetOriginalArgs():
4436 if arg.IsConstant():
4437 continue
4438 if invalid_arg is arg:
4439 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4440 value_index)
4441 else:
4442 arg_string = arg.GetValidArg(func)
4443 arg_strings.append(arg_string)
4444 gl_arg_strings = []
4445 for arg in func.GetOriginalArgs():
4446 gl_arg_strings.append("_")
4447 gl_func_name = func.GetGLTestFunctionName()
4448 gl_error_test = ''
4449 if not gl_error == None:
4450 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4452 vars = {
4453 'name': func.name,
4454 'arg_index': invalid_arg_index,
4455 'value_index': value_index,
4456 'gl_func_name': gl_func_name,
4457 'args': ", ".join(arg_strings),
4458 'all_but_last_args': ", ".join(arg_strings[:-1]),
4459 'gl_args': ", ".join(gl_arg_strings),
4460 'parse_result': parse_result,
4461 'gl_error_test': gl_error_test,
4463 for extra in extras:
4464 vars.update(extra)
4465 file.Write(test % vars)
4467 def WriteServiceUnitTest(self, func, file, *extras):
4468 """Writes the service unit test for a command."""
4470 if func.name == 'Enable':
4471 valid_test = """
4472 TEST_P(%(test_name)s, %(name)sValidArgs) {
4473 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4474 SpecializedSetup<cmds::%(name)s, 0>(true);
4475 cmds::%(name)s cmd;
4476 cmd.Init(%(args)s);"""
4477 elif func.name == 'Disable':
4478 valid_test = """
4479 TEST_P(%(test_name)s, %(name)sValidArgs) {
4480 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4481 SpecializedSetup<cmds::%(name)s, 0>(true);
4482 cmds::%(name)s cmd;
4483 cmd.Init(%(args)s);"""
4484 else:
4485 valid_test = """
4486 TEST_P(%(test_name)s, %(name)sValidArgs) {
4487 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4488 SpecializedSetup<cmds::%(name)s, 0>(true);
4489 cmds::%(name)s cmd;
4490 cmd.Init(%(args)s);"""
4491 if func.IsUnsafe():
4492 valid_test += """
4493 decoder_->set_unsafe_es3_apis_enabled(true);
4494 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4495 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4496 decoder_->set_unsafe_es3_apis_enabled(false);
4497 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4500 else:
4501 valid_test += """
4502 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4503 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4506 self.WriteValidUnitTest(func, file, valid_test, *extras)
4508 if not func.IsUnsafe():
4509 invalid_test = """
4510 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4511 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4512 SpecializedSetup<cmds::%(name)s, 0>(false);
4513 cmds::%(name)s cmd;
4514 cmd.Init(%(args)s);
4515 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4518 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4520 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4521 """Writes the service unit test for an immediate command."""
4522 file.Write("// TODO(gman): %s\n" % func.name)
4524 def WriteImmediateValidationCode(self, func, file):
4525 """Writes the validation code for an immediate version of a command."""
4526 pass
4528 def WriteBucketServiceUnitTest(self, func, file, *extras):
4529 """Writes the service unit test for a bucket command."""
4530 file.Write("// TODO(gman): %s\n" % func.name)
4532 def WriteBucketValidationCode(self, func, file):
4533 """Writes the validation code for a bucket version of a command."""
4534 file.Write("// TODO(gman): %s\n" % func.name)
4536 def WriteGLES2ImplementationDeclaration(self, func, file):
4537 """Writes the GLES2 Implemention declaration."""
4538 impl_decl = func.GetInfo('impl_decl')
4539 if impl_decl == None or impl_decl == True:
4540 file.Write("%s %s(%s) override;\n" %
4541 (func.return_type, func.original_name,
4542 func.MakeTypedOriginalArgString("")))
4543 file.Write("\n")
4545 def WriteGLES2CLibImplementation(self, func, file):
4546 file.Write("%s GLES2%s(%s) {\n" %
4547 (func.return_type, func.name,
4548 func.MakeTypedOriginalArgString("")))
4549 result_string = "return "
4550 if func.return_type == "void":
4551 result_string = ""
4552 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4553 (result_string, func.original_name,
4554 func.MakeOriginalArgString("")))
4555 file.Write("}\n")
4557 def WriteGLES2Header(self, func, file):
4558 """Writes a re-write macro for GLES"""
4559 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4561 def WriteClientGLCallLog(self, func, file):
4562 """Writes a logging macro for the client side code."""
4563 comma = ""
4564 if len(func.GetOriginalArgs()):
4565 comma = " << "
4566 file.Write(
4567 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4568 (func.original_name, comma, func.MakeLogArgString()))
4570 def WriteClientGLReturnLog(self, func, file):
4571 """Writes the return value logging code."""
4572 if func.return_type != "void":
4573 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4575 def WriteGLES2ImplementationHeader(self, func, file):
4576 """Writes the GLES2 Implemention."""
4577 self.WriteGLES2ImplementationDeclaration(func, file)
4579 def WriteGLES2TraceImplementationHeader(self, func, file):
4580 """Writes the GLES2 Trace Implemention header."""
4581 file.Write("%s %s(%s) override;\n" %
4582 (func.return_type, func.original_name,
4583 func.MakeTypedOriginalArgString("")))
4585 def WriteGLES2TraceImplementation(self, func, file):
4586 """Writes the GLES2 Trace Implemention."""
4587 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4588 (func.return_type, func.original_name,
4589 func.MakeTypedOriginalArgString("")))
4590 result_string = "return "
4591 if func.return_type == "void":
4592 result_string = ""
4593 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4594 func.name)
4595 file.Write(" %sgl_->%s(%s);\n" %
4596 (result_string, func.name, func.MakeOriginalArgString("")))
4597 file.Write("}\n")
4598 file.Write("\n")
4600 def WriteGLES2Implementation(self, func, file):
4601 """Writes the GLES2 Implemention."""
4602 impl_func = func.GetInfo('impl_func')
4603 impl_decl = func.GetInfo('impl_decl')
4604 gen_cmd = func.GetInfo('gen_cmd')
4605 if (func.can_auto_generate and
4606 (impl_func == None or impl_func == True) and
4607 (impl_decl == None or impl_decl == True) and
4608 (gen_cmd == None or gen_cmd == True)):
4609 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4610 (func.return_type, func.original_name,
4611 func.MakeTypedOriginalArgString("")))
4612 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4613 self.WriteClientGLCallLog(func, file)
4614 func.WriteDestinationInitalizationValidation(file)
4615 for arg in func.GetOriginalArgs():
4616 arg.WriteClientSideValidationCode(file, func)
4617 file.Write(" helper_->%s(%s);\n" %
4618 (func.name, func.MakeHelperArgString("")))
4619 file.Write(" CheckGLError();\n")
4620 self.WriteClientGLReturnLog(func, file)
4621 file.Write("}\n")
4622 file.Write("\n")
4624 def WriteGLES2InterfaceHeader(self, func, file):
4625 """Writes the GLES2 Interface."""
4626 file.Write("virtual %s %s(%s) = 0;\n" %
4627 (func.return_type, func.original_name,
4628 func.MakeTypedOriginalArgString("")))
4630 def WriteMojoGLES2ImplHeader(self, func, file):
4631 """Writes the Mojo GLES2 implementation header."""
4632 file.Write("%s %s(%s) override;\n" %
4633 (func.return_type, func.original_name,
4634 func.MakeTypedOriginalArgString("")))
4636 def WriteMojoGLES2Impl(self, func, file):
4637 """Writes the Mojo GLES2 implementation."""
4638 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4639 (func.return_type, func.original_name,
4640 func.MakeTypedOriginalArgString("")))
4641 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4642 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4643 "occlusion_query_EXT", "CHROMIUM_image",
4644 "CHROMIUM_copy_texture",
4645 "CHROMIUM_pixel_transfer_buffer_object"]
4646 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4647 file.Write("MojoGLES2MakeCurrent(context_);");
4648 func_return = "gl" + func.original_name + "(" + \
4649 func.MakeOriginalArgString("") + ");"
4650 if func.return_type == "void":
4651 file.Write(func_return);
4652 else:
4653 file.Write("return " + func_return);
4654 else:
4655 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4656 func.original_name);
4657 if func.return_type != "void":
4658 file.Write("return 0;")
4659 file.Write("}")
4661 def WriteGLES2InterfaceStub(self, func, file):
4662 """Writes the GLES2 Interface stub declaration."""
4663 file.Write("%s %s(%s) override;\n" %
4664 (func.return_type, func.original_name,
4665 func.MakeTypedOriginalArgString("")))
4667 def WriteGLES2InterfaceStubImpl(self, func, file):
4668 """Writes the GLES2 Interface stub declaration."""
4669 args = func.GetOriginalArgs()
4670 arg_string = ", ".join(
4671 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4672 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4673 (func.return_type, func.original_name, arg_string))
4674 if func.return_type != "void":
4675 file.Write(" return 0;\n")
4676 file.Write("}\n")
4678 def WriteGLES2ImplementationUnitTest(self, func, file):
4679 """Writes the GLES2 Implemention unit test."""
4680 client_test = func.GetInfo('client_test')
4681 if (func.can_auto_generate and
4682 (client_test == None or client_test == True)):
4683 code = """
4684 TEST_F(GLES2ImplementationTest, %(name)s) {
4685 struct Cmds {
4686 cmds::%(name)s cmd;
4688 Cmds expected;
4689 expected.cmd.Init(%(cmd_args)s);
4691 gl_->%(name)s(%(args)s);
4692 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4695 cmd_arg_strings = [
4696 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4699 gl_arg_strings = [
4700 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4703 file.Write(code % {
4704 'name': func.name,
4705 'args': ", ".join(gl_arg_strings),
4706 'cmd_args': ", ".join(cmd_arg_strings),
4709 # Test constants for invalid values, as they are not tested by the
4710 # service.
4711 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4712 if constants:
4713 code = """
4714 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4715 gl_->%(name)s(%(args)s);
4716 EXPECT_TRUE(NoCommandsWritten());
4717 EXPECT_EQ(%(gl_error)s, CheckError());
4720 for invalid_arg in constants:
4721 gl_arg_strings = []
4722 invalid = invalid_arg.GetInvalidArg(func)
4723 for arg in func.GetOriginalArgs():
4724 if arg is invalid_arg:
4725 gl_arg_strings.append(invalid[0])
4726 else:
4727 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4729 file.Write(code % {
4730 'name': func.name,
4731 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4732 'args': ", ".join(gl_arg_strings),
4733 'gl_error': invalid[2],
4735 else:
4736 if client_test != False:
4737 file.Write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4739 def WriteDestinationInitalizationValidation(self, func, file):
4740 """Writes the client side destintion initialization validation."""
4741 for arg in func.GetOriginalArgs():
4742 arg.WriteDestinationInitalizationValidation(file, func)
4744 def WriteTraceEvent(self, func, file):
4745 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4746 func.original_name)
4748 def WriteImmediateCmdComputeSize(self, func, file):
4749 """Writes the size computation code for the immediate version of a cmd."""
4750 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4751 file.Write(" return static_cast<uint32_t>(\n")
4752 file.Write(" sizeof(ValueType) + // NOLINT\n")
4753 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4754 file.Write(" }\n")
4755 file.Write("\n")
4757 def WriteImmediateCmdSetHeader(self, func, file):
4758 """Writes the SetHeader function for the immediate version of a cmd."""
4759 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4760 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4761 file.Write(" }\n")
4762 file.Write("\n")
4764 def WriteImmediateCmdInit(self, func, file):
4765 """Writes the Init function for the immediate version of a command."""
4766 raise NotImplementedError(func.name)
4768 def WriteImmediateCmdSet(self, func, file):
4769 """Writes the Set function for the immediate version of a command."""
4770 raise NotImplementedError(func.name)
4772 def WriteCmdHelper(self, func, file):
4773 """Writes the cmd helper definition for a cmd."""
4774 code = """ void %(name)s(%(typed_args)s) {
4775 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4776 if (c) {
4777 c->Init(%(args)s);
4782 file.Write(code % {
4783 "name": func.name,
4784 "typed_args": func.MakeTypedCmdArgString(""),
4785 "args": func.MakeCmdArgString(""),
4788 def WriteImmediateCmdHelper(self, func, file):
4789 """Writes the cmd helper definition for the immediate version of a cmd."""
4790 code = """ void %(name)s(%(typed_args)s) {
4791 const uint32_t s = 0; // TODO(gman): compute correct size
4792 gles2::cmds::%(name)s* c =
4793 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4794 if (c) {
4795 c->Init(%(args)s);
4800 file.Write(code % {
4801 "name": func.name,
4802 "typed_args": func.MakeTypedCmdArgString(""),
4803 "args": func.MakeCmdArgString(""),
4807 class StateSetHandler(TypeHandler):
4808 """Handler for commands that simply set state."""
4810 def __init__(self):
4811 TypeHandler.__init__(self)
4813 def WriteHandlerImplementation(self, func, file):
4814 """Overrriden from TypeHandler."""
4815 state_name = func.GetInfo('state')
4816 state = _STATES[state_name]
4817 states = state['states']
4818 args = func.GetOriginalArgs()
4819 for ndx,item in enumerate(states):
4820 code = []
4821 if 'range_checks' in item:
4822 for range_check in item['range_checks']:
4823 code.append("%s %s" % (args[ndx].name, range_check['check']))
4824 if 'nan_check' in item:
4825 # Drivers might generate an INVALID_VALUE error when a value is set
4826 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4827 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4828 # Make this behavior consistent within Chromium, and avoid leaking GL
4829 # errors by generating the error in the command buffer instead of
4830 # letting the GL driver generate it.
4831 code.append("std::isnan(%s)" % args[ndx].name)
4832 if len(code):
4833 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4834 file.Write(
4835 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4836 ' "%s", "%s out of range");\n' %
4837 (func.name, args[ndx].name))
4838 file.Write(" return error::kNoError;\n")
4839 file.Write(" }\n")
4840 code = []
4841 for ndx,item in enumerate(states):
4842 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4843 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4844 for ndx,item in enumerate(states):
4845 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4846 if 'state_flag' in state:
4847 file.Write(" %s = true;\n" % state['state_flag'])
4848 if not func.GetInfo("no_gl"):
4849 for ndx,item in enumerate(states):
4850 if item.get('cached', False):
4851 file.Write(" state_.%s = %s;\n" %
4852 (CachedStateName(item), args[ndx].name))
4853 file.Write(" %s(%s);\n" %
4854 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4855 file.Write(" }\n")
4857 def WriteServiceUnitTest(self, func, file, *extras):
4858 """Overrriden from TypeHandler."""
4859 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
4860 state_name = func.GetInfo('state')
4861 state = _STATES[state_name]
4862 states = state['states']
4863 for ndx,item in enumerate(states):
4864 if 'range_checks' in item:
4865 for check_ndx, range_check in enumerate(item['range_checks']):
4866 valid_test = """
4867 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4868 SpecializedSetup<cmds::%(name)s, 0>(false);
4869 cmds::%(name)s cmd;
4870 cmd.Init(%(args)s);
4871 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4872 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4875 name = func.name
4876 arg_strings = [
4877 arg.GetValidArg(func) \
4878 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4881 arg_strings[ndx] = range_check['test_value']
4882 vars = {
4883 'name': name,
4884 'ndx': ndx,
4885 'check_ndx': check_ndx,
4886 'args': ", ".join(arg_strings),
4888 for extra in extras:
4889 vars.update(extra)
4890 file.Write(valid_test % vars)
4891 if 'nan_check' in item:
4892 valid_test = """
4893 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4894 SpecializedSetup<cmds::%(name)s, 0>(false);
4895 cmds::%(name)s cmd;
4896 cmd.Init(%(args)s);
4897 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4898 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4901 name = func.name
4902 arg_strings = [
4903 arg.GetValidArg(func) \
4904 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4907 arg_strings[ndx] = 'nanf("")'
4908 vars = {
4909 'name': name,
4910 'ndx': ndx,
4911 'args': ", ".join(arg_strings),
4913 for extra in extras:
4914 vars.update(extra)
4915 file.Write(valid_test % vars)
4918 class StateSetRGBAlphaHandler(TypeHandler):
4919 """Handler for commands that simply set state that have rgb/alpha."""
4921 def __init__(self):
4922 TypeHandler.__init__(self)
4924 def WriteHandlerImplementation(self, func, file):
4925 """Overrriden from TypeHandler."""
4926 state_name = func.GetInfo('state')
4927 state = _STATES[state_name]
4928 states = state['states']
4929 args = func.GetOriginalArgs()
4930 num_args = len(args)
4931 code = []
4932 for ndx,item in enumerate(states):
4933 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
4934 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4935 for ndx, item in enumerate(states):
4936 file.Write(" state_.%s = %s;\n" %
4937 (item['name'], args[ndx % num_args].name))
4938 if 'state_flag' in state:
4939 file.Write(" %s = true;\n" % state['state_flag'])
4940 if not func.GetInfo("no_gl"):
4941 file.Write(" %s(%s);\n" %
4942 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4943 file.Write(" }\n")
4946 class StateSetFrontBackSeparateHandler(TypeHandler):
4947 """Handler for commands that simply set state that have front/back."""
4949 def __init__(self):
4950 TypeHandler.__init__(self)
4952 def WriteHandlerImplementation(self, func, file):
4953 """Overrriden from TypeHandler."""
4954 state_name = func.GetInfo('state')
4955 state = _STATES[state_name]
4956 states = state['states']
4957 args = func.GetOriginalArgs()
4958 face = args[0].name
4959 num_args = len(args)
4960 file.Write(" bool changed = false;\n")
4961 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4962 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4963 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4964 code = []
4965 for ndx, item in enumerate(group):
4966 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
4967 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
4968 file.Write(" }\n")
4969 file.Write(" if (changed) {\n")
4970 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4971 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4972 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4973 for ndx, item in enumerate(group):
4974 file.Write(" state_.%s = %s;\n" %
4975 (item['name'], args[ndx + 1].name))
4976 file.Write(" }\n")
4977 if 'state_flag' in state:
4978 file.Write(" %s = true;\n" % state['state_flag'])
4979 if not func.GetInfo("no_gl"):
4980 file.Write(" %s(%s);\n" %
4981 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4982 file.Write(" }\n")
4985 class StateSetFrontBackHandler(TypeHandler):
4986 """Handler for commands that simply set state that set both front/back."""
4988 def __init__(self):
4989 TypeHandler.__init__(self)
4991 def WriteHandlerImplementation(self, func, file):
4992 """Overrriden from TypeHandler."""
4993 state_name = func.GetInfo('state')
4994 state = _STATES[state_name]
4995 states = state['states']
4996 args = func.GetOriginalArgs()
4997 num_args = len(args)
4998 code = []
4999 for group_ndx, group in enumerate(Grouper(num_args, states)):
5000 for ndx, item in enumerate(group):
5001 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5002 file.Write(" if (%s) {\n" % " ||\n ".join(code))
5003 for group_ndx, group in enumerate(Grouper(num_args, states)):
5004 for ndx, item in enumerate(group):
5005 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5006 if 'state_flag' in state:
5007 file.Write(" %s = true;\n" % state['state_flag'])
5008 if not func.GetInfo("no_gl"):
5009 file.Write(" %s(%s);\n" %
5010 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5011 file.Write(" }\n")
5014 class StateSetNamedParameter(TypeHandler):
5015 """Handler for commands that set a state chosen with an enum parameter."""
5017 def __init__(self):
5018 TypeHandler.__init__(self)
5020 def WriteHandlerImplementation(self, func, file):
5021 """Overridden from TypeHandler."""
5022 state_name = func.GetInfo('state')
5023 state = _STATES[state_name]
5024 states = state['states']
5025 args = func.GetOriginalArgs()
5026 num_args = len(args)
5027 assert num_args == 2
5028 file.Write(" switch (%s) {\n" % args[0].name)
5029 for state in states:
5030 file.Write(" case %s:\n" % state['enum'])
5031 file.Write(" if (state_.%s != %s) {\n" %
5032 (state['name'], args[1].name))
5033 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
5034 if not func.GetInfo("no_gl"):
5035 file.Write(" %s(%s);\n" %
5036 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5037 file.Write(" }\n")
5038 file.Write(" break;\n")
5039 file.Write(" default:\n")
5040 file.Write(" NOTREACHED();\n")
5041 file.Write(" }\n")
5044 class CustomHandler(TypeHandler):
5045 """Handler for commands that are auto-generated but require minor tweaks."""
5047 def __init__(self):
5048 TypeHandler.__init__(self)
5050 def WriteServiceImplementation(self, func, file):
5051 """Overrriden from TypeHandler."""
5052 pass
5054 def WriteImmediateServiceImplementation(self, func, file):
5055 """Overrriden from TypeHandler."""
5056 pass
5058 def WriteBucketServiceImplementation(self, func, file):
5059 """Overrriden from TypeHandler."""
5060 pass
5062 def WriteServiceUnitTest(self, func, file, *extras):
5063 """Overrriden from TypeHandler."""
5064 file.Write("// TODO(gman): %s\n\n" % func.name)
5066 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5067 """Overrriden from TypeHandler."""
5068 file.Write("// TODO(gman): %s\n\n" % func.name)
5070 def WriteImmediateCmdGetTotalSize(self, func, file):
5071 """Overrriden from TypeHandler."""
5072 file.Write(
5073 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5075 def WriteImmediateCmdInit(self, func, file):
5076 """Overrriden from TypeHandler."""
5077 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5078 self.WriteImmediateCmdGetTotalSize(func, file)
5079 file.Write(" SetHeader(total_size);\n")
5080 args = func.GetCmdArgs()
5081 for arg in args:
5082 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5083 file.Write(" }\n")
5084 file.Write("\n")
5086 def WriteImmediateCmdSet(self, func, file):
5087 """Overrriden from TypeHandler."""
5088 copy_args = func.MakeCmdArgString("_", False)
5089 file.Write(" void* Set(void* cmd%s) {\n" %
5090 func.MakeTypedCmdArgString("_", True))
5091 self.WriteImmediateCmdGetTotalSize(func, file)
5092 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5093 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5094 "cmd, total_size);\n")
5095 file.Write(" }\n")
5096 file.Write("\n")
5099 class TodoHandler(CustomHandler):
5100 """Handle for commands that are not yet implemented."""
5102 def NeedsDataTransferFunction(self, func):
5103 """Overriden from TypeHandler."""
5104 return False
5106 def WriteImmediateFormatTest(self, func, file):
5107 """Overrriden from TypeHandler."""
5108 pass
5110 def WriteGLES2ImplementationUnitTest(self, func, file):
5111 """Overrriden from TypeHandler."""
5112 pass
5114 def WriteGLES2Implementation(self, func, file):
5115 """Overrriden from TypeHandler."""
5116 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5117 (func.return_type, func.original_name,
5118 func.MakeTypedOriginalArgString("")))
5119 file.Write(" // TODO: for now this is a no-op\n")
5120 file.Write(
5121 " SetGLError("
5122 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5123 func.name)
5124 if func.return_type != "void":
5125 file.Write(" return 0;\n")
5126 file.Write("}\n")
5127 file.Write("\n")
5129 def WriteServiceImplementation(self, func, file):
5130 """Overrriden from TypeHandler."""
5131 self.WriteServiceHandlerFunctionHeader(func, file)
5132 file.Write(" // TODO: for now this is a no-op\n")
5133 file.Write(
5134 " LOCAL_SET_GL_ERROR("
5135 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5136 func.name)
5137 file.Write(" return error::kNoError;\n")
5138 file.Write("}\n")
5139 file.Write("\n")
5142 class HandWrittenHandler(CustomHandler):
5143 """Handler for comands where everything must be written by hand."""
5145 def InitFunction(self, func):
5146 """Add or adjust anything type specific for this function."""
5147 CustomHandler.InitFunction(self, func)
5148 func.can_auto_generate = False
5150 def NeedsDataTransferFunction(self, func):
5151 """Overriden from TypeHandler."""
5152 # If specified explicitly, force the data transfer method.
5153 if func.GetInfo('data_transfer_methods'):
5154 return True
5155 return False
5157 def WriteStruct(self, func, file):
5158 """Overrriden from TypeHandler."""
5159 pass
5161 def WriteDocs(self, func, file):
5162 """Overrriden from TypeHandler."""
5163 pass
5165 def WriteServiceUnitTest(self, func, file, *extras):
5166 """Overrriden from TypeHandler."""
5167 file.Write("// TODO(gman): %s\n\n" % func.name)
5169 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5170 """Overrriden from TypeHandler."""
5171 file.Write("// TODO(gman): %s\n\n" % func.name)
5173 def WriteBucketServiceUnitTest(self, func, file, *extras):
5174 """Overrriden from TypeHandler."""
5175 file.Write("// TODO(gman): %s\n\n" % func.name)
5177 def WriteServiceImplementation(self, func, file):
5178 """Overrriden from TypeHandler."""
5179 pass
5181 def WriteImmediateServiceImplementation(self, func, file):
5182 """Overrriden from TypeHandler."""
5183 pass
5185 def WriteBucketServiceImplementation(self, func, file):
5186 """Overrriden from TypeHandler."""
5187 pass
5189 def WriteImmediateCmdHelper(self, func, file):
5190 """Overrriden from TypeHandler."""
5191 pass
5193 def WriteCmdHelper(self, func, file):
5194 """Overrriden from TypeHandler."""
5195 pass
5197 def WriteFormatTest(self, func, file):
5198 """Overrriden from TypeHandler."""
5199 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5201 def WriteImmediateFormatTest(self, func, file):
5202 """Overrriden from TypeHandler."""
5203 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5205 def WriteBucketFormatTest(self, func, file):
5206 """Overrriden from TypeHandler."""
5207 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5211 class ManualHandler(CustomHandler):
5212 """Handler for commands who's handlers must be written by hand."""
5214 def __init__(self):
5215 CustomHandler.__init__(self)
5217 def InitFunction(self, func):
5218 """Overrriden from TypeHandler."""
5219 if (func.name == 'CompressedTexImage2DBucket' or
5220 func.name == 'CompressedTexImage3DBucket'):
5221 func.cmd_args = func.cmd_args[:-1]
5222 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5223 else:
5224 CustomHandler.InitFunction(self, func)
5226 def WriteServiceImplementation(self, func, file):
5227 """Overrriden from TypeHandler."""
5228 pass
5230 def WriteBucketServiceImplementation(self, func, file):
5231 """Overrriden from TypeHandler."""
5232 pass
5234 def WriteServiceUnitTest(self, func, file, *extras):
5235 """Overrriden from TypeHandler."""
5236 file.Write("// TODO(gman): %s\n\n" % func.name)
5238 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5239 """Overrriden from TypeHandler."""
5240 file.Write("// TODO(gman): %s\n\n" % func.name)
5242 def WriteImmediateServiceImplementation(self, func, file):
5243 """Overrriden from TypeHandler."""
5244 pass
5246 def WriteImmediateFormatTest(self, func, file):
5247 """Overrriden from TypeHandler."""
5248 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
5250 def WriteGLES2Implementation(self, func, file):
5251 """Overrriden from TypeHandler."""
5252 if func.GetInfo('impl_func'):
5253 super(ManualHandler, self).WriteGLES2Implementation(func, file)
5255 def WriteGLES2ImplementationHeader(self, func, file):
5256 """Overrriden from TypeHandler."""
5257 file.Write("%s %s(%s) override;\n" %
5258 (func.return_type, func.original_name,
5259 func.MakeTypedOriginalArgString("")))
5260 file.Write("\n")
5262 def WriteImmediateCmdGetTotalSize(self, func, file):
5263 """Overrriden from TypeHandler."""
5264 # TODO(gman): Move this data to _FUNCTION_INFO?
5265 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
5268 class DataHandler(TypeHandler):
5269 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5270 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5271 def __init__(self):
5272 TypeHandler.__init__(self)
5274 def InitFunction(self, func):
5275 """Overrriden from TypeHandler."""
5276 if (func.name == 'CompressedTexSubImage2DBucket' or
5277 func.name == 'CompressedTexSubImage3DBucket'):
5278 func.cmd_args = func.cmd_args[:-1]
5279 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5281 def WriteGetDataSizeCode(self, func, file):
5282 """Overrriden from TypeHandler."""
5283 # TODO(gman): Move this data to _FUNCTION_INFO?
5284 name = func.name
5285 if name.endswith("Immediate"):
5286 name = name[0:-9]
5287 if name == 'BufferData' or name == 'BufferSubData':
5288 file.Write(" uint32_t data_size = size;\n")
5289 elif (name == 'CompressedTexImage2D' or
5290 name == 'CompressedTexSubImage2D' or
5291 name == 'CompressedTexImage3D' or
5292 name == 'CompressedTexSubImage3D'):
5293 file.Write(" uint32_t data_size = imageSize;\n")
5294 elif (name == 'CompressedTexSubImage2DBucket' or
5295 name == 'CompressedTexSubImage3DBucket'):
5296 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5297 file.Write(" uint32_t data_size = bucket->size();\n")
5298 file.Write(" GLsizei imageSize = data_size;\n")
5299 elif name == 'TexImage2D' or name == 'TexSubImage2D':
5300 code = """ uint32_t data_size;
5301 if (!GLES2Util::ComputeImageDataSize(
5302 width, height, format, type, unpack_alignment_, &data_size)) {
5303 return error::kOutOfBounds;
5306 file.Write(code)
5307 else:
5308 file.Write(
5309 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5311 def WriteImmediateCmdGetTotalSize(self, func, file):
5312 """Overrriden from TypeHandler."""
5313 pass
5315 def WriteImmediateCmdSizeTest(self, func, file):
5316 """Overrriden from TypeHandler."""
5317 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5319 def WriteImmediateCmdInit(self, func, file):
5320 """Overrriden from TypeHandler."""
5321 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5322 self.WriteImmediateCmdGetTotalSize(func, file)
5323 file.Write(" SetHeader(total_size);\n")
5324 args = func.GetCmdArgs()
5325 for arg in args:
5326 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5327 file.Write(" }\n")
5328 file.Write("\n")
5330 def WriteImmediateCmdSet(self, func, file):
5331 """Overrriden from TypeHandler."""
5332 copy_args = func.MakeCmdArgString("_", False)
5333 file.Write(" void* Set(void* cmd%s) {\n" %
5334 func.MakeTypedCmdArgString("_", True))
5335 self.WriteImmediateCmdGetTotalSize(func, file)
5336 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5337 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5338 "cmd, total_size);\n")
5339 file.Write(" }\n")
5340 file.Write("\n")
5342 def WriteImmediateFormatTest(self, func, file):
5343 """Overrriden from TypeHandler."""
5344 # TODO(gman): Remove this exception.
5345 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
5346 return
5348 def WriteServiceUnitTest(self, func, file, *extras):
5349 """Overrriden from TypeHandler."""
5350 file.Write("// TODO(gman): %s\n\n" % func.name)
5352 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5353 """Overrriden from TypeHandler."""
5354 file.Write("// TODO(gman): %s\n\n" % func.name)
5356 def WriteBucketServiceImplementation(self, func, file):
5357 """Overrriden from TypeHandler."""
5358 if ((not func.name == 'CompressedTexSubImage2DBucket') and
5359 (not func.name == 'CompressedTexSubImage3DBucket')):
5360 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
5363 class BindHandler(TypeHandler):
5364 """Handler for glBind___ type functions."""
5366 def __init__(self):
5367 TypeHandler.__init__(self)
5369 def WriteServiceUnitTest(self, func, file, *extras):
5370 """Overrriden from TypeHandler."""
5372 if len(func.GetOriginalArgs()) == 1:
5373 valid_test = """
5374 TEST_P(%(test_name)s, %(name)sValidArgs) {
5375 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5376 SpecializedSetup<cmds::%(name)s, 0>(true);
5377 cmds::%(name)s cmd;
5378 cmd.Init(%(args)s);"""
5379 if func.IsUnsafe():
5380 valid_test += """
5381 decoder_->set_unsafe_es3_apis_enabled(true);
5382 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5383 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5384 decoder_->set_unsafe_es3_apis_enabled(false);
5385 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5388 else:
5389 valid_test += """
5390 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5391 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5394 if func.GetInfo("gen_func"):
5395 valid_test += """
5396 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5397 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5398 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5399 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5400 SpecializedSetup<cmds::%(name)s, 0>(true);
5401 cmds::%(name)s cmd;
5402 cmd.Init(kNewClientId);
5403 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5404 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5405 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5408 self.WriteValidUnitTest(func, file, valid_test, {
5409 'resource_type': func.GetOriginalArgs()[0].resource_type,
5410 'gl_gen_func_name': func.GetInfo("gen_func"),
5411 }, *extras)
5412 else:
5413 valid_test = """
5414 TEST_P(%(test_name)s, %(name)sValidArgs) {
5415 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5416 SpecializedSetup<cmds::%(name)s, 0>(true);
5417 cmds::%(name)s cmd;
5418 cmd.Init(%(args)s);"""
5419 if func.IsUnsafe():
5420 valid_test += """
5421 decoder_->set_unsafe_es3_apis_enabled(true);
5422 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5423 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5424 decoder_->set_unsafe_es3_apis_enabled(false);
5425 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5428 else:
5429 valid_test += """
5430 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5431 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5434 if func.GetInfo("gen_func"):
5435 valid_test += """
5436 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5437 EXPECT_CALL(*gl_,
5438 %(gl_func_name)s(%(gl_args_with_new_id)s));
5439 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5440 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5441 SpecializedSetup<cmds::%(name)s, 0>(true);
5442 cmds::%(name)s cmd;
5443 cmd.Init(%(args_with_new_id)s);"""
5444 if func.IsUnsafe():
5445 valid_test += """
5446 decoder_->set_unsafe_es3_apis_enabled(true);
5447 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5448 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5449 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5450 decoder_->set_unsafe_es3_apis_enabled(false);
5451 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5454 else:
5455 valid_test += """
5456 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5457 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5458 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5462 gl_args_with_new_id = []
5463 args_with_new_id = []
5464 for arg in func.GetOriginalArgs():
5465 if hasattr(arg, 'resource_type'):
5466 gl_args_with_new_id.append('kNewServiceId')
5467 args_with_new_id.append('kNewClientId')
5468 else:
5469 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5470 args_with_new_id.append(arg.GetValidArg(func))
5471 self.WriteValidUnitTest(func, file, valid_test, {
5472 'args_with_new_id': ", ".join(args_with_new_id),
5473 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5474 'resource_type': func.GetResourceIdArg().resource_type,
5475 'gl_gen_func_name': func.GetInfo("gen_func"),
5476 }, *extras)
5478 invalid_test = """
5479 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5480 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5481 SpecializedSetup<cmds::%(name)s, 0>(false);
5482 cmds::%(name)s cmd;
5483 cmd.Init(%(args)s);
5484 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5487 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
5489 def WriteGLES2Implementation(self, func, file):
5490 """Writes the GLES2 Implemention."""
5492 impl_func = func.GetInfo('impl_func')
5493 impl_decl = func.GetInfo('impl_decl')
5495 if (func.can_auto_generate and
5496 (impl_func == None or impl_func == True) and
5497 (impl_decl == None or impl_decl == True)):
5499 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5500 (func.return_type, func.original_name,
5501 func.MakeTypedOriginalArgString("")))
5502 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5503 func.WriteDestinationInitalizationValidation(file)
5504 self.WriteClientGLCallLog(func, file)
5505 for arg in func.GetOriginalArgs():
5506 arg.WriteClientSideValidationCode(file, func)
5508 code = """ if (Is%(type)sReservedId(%(id)s)) {
5509 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5510 return;
5512 %(name)sHelper(%(arg_string)s);
5513 CheckGLError();
5517 name_arg = func.GetResourceIdArg()
5518 file.Write(code % {
5519 'name': func.name,
5520 'arg_string': func.MakeOriginalArgString(""),
5521 'id': name_arg.name,
5522 'type': name_arg.resource_type,
5523 'lc_type': name_arg.resource_type.lower(),
5526 def WriteGLES2ImplementationUnitTest(self, func, file):
5527 """Overrriden from TypeHandler."""
5528 client_test = func.GetInfo('client_test')
5529 if client_test == False:
5530 return
5531 code = """
5532 TEST_F(GLES2ImplementationTest, %(name)s) {
5533 struct Cmds {
5534 cmds::%(name)s cmd;
5536 Cmds expected;
5537 expected.cmd.Init(%(cmd_args)s);
5539 gl_->%(name)s(%(args)s);
5540 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5541 if not func.IsUnsafe():
5542 code += """
5543 ClearCommands();
5544 gl_->%(name)s(%(args)s);
5545 EXPECT_TRUE(NoCommandsWritten());"""
5546 code += """
5549 cmd_arg_strings = [
5550 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5552 gl_arg_strings = [
5553 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5556 file.Write(code % {
5557 'name': func.name,
5558 'args': ", ".join(gl_arg_strings),
5559 'cmd_args': ", ".join(cmd_arg_strings),
5563 class GENnHandler(TypeHandler):
5564 """Handler for glGen___ type functions."""
5566 def __init__(self):
5567 TypeHandler.__init__(self)
5569 def InitFunction(self, func):
5570 """Overrriden from TypeHandler."""
5571 pass
5573 def WriteGetDataSizeCode(self, func, file):
5574 """Overrriden from TypeHandler."""
5575 code = """ uint32_t data_size;
5576 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5577 return error::kOutOfBounds;
5580 file.Write(code)
5582 def WriteHandlerImplementation (self, func, file):
5583 """Overrriden from TypeHandler."""
5584 file.Write(" if (!%sHelper(n, %s)) {\n"
5585 " return error::kInvalidArguments;\n"
5586 " }\n" %
5587 (func.name, func.GetLastOriginalArg().name))
5589 def WriteImmediateHandlerImplementation(self, func, file):
5590 """Overrriden from TypeHandler."""
5591 if func.IsUnsafe():
5592 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5593 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5594 return error::kInvalidArguments;
5597 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5598 gl%(func_name)s(n, service_ids.get());
5599 for (GLsizei ii = 0; ii < n; ++ii) {
5600 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5602 """ % { 'func_name': func.original_name,
5603 'last_arg_name': func.GetLastOriginalArg().name,
5604 'resource_name': func.GetInfo('resource_type') })
5605 else:
5606 file.Write(" if (!%sHelper(n, %s)) {\n"
5607 " return error::kInvalidArguments;\n"
5608 " }\n" %
5609 (func.original_name, func.GetLastOriginalArg().name))
5611 def WriteGLES2Implementation(self, func, file):
5612 """Overrriden from TypeHandler."""
5613 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5614 for (GLsizei i = 0; i < n; ++i) {
5615 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5617 });""" % func.GetOriginalArgs()[1].name)
5618 args = {
5619 'log_code': log_code,
5620 'return_type': func.return_type,
5621 'name': func.original_name,
5622 'typed_args': func.MakeTypedOriginalArgString(""),
5623 'args': func.MakeOriginalArgString(""),
5624 'resource_types': func.GetInfo('resource_types'),
5625 'count_name': func.GetOriginalArgs()[0].name,
5627 file.Write(
5628 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5629 args)
5630 func.WriteDestinationInitalizationValidation(file)
5631 self.WriteClientGLCallLog(func, file)
5632 for arg in func.GetOriginalArgs():
5633 arg.WriteClientSideValidationCode(file, func)
5634 not_shared = func.GetInfo('not_shared')
5635 if not_shared:
5636 alloc_code = (
5638 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5639 for (GLsizei ii = 0; ii < n; ++ii)
5640 %s[ii] = id_allocator->AllocateID();""" %
5641 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5642 else:
5643 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5644 MakeIds(this, 0, %(args)s);""" % args)
5645 args['alloc_code'] = alloc_code
5647 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5648 %(alloc_code)s
5649 %(name)sHelper(%(args)s);
5650 helper_->%(name)sImmediate(%(args)s);
5651 if (share_group_->bind_generates_resource())
5652 helper_->CommandBufferHelper::Flush();
5653 %(log_code)s
5654 CheckGLError();
5658 file.Write(code % args)
5660 def WriteGLES2ImplementationUnitTest(self, func, file):
5661 """Overrriden from TypeHandler."""
5662 code = """
5663 TEST_F(GLES2ImplementationTest, %(name)s) {
5664 GLuint ids[2] = { 0, };
5665 struct Cmds {
5666 cmds::%(name)sImmediate gen;
5667 GLuint data[2];
5669 Cmds expected;
5670 expected.gen.Init(arraysize(ids), &ids[0]);
5671 expected.data[0] = k%(types)sStartId;
5672 expected.data[1] = k%(types)sStartId + 1;
5673 gl_->%(name)s(arraysize(ids), &ids[0]);
5674 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5675 EXPECT_EQ(k%(types)sStartId, ids[0]);
5676 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5679 file.Write(code % {
5680 'name': func.name,
5681 'types': func.GetInfo('resource_types'),
5684 def WriteServiceUnitTest(self, func, file, *extras):
5685 """Overrriden from TypeHandler."""
5686 valid_test = """
5687 TEST_P(%(test_name)s, %(name)sValidArgs) {
5688 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5689 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5690 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5691 SpecializedSetup<cmds::%(name)s, 0>(true);
5692 cmds::%(name)s cmd;
5693 cmd.Init(%(args)s);
5694 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5695 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5696 if func.IsUnsafe():
5697 valid_test += """
5698 GLuint service_id;
5699 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5700 EXPECT_EQ(kNewServiceId, service_id)
5703 else:
5704 valid_test += """
5705 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5708 self.WriteValidUnitTest(func, file, valid_test, {
5709 'resource_name': func.GetInfo('resource_type'),
5710 }, *extras)
5711 invalid_test = """
5712 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5713 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5714 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5715 SpecializedSetup<cmds::%(name)s, 0>(false);
5716 cmds::%(name)s cmd;
5717 cmd.Init(%(args)s);
5718 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5721 self.WriteValidUnitTest(func, file, invalid_test, {
5722 'resource_name': func.GetInfo('resource_type').lower(),
5723 }, *extras)
5725 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5726 """Overrriden from TypeHandler."""
5727 valid_test = """
5728 TEST_P(%(test_name)s, %(name)sValidArgs) {
5729 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5730 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5731 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5732 GLuint temp = kNewClientId;
5733 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5734 if func.IsUnsafe():
5735 valid_test += """
5736 decoder_->set_unsafe_es3_apis_enabled(true);"""
5737 valid_test += """
5738 cmd->Init(1, &temp);
5739 EXPECT_EQ(error::kNoError,
5740 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5741 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5742 if func.IsUnsafe():
5743 valid_test += """
5744 GLuint service_id;
5745 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5746 EXPECT_EQ(kNewServiceId, service_id);
5747 decoder_->set_unsafe_es3_apis_enabled(false);
5748 EXPECT_EQ(error::kUnknownCommand,
5749 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5752 else:
5753 valid_test += """
5754 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5757 self.WriteValidUnitTest(func, file, valid_test, {
5758 'resource_name': func.GetInfo('resource_type'),
5759 }, *extras)
5760 invalid_test = """
5761 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5762 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5763 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5764 SpecializedSetup<cmds::%(name)s, 0>(false);
5765 cmd->Init(1, &client_%(resource_name)s_id_);"""
5766 if func.IsUnsafe():
5767 invalid_test += """
5768 decoder_->set_unsafe_es3_apis_enabled(true);
5769 EXPECT_EQ(error::kInvalidArguments,
5770 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5771 decoder_->set_unsafe_es3_apis_enabled(false);
5774 else:
5775 invalid_test += """
5776 EXPECT_EQ(error::kInvalidArguments,
5777 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5780 self.WriteValidUnitTest(func, file, invalid_test, {
5781 'resource_name': func.GetInfo('resource_type').lower(),
5782 }, *extras)
5784 def WriteImmediateCmdComputeSize(self, func, file):
5785 """Overrriden from TypeHandler."""
5786 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5787 file.Write(
5788 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5789 file.Write(" }\n")
5790 file.Write("\n")
5791 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5792 file.Write(" return static_cast<uint32_t>(\n")
5793 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5794 file.Write(" }\n")
5795 file.Write("\n")
5797 def WriteImmediateCmdSetHeader(self, func, file):
5798 """Overrriden from TypeHandler."""
5799 file.Write(" void SetHeader(GLsizei n) {\n")
5800 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5801 file.Write(" }\n")
5802 file.Write("\n")
5804 def WriteImmediateCmdInit(self, func, file):
5805 """Overrriden from TypeHandler."""
5806 last_arg = func.GetLastOriginalArg()
5807 file.Write(" void Init(%s, %s _%s) {\n" %
5808 (func.MakeTypedCmdArgString("_"),
5809 last_arg.type, last_arg.name))
5810 file.Write(" SetHeader(_n);\n")
5811 args = func.GetCmdArgs()
5812 for arg in args:
5813 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5814 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5815 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5816 file.Write(" }\n")
5817 file.Write("\n")
5819 def WriteImmediateCmdSet(self, func, file):
5820 """Overrriden from TypeHandler."""
5821 last_arg = func.GetLastOriginalArg()
5822 copy_args = func.MakeCmdArgString("_", False)
5823 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5824 (func.MakeTypedCmdArgString("_", True),
5825 last_arg.type, last_arg.name))
5826 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5827 (copy_args, last_arg.name))
5828 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5829 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5830 "cmd, size);\n")
5831 file.Write(" }\n")
5832 file.Write("\n")
5834 def WriteImmediateCmdHelper(self, func, file):
5835 """Overrriden from TypeHandler."""
5836 code = """ void %(name)s(%(typed_args)s) {
5837 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5838 gles2::cmds::%(name)s* c =
5839 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5840 if (c) {
5841 c->Init(%(args)s);
5846 file.Write(code % {
5847 "name": func.name,
5848 "typed_args": func.MakeTypedOriginalArgString(""),
5849 "args": func.MakeOriginalArgString(""),
5852 def WriteImmediateFormatTest(self, func, file):
5853 """Overrriden from TypeHandler."""
5854 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5855 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5856 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5857 (func.name, func.name))
5858 file.Write(" void* next_cmd = cmd.Set(\n")
5859 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5860 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5861 func.name)
5862 file.Write(" cmd.header.command);\n")
5863 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5864 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5865 file.Write(" cmd.header.size * 4u);\n")
5866 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5867 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5868 file.Write(" next_cmd, sizeof(cmd) +\n")
5869 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5870 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5871 file.Write("}\n")
5872 file.Write("\n")
5875 class CreateHandler(TypeHandler):
5876 """Handler for glCreate___ type functions."""
5878 def __init__(self):
5879 TypeHandler.__init__(self)
5881 def InitFunction(self, func):
5882 """Overrriden from TypeHandler."""
5883 func.AddCmdArg(Argument("client_id", 'uint32_t'))
5885 def __GetResourceType(self, func):
5886 if func.return_type == "GLsync":
5887 return "Sync"
5888 else:
5889 return func.name[6:] # Create*
5891 def WriteServiceUnitTest(self, func, file, *extras):
5892 """Overrriden from TypeHandler."""
5893 valid_test = """
5894 TEST_P(%(test_name)s, %(name)sValidArgs) {
5895 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5896 .WillOnce(Return(%(const_service_id)s));
5897 SpecializedSetup<cmds::%(name)s, 0>(true);
5898 cmds::%(name)s cmd;
5899 cmd.Init(%(args)s%(comma)skNewClientId);"""
5900 if func.IsUnsafe():
5901 valid_test += """
5902 decoder_->set_unsafe_es3_apis_enabled(true);"""
5903 valid_test += """
5904 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5905 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5906 if func.IsUnsafe():
5907 valid_test += """
5908 %(return_type)s service_id = 0;
5909 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5910 EXPECT_EQ(%(const_service_id)s, service_id);
5911 decoder_->set_unsafe_es3_apis_enabled(false);
5912 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5915 else:
5916 valid_test += """
5917 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5920 comma = ""
5921 cmd_arg_count = 0
5922 for arg in func.GetOriginalArgs():
5923 if not arg.IsConstant():
5924 cmd_arg_count += 1
5925 if cmd_arg_count:
5926 comma = ", "
5927 if func.return_type == 'GLsync':
5928 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5929 "<GLsync>(kNewServiceId);\n ")
5930 const_service_id = "kNewServiceIdGLuint"
5931 else:
5932 id_type_cast = ""
5933 const_service_id = "kNewServiceId"
5934 self.WriteValidUnitTest(func, file, valid_test, {
5935 'comma': comma,
5936 'resource_type': self.__GetResourceType(func),
5937 'return_type': func.return_type,
5938 'id_type_cast': id_type_cast,
5939 'const_service_id': const_service_id,
5940 }, *extras)
5941 invalid_test = """
5942 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5943 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5944 SpecializedSetup<cmds::%(name)s, 0>(false);
5945 cmds::%(name)s cmd;
5946 cmd.Init(%(args)s%(comma)skNewClientId);
5947 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5950 self.WriteInvalidUnitTest(func, file, invalid_test, {
5951 'comma': comma,
5952 }, *extras)
5954 def WriteHandlerImplementation (self, func, file):
5955 """Overrriden from TypeHandler."""
5956 if func.IsUnsafe():
5957 code = """ uint32_t client_id = c.client_id;
5958 %(return_type)s service_id = 0;
5959 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5960 return error::kInvalidArguments;
5962 service_id = %(gl_func_name)s(%(gl_args)s);
5963 if (service_id) {
5964 group_->Add%(resource_name)sId(client_id, service_id);
5967 else:
5968 code = """ uint32_t client_id = c.client_id;
5969 if (Get%(resource_name)s(client_id)) {
5970 return error::kInvalidArguments;
5972 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5973 if (service_id) {
5974 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5977 file.Write(code % {
5978 'resource_name': self.__GetResourceType(func),
5979 'return_type': func.return_type,
5980 'gl_func_name': func.GetGLFunctionName(),
5981 'gl_args': func.MakeOriginalArgString(""),
5982 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
5984 def WriteGLES2Implementation(self, func, file):
5985 """Overrriden from TypeHandler."""
5986 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5987 (func.return_type, func.original_name,
5988 func.MakeTypedOriginalArgString("")))
5989 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5990 func.WriteDestinationInitalizationValidation(file)
5991 self.WriteClientGLCallLog(func, file)
5992 for arg in func.GetOriginalArgs():
5993 arg.WriteClientSideValidationCode(file, func)
5994 file.Write(" GLuint client_id;\n")
5995 if func.return_type == "GLsync":
5996 file.Write(
5997 " GetIdHandler(id_namespaces::kSyncs)->\n")
5998 else:
5999 file.Write(
6000 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6001 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
6002 file.Write(" helper_->%s(%s);\n" %
6003 (func.name, func.MakeCmdArgString("")))
6004 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6005 file.Write(" CheckGLError();\n")
6006 if func.return_type == "GLsync":
6007 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
6008 else:
6009 file.Write(" return client_id;\n")
6010 file.Write("}\n")
6011 file.Write("\n")
6014 class DeleteHandler(TypeHandler):
6015 """Handler for glDelete___ single resource type functions."""
6017 def __init__(self):
6018 TypeHandler.__init__(self)
6020 def WriteServiceImplementation(self, func, file):
6021 """Overrriden from TypeHandler."""
6022 if func.IsUnsafe():
6023 TypeHandler.WriteServiceImplementation(self, func, file)
6024 # HandleDeleteShader and HandleDeleteProgram are manually written.
6025 pass
6027 def WriteGLES2Implementation(self, func, file):
6028 """Overrriden from TypeHandler."""
6029 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6030 (func.return_type, func.original_name,
6031 func.MakeTypedOriginalArgString("")))
6032 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6033 func.WriteDestinationInitalizationValidation(file)
6034 self.WriteClientGLCallLog(func, file)
6035 for arg in func.GetOriginalArgs():
6036 arg.WriteClientSideValidationCode(file, func)
6037 file.Write(
6038 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
6039 file.Write(" %sHelper(%s);\n" %
6040 (func.original_name, func.GetOriginalArgs()[-1].name))
6041 file.Write(" CheckGLError();\n")
6042 file.Write("}\n")
6043 file.Write("\n")
6045 def WriteHandlerImplementation (self, func, file):
6046 """Overrriden from TypeHandler."""
6047 assert len(func.GetOriginalArgs()) == 1
6048 arg = func.GetOriginalArgs()[0]
6049 if func.IsUnsafe():
6050 file.Write(""" %(arg_type)s service_id = 0;
6051 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6052 glDelete%(resource_type)s(service_id);
6053 group_->Remove%(resource_type)sId(%(arg_name)s);
6054 } else {
6055 LOCAL_SET_GL_ERROR(
6056 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6058 """ % { 'resource_type': func.GetInfo('resource_type'),
6059 'arg_name': arg.name,
6060 'arg_type': arg.type,
6061 'func_name': func.original_name })
6062 else:
6063 file.Write(" %sHelper(%s);\n" % (func.original_name, arg.name))
6065 class DELnHandler(TypeHandler):
6066 """Handler for glDelete___ type functions."""
6068 def __init__(self):
6069 TypeHandler.__init__(self)
6071 def WriteGetDataSizeCode(self, func, file):
6072 """Overrriden from TypeHandler."""
6073 code = """ uint32_t data_size;
6074 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6075 return error::kOutOfBounds;
6078 file.Write(code)
6080 def WriteGLES2ImplementationUnitTest(self, func, file):
6081 """Overrriden from TypeHandler."""
6082 code = """
6083 TEST_F(GLES2ImplementationTest, %(name)s) {
6084 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6085 struct Cmds {
6086 cmds::%(name)sImmediate del;
6087 GLuint data[2];
6089 Cmds expected;
6090 expected.del.Init(arraysize(ids), &ids[0]);
6091 expected.data[0] = k%(types)sStartId;
6092 expected.data[1] = k%(types)sStartId + 1;
6093 gl_->%(name)s(arraysize(ids), &ids[0]);
6094 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6097 file.Write(code % {
6098 'name': func.name,
6099 'types': func.GetInfo('resource_types'),
6102 def WriteServiceUnitTest(self, func, file, *extras):
6103 """Overrriden from TypeHandler."""
6104 valid_test = """
6105 TEST_P(%(test_name)s, %(name)sValidArgs) {
6106 EXPECT_CALL(
6107 *gl_,
6108 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6109 .Times(1);
6110 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6111 SpecializedSetup<cmds::%(name)s, 0>(true);
6112 cmds::%(name)s cmd;
6113 cmd.Init(%(args)s);
6114 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6115 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6116 EXPECT_TRUE(
6117 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6120 self.WriteValidUnitTest(func, file, valid_test, {
6121 'resource_name': func.GetInfo('resource_type').lower(),
6122 'upper_resource_name': func.GetInfo('resource_type'),
6123 }, *extras)
6124 invalid_test = """
6125 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6126 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6127 SpecializedSetup<cmds::%(name)s, 0>(false);
6128 cmds::%(name)s cmd;
6129 cmd.Init(%(args)s);
6130 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6133 self.WriteValidUnitTest(func, file, invalid_test, *extras)
6135 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6136 """Overrriden from TypeHandler."""
6137 valid_test = """
6138 TEST_P(%(test_name)s, %(name)sValidArgs) {
6139 EXPECT_CALL(
6140 *gl_,
6141 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6142 .Times(1);
6143 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6144 SpecializedSetup<cmds::%(name)s, 0>(true);
6145 cmd.Init(1, &client_%(resource_name)s_id_);"""
6146 if func.IsUnsafe():
6147 valid_test += """
6148 decoder_->set_unsafe_es3_apis_enabled(true);"""
6149 valid_test += """
6150 EXPECT_EQ(error::kNoError,
6151 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6152 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6153 if func.IsUnsafe():
6154 valid_test += """
6155 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6156 client_%(resource_name)s_id_, NULL));
6157 decoder_->set_unsafe_es3_apis_enabled(false);
6158 EXPECT_EQ(error::kUnknownCommand,
6159 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6162 else:
6163 valid_test += """
6164 EXPECT_TRUE(
6165 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6168 self.WriteValidUnitTest(func, file, valid_test, {
6169 'resource_name': func.GetInfo('resource_type').lower(),
6170 'upper_resource_name': func.GetInfo('resource_type'),
6171 }, *extras)
6172 invalid_test = """
6173 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6174 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6175 SpecializedSetup<cmds::%(name)s, 0>(false);
6176 GLuint temp = kInvalidClientId;
6177 cmd.Init(1, &temp);"""
6178 if func.IsUnsafe():
6179 invalid_test += """
6180 decoder_->set_unsafe_es3_apis_enabled(true);
6181 EXPECT_EQ(error::kNoError,
6182 ExecuteImmediateCmd(cmd, sizeof(temp)));
6183 decoder_->set_unsafe_es3_apis_enabled(false);
6184 EXPECT_EQ(error::kUnknownCommand,
6185 ExecuteImmediateCmd(cmd, sizeof(temp)));
6188 else:
6189 invalid_test += """
6190 EXPECT_EQ(error::kNoError,
6191 ExecuteImmediateCmd(cmd, sizeof(temp)));
6194 self.WriteValidUnitTest(func, file, invalid_test, *extras)
6196 def WriteHandlerImplementation (self, func, file):
6197 """Overrriden from TypeHandler."""
6198 file.Write(" %sHelper(n, %s);\n" %
6199 (func.name, func.GetLastOriginalArg().name))
6201 def WriteImmediateHandlerImplementation (self, func, file):
6202 """Overrriden from TypeHandler."""
6203 if func.IsUnsafe():
6204 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6205 GLuint service_id = 0;
6206 if (group_->Get%(resource_type)sServiceId(
6207 %(last_arg_name)s[ii], &service_id)) {
6208 glDelete%(resource_type)ss(1, &service_id);
6209 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6212 """ % { 'resource_type': func.GetInfo('resource_type'),
6213 'last_arg_name': func.GetLastOriginalArg().name })
6214 else:
6215 file.Write(" %sHelper(n, %s);\n" %
6216 (func.original_name, func.GetLastOriginalArg().name))
6218 def WriteGLES2Implementation(self, func, file):
6219 """Overrriden from TypeHandler."""
6220 impl_decl = func.GetInfo('impl_decl')
6221 if impl_decl == None or impl_decl == True:
6222 args = {
6223 'return_type': func.return_type,
6224 'name': func.original_name,
6225 'typed_args': func.MakeTypedOriginalArgString(""),
6226 'args': func.MakeOriginalArgString(""),
6227 'resource_type': func.GetInfo('resource_type').lower(),
6228 'count_name': func.GetOriginalArgs()[0].name,
6230 file.Write(
6231 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6232 args)
6233 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6234 func.WriteDestinationInitalizationValidation(file)
6235 self.WriteClientGLCallLog(func, file)
6236 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6237 for (GLsizei i = 0; i < n; ++i) {
6238 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6241 """ % func.GetOriginalArgs()[1].name)
6242 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6243 for (GLsizei i = 0; i < n; ++i) {
6244 DCHECK(%s[i] != 0);
6247 """ % func.GetOriginalArgs()[1].name)
6248 for arg in func.GetOriginalArgs():
6249 arg.WriteClientSideValidationCode(file, func)
6250 code = """ %(name)sHelper(%(args)s);
6251 CheckGLError();
6255 file.Write(code % args)
6257 def WriteImmediateCmdComputeSize(self, func, file):
6258 """Overrriden from TypeHandler."""
6259 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6260 file.Write(
6261 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6262 file.Write(" }\n")
6263 file.Write("\n")
6264 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
6265 file.Write(" return static_cast<uint32_t>(\n")
6266 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6267 file.Write(" }\n")
6268 file.Write("\n")
6270 def WriteImmediateCmdSetHeader(self, func, file):
6271 """Overrriden from TypeHandler."""
6272 file.Write(" void SetHeader(GLsizei n) {\n")
6273 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6274 file.Write(" }\n")
6275 file.Write("\n")
6277 def WriteImmediateCmdInit(self, func, file):
6278 """Overrriden from TypeHandler."""
6279 last_arg = func.GetLastOriginalArg()
6280 file.Write(" void Init(%s, %s _%s) {\n" %
6281 (func.MakeTypedCmdArgString("_"),
6282 last_arg.type, last_arg.name))
6283 file.Write(" SetHeader(_n);\n")
6284 args = func.GetCmdArgs()
6285 for arg in args:
6286 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6287 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6288 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
6289 file.Write(" }\n")
6290 file.Write("\n")
6292 def WriteImmediateCmdSet(self, func, file):
6293 """Overrriden from TypeHandler."""
6294 last_arg = func.GetLastOriginalArg()
6295 copy_args = func.MakeCmdArgString("_", False)
6296 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6297 (func.MakeTypedCmdArgString("_", True),
6298 last_arg.type, last_arg.name))
6299 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6300 (copy_args, last_arg.name))
6301 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6302 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6303 "cmd, size);\n")
6304 file.Write(" }\n")
6305 file.Write("\n")
6307 def WriteImmediateCmdHelper(self, func, file):
6308 """Overrriden from TypeHandler."""
6309 code = """ void %(name)s(%(typed_args)s) {
6310 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6311 gles2::cmds::%(name)s* c =
6312 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6313 if (c) {
6314 c->Init(%(args)s);
6319 file.Write(code % {
6320 "name": func.name,
6321 "typed_args": func.MakeTypedOriginalArgString(""),
6322 "args": func.MakeOriginalArgString(""),
6325 def WriteImmediateFormatTest(self, func, file):
6326 """Overrriden from TypeHandler."""
6327 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6328 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6329 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6330 (func.name, func.name))
6331 file.Write(" void* next_cmd = cmd.Set(\n")
6332 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6333 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6334 func.name)
6335 file.Write(" cmd.header.command);\n")
6336 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6337 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6338 file.Write(" cmd.header.size * 4u);\n")
6339 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6340 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6341 file.Write(" next_cmd, sizeof(cmd) +\n")
6342 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6343 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6344 file.Write("}\n")
6345 file.Write("\n")
6348 class GETnHandler(TypeHandler):
6349 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6351 def __init__(self):
6352 TypeHandler.__init__(self)
6354 def NeedsDataTransferFunction(self, func):
6355 """Overriden from TypeHandler."""
6356 return False
6358 def WriteServiceImplementation(self, func, file):
6359 """Overrriden from TypeHandler."""
6360 self.WriteServiceHandlerFunctionHeader(func, file)
6361 last_arg = func.GetLastOriginalArg()
6362 # All except shm_id and shm_offset.
6363 all_but_last_args = func.GetCmdArgs()[:-2]
6364 for arg in all_but_last_args:
6365 arg.WriteGetCode(file)
6367 code = """ typedef cmds::%(func_name)s::Result Result;
6368 GLsizei num_values = 0;
6369 GetNumValuesReturnedForGLGet(pname, &num_values);
6370 Result* result = GetSharedMemoryAs<Result*>(
6371 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6372 Result::ComputeSize(num_values));
6373 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6375 file.Write(code % {
6376 'last_arg_type': last_arg.type,
6377 'last_arg_name': last_arg.name,
6378 'func_name': func.name,
6380 func.WriteHandlerValidation(file)
6381 code = """ // Check that the client initialized the result.
6382 if (result->size != 0) {
6383 return error::kInvalidArguments;
6386 shadowed = func.GetInfo('shadowed')
6387 if not shadowed:
6388 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
6389 file.Write(code)
6390 func.WriteHandlerImplementation(file)
6391 if shadowed:
6392 code = """ result->SetNumResults(num_values);
6393 return error::kNoError;
6396 else:
6397 code = """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6398 if (error == GL_NO_ERROR) {
6399 result->SetNumResults(num_values);
6401 return error::kNoError;
6405 file.Write(code % {'func_name': func.name})
6407 def WriteGLES2Implementation(self, func, file):
6408 """Overrriden from TypeHandler."""
6409 impl_decl = func.GetInfo('impl_decl')
6410 if impl_decl == None or impl_decl == True:
6411 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6412 (func.return_type, func.original_name,
6413 func.MakeTypedOriginalArgString("")))
6414 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6415 func.WriteDestinationInitalizationValidation(file)
6416 self.WriteClientGLCallLog(func, file)
6417 for arg in func.GetOriginalArgs():
6418 arg.WriteClientSideValidationCode(file, func)
6419 all_but_last_args = func.GetOriginalArgs()[:-1]
6420 args = []
6421 has_length_arg = False
6422 for arg in all_but_last_args:
6423 if arg.type == 'GLsync':
6424 args.append('ToGLuint(%s)' % arg.name)
6425 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6426 continue
6427 elif arg.name == 'length':
6428 has_length_arg = True
6429 continue
6430 else:
6431 args.append(arg.name)
6432 arg_string = ", ".join(args)
6433 all_arg_string = (
6434 ", ".join([
6435 "%s" % arg.name
6436 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6437 self.WriteTraceEvent(func, file)
6438 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6439 return;
6441 typedef cmds::%(func_name)s::Result Result;
6442 Result* result = GetResultAs<Result*>();
6443 if (!result) {
6444 return;
6446 result->SetNumResults(0);
6447 helper_->%(func_name)s(%(arg_string)s,
6448 GetResultShmId(), GetResultShmOffset());
6449 WaitForCmd();
6450 result->CopyResult(%(last_arg_name)s);
6451 GPU_CLIENT_LOG_CODE_BLOCK({
6452 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6453 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6455 });"""
6456 if has_length_arg:
6457 code += """
6458 if (length) {
6459 *length = result->GetNumResults();
6460 }"""
6461 code += """
6462 CheckGLError();
6465 file.Write(code % {
6466 'func_name': func.name,
6467 'arg_string': arg_string,
6468 'all_arg_string': all_arg_string,
6469 'last_arg_name': func.GetLastOriginalArg().name,
6472 def WriteGLES2ImplementationUnitTest(self, func, file):
6473 """Writes the GLES2 Implemention unit test."""
6474 code = """
6475 TEST_F(GLES2ImplementationTest, %(name)s) {
6476 struct Cmds {
6477 cmds::%(name)s cmd;
6479 typedef cmds::%(name)s::Result::Type ResultType;
6480 ResultType result = 0;
6481 Cmds expected;
6482 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6483 sizeof(uint32_t) + sizeof(ResultType));
6484 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6485 EXPECT_CALL(*command_buffer(), OnFlush())
6486 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6487 .RetiresOnSaturation();
6488 gl_->%(name)s(%(args)s, &result);
6489 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6490 EXPECT_EQ(static_cast<ResultType>(1), result);
6493 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6494 if not first_cmd_arg:
6495 return
6497 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6498 func)
6500 cmd_arg_strings = [first_cmd_arg]
6501 for arg in func.GetCmdArgs()[1:-2]:
6502 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6503 gl_arg_strings = [first_gl_arg]
6504 for arg in func.GetOriginalArgs()[1:-1]:
6505 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6507 file.Write(code % {
6508 'name': func.name,
6509 'args': ", ".join(gl_arg_strings),
6510 'cmd_args': ", ".join(cmd_arg_strings),
6513 def WriteServiceUnitTest(self, func, file, *extras):
6514 """Overrriden from TypeHandler."""
6515 valid_test = """
6516 TEST_P(%(test_name)s, %(name)sValidArgs) {
6517 EXPECT_CALL(*gl_, GetError())
6518 .WillOnce(Return(GL_NO_ERROR))
6519 .WillOnce(Return(GL_NO_ERROR))
6520 .RetiresOnSaturation();
6521 SpecializedSetup<cmds::%(name)s, 0>(true);
6522 typedef cmds::%(name)s::Result Result;
6523 Result* result = static_cast<Result*>(shared_memory_address_);
6524 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6525 result->size = 0;
6526 cmds::%(name)s cmd;
6527 cmd.Init(%(cmd_args)s);"""
6528 if func.IsUnsafe():
6529 valid_test += """
6530 decoder_->set_unsafe_es3_apis_enabled(true);"""
6531 valid_test += """
6532 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6533 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6534 %(valid_pname)s),
6535 result->GetNumResults());
6536 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6537 if func.IsUnsafe():
6538 valid_test += """
6539 decoder_->set_unsafe_es3_apis_enabled(false);
6540 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6541 valid_test += """
6544 gl_arg_strings = []
6545 cmd_arg_strings = []
6546 valid_pname = ''
6547 for arg in func.GetOriginalArgs()[:-1]:
6548 if arg.name == 'length':
6549 gl_arg_value = 'nullptr'
6550 elif arg.name.endswith('size'):
6551 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6552 valid_pname)
6553 elif arg.type == 'GLsync':
6554 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6555 else:
6556 gl_arg_value = arg.GetValidGLArg(func)
6557 gl_arg_strings.append(gl_arg_value)
6558 if arg.name == 'pname':
6559 valid_pname = gl_arg_value
6560 if arg.name.endswith('size') or arg.name == 'length':
6561 continue
6562 if arg.type == 'GLsync':
6563 arg_value = 'client_sync_id_'
6564 else:
6565 arg_value = arg.GetValidArg(func)
6566 cmd_arg_strings.append(arg_value)
6567 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6568 gl_arg_strings.append("_")
6569 else:
6570 gl_arg_strings.append("result->GetData()")
6571 cmd_arg_strings.append("shared_memory_id_")
6572 cmd_arg_strings.append("shared_memory_offset_")
6574 self.WriteValidUnitTest(func, file, valid_test, {
6575 'local_gl_args': ", ".join(gl_arg_strings),
6576 'cmd_args': ", ".join(cmd_arg_strings),
6577 'valid_pname': valid_pname,
6578 }, *extras)
6580 if not func.IsUnsafe():
6581 invalid_test = """
6582 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6583 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6584 SpecializedSetup<cmds::%(name)s, 0>(false);
6585 cmds::%(name)s::Result* result =
6586 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6587 result->size = 0;
6588 cmds::%(name)s cmd;
6589 cmd.Init(%(args)s);
6590 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6591 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6594 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
6596 class ArrayArgTypeHandler(TypeHandler):
6597 """Base class for type handlers that handle args that are arrays"""
6599 def __init__(self):
6600 TypeHandler.__init__(self)
6602 def GetArrayType(self, func):
6603 """Returns the type of the element in the element array being PUT to."""
6604 for arg in func.GetOriginalArgs():
6605 if arg.IsPointer():
6606 element_type = arg.GetPointedType()
6607 return element_type
6609 # Special case: array type handler is used for a function that is forwarded
6610 # to the actual array type implementation
6611 element_type = func.GetOriginalArgs()[-1].type
6612 assert all(arg.type == element_type \
6613 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6614 return element_type
6616 def GetArrayCount(self, func):
6617 """Returns the count of the elements in the array being PUT to."""
6618 return func.GetInfo('count')
6620 class PUTHandler(ArrayArgTypeHandler):
6621 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6623 def __init__(self):
6624 ArrayArgTypeHandler.__init__(self)
6626 def WriteServiceUnitTest(self, func, file, *extras):
6627 """Writes the service unit test for a command."""
6628 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6629 if func.GetInfo("first_element_only"):
6630 gl_arg_strings = [
6631 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6633 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6634 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6635 ", ".join(gl_arg_strings))
6636 valid_test = """
6637 TEST_P(%(test_name)s, %(name)sValidArgs) {
6638 SpecializedSetup<cmds::%(name)s, 0>(true);
6639 cmds::%(name)s cmd;
6640 cmd.Init(%(args)s);
6641 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6642 %(expected_call)s
6643 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6644 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6647 extra = {
6648 'data_type': self.GetArrayType(func),
6649 'data_value': func.GetInfo('data_value') or '0',
6650 'expected_call': expected_call,
6652 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6654 invalid_test = """
6655 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6656 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6657 SpecializedSetup<cmds::%(name)s, 0>(false);
6658 cmds::%(name)s cmd;
6659 cmd.Init(%(args)s);
6660 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6661 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6664 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6666 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6667 """Writes the service unit test for a command."""
6668 valid_test = """
6669 TEST_P(%(test_name)s, %(name)sValidArgs) {
6670 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6671 SpecializedSetup<cmds::%(name)s, 0>(true);
6672 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6673 cmd.Init(%(gl_args)s, &temp[0]);
6674 EXPECT_CALL(
6675 *gl_,
6676 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6677 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6678 if func.IsUnsafe():
6679 valid_test += """
6680 decoder_->set_unsafe_es3_apis_enabled(true);"""
6681 valid_test += """
6682 EXPECT_EQ(error::kNoError,
6683 ExecuteImmediateCmd(cmd, sizeof(temp)));
6684 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6685 if func.IsUnsafe():
6686 valid_test += """
6687 decoder_->set_unsafe_es3_apis_enabled(false);
6688 EXPECT_EQ(error::kUnknownCommand,
6689 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6690 valid_test += """
6693 gl_arg_strings = [
6694 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6696 gl_any_strings = ["_"] * len(gl_arg_strings)
6698 extra = {
6699 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6700 'data_type': self.GetArrayType(func),
6701 'data_count': self.GetArrayCount(func),
6702 'data_value': func.GetInfo('data_value') or '0',
6703 'gl_args': ", ".join(gl_arg_strings),
6704 'gl_any_args': ", ".join(gl_any_strings),
6706 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6708 invalid_test = """
6709 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6710 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6711 if func.IsUnsafe():
6712 invalid_test += """
6713 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6715 else:
6716 invalid_test += """
6717 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6719 invalid_test += """
6720 SpecializedSetup<cmds::%(name)s, 0>(false);
6721 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6722 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6723 if func.IsUnsafe():
6724 invalid_test += """
6725 decoder_->set_unsafe_es3_apis_enabled(true);
6726 EXPECT_EQ(error::%(parse_result)s,
6727 ExecuteImmediateCmd(cmd, sizeof(temp)));
6728 decoder_->set_unsafe_es3_apis_enabled(false);
6731 else:
6732 invalid_test += """
6733 EXPECT_EQ(error::%(parse_result)s,
6734 ExecuteImmediateCmd(cmd, sizeof(temp)));
6735 %(gl_error_test)s
6738 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6740 def WriteGetDataSizeCode(self, func, file):
6741 """Overrriden from TypeHandler."""
6742 code = """ uint32_t data_size;
6743 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6744 return error::kOutOfBounds;
6747 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6748 if func.IsImmediate():
6749 file.Write(" if (data_size > immediate_data_size) {\n")
6750 file.Write(" return error::kOutOfBounds;\n")
6751 file.Write(" }\n")
6753 def __NeedsToCalcDataCount(self, func):
6754 use_count_func = func.GetInfo('use_count_func')
6755 return use_count_func != None and use_count_func != False
6757 def WriteGLES2Implementation(self, func, file):
6758 """Overrriden from TypeHandler."""
6759 impl_func = func.GetInfo('impl_func')
6760 if (impl_func != None and impl_func != True):
6761 return;
6762 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6763 (func.return_type, func.original_name,
6764 func.MakeTypedOriginalArgString("")))
6765 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6766 func.WriteDestinationInitalizationValidation(file)
6767 self.WriteClientGLCallLog(func, file)
6769 if self.__NeedsToCalcDataCount(func):
6770 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6771 (func.name, func.GetOriginalArgs()[0].name))
6772 file.Write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6773 else:
6774 file.Write(" size_t count = %d;" % self.GetArrayCount(func))
6775 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6776 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6777 func.GetLastOriginalArg().name)
6778 for arg in func.GetOriginalArgs():
6779 arg.WriteClientSideValidationCode(file, func)
6780 file.Write(" helper_->%sImmediate(%s);\n" %
6781 (func.name, func.MakeOriginalArgString("")))
6782 file.Write(" CheckGLError();\n")
6783 file.Write("}\n")
6784 file.Write("\n")
6786 def WriteGLES2ImplementationUnitTest(self, func, file):
6787 """Writes the GLES2 Implemention unit test."""
6788 client_test = func.GetInfo('client_test')
6789 if (client_test != None and client_test != True):
6790 return;
6791 code = """
6792 TEST_F(GLES2ImplementationTest, %(name)s) {
6793 %(type)s data[%(count)d] = {0};
6794 struct Cmds {
6795 cmds::%(name)sImmediate cmd;
6796 %(type)s data[%(count)d];
6799 for (int jj = 0; jj < %(count)d; ++jj) {
6800 data[jj] = static_cast<%(type)s>(jj);
6802 Cmds expected;
6803 expected.cmd.Init(%(cmd_args)s, &data[0]);
6804 gl_->%(name)s(%(args)s, &data[0]);
6805 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6808 cmd_arg_strings = [
6809 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6811 gl_arg_strings = [
6812 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6815 file.Write(code % {
6816 'name': func.name,
6817 'type': self.GetArrayType(func),
6818 'count': self.GetArrayCount(func),
6819 'args': ", ".join(gl_arg_strings),
6820 'cmd_args': ", ".join(cmd_arg_strings),
6823 def WriteImmediateCmdComputeSize(self, func, file):
6824 """Overrriden from TypeHandler."""
6825 file.Write(" static uint32_t ComputeDataSize() {\n")
6826 file.Write(" return static_cast<uint32_t>(\n")
6827 file.Write(" sizeof(%s) * %d);\n" %
6828 (self.GetArrayType(func), self.GetArrayCount(func)))
6829 file.Write(" }\n")
6830 file.Write("\n")
6831 if self.__NeedsToCalcDataCount(func):
6832 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6833 (func.GetOriginalArgs()[0].type,
6834 func.GetOriginalArgs()[0].name))
6835 file.Write(" return static_cast<uint32_t>(\n")
6836 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6837 (self.GetArrayType(func), func.original_name,
6838 func.GetOriginalArgs()[0].name))
6839 file.Write(" }\n")
6840 file.Write("\n")
6841 file.Write(" static uint32_t ComputeSize() {\n")
6842 file.Write(" return static_cast<uint32_t>(\n")
6843 file.Write(
6844 " sizeof(ValueType) + ComputeDataSize());\n")
6845 file.Write(" }\n")
6846 file.Write("\n")
6848 def WriteImmediateCmdSetHeader(self, func, file):
6849 """Overrriden from TypeHandler."""
6850 file.Write(" void SetHeader() {\n")
6851 file.Write(
6852 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6853 file.Write(" }\n")
6854 file.Write("\n")
6856 def WriteImmediateCmdInit(self, func, file):
6857 """Overrriden from TypeHandler."""
6858 last_arg = func.GetLastOriginalArg()
6859 file.Write(" void Init(%s, %s _%s) {\n" %
6860 (func.MakeTypedCmdArgString("_"),
6861 last_arg.type, last_arg.name))
6862 file.Write(" SetHeader();\n")
6863 args = func.GetCmdArgs()
6864 for arg in args:
6865 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6866 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6867 if self.__NeedsToCalcDataCount(func):
6868 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6869 (last_arg.name, func.GetOriginalArgs()[0].name))
6870 file.Write("""
6871 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6872 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6873 ComputeEffectiveDataSize(%(arg)s);
6874 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6875 """ % { 'arg': func.GetOriginalArgs()[0].name, })
6876 else:
6877 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
6878 file.Write(" }\n")
6879 file.Write("\n")
6881 def WriteImmediateCmdSet(self, func, file):
6882 """Overrriden from TypeHandler."""
6883 last_arg = func.GetLastOriginalArg()
6884 copy_args = func.MakeCmdArgString("_", False)
6885 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6886 (func.MakeTypedCmdArgString("_", True),
6887 last_arg.type, last_arg.name))
6888 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6889 (copy_args, last_arg.name))
6890 file.Write(" const uint32_t size = ComputeSize();\n")
6891 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6892 "cmd, size);\n")
6893 file.Write(" }\n")
6894 file.Write("\n")
6896 def WriteImmediateCmdHelper(self, func, file):
6897 """Overrriden from TypeHandler."""
6898 code = """ void %(name)s(%(typed_args)s) {
6899 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6900 gles2::cmds::%(name)s* c =
6901 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6902 if (c) {
6903 c->Init(%(args)s);
6908 file.Write(code % {
6909 "name": func.name,
6910 "typed_args": func.MakeTypedOriginalArgString(""),
6911 "args": func.MakeOriginalArgString(""),
6914 def WriteImmediateFormatTest(self, func, file):
6915 """Overrriden from TypeHandler."""
6916 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6917 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6918 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6919 for v in range(0, self.GetArrayCount(func)):
6920 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6921 (self.GetArrayType(func), v))
6922 file.Write(" };\n")
6923 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6924 (func.name, func.name))
6925 file.Write(" void* next_cmd = cmd.Set(\n")
6926 file.Write(" &cmd")
6927 args = func.GetCmdArgs()
6928 for value, arg in enumerate(args):
6929 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
6930 file.Write(",\n data);\n")
6931 args = func.GetCmdArgs()
6932 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6933 % func.name)
6934 file.Write(" cmd.header.command);\n")
6935 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6936 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6937 file.Write(" cmd.header.size * 4u);\n")
6938 for value, arg in enumerate(args):
6939 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6940 (arg.type, value + 11, arg.name))
6941 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6942 file.Write(" next_cmd, sizeof(cmd) +\n")
6943 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6944 file.Write(" // TODO(gman): Check that data was inserted;\n")
6945 file.Write("}\n")
6946 file.Write("\n")
6949 class PUTnHandler(ArrayArgTypeHandler):
6950 """Handler for PUTn 'glUniform__v' type functions."""
6952 def __init__(self):
6953 ArrayArgTypeHandler.__init__(self)
6955 def WriteServiceUnitTest(self, func, file, *extras):
6956 """Overridden from TypeHandler."""
6957 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
6959 valid_test = """
6960 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6961 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6962 SpecializedSetup<cmds::%(name)s, 0>(true);
6963 cmds::%(name)s cmd;
6964 cmd.Init(%(args)s);
6965 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6966 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6969 gl_arg_strings = []
6970 arg_strings = []
6971 for count, arg in enumerate(func.GetOriginalArgs()):
6972 # hardcoded to match unit tests.
6973 if count == 0:
6974 # the location of the second element of the 2nd uniform.
6975 # defined in GLES2DecoderBase::SetupShaderForUniform
6976 gl_arg_strings.append("3")
6977 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
6978 elif count == 1:
6979 # the number of elements that gl will be called with.
6980 gl_arg_strings.append("3")
6981 # the number of elements requested in the command.
6982 arg_strings.append("5")
6983 else:
6984 gl_arg_strings.append(arg.GetValidGLArg(func))
6985 if not arg.IsConstant():
6986 arg_strings.append(arg.GetValidArg(func))
6987 extra = {
6988 'gl_args': ", ".join(gl_arg_strings),
6989 'args': ", ".join(arg_strings),
6991 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6993 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6994 """Overridden from TypeHandler."""
6995 valid_test = """
6996 TEST_P(%(test_name)s, %(name)sValidArgs) {
6997 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6998 EXPECT_CALL(
6999 *gl_,
7000 %(gl_func_name)s(%(gl_args)s,
7001 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7002 SpecializedSetup<cmds::%(name)s, 0>(true);
7003 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7004 cmd.Init(%(args)s, &temp[0]);"""
7005 if func.IsUnsafe():
7006 valid_test += """
7007 decoder_->set_unsafe_es3_apis_enabled(true);"""
7008 valid_test += """
7009 EXPECT_EQ(error::kNoError,
7010 ExecuteImmediateCmd(cmd, sizeof(temp)));
7011 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7012 if func.IsUnsafe():
7013 valid_test += """
7014 decoder_->set_unsafe_es3_apis_enabled(false);
7015 EXPECT_EQ(error::kUnknownCommand,
7016 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7017 valid_test += """
7020 gl_arg_strings = []
7021 gl_any_strings = []
7022 arg_strings = []
7023 for arg in func.GetOriginalArgs()[0:-1]:
7024 gl_arg_strings.append(arg.GetValidGLArg(func))
7025 gl_any_strings.append("_")
7026 if not arg.IsConstant():
7027 arg_strings.append(arg.GetValidArg(func))
7028 extra = {
7029 'data_type': self.GetArrayType(func),
7030 'data_count': self.GetArrayCount(func),
7031 'args': ", ".join(arg_strings),
7032 'gl_args': ", ".join(gl_arg_strings),
7033 'gl_any_args': ", ".join(gl_any_strings),
7035 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
7037 invalid_test = """
7038 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7039 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7040 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7041 SpecializedSetup<cmds::%(name)s, 0>(false);
7042 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7043 cmd.Init(%(all_but_last_args)s, &temp[0]);
7044 EXPECT_EQ(error::%(parse_result)s,
7045 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7048 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
7050 def WriteGetDataSizeCode(self, func, file):
7051 """Overrriden from TypeHandler."""
7052 code = """ uint32_t data_size;
7053 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7054 return error::kOutOfBounds;
7057 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
7058 if func.IsImmediate():
7059 file.Write(" if (data_size > immediate_data_size) {\n")
7060 file.Write(" return error::kOutOfBounds;\n")
7061 file.Write(" }\n")
7063 def WriteGLES2Implementation(self, func, file):
7064 """Overrriden from TypeHandler."""
7065 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7066 (func.return_type, func.original_name,
7067 func.MakeTypedOriginalArgString("")))
7068 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7069 func.WriteDestinationInitalizationValidation(file)
7070 self.WriteClientGLCallLog(func, file)
7071 last_pointer_name = func.GetLastOriginalPointerArg().name
7072 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7073 for (GLsizei i = 0; i < count; ++i) {
7074 """)
7075 values_str = ' << ", " << '.join(
7076 ["%s[%d + i * %d]" % (
7077 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
7078 0, self.GetArrayCount(func))])
7079 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
7080 file.Write(" }\n });\n")
7081 for arg in func.GetOriginalArgs():
7082 arg.WriteClientSideValidationCode(file, func)
7083 file.Write(" helper_->%sImmediate(%s);\n" %
7084 (func.name, func.MakeInitString("")))
7085 file.Write(" CheckGLError();\n")
7086 file.Write("}\n")
7087 file.Write("\n")
7089 def WriteGLES2ImplementationUnitTest(self, func, file):
7090 """Writes the GLES2 Implemention unit test."""
7091 code = """
7092 TEST_F(GLES2ImplementationTest, %(name)s) {
7093 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7094 struct Cmds {
7095 cmds::%(name)sImmediate cmd;
7096 %(type)s data[%(count_param)d][%(count)d];
7099 Cmds expected;
7100 for (int ii = 0; ii < %(count_param)d; ++ii) {
7101 for (int jj = 0; jj < %(count)d; ++jj) {
7102 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7105 expected.cmd.Init(%(cmd_args)s);
7106 gl_->%(name)s(%(args)s);
7107 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7110 cmd_arg_strings = []
7111 for arg in func.GetCmdArgs():
7112 if arg.name.endswith("_shm_id"):
7113 cmd_arg_strings.append("&data[0][0]")
7114 elif arg.name.endswith("_shm_offset"):
7115 continue
7116 else:
7117 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
7118 gl_arg_strings = []
7119 count_param = 0
7120 for arg in func.GetOriginalArgs():
7121 if arg.IsPointer():
7122 valid_value = "&data[0][0]"
7123 else:
7124 valid_value = arg.GetValidClientSideArg(func)
7125 gl_arg_strings.append(valid_value)
7126 if arg.name == "count":
7127 count_param = int(valid_value)
7128 file.Write(code % {
7129 'name': func.name,
7130 'type': self.GetArrayType(func),
7131 'count': self.GetArrayCount(func),
7132 'args': ", ".join(gl_arg_strings),
7133 'cmd_args': ", ".join(cmd_arg_strings),
7134 'count_param': count_param,
7137 # Test constants for invalid values, as they are not tested by the
7138 # service.
7139 constants = [
7140 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
7142 if not constants:
7143 return
7145 code = """
7146 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7147 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7148 for (int ii = 0; ii < %(count_param)d; ++ii) {
7149 for (int jj = 0; jj < %(count)d; ++jj) {
7150 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7153 gl_->%(name)s(%(args)s);
7154 EXPECT_TRUE(NoCommandsWritten());
7155 EXPECT_EQ(%(gl_error)s, CheckError());
7158 for invalid_arg in constants:
7159 gl_arg_strings = []
7160 invalid = invalid_arg.GetInvalidArg(func)
7161 for arg in func.GetOriginalArgs():
7162 if arg is invalid_arg:
7163 gl_arg_strings.append(invalid[0])
7164 elif arg.IsPointer():
7165 gl_arg_strings.append("&data[0][0]")
7166 else:
7167 valid_value = arg.GetValidClientSideArg(func)
7168 gl_arg_strings.append(valid_value)
7169 if arg.name == "count":
7170 count_param = int(valid_value)
7172 file.Write(code % {
7173 'name': func.name,
7174 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
7175 'type': self.GetArrayType(func),
7176 'count': self.GetArrayCount(func),
7177 'args': ", ".join(gl_arg_strings),
7178 'gl_error': invalid[2],
7179 'count_param': count_param,
7183 def WriteImmediateCmdComputeSize(self, func, file):
7184 """Overrriden from TypeHandler."""
7185 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7186 file.Write(" return static_cast<uint32_t>(\n")
7187 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
7188 (self.GetArrayType(func), self.GetArrayCount(func)))
7189 file.Write(" }\n")
7190 file.Write("\n")
7191 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
7192 file.Write(" return static_cast<uint32_t>(\n")
7193 file.Write(
7194 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7195 file.Write(" }\n")
7196 file.Write("\n")
7198 def WriteImmediateCmdSetHeader(self, func, file):
7199 """Overrriden from TypeHandler."""
7200 file.Write(" void SetHeader(GLsizei count) {\n")
7201 file.Write(
7202 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7203 file.Write(" }\n")
7204 file.Write("\n")
7206 def WriteImmediateCmdInit(self, func, file):
7207 """Overrriden from TypeHandler."""
7208 file.Write(" void Init(%s) {\n" %
7209 func.MakeTypedInitString("_"))
7210 file.Write(" SetHeader(_count);\n")
7211 args = func.GetCmdArgs()
7212 for arg in args:
7213 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
7214 file.Write(" memcpy(ImmediateDataAddress(this),\n")
7215 pointer_arg = func.GetLastOriginalPointerArg()
7216 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
7217 file.Write(" }\n")
7218 file.Write("\n")
7220 def WriteImmediateCmdSet(self, func, file):
7221 """Overrriden from TypeHandler."""
7222 file.Write(" void* Set(void* cmd%s) {\n" %
7223 func.MakeTypedInitString("_", True))
7224 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7225 func.MakeInitString("_"))
7226 file.Write(" const uint32_t size = ComputeSize(_count);\n")
7227 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7228 "cmd, size);\n")
7229 file.Write(" }\n")
7230 file.Write("\n")
7232 def WriteImmediateCmdHelper(self, func, file):
7233 """Overrriden from TypeHandler."""
7234 code = """ void %(name)s(%(typed_args)s) {
7235 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7236 gles2::cmds::%(name)s* c =
7237 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7238 if (c) {
7239 c->Init(%(args)s);
7244 file.Write(code % {
7245 "name": func.name,
7246 "typed_args": func.MakeTypedInitString(""),
7247 "args": func.MakeInitString("")
7250 def WriteImmediateFormatTest(self, func, file):
7251 """Overrriden from TypeHandler."""
7252 args = func.GetOriginalArgs()
7253 count_param = 0
7254 for arg in args:
7255 if arg.name == "count":
7256 count_param = int(arg.GetValidClientSideCmdArg(func))
7257 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7258 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
7259 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
7260 for v in range(0, self.GetArrayCount(func) * count_param):
7261 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7262 (self.GetArrayType(func), v))
7263 file.Write(" };\n")
7264 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7265 (func.name, func.name))
7266 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
7267 file.Write(" const size_t kExpectedCmdSize =\n")
7268 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7269 (self.GetArrayType(func), self.GetArrayCount(func)))
7270 file.Write(" void* next_cmd = cmd.Set(\n")
7271 file.Write(" &cmd")
7272 for value, arg in enumerate(args):
7273 if arg.IsPointer():
7274 file.Write(",\n data")
7275 elif arg.IsConstant():
7276 continue
7277 else:
7278 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
7279 file.Write(");\n")
7280 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7281 func.name)
7282 file.Write(" cmd.header.command);\n")
7283 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7284 for value, arg in enumerate(args):
7285 if arg.IsPointer() or arg.IsConstant():
7286 continue
7287 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7288 (arg.type, value + 1, arg.name))
7289 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7290 file.Write(" next_cmd, sizeof(cmd) +\n")
7291 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7292 file.Write(" // TODO(gman): Check that data was inserted;\n")
7293 file.Write("}\n")
7294 file.Write("\n")
7296 class PUTSTRHandler(ArrayArgTypeHandler):
7297 """Handler for functions that pass a string array."""
7299 def __init__(self):
7300 ArrayArgTypeHandler.__init__(self)
7302 def __GetDataArg(self, func):
7303 """Return the argument that points to the 2D char arrays"""
7304 for arg in func.GetOriginalArgs():
7305 if arg.IsPointer2D():
7306 return arg
7307 return None
7309 def __GetLengthArg(self, func):
7310 """Return the argument that holds length for each char array"""
7311 for arg in func.GetOriginalArgs():
7312 if arg.IsPointer() and not arg.IsPointer2D():
7313 return arg
7314 return None
7316 def WriteGLES2Implementation(self, func, file):
7317 """Overrriden from TypeHandler."""
7318 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7319 (func.return_type, func.original_name,
7320 func.MakeTypedOriginalArgString("")))
7321 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7322 func.WriteDestinationInitalizationValidation(file)
7323 self.WriteClientGLCallLog(func, file)
7324 data_arg = self.__GetDataArg(func)
7325 length_arg = self.__GetLengthArg(func)
7326 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
7327 for (GLsizei ii = 0; ii < count; ++ii) {
7328 if (%(data)s[ii]) {"""
7329 if length_arg == None:
7330 log_code_block += """
7331 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7332 else:
7333 log_code_block += """
7334 if (%(length)s && %(length)s[ii] >= 0) {
7335 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7336 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7337 } else {
7338 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7339 }"""
7340 log_code_block += """
7341 } else {
7342 GPU_CLIENT_LOG(" " << ii << ": NULL");
7347 file.Write(log_code_block % {
7348 'data': data_arg.name,
7349 'length': length_arg.name if not length_arg == None else ''
7351 for arg in func.GetOriginalArgs():
7352 arg.WriteClientSideValidationCode(file, func)
7354 bucket_args = []
7355 for arg in func.GetOriginalArgs():
7356 if arg.name == 'count' or arg == self.__GetLengthArg(func):
7357 continue
7358 if arg == self.__GetDataArg(func):
7359 bucket_args.append('kResultBucketId')
7360 else:
7361 bucket_args.append(arg.name)
7362 code_block = """
7363 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7364 return;
7366 helper_->%(func_name)sBucket(%(bucket_args)s);
7367 helper_->SetBucketSize(kResultBucketId, 0);
7368 CheckGLError();
7372 file.Write(code_block % {
7373 'data': data_arg.name,
7374 'length': length_arg.name if not length_arg == None else 'NULL',
7375 'func_name': func.name,
7376 'bucket_args': ', '.join(bucket_args),
7379 def WriteGLES2ImplementationUnitTest(self, func, file):
7380 """Overrriden from TypeHandler."""
7381 code = """
7382 TEST_F(GLES2ImplementationTest, %(name)s) {
7383 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7384 const char* kString1 = "happy";
7385 const char* kString2 = "ending";
7386 const size_t kString1Size = ::strlen(kString1) + 1;
7387 const size_t kString2Size = ::strlen(kString2) + 1;
7388 const size_t kHeaderSize = sizeof(GLint) * 3;
7389 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7390 const size_t kPaddedHeaderSize =
7391 transfer_buffer_->RoundToAlignment(kHeaderSize);
7392 const size_t kPaddedString1Size =
7393 transfer_buffer_->RoundToAlignment(kString1Size);
7394 const size_t kPaddedString2Size =
7395 transfer_buffer_->RoundToAlignment(kString2Size);
7396 struct Cmds {
7397 cmd::SetBucketSize set_bucket_size;
7398 cmd::SetBucketData set_bucket_header;
7399 cmd::SetToken set_token1;
7400 cmd::SetBucketData set_bucket_data1;
7401 cmd::SetToken set_token2;
7402 cmd::SetBucketData set_bucket_data2;
7403 cmd::SetToken set_token3;
7404 cmds::%(name)sBucket cmd_bucket;
7405 cmd::SetBucketSize clear_bucket_size;
7408 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7409 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7410 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7412 Cmds expected;
7413 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7414 expected.set_bucket_header.Init(
7415 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7416 expected.set_token1.Init(GetNextToken());
7417 expected.set_bucket_data1.Init(
7418 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7419 expected.set_token2.Init(GetNextToken());
7420 expected.set_bucket_data2.Init(
7421 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7422 mem2.offset);
7423 expected.set_token3.Init(GetNextToken());
7424 expected.cmd_bucket.Init(%(bucket_args)s);
7425 expected.clear_bucket_size.Init(kBucketId, 0);
7426 const char* kStrings[] = { kString1, kString2 };
7427 gl_->%(name)s(%(gl_args)s);
7428 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7431 gl_args = []
7432 bucket_args = []
7433 for arg in func.GetOriginalArgs():
7434 if arg == self.__GetDataArg(func):
7435 gl_args.append('kStrings')
7436 bucket_args.append('kBucketId')
7437 elif arg == self.__GetLengthArg(func):
7438 gl_args.append('NULL')
7439 elif arg.name == 'count':
7440 gl_args.append('2')
7441 else:
7442 gl_args.append(arg.GetValidClientSideArg(func))
7443 bucket_args.append(arg.GetValidClientSideArg(func))
7444 file.Write(code % {
7445 'name': func.name,
7446 'gl_args': ", ".join(gl_args),
7447 'bucket_args': ", ".join(bucket_args),
7450 if self.__GetLengthArg(func) == None:
7451 return
7452 code = """
7453 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7454 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7455 const char* kString = "foobar******";
7456 const size_t kStringSize = 6; // We only need "foobar".
7457 const size_t kHeaderSize = sizeof(GLint) * 2;
7458 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7459 const size_t kPaddedHeaderSize =
7460 transfer_buffer_->RoundToAlignment(kHeaderSize);
7461 const size_t kPaddedStringSize =
7462 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7463 struct Cmds {
7464 cmd::SetBucketSize set_bucket_size;
7465 cmd::SetBucketData set_bucket_header;
7466 cmd::SetToken set_token1;
7467 cmd::SetBucketData set_bucket_data;
7468 cmd::SetToken set_token2;
7469 cmds::ShaderSourceBucket shader_source_bucket;
7470 cmd::SetBucketSize clear_bucket_size;
7473 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7474 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7476 Cmds expected;
7477 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7478 expected.set_bucket_header.Init(
7479 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7480 expected.set_token1.Init(GetNextToken());
7481 expected.set_bucket_data.Init(
7482 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7483 expected.set_token2.Init(GetNextToken());
7484 expected.shader_source_bucket.Init(%(bucket_args)s);
7485 expected.clear_bucket_size.Init(kBucketId, 0);
7486 const char* kStrings[] = { kString };
7487 const GLint kLength[] = { kStringSize };
7488 gl_->%(name)s(%(gl_args)s);
7489 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7492 gl_args = []
7493 for arg in func.GetOriginalArgs():
7494 if arg == self.__GetDataArg(func):
7495 gl_args.append('kStrings')
7496 elif arg == self.__GetLengthArg(func):
7497 gl_args.append('kLength')
7498 elif arg.name == 'count':
7499 gl_args.append('1')
7500 else:
7501 gl_args.append(arg.GetValidClientSideArg(func))
7502 file.Write(code % {
7503 'name': func.name,
7504 'gl_args': ", ".join(gl_args),
7505 'bucket_args': ", ".join(bucket_args),
7508 def WriteBucketServiceUnitTest(self, func, file, *extras):
7509 """Overrriden from TypeHandler."""
7510 cmd_args = []
7511 cmd_args_with_invalid_id = []
7512 gl_args = []
7513 for index, arg in enumerate(func.GetOriginalArgs()):
7514 if arg == self.__GetLengthArg(func):
7515 gl_args.append('_')
7516 elif arg.name == 'count':
7517 gl_args.append('1')
7518 elif arg == self.__GetDataArg(func):
7519 cmd_args.append('kBucketId')
7520 cmd_args_with_invalid_id.append('kBucketId')
7521 gl_args.append('_')
7522 elif index == 0: # Resource ID arg
7523 cmd_args.append(arg.GetValidArg(func))
7524 cmd_args_with_invalid_id.append('kInvalidClientId')
7525 gl_args.append(arg.GetValidGLArg(func))
7526 else:
7527 cmd_args.append(arg.GetValidArg(func))
7528 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7529 gl_args.append(arg.GetValidGLArg(func))
7531 test = """
7532 TEST_P(%(test_name)s, %(name)sValidArgs) {
7533 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7534 const uint32 kBucketId = 123;
7535 const char kSource0[] = "hello";
7536 const char* kSource[] = { kSource0 };
7537 const char kValidStrEnd = 0;
7538 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7539 cmds::%(name)s cmd;
7540 cmd.Init(%(cmd_args)s);
7541 decoder_->set_unsafe_es3_apis_enabled(true);
7542 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7543 if func.IsUnsafe():
7544 test += """
7545 decoder_->set_unsafe_es3_apis_enabled(false);
7546 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7548 test += """
7551 self.WriteValidUnitTest(func, file, test, {
7552 'cmd_args': ", ".join(cmd_args),
7553 'gl_args': ", ".join(gl_args),
7554 }, *extras)
7556 test = """
7557 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7558 const uint32 kBucketId = 123;
7559 const char kSource0[] = "hello";
7560 const char* kSource[] = { kSource0 };
7561 const char kValidStrEnd = 0;
7562 decoder_->set_unsafe_es3_apis_enabled(true);
7563 cmds::%(name)s cmd;
7564 // Test no bucket.
7565 cmd.Init(%(cmd_args)s);
7566 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7567 // Test invalid client.
7568 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7569 cmd.Init(%(cmd_args_with_invalid_id)s);
7570 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7571 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7574 self.WriteValidUnitTest(func, file, test, {
7575 'cmd_args': ", ".join(cmd_args),
7576 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7577 }, *extras)
7579 test = """
7580 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7581 const uint32 kBucketId = 123;
7582 const char kSource0[] = "hello";
7583 const char* kSource[] = { kSource0 };
7584 const char kValidStrEnd = 0;
7585 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7586 const GLsizei kTests[] = {
7587 kCount + 1,
7589 std::numeric_limits<GLsizei>::max(),
7592 decoder_->set_unsafe_es3_apis_enabled(true);
7593 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7594 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7595 cmds::%(name)s cmd;
7596 cmd.Init(%(cmd_args)s);
7597 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7601 self.WriteValidUnitTest(func, file, test, {
7602 'cmd_args': ", ".join(cmd_args),
7603 }, *extras)
7605 test = """
7606 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7607 const uint32 kBucketId = 123;
7608 const char kSource0[] = "hello";
7609 const char* kSource[] = { kSource0 };
7610 const char kInvalidStrEnd = '*';
7611 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7612 cmds::%(name)s cmd;
7613 cmd.Init(%(cmd_args)s);
7614 decoder_->set_unsafe_es3_apis_enabled(true);
7615 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7618 self.WriteValidUnitTest(func, file, test, {
7619 'cmd_args': ", ".join(cmd_args),
7620 }, *extras)
7623 class PUTXnHandler(ArrayArgTypeHandler):
7624 """Handler for glUniform?f functions."""
7625 def __init__(self):
7626 ArrayArgTypeHandler.__init__(self)
7628 def WriteHandlerImplementation(self, func, file):
7629 """Overrriden from TypeHandler."""
7630 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7631 if func.IsUnsafe():
7632 code += """
7633 gl%(name)sv(%(location)s, 1, &temp[0]);
7635 else:
7636 code += """
7637 Do%(name)sv(%(location)s, 1, &temp[0]);
7639 values = ""
7640 args = func.GetOriginalArgs()
7641 count = int(self.GetArrayCount(func))
7642 num_args = len(args)
7643 for ii in range(count):
7644 values += "%s, " % args[len(args) - count + ii].name
7646 file.Write(code % {
7647 'name': func.name,
7648 'count': self.GetArrayCount(func),
7649 'type': self.GetArrayType(func),
7650 'location': args[0].name,
7651 'args': func.MakeOriginalArgString(""),
7652 'values': values,
7655 def WriteServiceUnitTest(self, func, file, *extras):
7656 """Overrriden from TypeHandler."""
7657 valid_test = """
7658 TEST_P(%(test_name)s, %(name)sValidArgs) {
7659 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7660 SpecializedSetup<cmds::%(name)s, 0>(true);
7661 cmds::%(name)s cmd;
7662 cmd.Init(%(args)s);"""
7663 if func.IsUnsafe():
7664 valid_test += """
7665 decoder_->set_unsafe_es3_apis_enabled(true);"""
7666 valid_test += """
7667 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7668 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7669 if func.IsUnsafe():
7670 valid_test += """
7671 decoder_->set_unsafe_es3_apis_enabled(false);
7672 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7673 valid_test += """
7676 args = func.GetOriginalArgs()
7677 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7678 self.WriteValidUnitTest(func, file, valid_test, {
7679 'name': func.name,
7680 'count': self.GetArrayCount(func),
7681 'local_args': local_args,
7682 }, *extras)
7684 invalid_test = """
7685 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7686 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7687 SpecializedSetup<cmds::%(name)s, 0>(false);
7688 cmds::%(name)s cmd;
7689 cmd.Init(%(args)s);
7690 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7693 self.WriteInvalidUnitTest(func, file, invalid_test, {
7694 'name': func.GetInfo('name'),
7695 'count': self.GetArrayCount(func),
7699 class GLcharHandler(CustomHandler):
7700 """Handler for functions that pass a single string ."""
7702 def __init__(self):
7703 CustomHandler.__init__(self)
7705 def WriteImmediateCmdComputeSize(self, func, file):
7706 """Overrriden from TypeHandler."""
7707 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7708 file.Write(" return static_cast<uint32_t>(\n")
7709 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7710 file.Write(" }\n")
7712 def WriteImmediateCmdSetHeader(self, func, file):
7713 """Overrriden from TypeHandler."""
7714 code = """
7715 void SetHeader(uint32_t data_size) {
7716 header.SetCmdBySize<ValueType>(data_size);
7719 file.Write(code)
7721 def WriteImmediateCmdInit(self, func, file):
7722 """Overrriden from TypeHandler."""
7723 last_arg = func.GetLastOriginalArg()
7724 args = func.GetCmdArgs()
7725 set_code = []
7726 for arg in args:
7727 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7728 code = """
7729 void Init(%(typed_args)s, uint32_t _data_size) {
7730 SetHeader(_data_size);
7731 %(set_code)s
7732 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7736 file.Write(code % {
7737 "typed_args": func.MakeTypedArgString("_"),
7738 "set_code": "\n".join(set_code),
7739 "last_arg": last_arg.name
7742 def WriteImmediateCmdSet(self, func, file):
7743 """Overrriden from TypeHandler."""
7744 last_arg = func.GetLastOriginalArg()
7745 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7746 func.MakeTypedCmdArgString("_", True))
7747 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7748 func.MakeCmdArgString("_"))
7749 file.Write(" return NextImmediateCmdAddress<ValueType>("
7750 "cmd, _data_size);\n")
7751 file.Write(" }\n")
7752 file.Write("\n")
7754 def WriteImmediateCmdHelper(self, func, file):
7755 """Overrriden from TypeHandler."""
7756 code = """ void %(name)s(%(typed_args)s) {
7757 const uint32_t data_size = strlen(name);
7758 gles2::cmds::%(name)s* c =
7759 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7760 if (c) {
7761 c->Init(%(args)s, data_size);
7766 file.Write(code % {
7767 "name": func.name,
7768 "typed_args": func.MakeTypedOriginalArgString(""),
7769 "args": func.MakeOriginalArgString(""),
7773 def WriteImmediateFormatTest(self, func, file):
7774 """Overrriden from TypeHandler."""
7775 init_code = []
7776 check_code = []
7777 all_but_last_arg = func.GetCmdArgs()[:-1]
7778 for value, arg in enumerate(all_but_last_arg):
7779 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7780 for value, arg in enumerate(all_but_last_arg):
7781 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7782 (arg.type, value + 11, arg.name))
7783 code = """
7784 TEST_F(GLES2FormatTest, %(func_name)s) {
7785 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7786 static const char* const test_str = \"test string\";
7787 void* next_cmd = cmd.Set(
7788 &cmd,
7789 %(init_code)s
7790 test_str,
7791 strlen(test_str));
7792 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7793 cmd.header.command);
7794 EXPECT_EQ(sizeof(cmd) +
7795 RoundSizeToMultipleOfEntries(strlen(test_str)),
7796 cmd.header.size * 4u);
7797 EXPECT_EQ(static_cast<char*>(next_cmd),
7798 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7799 RoundSizeToMultipleOfEntries(strlen(test_str)));
7800 %(check_code)s
7801 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7802 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7803 CheckBytesWritten(
7804 next_cmd,
7805 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7806 sizeof(cmd) + strlen(test_str));
7810 file.Write(code % {
7811 'func_name': func.name,
7812 'init_code': "\n".join(init_code),
7813 'check_code': "\n".join(check_code),
7817 class GLcharNHandler(CustomHandler):
7818 """Handler for functions that pass a single string with an optional len."""
7820 def __init__(self):
7821 CustomHandler.__init__(self)
7823 def InitFunction(self, func):
7824 """Overrriden from TypeHandler."""
7825 func.cmd_args = []
7826 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7828 def NeedsDataTransferFunction(self, func):
7829 """Overriden from TypeHandler."""
7830 return False
7832 def AddBucketFunction(self, generator, func):
7833 """Overrriden from TypeHandler."""
7834 pass
7836 def WriteServiceImplementation(self, func, file):
7837 """Overrriden from TypeHandler."""
7838 self.WriteServiceHandlerFunctionHeader(func, file)
7839 file.Write("""
7840 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7841 Bucket* bucket = GetBucket(bucket_id);
7842 if (!bucket || bucket->size() == 0) {
7843 return error::kInvalidArguments;
7845 std::string str;
7846 if (!bucket->GetAsString(&str)) {
7847 return error::kInvalidArguments;
7849 %(gl_func_name)s(0, str.c_str());
7850 return error::kNoError;
7853 """ % {
7854 'name': func.name,
7855 'gl_func_name': func.GetGLFunctionName(),
7856 'bucket_id': func.cmd_args[0].name,
7860 class IsHandler(TypeHandler):
7861 """Handler for glIs____ type and glGetError functions."""
7863 def __init__(self):
7864 TypeHandler.__init__(self)
7866 def InitFunction(self, func):
7867 """Overrriden from TypeHandler."""
7868 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7869 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7870 if func.GetInfo('result') == None:
7871 func.AddInfo('result', ['uint32_t'])
7873 def WriteServiceUnitTest(self, func, file, *extras):
7874 """Overrriden from TypeHandler."""
7875 valid_test = """
7876 TEST_P(%(test_name)s, %(name)sValidArgs) {
7877 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7878 SpecializedSetup<cmds::%(name)s, 0>(true);
7879 cmds::%(name)s cmd;
7880 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7881 if func.IsUnsafe():
7882 valid_test += """
7883 decoder_->set_unsafe_es3_apis_enabled(true);"""
7884 valid_test += """
7885 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7886 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7887 if func.IsUnsafe():
7888 valid_test += """
7889 decoder_->set_unsafe_es3_apis_enabled(false);
7890 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7891 valid_test += """
7894 comma = ""
7895 if len(func.GetOriginalArgs()):
7896 comma =", "
7897 self.WriteValidUnitTest(func, file, valid_test, {
7898 'comma': comma,
7899 }, *extras)
7901 invalid_test = """
7902 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7903 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7904 SpecializedSetup<cmds::%(name)s, 0>(false);
7905 cmds::%(name)s cmd;
7906 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7907 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7910 self.WriteInvalidUnitTest(func, file, invalid_test, {
7911 'comma': comma,
7912 }, *extras)
7914 invalid_test = """
7915 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7916 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7917 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7918 if func.IsUnsafe():
7919 invalid_test += """
7920 decoder_->set_unsafe_es3_apis_enabled(true);"""
7921 invalid_test += """
7922 cmds::%(name)s cmd;
7923 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7924 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7925 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7926 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7927 if func.IsUnsafe():
7928 invalid_test += """
7929 decoder_->set_unsafe_es3_apis_enabled(true);"""
7930 invalid_test += """
7933 self.WriteValidUnitTest(func, file, invalid_test, {
7934 'comma': comma,
7935 }, *extras)
7937 def WriteServiceImplementation(self, func, file):
7938 """Overrriden from TypeHandler."""
7939 self.WriteServiceHandlerFunctionHeader(func, file)
7940 args = func.GetOriginalArgs()
7941 for arg in args:
7942 arg.WriteGetCode(file)
7944 code = """ typedef cmds::%(func_name)s::Result Result;
7945 Result* result_dst = GetSharedMemoryAs<Result*>(
7946 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7947 if (!result_dst) {
7948 return error::kOutOfBounds;
7951 file.Write(code % {'func_name': func.name})
7952 func.WriteHandlerValidation(file)
7953 if func.IsUnsafe():
7954 assert func.GetInfo('id_mapping')
7955 assert len(func.GetInfo('id_mapping')) == 1
7956 assert len(args) == 1
7957 id_type = func.GetInfo('id_mapping')[0]
7958 file.Write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
7959 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7960 (id_type, id_type.lower(), id_type.lower()))
7961 else:
7962 file.Write(" *result_dst = %s(%s);\n" %
7963 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
7964 file.Write(" return error::kNoError;\n")
7965 file.Write("}\n")
7966 file.Write("\n")
7968 def WriteGLES2Implementation(self, func, file):
7969 """Overrriden from TypeHandler."""
7970 impl_func = func.GetInfo('impl_func')
7971 if impl_func == None or impl_func == True:
7972 error_value = func.GetInfo("error_value") or "GL_FALSE"
7973 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7974 (func.return_type, func.original_name,
7975 func.MakeTypedOriginalArgString("")))
7976 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7977 self.WriteTraceEvent(func, file)
7978 func.WriteDestinationInitalizationValidation(file)
7979 self.WriteClientGLCallLog(func, file)
7980 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
7981 file.Write(" Result* result = GetResultAs<Result*>();\n")
7982 file.Write(" if (!result) {\n")
7983 file.Write(" return %s;\n" % error_value)
7984 file.Write(" }\n")
7985 file.Write(" *result = 0;\n")
7986 assert len(func.GetOriginalArgs()) == 1
7987 id_arg = func.GetOriginalArgs()[0]
7988 if id_arg.type == 'GLsync':
7989 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
7990 else:
7991 arg_string = func.MakeOriginalArgString("")
7992 file.Write(
7993 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7994 (func.name, arg_string))
7995 file.Write(" WaitForCmd();\n")
7996 file.Write(" %s result_value = *result" % func.return_type)
7997 if func.return_type == "GLboolean":
7998 file.Write(" != 0")
7999 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8000 file.Write(" CheckGLError();\n")
8001 file.Write(" return result_value;\n")
8002 file.Write("}\n")
8003 file.Write("\n")
8005 def WriteGLES2ImplementationUnitTest(self, func, file):
8006 """Overrriden from TypeHandler."""
8007 client_test = func.GetInfo('client_test')
8008 if client_test == None or client_test == True:
8009 code = """
8010 TEST_F(GLES2ImplementationTest, %(name)s) {
8011 struct Cmds {
8012 cmds::%(name)s cmd;
8015 Cmds expected;
8016 ExpectedMemoryInfo result1 =
8017 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8018 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8020 EXPECT_CALL(*command_buffer(), OnFlush())
8021 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8022 .RetiresOnSaturation();
8024 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8025 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8026 EXPECT_TRUE(result);
8029 args = func.GetOriginalArgs()
8030 assert len(args) == 1
8031 file.Write(code % {
8032 'name': func.name,
8033 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
8034 'gl_id_value': args[0].GetValidClientSideArg(func) })
8037 class STRnHandler(TypeHandler):
8038 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8039 GetTranslatedShaderSourceANGLE."""
8041 def __init__(self):
8042 TypeHandler.__init__(self)
8044 def InitFunction(self, func):
8045 """Overrriden from TypeHandler."""
8046 # remove all but the first cmd args.
8047 cmd_args = func.GetCmdArgs()
8048 func.ClearCmdArgs()
8049 func.AddCmdArg(cmd_args[0])
8050 # add on a bucket id.
8051 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8053 def WriteGLES2Implementation(self, func, file):
8054 """Overrriden from TypeHandler."""
8055 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8056 GPU_CLIENT_SINGLE_THREAD_CHECK();
8058 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8059 << "] gl%(func_name)s" << "("
8060 << %(arg0)s << ", "
8061 << %(arg1)s << ", "
8062 << static_cast<void*>(%(arg2)s) << ", "
8063 << static_cast<void*>(%(arg3)s) << ")");
8064 helper_->SetBucketSize(kResultBucketId, 0);
8065 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8066 std::string str;
8067 GLsizei max_size = 0;
8068 if (GetBucketAsString(kResultBucketId, &str)) {
8069 if (bufsize > 0) {
8070 max_size =
8071 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8072 memcpy(%(dest_name)s, str.c_str(), max_size);
8073 %(dest_name)s[max_size] = '\\0';
8074 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8077 if (%(length_name)s != NULL) {
8078 *%(length_name)s = max_size;
8080 CheckGLError();
8083 args = func.GetOriginalArgs()
8084 str_args = {
8085 'return_type': func.return_type,
8086 'func_name': func.original_name,
8087 'args': func.MakeTypedOriginalArgString(""),
8088 'id_name': args[0].name,
8089 'bufsize_name': args[1].name,
8090 'length_name': args[2].name,
8091 'dest_name': args[3].name,
8092 'arg0': args[0].name,
8093 'arg1': args[1].name,
8094 'arg2': args[2].name,
8095 'arg3': args[3].name,
8097 file.Write(code_1 % str_args)
8098 func.WriteDestinationInitalizationValidation(file)
8099 file.Write(code_2 % str_args)
8101 def WriteServiceUnitTest(self, func, file, *extras):
8102 """Overrriden from TypeHandler."""
8103 valid_test = """
8104 TEST_P(%(test_name)s, %(name)sValidArgs) {
8105 const char* kInfo = "hello";
8106 const uint32_t kBucketId = 123;
8107 SpecializedSetup<cmds::%(name)s, 0>(true);
8108 %(expect_len_code)s
8109 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8110 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8111 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8112 cmds::%(name)s cmd;
8113 cmd.Init(%(args)s);
8114 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8115 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8116 ASSERT_TRUE(bucket != NULL);
8117 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8118 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8119 bucket->size()));
8120 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8123 args = func.GetOriginalArgs()
8124 id_name = args[0].GetValidGLArg(func)
8125 get_len_func = func.GetInfo('get_len_func')
8126 get_len_enum = func.GetInfo('get_len_enum')
8127 sub = {
8128 'id_name': id_name,
8129 'get_len_func': get_len_func,
8130 'get_len_enum': get_len_enum,
8131 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8132 args[0].GetValidGLArg(func),
8133 'args': '%s, kBucketId' % args[0].GetValidArg(func),
8134 'expect_len_code': '',
8136 if get_len_func and get_len_func[0:2] == 'gl':
8137 sub['expect_len_code'] = (
8138 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8139 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8140 get_len_func[2:], id_name, get_len_enum)
8141 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
8143 invalid_test = """
8144 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8145 const uint32_t kBucketId = 123;
8146 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8147 .Times(0);
8148 cmds::%(name)s cmd;
8149 cmd.Init(kInvalidClientId, kBucketId);
8150 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8151 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8154 self.WriteValidUnitTest(func, file, invalid_test, *extras)
8156 def WriteServiceImplementation(self, func, file):
8157 """Overrriden from TypeHandler."""
8158 pass
8160 class NamedType(object):
8161 """A class that represents a type of an argument in a client function.
8163 A type of an argument that is to be passed through in the command buffer
8164 command. Currently used only for the arguments that are specificly named in
8165 the 'cmd_buffer_functions.txt' file, mostly enums.
8168 def __init__(self, info):
8169 assert not 'is_complete' in info or info['is_complete'] == True
8170 self.info = info
8171 self.valid = info['valid']
8172 if 'invalid' in info:
8173 self.invalid = info['invalid']
8174 else:
8175 self.invalid = []
8176 if 'valid_es3' in info:
8177 self.valid_es3 = info['valid_es3']
8178 else:
8179 self.valid_es3 = []
8180 if 'deprecated_es3' in info:
8181 self.deprecated_es3 = info['deprecated_es3']
8182 else:
8183 self.deprecated_es3 = []
8185 def GetType(self):
8186 return self.info['type']
8188 def GetInvalidValues(self):
8189 return self.invalid
8191 def GetValidValues(self):
8192 return self.valid
8194 def GetValidValuesES3(self):
8195 return self.valid_es3
8197 def GetDeprecatedValuesES3(self):
8198 return self.deprecated_es3
8200 def IsConstant(self):
8201 if not 'is_complete' in self.info:
8202 return False
8204 return len(self.GetValidValues()) == 1
8206 def GetConstantValue(self):
8207 return self.GetValidValues()[0]
8209 class Argument(object):
8210 """A class that represents a function argument."""
8212 cmd_type_map_ = {
8213 'GLenum': 'uint32_t',
8214 'GLint': 'int32_t',
8215 'GLintptr': 'int32_t',
8216 'GLsizei': 'int32_t',
8217 'GLsizeiptr': 'int32_t',
8218 'GLfloat': 'float',
8219 'GLclampf': 'float',
8221 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8223 def __init__(self, name, type):
8224 self.name = name
8225 self.optional = type.endswith("Optional*")
8226 if self.optional:
8227 type = type[:-9] + "*"
8228 self.type = type
8230 if type in self.cmd_type_map_:
8231 self.cmd_type = self.cmd_type_map_[type]
8232 else:
8233 self.cmd_type = 'uint32_t'
8235 def IsPointer(self):
8236 """Returns true if argument is a pointer."""
8237 return False
8239 def IsPointer2D(self):
8240 """Returns true if argument is a 2D pointer."""
8241 return False
8243 def IsConstant(self):
8244 """Returns true if the argument has only one valid value."""
8245 return False
8247 def AddCmdArgs(self, args):
8248 """Adds command arguments for this argument to the given list."""
8249 if not self.IsConstant():
8250 return args.append(self)
8252 def AddInitArgs(self, args):
8253 """Adds init arguments for this argument to the given list."""
8254 if not self.IsConstant():
8255 return args.append(self)
8257 def GetValidArg(self, func):
8258 """Gets a valid value for this argument."""
8259 valid_arg = func.GetValidArg(self)
8260 if valid_arg != None:
8261 return valid_arg
8263 index = func.GetOriginalArgs().index(self)
8264 return str(index + 1)
8266 def GetValidClientSideArg(self, func):
8267 """Gets a valid value for this argument."""
8268 valid_arg = func.GetValidArg(self)
8269 if valid_arg != None:
8270 return valid_arg
8272 if self.IsPointer():
8273 return 'nullptr'
8274 index = func.GetOriginalArgs().index(self)
8275 if self.type == 'GLsync':
8276 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
8277 return str(index + 1)
8279 def GetValidClientSideCmdArg(self, func):
8280 """Gets a valid value for this argument."""
8281 valid_arg = func.GetValidArg(self)
8282 if valid_arg != None:
8283 return valid_arg
8284 try:
8285 index = func.GetOriginalArgs().index(self)
8286 return str(index + 1)
8287 except ValueError:
8288 pass
8289 index = func.GetCmdArgs().index(self)
8290 return str(index + 1)
8292 def GetValidGLArg(self, func):
8293 """Gets a valid GL value for this argument."""
8294 value = self.GetValidArg(func)
8295 if self.type == 'GLsync':
8296 return ("reinterpret_cast<GLsync>(%s)" % value)
8297 return value
8299 def GetValidNonCachedClientSideArg(self, func):
8300 """Returns a valid value for this argument in a GL call.
8301 Using the value will produce a command buffer service invocation.
8302 Returns None if there is no such value."""
8303 value = '123'
8304 if self.type == 'GLsync':
8305 return ("reinterpret_cast<GLsync>(%s)" % value)
8306 return value
8308 def GetValidNonCachedClientSideCmdArg(self, func):
8309 """Returns a valid value for this argument in a command buffer command.
8310 Calling the GL function with the value returned by
8311 GetValidNonCachedClientSideArg will result in a command buffer command
8312 that contains the value returned by this function. """
8313 return '123'
8315 def GetNumInvalidValues(self, func):
8316 """returns the number of invalid values to be tested."""
8317 return 0
8319 def GetInvalidArg(self, index):
8320 """returns an invalid value and expected parse result by index."""
8321 return ("---ERROR0---", "---ERROR2---", None)
8323 def GetLogArg(self):
8324 """Get argument appropriate for LOG macro."""
8325 if self.type == 'GLboolean':
8326 return 'GLES2Util::GetStringBool(%s)' % self.name
8327 if self.type == 'GLenum':
8328 return 'GLES2Util::GetStringEnum(%s)' % self.name
8329 return self.name
8331 def WriteGetCode(self, file):
8332 """Writes the code to get an argument from a command structure."""
8333 if self.type == 'GLsync':
8334 my_type = 'GLuint'
8335 else:
8336 my_type = self.type
8337 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
8338 (my_type, self.name, my_type, self.name))
8340 def WriteValidationCode(self, file, func):
8341 """Writes the validation code for an argument."""
8342 pass
8344 def WriteClientSideValidationCode(self, file, func):
8345 """Writes the validation code for an argument."""
8346 pass
8348 def WriteDestinationInitalizationValidation(self, file, func):
8349 """Writes the client side destintion initialization validation."""
8350 pass
8352 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
8353 """Writes the client side destintion initialization validation if needed."""
8354 parts = self.type.split(" ")
8355 if len(parts) > 1:
8356 return
8357 if parts[0] in self.need_validation_:
8358 file.Write(
8359 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8360 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
8363 def WriteGetAddress(self, file):
8364 """Writes the code to get the address this argument refers to."""
8365 pass
8367 def GetImmediateVersion(self):
8368 """Gets the immediate version of this argument."""
8369 return self
8371 def GetBucketVersion(self):
8372 """Gets the bucket version of this argument."""
8373 return self
8376 class BoolArgument(Argument):
8377 """class for GLboolean"""
8379 def __init__(self, name, type):
8380 Argument.__init__(self, name, 'GLboolean')
8382 def GetValidArg(self, func):
8383 """Gets a valid value for this argument."""
8384 return 'true'
8386 def GetValidClientSideArg(self, func):
8387 """Gets a valid value for this argument."""
8388 return 'true'
8390 def GetValidClientSideCmdArg(self, func):
8391 """Gets a valid value for this argument."""
8392 return 'true'
8394 def GetValidGLArg(self, func):
8395 """Gets a valid GL value for this argument."""
8396 return 'true'
8399 class UniformLocationArgument(Argument):
8400 """class for uniform locations."""
8402 def __init__(self, name):
8403 Argument.__init__(self, name, "GLint")
8405 def WriteGetCode(self, file):
8406 """Writes the code to get an argument from a command structure."""
8407 code = """ %s %s = static_cast<%s>(c.%s);
8409 file.Write(code % (self.type, self.name, self.type, self.name))
8411 class DataSizeArgument(Argument):
8412 """class for data_size which Bucket commands do not need."""
8414 def __init__(self, name):
8415 Argument.__init__(self, name, "uint32_t")
8417 def GetBucketVersion(self):
8418 return None
8421 class SizeArgument(Argument):
8422 """class for GLsizei and GLsizeiptr."""
8424 def __init__(self, name, type):
8425 Argument.__init__(self, name, type)
8427 def GetNumInvalidValues(self, func):
8428 """overridden from Argument."""
8429 if func.IsImmediate():
8430 return 0
8431 return 1
8433 def GetInvalidArg(self, index):
8434 """overridden from Argument."""
8435 return ("-1", "kNoError", "GL_INVALID_VALUE")
8437 def WriteValidationCode(self, file, func):
8438 """overridden from Argument."""
8439 if func.IsUnsafe():
8440 return
8441 code = """ if (%(var_name)s < 0) {
8442 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8443 return error::kNoError;
8446 file.Write(code % {
8447 "var_name": self.name,
8448 "func_name": func.original_name,
8451 def WriteClientSideValidationCode(self, file, func):
8452 """overridden from Argument."""
8453 code = """ if (%(var_name)s < 0) {
8454 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8455 return;
8458 file.Write(code % {
8459 "var_name": self.name,
8460 "func_name": func.original_name,
8464 class SizeNotNegativeArgument(SizeArgument):
8465 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8467 def __init__(self, name, type, gl_type):
8468 SizeArgument.__init__(self, name, gl_type)
8470 def GetInvalidArg(self, index):
8471 """overridden from SizeArgument."""
8472 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8474 def WriteValidationCode(self, file, func):
8475 """overridden from SizeArgument."""
8476 pass
8479 class EnumBaseArgument(Argument):
8480 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8481 ValidatedBoolArgument."""
8483 def __init__(self, name, gl_type, type, gl_error):
8484 Argument.__init__(self, name, gl_type)
8486 self.local_type = type
8487 self.gl_error = gl_error
8488 name = type[len(gl_type):]
8489 self.type_name = name
8490 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8492 def IsConstant(self):
8493 return self.named_type.IsConstant()
8495 def GetConstantValue(self):
8496 return self.named_type.GetConstantValue()
8498 def WriteValidationCode(self, file, func):
8499 if func.IsUnsafe():
8500 return
8501 if self.named_type.IsConstant():
8502 return
8503 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8504 (ToUnderscore(self.type_name), self.name))
8505 if self.gl_error == "GL_INVALID_ENUM":
8506 file.Write(
8507 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8508 (func.original_name, self.name, self.name))
8509 else:
8510 file.Write(
8511 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8512 (self.gl_error, func.original_name, self.name, self.gl_error))
8513 file.Write(" return error::kNoError;\n")
8514 file.Write(" }\n")
8516 def WriteClientSideValidationCode(self, file, func):
8517 if not self.named_type.IsConstant():
8518 return
8519 file.Write(" if (%s != %s) {" % (self.name,
8520 self.GetConstantValue()))
8521 file.Write(
8522 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8523 (self.gl_error, func.original_name, self.name, self.gl_error))
8524 if func.return_type == "void":
8525 file.Write(" return;\n")
8526 else:
8527 file.Write(" return %s;\n" % func.GetErrorReturnString())
8528 file.Write(" }\n")
8530 def GetValidArg(self, func):
8531 valid_arg = func.GetValidArg(self)
8532 if valid_arg != None:
8533 return valid_arg
8534 valid = self.named_type.GetValidValues()
8535 if valid:
8536 num_valid = len(valid)
8537 return valid[0]
8539 index = func.GetOriginalArgs().index(self)
8540 return str(index + 1)
8542 def GetValidClientSideArg(self, func):
8543 """Gets a valid value for this argument."""
8544 return self.GetValidArg(func)
8546 def GetValidClientSideCmdArg(self, func):
8547 """Gets a valid value for this argument."""
8548 valid_arg = func.GetValidArg(self)
8549 if valid_arg != None:
8550 return valid_arg
8552 valid = self.named_type.GetValidValues()
8553 if valid:
8554 num_valid = len(valid)
8555 return valid[0]
8557 try:
8558 index = func.GetOriginalArgs().index(self)
8559 return str(index + 1)
8560 except ValueError:
8561 pass
8562 index = func.GetCmdArgs().index(self)
8563 return str(index + 1)
8565 def GetValidGLArg(self, func):
8566 """Gets a valid value for this argument."""
8567 return self.GetValidArg(func)
8569 def GetNumInvalidValues(self, func):
8570 """returns the number of invalid values to be tested."""
8571 return len(self.named_type.GetInvalidValues())
8573 def GetInvalidArg(self, index):
8574 """returns an invalid value by index."""
8575 invalid = self.named_type.GetInvalidValues()
8576 if invalid:
8577 num_invalid = len(invalid)
8578 if index >= num_invalid:
8579 index = num_invalid - 1
8580 return (invalid[index], "kNoError", self.gl_error)
8581 return ("---ERROR1---", "kNoError", self.gl_error)
8584 class EnumArgument(EnumBaseArgument):
8585 """A class that represents a GLenum argument"""
8587 def __init__(self, name, type):
8588 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8590 def GetLogArg(self):
8591 """Overridden from Argument."""
8592 return ("GLES2Util::GetString%s(%s)" %
8593 (self.type_name, self.name))
8596 class IntArgument(EnumBaseArgument):
8597 """A class for a GLint argument that can only accept specific values.
8599 For example glTexImage2D takes a GLint for its internalformat
8600 argument instead of a GLenum.
8603 def __init__(self, name, type):
8604 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8607 class ValidatedBoolArgument(EnumBaseArgument):
8608 """A class for a GLboolean argument that can only accept specific values.
8610 For example glUniformMatrix takes a GLboolean for it's transpose but it
8611 must be false.
8614 def __init__(self, name, type):
8615 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8617 def GetLogArg(self):
8618 """Overridden from Argument."""
8619 return 'GLES2Util::GetStringBool(%s)' % self.name
8622 class BitFieldArgument(EnumBaseArgument):
8623 """A class for a GLbitfield argument that can only accept specific values.
8625 For example glFenceSync takes a GLbitfield for its flags argument bit it
8626 must be 0.
8629 def __init__(self, name, type):
8630 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8631 "GL_INVALID_VALUE")
8634 class ImmediatePointerArgument(Argument):
8635 """A class that represents an immediate argument to a function.
8637 An immediate argument is one where the data follows the command.
8640 def __init__(self, name, type):
8641 Argument.__init__(self, name, type)
8643 def IsPointer(self):
8644 return True
8646 def GetPointedType(self):
8647 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8648 assert match
8649 return match.groupdict()['element_type']
8651 def AddCmdArgs(self, args):
8652 """Overridden from Argument."""
8653 pass
8655 def WriteGetCode(self, file):
8656 """Overridden from Argument."""
8657 file.Write(
8658 " %s %s = GetImmediateDataAs<%s>(\n" %
8659 (self.type, self.name, self.type))
8660 file.Write(" c, data_size, immediate_data_size);\n")
8662 def WriteValidationCode(self, file, func):
8663 """Overridden from Argument."""
8664 if self.optional:
8665 return
8666 file.Write(" if (%s == NULL) {\n" % self.name)
8667 file.Write(" return error::kOutOfBounds;\n")
8668 file.Write(" }\n")
8670 def GetImmediateVersion(self):
8671 """Overridden from Argument."""
8672 return None
8674 def WriteDestinationInitalizationValidation(self, file, func):
8675 """Overridden from Argument."""
8676 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8678 def GetLogArg(self):
8679 """Overridden from Argument."""
8680 return "static_cast<const void*>(%s)" % self.name
8683 class PointerArgument(Argument):
8684 """A class that represents a pointer argument to a function."""
8686 def __init__(self, name, type):
8687 Argument.__init__(self, name, type)
8689 def IsPointer(self):
8690 """Overridden from Argument."""
8691 return True
8693 def IsPointer2D(self):
8694 """Overridden from Argument."""
8695 return self.type.count('*') == 2
8697 def GetPointedType(self):
8698 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8699 assert match
8700 return match.groupdict()['element_type']
8702 def GetValidArg(self, func):
8703 """Overridden from Argument."""
8704 return "shared_memory_id_, shared_memory_offset_"
8706 def GetValidGLArg(self, func):
8707 """Overridden from Argument."""
8708 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8710 def GetNumInvalidValues(self, func):
8711 """Overridden from Argument."""
8712 return 2
8714 def GetInvalidArg(self, index):
8715 """Overridden from Argument."""
8716 if index == 0:
8717 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8718 else:
8719 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8720 "kOutOfBounds", None)
8722 def GetLogArg(self):
8723 """Overridden from Argument."""
8724 return "static_cast<const void*>(%s)" % self.name
8726 def AddCmdArgs(self, args):
8727 """Overridden from Argument."""
8728 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8729 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8731 def WriteGetCode(self, file):
8732 """Overridden from Argument."""
8733 file.Write(
8734 " %s %s = GetSharedMemoryAs<%s>(\n" %
8735 (self.type, self.name, self.type))
8736 file.Write(
8737 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8738 (self.name, self.name))
8740 def WriteGetAddress(self, file):
8741 """Overridden from Argument."""
8742 file.Write(
8743 " %s %s = GetSharedMemoryAs<%s>(\n" %
8744 (self.type, self.name, self.type))
8745 file.Write(
8746 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8747 (self.name, self.name, self.name))
8749 def WriteValidationCode(self, file, func):
8750 """Overridden from Argument."""
8751 if self.optional:
8752 return
8753 file.Write(" if (%s == NULL) {\n" % self.name)
8754 file.Write(" return error::kOutOfBounds;\n")
8755 file.Write(" }\n")
8757 def GetImmediateVersion(self):
8758 """Overridden from Argument."""
8759 return ImmediatePointerArgument(self.name, self.type)
8761 def GetBucketVersion(self):
8762 """Overridden from Argument."""
8763 if self.type.find('char') >= 0:
8764 if self.IsPointer2D():
8765 return InputStringArrayBucketArgument(self.name, self.type)
8766 return InputStringBucketArgument(self.name, self.type)
8767 return BucketPointerArgument(self.name, self.type)
8769 def WriteDestinationInitalizationValidation(self, file, func):
8770 """Overridden from Argument."""
8771 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8774 class BucketPointerArgument(PointerArgument):
8775 """A class that represents an bucket argument to a function."""
8777 def __init__(self, name, type):
8778 Argument.__init__(self, name, type)
8780 def AddCmdArgs(self, args):
8781 """Overridden from Argument."""
8782 pass
8784 def WriteGetCode(self, file):
8785 """Overridden from Argument."""
8786 file.Write(
8787 " %s %s = bucket->GetData(0, data_size);\n" %
8788 (self.type, self.name))
8790 def WriteValidationCode(self, file, func):
8791 """Overridden from Argument."""
8792 pass
8794 def GetImmediateVersion(self):
8795 """Overridden from Argument."""
8796 return None
8798 def WriteDestinationInitalizationValidation(self, file, func):
8799 """Overridden from Argument."""
8800 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8802 def GetLogArg(self):
8803 """Overridden from Argument."""
8804 return "static_cast<const void*>(%s)" % self.name
8807 class InputStringBucketArgument(Argument):
8808 """A string input argument where the string is passed in a bucket."""
8810 def __init__(self, name, type):
8811 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8813 def IsPointer(self):
8814 """Overridden from Argument."""
8815 return True
8817 def IsPointer2D(self):
8818 """Overridden from Argument."""
8819 return False
8822 class InputStringArrayBucketArgument(Argument):
8823 """A string array input argument where the strings are passed in a bucket."""
8825 def __init__(self, name, type):
8826 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8827 self._original_name = name
8829 def WriteGetCode(self, file):
8830 """Overridden from Argument."""
8831 code = """
8832 Bucket* bucket = GetBucket(c.%(name)s);
8833 if (!bucket) {
8834 return error::kInvalidArguments;
8836 GLsizei count = 0;
8837 std::vector<char*> strs;
8838 std::vector<GLint> len;
8839 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8840 return error::kInvalidArguments;
8842 const char** %(original_name)s =
8843 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8844 const GLint* length =
8845 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8846 (void)length;
8848 file.Write(code % {
8849 'name': self.name,
8850 'original_name': self._original_name,
8853 def GetValidArg(self, func):
8854 return "kNameBucketId"
8856 def GetValidGLArg(self, func):
8857 return "_"
8859 def IsPointer(self):
8860 """Overridden from Argument."""
8861 return True
8863 def IsPointer2D(self):
8864 """Overridden from Argument."""
8865 return True
8868 class ResourceIdArgument(Argument):
8869 """A class that represents a resource id argument to a function."""
8871 def __init__(self, name, type):
8872 match = re.match("(GLid\w+)", type)
8873 self.resource_type = match.group(1)[4:]
8874 if self.resource_type == "Sync":
8875 type = type.replace(match.group(1), "GLsync")
8876 else:
8877 type = type.replace(match.group(1), "GLuint")
8878 Argument.__init__(self, name, type)
8880 def WriteGetCode(self, file):
8881 """Overridden from Argument."""
8882 if self.type == "GLsync":
8883 my_type = "GLuint"
8884 else:
8885 my_type = self.type
8886 file.Write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8888 def GetValidArg(self, func):
8889 return "client_%s_id_" % self.resource_type.lower()
8891 def GetValidGLArg(self, func):
8892 if self.resource_type == "Sync":
8893 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8894 return "kService%sId" % self.resource_type
8897 class ResourceIdBindArgument(Argument):
8898 """Represents a resource id argument to a bind function."""
8900 def __init__(self, name, type):
8901 match = re.match("(GLidBind\w+)", type)
8902 self.resource_type = match.group(1)[8:]
8903 type = type.replace(match.group(1), "GLuint")
8904 Argument.__init__(self, name, type)
8906 def WriteGetCode(self, file):
8907 """Overridden from Argument."""
8908 code = """ %(type)s %(name)s = c.%(name)s;
8910 file.Write(code % {'type': self.type, 'name': self.name})
8912 def GetValidArg(self, func):
8913 return "client_%s_id_" % self.resource_type.lower()
8915 def GetValidGLArg(self, func):
8916 return "kService%sId" % self.resource_type
8919 class ResourceIdZeroArgument(Argument):
8920 """Represents a resource id argument to a function that can be zero."""
8922 def __init__(self, name, type):
8923 match = re.match("(GLidZero\w+)", type)
8924 self.resource_type = match.group(1)[8:]
8925 type = type.replace(match.group(1), "GLuint")
8926 Argument.__init__(self, name, type)
8928 def WriteGetCode(self, file):
8929 """Overridden from Argument."""
8930 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
8932 def GetValidArg(self, func):
8933 return "client_%s_id_" % self.resource_type.lower()
8935 def GetValidGLArg(self, func):
8936 return "kService%sId" % self.resource_type
8938 def GetNumInvalidValues(self, func):
8939 """returns the number of invalid values to be tested."""
8940 return 1
8942 def GetInvalidArg(self, index):
8943 """returns an invalid value by index."""
8944 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8947 class Function(object):
8948 """A class that represents a function."""
8950 type_handlers = {
8951 '': TypeHandler(),
8952 'Bind': BindHandler(),
8953 'Create': CreateHandler(),
8954 'Custom': CustomHandler(),
8955 'Data': DataHandler(),
8956 'Delete': DeleteHandler(),
8957 'DELn': DELnHandler(),
8958 'GENn': GENnHandler(),
8959 'GETn': GETnHandler(),
8960 'GLchar': GLcharHandler(),
8961 'GLcharN': GLcharNHandler(),
8962 'HandWritten': HandWrittenHandler(),
8963 'Is': IsHandler(),
8964 'Manual': ManualHandler(),
8965 'PUT': PUTHandler(),
8966 'PUTn': PUTnHandler(),
8967 'PUTSTR': PUTSTRHandler(),
8968 'PUTXn': PUTXnHandler(),
8969 'StateSet': StateSetHandler(),
8970 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8971 'StateSetFrontBack': StateSetFrontBackHandler(),
8972 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8973 'StateSetNamedParameter': StateSetNamedParameter(),
8974 'STRn': STRnHandler(),
8975 'Todo': TodoHandler(),
8978 def __init__(self, name, info):
8979 self.name = name
8980 self.original_name = info['original_name']
8982 self.original_args = self.ParseArgs(info['original_args'])
8984 if 'cmd_args' in info:
8985 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
8986 else:
8987 self.args_for_cmds = self.original_args[:]
8989 self.return_type = info['return_type']
8990 if self.return_type != 'void':
8991 self.return_arg = CreateArg(info['return_type'] + " result")
8992 else:
8993 self.return_arg = None
8995 self.num_pointer_args = sum(
8996 [1 for arg in self.args_for_cmds if arg.IsPointer()])
8997 if self.num_pointer_args > 0:
8998 for arg in reversed(self.original_args):
8999 if arg.IsPointer():
9000 self.last_original_pointer_arg = arg
9001 break
9002 else:
9003 self.last_original_pointer_arg = None
9004 self.info = info
9005 self.type_handler = self.type_handlers[info['type']]
9006 self.can_auto_generate = (self.num_pointer_args == 0 and
9007 info['return_type'] == "void")
9008 self.InitFunction()
9010 def ParseArgs(self, arg_string):
9011 """Parses a function arg string."""
9012 args = []
9013 parts = arg_string.split(',')
9014 for arg_string in parts:
9015 arg = CreateArg(arg_string)
9016 if arg:
9017 args.append(arg)
9018 return args
9020 def IsType(self, type_name):
9021 """Returns true if function is a certain type."""
9022 return self.info['type'] == type_name
9024 def InitFunction(self):
9025 """Creates command args and calls the init function for the type handler.
9027 Creates argument lists for command buffer commands, eg. self.cmd_args and
9028 self.init_args.
9029 Calls the type function initialization.
9030 Override to create different kind of command buffer command argument lists.
9032 self.cmd_args = []
9033 for arg in self.args_for_cmds:
9034 arg.AddCmdArgs(self.cmd_args)
9036 self.init_args = []
9037 for arg in self.args_for_cmds:
9038 arg.AddInitArgs(self.init_args)
9040 if self.return_arg:
9041 self.init_args.append(self.return_arg)
9043 self.type_handler.InitFunction(self)
9045 def IsImmediate(self):
9046 """Returns whether the function is immediate data function or not."""
9047 return False
9049 def IsUnsafe(self):
9050 """Returns whether the function has service side validation or not."""
9051 return self.GetInfo('unsafe', False)
9053 def GetInfo(self, name, default = None):
9054 """Returns a value from the function info for this function."""
9055 if name in self.info:
9056 return self.info[name]
9057 return default
9059 def GetValidArg(self, arg):
9060 """Gets a valid argument value for the parameter arg from the function info
9061 if one exists."""
9062 try:
9063 index = self.GetOriginalArgs().index(arg)
9064 except ValueError:
9065 return None
9067 valid_args = self.GetInfo('valid_args')
9068 if valid_args and str(index) in valid_args:
9069 return valid_args[str(index)]
9070 return None
9072 def AddInfo(self, name, value):
9073 """Adds an info."""
9074 self.info[name] = value
9076 def IsExtension(self):
9077 return self.GetInfo('extension') or self.GetInfo('extension_flag')
9079 def IsCoreGLFunction(self):
9080 return (not self.IsExtension() and
9081 not self.GetInfo('pepper_interface') and
9082 not self.IsUnsafe())
9084 def InPepperInterface(self, interface):
9085 ext = self.GetInfo('pepper_interface')
9086 if not interface.GetName():
9087 return self.IsCoreGLFunction()
9088 return ext == interface.GetName()
9090 def InAnyPepperExtension(self):
9091 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
9093 def GetErrorReturnString(self):
9094 if self.GetInfo("error_return"):
9095 return self.GetInfo("error_return")
9096 elif self.return_type == "GLboolean":
9097 return "GL_FALSE"
9098 elif "*" in self.return_type:
9099 return "NULL"
9100 return "0"
9102 def GetGLFunctionName(self):
9103 """Gets the function to call to execute GL for this command."""
9104 if self.GetInfo('decoder_func'):
9105 return self.GetInfo('decoder_func')
9106 return "gl%s" % self.original_name
9108 def GetGLTestFunctionName(self):
9109 gl_func_name = self.GetInfo('gl_test_func')
9110 if gl_func_name == None:
9111 gl_func_name = self.GetGLFunctionName()
9112 if gl_func_name.startswith("gl"):
9113 gl_func_name = gl_func_name[2:]
9114 else:
9115 gl_func_name = self.original_name
9116 return gl_func_name
9118 def GetDataTransferMethods(self):
9119 return self.GetInfo('data_transfer_methods',
9120 ['immediate' if self.num_pointer_args == 1 else 'shm'])
9122 def AddCmdArg(self, arg):
9123 """Adds a cmd argument to this function."""
9124 self.cmd_args.append(arg)
9126 def GetCmdArgs(self):
9127 """Gets the command args for this function."""
9128 return self.cmd_args
9130 def ClearCmdArgs(self):
9131 """Clears the command args for this function."""
9132 self.cmd_args = []
9134 def GetCmdConstants(self):
9135 """Gets the constants for this function."""
9136 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
9138 def GetInitArgs(self):
9139 """Gets the init args for this function."""
9140 return self.init_args
9142 def GetOriginalArgs(self):
9143 """Gets the original arguments to this function."""
9144 return self.original_args
9146 def GetLastOriginalArg(self):
9147 """Gets the last original argument to this function."""
9148 return self.original_args[len(self.original_args) - 1]
9150 def GetLastOriginalPointerArg(self):
9151 return self.last_original_pointer_arg
9153 def GetResourceIdArg(self):
9154 for arg in self.original_args:
9155 if hasattr(arg, 'resource_type'):
9156 return arg
9157 return None
9159 def _MaybePrependComma(self, arg_string, add_comma):
9160 """Adds a comma if arg_string is not empty and add_comma is true."""
9161 comma = ""
9162 if add_comma and len(arg_string):
9163 comma = ", "
9164 return "%s%s" % (comma, arg_string)
9166 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
9167 """Gets a list of arguments as they are in GL."""
9168 args = self.GetOriginalArgs()
9169 arg_string = ", ".join(
9170 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9171 return self._MaybePrependComma(arg_string, add_comma)
9173 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9174 """Gets the list of arguments as they are in GL."""
9175 args = self.GetOriginalArgs()
9176 arg_string = separator.join(
9177 ["%s%s" % (prefix, arg.name) for arg in args])
9178 return self._MaybePrependComma(arg_string, add_comma)
9180 def MakeTypedHelperArgString(self, prefix, add_comma = False):
9181 """Gets a list of typed GL arguments after removing unneeded arguments."""
9182 args = self.GetOriginalArgs()
9183 arg_string = ", ".join(
9184 ["%s %s%s" % (
9185 arg.type,
9186 prefix,
9187 arg.name,
9188 ) for arg in args if not arg.IsConstant()])
9189 return self._MaybePrependComma(arg_string, add_comma)
9191 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
9192 """Gets a list of GL arguments after removing unneeded arguments."""
9193 args = self.GetOriginalArgs()
9194 arg_string = separator.join(
9195 ["%s%s" % (prefix, arg.name)
9196 for arg in args if not arg.IsConstant()])
9197 return self._MaybePrependComma(arg_string, add_comma)
9199 def MakeTypedPepperArgString(self, prefix):
9200 """Gets a list of arguments as they need to be for Pepper."""
9201 if self.GetInfo("pepper_args"):
9202 return self.GetInfo("pepper_args")
9203 else:
9204 return self.MakeTypedOriginalArgString(prefix, False)
9206 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
9207 """Converts a C type name to the corresponding Pepper IDL type."""
9208 idltype = {
9209 'char*': '[out] str_t',
9210 'const GLchar* const*': '[out] cstr_t',
9211 'const char*': 'cstr_t',
9212 'const void*': 'mem_t',
9213 'void*': '[out] mem_t',
9214 'void**': '[out] mem_ptr_t',
9215 }.get(ctype, ctype)
9216 # We use "GLxxx_ptr_t" for "GLxxx*".
9217 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
9218 if matched:
9219 idltype = matched.group(2) + '_ptr_t'
9220 if not matched.group(1):
9221 idltype = '[out] ' + idltype
9222 # If an in/out specifier is not specified yet, prepend [in].
9223 if idltype[0] != '[':
9224 idltype = '[in] ' + idltype
9225 # Strip the in/out specifier for a return type.
9226 if is_for_return_type:
9227 idltype = re.sub(r'\[\w+\] ', '', idltype)
9228 return idltype
9230 def MakeTypedPepperIdlArgStrings(self):
9231 """Gets a list of arguments as they need to be for Pepper IDL."""
9232 args = self.GetOriginalArgs()
9233 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
9234 for arg in args]
9236 def GetPepperName(self):
9237 if self.GetInfo("pepper_name"):
9238 return self.GetInfo("pepper_name")
9239 return self.name
9241 def MakeTypedCmdArgString(self, prefix, add_comma = False):
9242 """Gets a typed list of arguments as they need to be for command buffers."""
9243 args = self.GetCmdArgs()
9244 arg_string = ", ".join(
9245 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9246 return self._MaybePrependComma(arg_string, add_comma)
9248 def MakeCmdArgString(self, prefix, add_comma = False):
9249 """Gets the list of arguments as they need to be for command buffers."""
9250 args = self.GetCmdArgs()
9251 arg_string = ", ".join(
9252 ["%s%s" % (prefix, arg.name) for arg in args])
9253 return self._MaybePrependComma(arg_string, add_comma)
9255 def MakeTypedInitString(self, prefix, add_comma = False):
9256 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9257 args = self.GetInitArgs()
9258 arg_string = ", ".join(
9259 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9260 return self._MaybePrependComma(arg_string, add_comma)
9262 def MakeInitString(self, prefix, add_comma = False):
9263 """Gets the list of arguments as they need to be for cmd Init/Set."""
9264 args = self.GetInitArgs()
9265 arg_string = ", ".join(
9266 ["%s%s" % (prefix, arg.name) for arg in args])
9267 return self._MaybePrependComma(arg_string, add_comma)
9269 def MakeLogArgString(self):
9270 """Makes a string of the arguments for the LOG macros"""
9271 args = self.GetOriginalArgs()
9272 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
9274 def WriteCommandDescription(self, file):
9275 """Writes a description of the command."""
9276 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
9278 def WriteHandlerValidation(self, file):
9279 """Writes validation code for the function."""
9280 for arg in self.GetOriginalArgs():
9281 arg.WriteValidationCode(file, self)
9282 self.WriteValidationCode(file)
9284 def WriteHandlerImplementation(self, file):
9285 """Writes the handler implementation for this command."""
9286 self.type_handler.WriteHandlerImplementation(self, file)
9288 def WriteValidationCode(self, file):
9289 """Writes the validation code for a command."""
9290 pass
9292 def WriteCmdFlag(self, file):
9293 """Writes the cmd cmd_flags constant."""
9294 flags = []
9295 # By default trace only at the highest level 3.
9296 trace_level = int(self.GetInfo('trace_level', default = 3))
9297 if trace_level not in xrange(0, 4):
9298 raise KeyError("Unhandled trace_level: %d" % trace_level)
9300 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
9302 if len(flags) > 0:
9303 cmd_flags = ' | '.join(flags)
9304 else:
9305 cmd_flags = 0
9307 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
9310 def WriteCmdArgFlag(self, file):
9311 """Writes the cmd kArgFlags constant."""
9312 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9314 def WriteCmdComputeSize(self, file):
9315 """Writes the ComputeSize function for the command."""
9316 file.Write(" static uint32_t ComputeSize() {\n")
9317 file.Write(
9318 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9319 file.Write(" }\n")
9320 file.Write("\n")
9322 def WriteCmdSetHeader(self, file):
9323 """Writes the cmd's SetHeader function."""
9324 file.Write(" void SetHeader() {\n")
9325 file.Write(" header.SetCmd<ValueType>();\n")
9326 file.Write(" }\n")
9327 file.Write("\n")
9329 def WriteCmdInit(self, file):
9330 """Writes the cmd's Init function."""
9331 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
9332 file.Write(" SetHeader();\n")
9333 args = self.GetCmdArgs()
9334 for arg in args:
9335 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
9336 file.Write(" }\n")
9337 file.Write("\n")
9339 def WriteCmdSet(self, file):
9340 """Writes the cmd's Set function."""
9341 copy_args = self.MakeCmdArgString("_", False)
9342 file.Write(" void* Set(void* cmd%s) {\n" %
9343 self.MakeTypedCmdArgString("_", True))
9344 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
9345 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
9346 file.Write(" }\n")
9347 file.Write("\n")
9349 def WriteStruct(self, file):
9350 self.type_handler.WriteStruct(self, file)
9352 def WriteDocs(self, file):
9353 self.type_handler.WriteDocs(self, file)
9355 def WriteCmdHelper(self, file):
9356 """Writes the cmd's helper."""
9357 self.type_handler.WriteCmdHelper(self, file)
9359 def WriteServiceImplementation(self, file):
9360 """Writes the service implementation for a command."""
9361 self.type_handler.WriteServiceImplementation(self, file)
9363 def WriteServiceUnitTest(self, file, *extras):
9364 """Writes the service implementation for a command."""
9365 self.type_handler.WriteServiceUnitTest(self, file, *extras)
9367 def WriteGLES2CLibImplementation(self, file):
9368 """Writes the GLES2 C Lib Implemention."""
9369 self.type_handler.WriteGLES2CLibImplementation(self, file)
9371 def WriteGLES2InterfaceHeader(self, file):
9372 """Writes the GLES2 Interface declaration."""
9373 self.type_handler.WriteGLES2InterfaceHeader(self, file)
9375 def WriteMojoGLES2ImplHeader(self, file):
9376 """Writes the Mojo GLES2 implementation header declaration."""
9377 self.type_handler.WriteMojoGLES2ImplHeader(self, file)
9379 def WriteMojoGLES2Impl(self, file):
9380 """Writes the Mojo GLES2 implementation declaration."""
9381 self.type_handler.WriteMojoGLES2Impl(self, file)
9383 def WriteGLES2InterfaceStub(self, file):
9384 """Writes the GLES2 Interface Stub declaration."""
9385 self.type_handler.WriteGLES2InterfaceStub(self, file)
9387 def WriteGLES2InterfaceStubImpl(self, file):
9388 """Writes the GLES2 Interface Stub declaration."""
9389 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
9391 def WriteGLES2ImplementationHeader(self, file):
9392 """Writes the GLES2 Implemention declaration."""
9393 self.type_handler.WriteGLES2ImplementationHeader(self, file)
9395 def WriteGLES2Implementation(self, file):
9396 """Writes the GLES2 Implemention definition."""
9397 self.type_handler.WriteGLES2Implementation(self, file)
9399 def WriteGLES2TraceImplementationHeader(self, file):
9400 """Writes the GLES2 Trace Implemention declaration."""
9401 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
9403 def WriteGLES2TraceImplementation(self, file):
9404 """Writes the GLES2 Trace Implemention definition."""
9405 self.type_handler.WriteGLES2TraceImplementation(self, file)
9407 def WriteGLES2Header(self, file):
9408 """Writes the GLES2 Implemention unit test."""
9409 self.type_handler.WriteGLES2Header(self, file)
9411 def WriteGLES2ImplementationUnitTest(self, file):
9412 """Writes the GLES2 Implemention unit test."""
9413 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
9415 def WriteDestinationInitalizationValidation(self, file):
9416 """Writes the client side destintion initialization validation."""
9417 self.type_handler.WriteDestinationInitalizationValidation(self, file)
9419 def WriteFormatTest(self, file):
9420 """Writes the cmd's format test."""
9421 self.type_handler.WriteFormatTest(self, file)
9424 class PepperInterface(object):
9425 """A class that represents a function."""
9427 def __init__(self, info):
9428 self.name = info["name"]
9429 self.dev = info["dev"]
9431 def GetName(self):
9432 return self.name
9434 def GetInterfaceName(self):
9435 upperint = ""
9436 dev = ""
9437 if self.name:
9438 upperint = "_" + self.name.upper()
9439 if self.dev:
9440 dev = "_DEV"
9441 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9443 def GetInterfaceString(self):
9444 dev = ""
9445 if self.dev:
9446 dev = "(Dev)"
9447 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9449 def GetStructName(self):
9450 dev = ""
9451 if self.dev:
9452 dev = "_Dev"
9453 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9456 class ImmediateFunction(Function):
9457 """A class that represnets an immediate function command."""
9459 def __init__(self, func):
9460 Function.__init__(
9461 self,
9462 "%sImmediate" % func.name,
9463 func.info)
9465 def InitFunction(self):
9466 # Override args in original_args and args_for_cmds with immediate versions
9467 # of the args.
9469 new_original_args = []
9470 for arg in self.original_args:
9471 new_arg = arg.GetImmediateVersion()
9472 if new_arg:
9473 new_original_args.append(new_arg)
9474 self.original_args = new_original_args
9476 new_args_for_cmds = []
9477 for arg in self.args_for_cmds:
9478 new_arg = arg.GetImmediateVersion()
9479 if new_arg:
9480 new_args_for_cmds.append(new_arg)
9482 self.args_for_cmds = new_args_for_cmds
9484 Function.InitFunction(self)
9486 def IsImmediate(self):
9487 return True
9489 def WriteCommandDescription(self, file):
9490 """Overridden from Function"""
9491 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9492 self.original_name)
9494 def WriteServiceImplementation(self, file):
9495 """Overridden from Function"""
9496 self.type_handler.WriteImmediateServiceImplementation(self, file)
9498 def WriteHandlerImplementation(self, file):
9499 """Overridden from Function"""
9500 self.type_handler.WriteImmediateHandlerImplementation(self, file)
9502 def WriteServiceUnitTest(self, file, *extras):
9503 """Writes the service implementation for a command."""
9504 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
9506 def WriteValidationCode(self, file):
9507 """Overridden from Function"""
9508 self.type_handler.WriteImmediateValidationCode(self, file)
9510 def WriteCmdArgFlag(self, file):
9511 """Overridden from Function"""
9512 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9514 def WriteCmdComputeSize(self, file):
9515 """Overridden from Function"""
9516 self.type_handler.WriteImmediateCmdComputeSize(self, file)
9518 def WriteCmdSetHeader(self, file):
9519 """Overridden from Function"""
9520 self.type_handler.WriteImmediateCmdSetHeader(self, file)
9522 def WriteCmdInit(self, file):
9523 """Overridden from Function"""
9524 self.type_handler.WriteImmediateCmdInit(self, file)
9526 def WriteCmdSet(self, file):
9527 """Overridden from Function"""
9528 self.type_handler.WriteImmediateCmdSet(self, file)
9530 def WriteCmdHelper(self, file):
9531 """Overridden from Function"""
9532 self.type_handler.WriteImmediateCmdHelper(self, file)
9534 def WriteFormatTest(self, file):
9535 """Overridden from Function"""
9536 self.type_handler.WriteImmediateFormatTest(self, file)
9539 class BucketFunction(Function):
9540 """A class that represnets a bucket version of a function command."""
9542 def __init__(self, func):
9543 Function.__init__(
9544 self,
9545 "%sBucket" % func.name,
9546 func.info)
9548 def InitFunction(self):
9549 # Override args in original_args and args_for_cmds with bucket versions
9550 # of the args.
9552 new_original_args = []
9553 for arg in self.original_args:
9554 new_arg = arg.GetBucketVersion()
9555 if new_arg:
9556 new_original_args.append(new_arg)
9557 self.original_args = new_original_args
9559 new_args_for_cmds = []
9560 for arg in self.args_for_cmds:
9561 new_arg = arg.GetBucketVersion()
9562 if new_arg:
9563 new_args_for_cmds.append(new_arg)
9565 self.args_for_cmds = new_args_for_cmds
9567 Function.InitFunction(self)
9569 def WriteCommandDescription(self, file):
9570 """Overridden from Function"""
9571 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9572 self.original_name)
9574 def WriteServiceImplementation(self, file):
9575 """Overridden from Function"""
9576 self.type_handler.WriteBucketServiceImplementation(self, file)
9578 def WriteHandlerImplementation(self, file):
9579 """Overridden from Function"""
9580 self.type_handler.WriteBucketHandlerImplementation(self, file)
9582 def WriteServiceUnitTest(self, file, *extras):
9583 """Overridden from Function"""
9584 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
9586 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9587 """Overridden from Function"""
9588 args = self.GetOriginalArgs()
9589 arg_string = separator.join(
9590 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9591 else arg.name) for arg in args])
9592 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9595 def CreateArg(arg_string):
9596 """Creates an Argument."""
9597 arg_parts = arg_string.split()
9598 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9599 return None
9600 # Is this a pointer argument?
9601 elif arg_string.find('*') >= 0:
9602 return PointerArgument(
9603 arg_parts[-1],
9604 " ".join(arg_parts[0:-1]))
9605 # Is this a resource argument? Must come after pointer check.
9606 elif arg_parts[0].startswith('GLidBind'):
9607 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9608 elif arg_parts[0].startswith('GLidZero'):
9609 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9610 elif arg_parts[0].startswith('GLid'):
9611 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9612 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9613 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9614 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9615 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9616 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9617 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9618 elif arg_parts[0].startswith('GLboolean'):
9619 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9620 elif arg_parts[0].startswith('GLintUniformLocation'):
9621 return UniformLocationArgument(arg_parts[-1])
9622 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9623 not arg_parts[0].startswith('GLintptr')):
9624 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9625 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9626 arg_parts[0].startswith('GLintptrNotNegative')):
9627 return SizeNotNegativeArgument(arg_parts[-1],
9628 " ".join(arg_parts[0:-1]),
9629 arg_parts[0][0:-11])
9630 elif arg_parts[0].startswith('GLsize'):
9631 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9632 else:
9633 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9636 class GLGenerator(object):
9637 """A class to generate GL command buffers."""
9639 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9641 def __init__(self, verbose):
9642 self.original_functions = []
9643 self.functions = []
9644 self.verbose = verbose
9645 self.errors = 0
9646 self.pepper_interfaces = []
9647 self.interface_info = {}
9648 self.generated_cpp_filenames = []
9650 for interface in _PEPPER_INTERFACES:
9651 interface = PepperInterface(interface)
9652 self.pepper_interfaces.append(interface)
9653 self.interface_info[interface.GetName()] = interface
9655 def AddFunction(self, func):
9656 """Adds a function."""
9657 self.functions.append(func)
9659 def GetFunctionInfo(self, name):
9660 """Gets a type info for the given function name."""
9661 if name in _FUNCTION_INFO:
9662 func_info = _FUNCTION_INFO[name].copy()
9663 else:
9664 func_info = {}
9666 if not 'type' in func_info:
9667 func_info['type'] = ''
9669 return func_info
9671 def Log(self, msg):
9672 """Prints something if verbose is true."""
9673 if self.verbose:
9674 print msg
9676 def Error(self, msg):
9677 """Prints an error."""
9678 print "Error: %s" % msg
9679 self.errors += 1
9681 def WriteLicense(self, file):
9682 """Writes the license."""
9683 file.Write(_LICENSE)
9685 def WriteNamespaceOpen(self, file):
9686 """Writes the code for the namespace."""
9687 file.Write("namespace gpu {\n")
9688 file.Write("namespace gles2 {\n")
9689 file.Write("\n")
9691 def WriteNamespaceClose(self, file):
9692 """Writes the code to close the namespace."""
9693 file.Write("} // namespace gles2\n")
9694 file.Write("} // namespace gpu\n")
9695 file.Write("\n")
9697 def ParseGLH(self, filename):
9698 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9699 f = open(filename, "r")
9700 functions = f.read()
9701 f.close()
9702 for line in functions.splitlines():
9703 match = self._function_re.match(line)
9704 if match:
9705 func_name = match.group(2)[2:]
9706 func_info = self.GetFunctionInfo(func_name)
9707 if func_info['type'] == 'Noop':
9708 continue
9710 parsed_func_info = {
9711 'original_name': func_name,
9712 'original_args': match.group(3),
9713 'return_type': match.group(1).strip(),
9716 for k in parsed_func_info.keys():
9717 if not k in func_info:
9718 func_info[k] = parsed_func_info[k]
9720 f = Function(func_name, func_info)
9721 self.original_functions.append(f)
9723 #for arg in f.GetOriginalArgs():
9724 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9725 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9727 gen_cmd = f.GetInfo('gen_cmd')
9728 if gen_cmd == True or gen_cmd == None:
9729 if f.type_handler.NeedsDataTransferFunction(f):
9730 methods = f.GetDataTransferMethods()
9731 if 'immediate' in methods:
9732 self.AddFunction(ImmediateFunction(f))
9733 if 'bucket' in methods:
9734 self.AddFunction(BucketFunction(f))
9735 if 'shm' in methods:
9736 self.AddFunction(f)
9737 else:
9738 self.AddFunction(f)
9740 self.Log("Auto Generated Functions : %d" %
9741 len([f for f in self.functions if f.can_auto_generate or
9742 (not f.IsType('') and not f.IsType('Custom') and
9743 not f.IsType('Todo'))]))
9745 funcs = [f for f in self.functions if not f.can_auto_generate and
9746 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9747 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9749 for f in funcs:
9750 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9752 def WriteCommandIds(self, filename):
9753 """Writes the command buffer format"""
9754 file = CHeaderWriter(filename)
9755 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9756 id = 256
9757 for func in self.functions:
9758 file.Write(" %-60s /* %d */ \\\n" %
9759 ("OP(%s)" % func.name, id))
9760 id += 1
9761 file.Write("\n")
9763 file.Write("enum CommandId {\n")
9764 file.Write(" kStartPoint = cmd::kLastCommonId, "
9765 "// All GLES2 commands start after this.\n")
9766 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9767 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9768 file.Write("#undef GLES2_CMD_OP\n")
9769 file.Write(" kNumCommands\n")
9770 file.Write("};\n")
9771 file.Write("\n")
9772 file.Close()
9773 self.generated_cpp_filenames.append(file.filename)
9775 def WriteFormat(self, filename):
9776 """Writes the command buffer format"""
9777 file = CHeaderWriter(filename)
9778 # Forward declaration of a few enums used in constant argument
9779 # to avoid including GL header files.
9780 enum_defines = {
9781 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9782 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9784 file.Write('\n')
9785 for enum in enum_defines:
9786 file.Write("#define %s %s\n" % (enum, enum_defines[enum]))
9787 file.Write('\n')
9788 for func in self.functions:
9789 if True:
9790 #gen_cmd = func.GetInfo('gen_cmd')
9791 #if gen_cmd == True or gen_cmd == None:
9792 func.WriteStruct(file)
9793 file.Write("\n")
9794 file.Close()
9795 self.generated_cpp_filenames.append(file.filename)
9797 def WriteDocs(self, filename):
9798 """Writes the command buffer doc version of the commands"""
9799 file = CWriter(filename)
9800 for func in self.functions:
9801 if True:
9802 #gen_cmd = func.GetInfo('gen_cmd')
9803 #if gen_cmd == True or gen_cmd == None:
9804 func.WriteDocs(file)
9805 file.Write("\n")
9806 file.Close()
9807 self.generated_cpp_filenames.append(file.filename)
9809 def WriteFormatTest(self, filename):
9810 """Writes the command buffer format test."""
9811 file = CHeaderWriter(
9812 filename,
9813 "// This file contains unit tests for gles2 commmands\n"
9814 "// It is included by gles2_cmd_format_test.cc\n"
9815 "\n")
9817 for func in self.functions:
9818 if True:
9819 #gen_cmd = func.GetInfo('gen_cmd')
9820 #if gen_cmd == True or gen_cmd == None:
9821 func.WriteFormatTest(file)
9823 file.Close()
9824 self.generated_cpp_filenames.append(file.filename)
9826 def WriteCmdHelperHeader(self, filename):
9827 """Writes the gles2 command helper."""
9828 file = CHeaderWriter(filename)
9830 for func in self.functions:
9831 if True:
9832 #gen_cmd = func.GetInfo('gen_cmd')
9833 #if gen_cmd == True or gen_cmd == None:
9834 func.WriteCmdHelper(file)
9836 file.Close()
9837 self.generated_cpp_filenames.append(file.filename)
9839 def WriteServiceContextStateHeader(self, filename):
9840 """Writes the service context state header."""
9841 file = CHeaderWriter(
9842 filename,
9843 "// It is included by context_state.h\n")
9844 file.Write("struct EnableFlags {\n")
9845 file.Write(" EnableFlags();\n")
9846 for capability in _CAPABILITY_FLAGS:
9847 file.Write(" bool %s;\n" % capability['name'])
9848 file.Write(" bool cached_%s;\n" % capability['name'])
9849 file.Write("};\n\n")
9851 for state_name in sorted(_STATES.keys()):
9852 state = _STATES[state_name]
9853 for item in state['states']:
9854 if isinstance(item['default'], list):
9855 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
9856 len(item['default'])))
9857 else:
9858 file.Write("%s %s;\n" % (item['type'], item['name']))
9860 if item.get('cached', False):
9861 if isinstance(item['default'], list):
9862 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9863 len(item['default'])))
9864 else:
9865 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
9867 file.Write("\n")
9869 file.Write("""
9870 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9871 switch (cap) {
9872 """)
9873 for capability in _CAPABILITY_FLAGS:
9874 file.Write("""\
9875 case GL_%s:
9876 """ % capability['name'].upper())
9877 file.Write("""\
9878 if (enable_flags.cached_%(name)s == enable &&
9879 !ignore_cached_state)
9880 return;
9881 enable_flags.cached_%(name)s = enable;
9882 break;
9883 """ % capability)
9885 file.Write("""\
9886 default:
9887 NOTREACHED();
9888 return;
9890 if (enable)
9891 glEnable(cap);
9892 else
9893 glDisable(cap);
9895 """)
9897 file.Close()
9898 self.generated_cpp_filenames.append(file.filename)
9900 def WriteClientContextStateHeader(self, filename):
9901 """Writes the client context state header."""
9902 file = CHeaderWriter(
9903 filename,
9904 "// It is included by client_context_state.h\n")
9905 file.Write("struct EnableFlags {\n")
9906 file.Write(" EnableFlags();\n")
9907 for capability in _CAPABILITY_FLAGS:
9908 file.Write(" bool %s;\n" % capability['name'])
9909 file.Write("};\n\n")
9911 file.Close()
9912 self.generated_cpp_filenames.append(file.filename)
9914 def WriteContextStateGetters(self, file, class_name):
9915 """Writes the state getters."""
9916 for gl_type in ["GLint", "GLfloat"]:
9917 file.Write("""
9918 bool %s::GetStateAs%s(
9919 GLenum pname, %s* params, GLsizei* num_written) const {
9920 switch (pname) {
9921 """ % (class_name, gl_type, gl_type))
9922 for state_name in sorted(_STATES.keys()):
9923 state = _STATES[state_name]
9924 if 'enum' in state:
9925 file.Write(" case %s:\n" % state['enum'])
9926 file.Write(" *num_written = %d;\n" % len(state['states']))
9927 file.Write(" if (params) {\n")
9928 for ndx,item in enumerate(state['states']):
9929 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9930 (ndx, gl_type, item['name']))
9931 file.Write(" }\n")
9932 file.Write(" return true;\n")
9933 else:
9934 for item in state['states']:
9935 file.Write(" case %s:\n" % item['enum'])
9936 if isinstance(item['default'], list):
9937 item_len = len(item['default'])
9938 file.Write(" *num_written = %d;\n" % item_len)
9939 file.Write(" if (params) {\n")
9940 if item['type'] == gl_type:
9941 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9942 (item['name'], item['type'], item_len))
9943 else:
9944 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9945 item_len)
9946 file.Write(" params[i] = %s;\n" %
9947 (GetGLGetTypeConversion(gl_type, item['type'],
9948 "%s[i]" % item['name'])))
9949 file.Write(" }\n");
9950 else:
9951 file.Write(" *num_written = 1;\n")
9952 file.Write(" if (params) {\n")
9953 file.Write(" params[0] = %s;\n" %
9954 (GetGLGetTypeConversion(gl_type, item['type'],
9955 item['name'])))
9956 file.Write(" }\n")
9957 file.Write(" return true;\n")
9958 for capability in _CAPABILITY_FLAGS:
9959 file.Write(" case GL_%s:\n" % capability['name'].upper())
9960 file.Write(" *num_written = 1;\n")
9961 file.Write(" if (params) {\n")
9962 file.Write(
9963 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9964 (gl_type, capability['name']))
9965 file.Write(" }\n")
9966 file.Write(" return true;\n")
9967 file.Write(""" default:
9968 return false;
9971 """)
9973 def WriteServiceContextStateImpl(self, filename):
9974 """Writes the context state service implementation."""
9975 file = CHeaderWriter(
9976 filename,
9977 "// It is included by context_state.cc\n")
9978 code = []
9979 for capability in _CAPABILITY_FLAGS:
9980 code.append("%s(%s)" %
9981 (capability['name'],
9982 ('false', 'true')['default' in capability]))
9983 code.append("cached_%s(%s)" %
9984 (capability['name'],
9985 ('false', 'true')['default' in capability]))
9986 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9987 ",\n ".join(code))
9988 file.Write("\n")
9990 file.Write("void ContextState::Initialize() {\n")
9991 for state_name in sorted(_STATES.keys()):
9992 state = _STATES[state_name]
9993 for item in state['states']:
9994 if isinstance(item['default'], list):
9995 for ndx, value in enumerate(item['default']):
9996 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
9997 else:
9998 file.Write(" %s = %s;\n" % (item['name'], item['default']))
9999 if item.get('cached', False):
10000 if isinstance(item['default'], list):
10001 for ndx, value in enumerate(item['default']):
10002 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
10003 else:
10004 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
10005 file.Write("}\n")
10007 file.Write("""
10008 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10009 """)
10010 def WriteCapabilities(test_prev, es3_caps):
10011 for capability in _CAPABILITY_FLAGS:
10012 capability_name = capability['name']
10013 capability_es3 = 'es3' in capability and capability['es3'] == True
10014 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
10015 continue
10016 if test_prev:
10017 file.Write(""" if (prev_state->enable_flags.cached_%s !=
10018 enable_flags.cached_%s) {\n""" %
10019 (capability_name, capability_name))
10020 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10021 (capability_name.upper(), capability_name))
10022 if test_prev:
10023 file.Write(" }")
10025 file.Write(" if (prev_state) {")
10026 WriteCapabilities(True, False)
10027 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10028 WriteCapabilities(True, True)
10029 file.Write(" }\n")
10030 file.Write(" } else {")
10031 WriteCapabilities(False, False)
10032 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10033 WriteCapabilities(False, True)
10034 file.Write(" }\n")
10035 file.Write(" }")
10037 file.Write("""}
10039 void ContextState::InitState(const ContextState *prev_state) const {
10040 """)
10042 def WriteStates(test_prev):
10043 # We need to sort the keys so the expectations match
10044 for state_name in sorted(_STATES.keys()):
10045 state = _STATES[state_name]
10046 if state['type'] == 'FrontBack':
10047 num_states = len(state['states'])
10048 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10049 if test_prev:
10050 file.Write(" if (")
10051 args = []
10052 for place, item in enumerate(group):
10053 item_name = CachedStateName(item)
10054 args.append('%s' % item_name)
10055 if test_prev:
10056 if place > 0:
10057 file.Write(' ||\n')
10058 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
10059 if test_prev:
10060 file.Write(")\n")
10061 file.Write(
10062 " gl%s(%s, %s);\n" %
10063 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10064 elif state['type'] == 'NamedParameter':
10065 for item in state['states']:
10066 item_name = CachedStateName(item)
10068 if 'extension_flag' in item:
10069 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
10070 item['extension_flag'])
10071 if test_prev:
10072 if isinstance(item['default'], list):
10073 file.Write(" if (memcmp(prev_state->%s, %s, "
10074 "sizeof(%s) * %d)) {\n" %
10075 (item_name, item_name, item['type'],
10076 len(item['default'])))
10077 else:
10078 file.Write(" if (prev_state->%s != %s) {\n " %
10079 (item_name, item_name))
10080 if 'gl_version_flag' in item:
10081 item_name = item['gl_version_flag']
10082 inverted = ''
10083 if item_name[0] == '!':
10084 inverted = '!'
10085 item_name = item_name[1:]
10086 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10087 (inverted, item_name))
10088 file.Write(" gl%s(%s, %s);\n" %
10089 (state['func'],
10090 (item['enum_set']
10091 if 'enum_set' in item else item['enum']),
10092 item['name']))
10093 if 'gl_version_flag' in item:
10094 file.Write(" }\n")
10095 if test_prev:
10096 if 'extension_flag' in item:
10097 file.Write(" ")
10098 file.Write(" }")
10099 if 'extension_flag' in item:
10100 file.Write(" }")
10101 else:
10102 if 'extension_flag' in state:
10103 file.Write(" if (feature_info_->feature_flags().%s)\n " %
10104 state['extension_flag'])
10105 if test_prev:
10106 file.Write(" if (")
10107 args = []
10108 for place, item in enumerate(state['states']):
10109 item_name = CachedStateName(item)
10110 args.append('%s' % item_name)
10111 if test_prev:
10112 if place > 0:
10113 file.Write(' ||\n')
10114 file.Write("(%s != prev_state->%s)" %
10115 (item_name, item_name))
10116 if test_prev:
10117 file.Write(" )\n")
10118 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
10120 file.Write(" if (prev_state) {")
10121 WriteStates(True)
10122 file.Write(" } else {")
10123 WriteStates(False)
10124 file.Write(" }")
10125 file.Write("}\n")
10127 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
10128 switch (cap) {
10129 """)
10130 for capability in _CAPABILITY_FLAGS:
10131 file.Write(" case GL_%s:\n" % capability['name'].upper())
10132 file.Write(" return enable_flags.%s;\n" % capability['name'])
10133 file.Write(""" default:
10134 NOTREACHED();
10135 return false;
10138 """)
10140 self.WriteContextStateGetters(file, "ContextState")
10141 file.Close()
10142 self.generated_cpp_filenames.append(file.filename)
10144 def WriteClientContextStateImpl(self, filename):
10145 """Writes the context state client side implementation."""
10146 file = CHeaderWriter(
10147 filename,
10148 "// It is included by client_context_state.cc\n")
10149 code = []
10150 for capability in _CAPABILITY_FLAGS:
10151 code.append("%s(%s)" %
10152 (capability['name'],
10153 ('false', 'true')['default' in capability]))
10154 file.Write(
10155 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10156 ",\n ".join(code))
10157 file.Write("\n")
10159 file.Write("""
10160 bool ClientContextState::SetCapabilityState(
10161 GLenum cap, bool enabled, bool* changed) {
10162 *changed = false;
10163 switch (cap) {
10164 """)
10165 for capability in _CAPABILITY_FLAGS:
10166 file.Write(" case GL_%s:\n" % capability['name'].upper())
10167 file.Write(""" if (enable_flags.%(name)s != enabled) {
10168 *changed = true;
10169 enable_flags.%(name)s = enabled;
10171 return true;
10172 """ % capability)
10173 file.Write(""" default:
10174 return false;
10177 """)
10178 file.Write("""bool ClientContextState::GetEnabled(
10179 GLenum cap, bool* enabled) const {
10180 switch (cap) {
10181 """)
10182 for capability in _CAPABILITY_FLAGS:
10183 file.Write(" case GL_%s:\n" % capability['name'].upper())
10184 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
10185 file.Write(" return true;\n")
10186 file.Write(""" default:
10187 return false;
10190 """)
10191 file.Close()
10192 self.generated_cpp_filenames.append(file.filename)
10194 def WriteServiceImplementation(self, filename):
10195 """Writes the service decorder implementation."""
10196 file = CHeaderWriter(
10197 filename,
10198 "// It is included by gles2_cmd_decoder.cc\n")
10200 for func in self.functions:
10201 if True:
10202 #gen_cmd = func.GetInfo('gen_cmd')
10203 #if gen_cmd == True or gen_cmd == None:
10204 func.WriteServiceImplementation(file)
10206 file.Write("""
10207 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10208 switch (cap) {
10209 """)
10210 for capability in _CAPABILITY_FLAGS:
10211 file.Write(" case GL_%s:\n" % capability['name'].upper())
10212 if 'state_flag' in capability:
10214 file.Write("""\
10215 state_.enable_flags.%(name)s = enabled;
10216 if (state_.enable_flags.cached_%(name)s != enabled
10217 || state_.ignore_cached_state) {
10218 %(state_flag)s = true;
10220 return false;
10221 """ % capability)
10222 else:
10223 file.Write("""\
10224 state_.enable_flags.%(name)s = enabled;
10225 if (state_.enable_flags.cached_%(name)s != enabled
10226 || state_.ignore_cached_state) {
10227 state_.enable_flags.cached_%(name)s = enabled;
10228 return true;
10230 return false;
10231 """ % capability)
10232 file.Write(""" default:
10233 NOTREACHED();
10234 return false;
10237 """)
10238 file.Close()
10239 self.generated_cpp_filenames.append(file.filename)
10241 def WriteServiceUnitTests(self, filename):
10242 """Writes the service decorder unit tests."""
10243 num_tests = len(self.functions)
10244 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
10245 count = 0
10246 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
10247 count += 1
10248 name = filename % count
10249 file = CHeaderWriter(
10250 name,
10251 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
10252 test_name = 'GLES2DecoderTest%d' % count
10253 end = test_num + FUNCTIONS_PER_FILE
10254 if end > num_tests:
10255 end = num_tests
10256 for idx in range(test_num, end):
10257 func = self.functions[idx]
10259 # Do any filtering of the functions here, so that the functions
10260 # will not move between the numbered files if filtering properties
10261 # are changed.
10262 if func.GetInfo('extension_flag'):
10263 continue
10265 if True:
10266 #gen_cmd = func.GetInfo('gen_cmd')
10267 #if gen_cmd == True or gen_cmd == None:
10268 if func.GetInfo('unit_test') == False:
10269 file.Write("// TODO(gman): %s\n" % func.name)
10270 else:
10271 func.WriteServiceUnitTest(file, {
10272 'test_name': test_name
10274 file.Close()
10275 self.generated_cpp_filenames.append(file.filename)
10276 file = CHeaderWriter(
10277 filename % 0,
10278 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
10279 file.Write(
10280 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10281 bool es3_capable) {""")
10282 for capability in _CAPABILITY_FLAGS:
10283 capability_es3 = 'es3' in capability and capability['es3'] == True
10284 if not capability_es3:
10285 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10286 (capability['name'].upper(),
10287 ('false', 'true')['default' in capability]))
10289 file.Write(" if (es3_capable) {")
10290 for capability in _CAPABILITY_FLAGS:
10291 capability_es3 = 'es3' in capability and capability['es3'] == True
10292 if capability_es3:
10293 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10294 (capability['name'].upper(),
10295 ('false', 'true')['default' in capability]))
10296 file.Write(""" }
10299 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10300 """)
10302 # We need to sort the keys so the expectations match
10303 for state_name in sorted(_STATES.keys()):
10304 state = _STATES[state_name]
10305 if state['type'] == 'FrontBack':
10306 num_states = len(state['states'])
10307 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10308 args = []
10309 for item in group:
10310 if 'expected' in item:
10311 args.append(item['expected'])
10312 else:
10313 args.append(item['default'])
10314 file.Write(
10315 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10316 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10317 file.Write(" .Times(1)\n")
10318 file.Write(" .RetiresOnSaturation();\n")
10319 elif state['type'] == 'NamedParameter':
10320 for item in state['states']:
10321 if 'extension_flag' in item:
10322 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10323 item['extension_flag'])
10324 file.Write(" ")
10325 expect_value = item['default']
10326 if isinstance(expect_value, list):
10327 # TODO: Currently we do not check array values.
10328 expect_value = "_"
10330 file.Write(
10331 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10332 (state['func'],
10333 (item['enum_set']
10334 if 'enum_set' in item else item['enum']),
10335 expect_value))
10336 file.Write(" .Times(1)\n")
10337 file.Write(" .RetiresOnSaturation();\n")
10338 if 'extension_flag' in item:
10339 file.Write(" }\n")
10340 else:
10341 if 'extension_flag' in state:
10342 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10343 state['extension_flag'])
10344 file.Write(" ")
10345 args = []
10346 for item in state['states']:
10347 if 'expected' in item:
10348 args.append(item['expected'])
10349 else:
10350 args.append(item['default'])
10351 # TODO: Currently we do not check array values.
10352 args = ["_" if isinstance(arg, list) else arg for arg in args]
10353 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10354 (state['func'], ", ".join(args)))
10355 file.Write(" .Times(1)\n")
10356 file.Write(" .RetiresOnSaturation();\n")
10357 if 'extension_flag' in state:
10358 file.Write(" }\n")
10359 file.Write("""}
10360 """)
10361 file.Close()
10362 self.generated_cpp_filenames.append(file.filename)
10364 def WriteServiceUnitTestsForExtensions(self, filename):
10365 """Writes the service decorder unit tests for functions with extension_flag.
10367 The functions are special in that they need a specific unit test
10368 baseclass to turn on the extension.
10370 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
10371 file = CHeaderWriter(
10372 filename,
10373 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
10374 for func in functions:
10375 if True:
10376 if func.GetInfo('unit_test') == False:
10377 file.Write("// TODO(gman): %s\n" % func.name)
10378 else:
10379 extension = ToCamelCase(
10380 ToGLExtensionString(func.GetInfo('extension_flag')))
10381 func.WriteServiceUnitTest(file, {
10382 'test_name': 'GLES2DecoderTestWith%s' % extension
10385 file.Close()
10386 self.generated_cpp_filenames.append(file.filename)
10388 def WriteGLES2Header(self, filename):
10389 """Writes the GLES2 header."""
10390 file = CHeaderWriter(
10391 filename,
10392 "// This file contains Chromium-specific GLES2 declarations.\n\n")
10394 for func in self.original_functions:
10395 func.WriteGLES2Header(file)
10397 file.Write("\n")
10398 file.Close()
10399 self.generated_cpp_filenames.append(file.filename)
10401 def WriteGLES2CLibImplementation(self, filename):
10402 """Writes the GLES2 c lib implementation."""
10403 file = CHeaderWriter(
10404 filename,
10405 "// These functions emulate GLES2 over command buffers.\n")
10407 for func in self.original_functions:
10408 func.WriteGLES2CLibImplementation(file)
10410 file.Write("""
10411 namespace gles2 {
10413 extern const NameToFunc g_gles2_function_table[] = {
10414 """)
10415 for func in self.original_functions:
10416 file.Write(
10417 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10418 (func.name, func.name))
10419 file.Write(""" { NULL, NULL, },
10422 } // namespace gles2
10423 """)
10424 file.Close()
10425 self.generated_cpp_filenames.append(file.filename)
10427 def WriteGLES2InterfaceHeader(self, filename):
10428 """Writes the GLES2 interface header."""
10429 file = CHeaderWriter(
10430 filename,
10431 "// This file is included by gles2_interface.h to declare the\n"
10432 "// GL api functions.\n")
10433 for func in self.original_functions:
10434 func.WriteGLES2InterfaceHeader(file)
10435 file.Close()
10436 self.generated_cpp_filenames.append(file.filename)
10438 def WriteMojoGLES2ImplHeader(self, filename):
10439 """Writes the Mojo GLES2 implementation header."""
10440 file = CHeaderWriter(
10441 filename,
10442 "// This file is included by gles2_interface.h to declare the\n"
10443 "// GL api functions.\n")
10445 code = """
10446 #include "gpu/command_buffer/client/gles2_interface.h"
10447 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10449 namespace mojo {
10451 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10452 public:
10453 explicit MojoGLES2Impl(MojoGLES2Context context) {
10454 context_ = context;
10456 ~MojoGLES2Impl() override {}
10458 file.Write(code);
10459 for func in self.original_functions:
10460 func.WriteMojoGLES2ImplHeader(file)
10461 code = """
10462 private:
10463 MojoGLES2Context context_;
10466 } // namespace mojo
10468 file.Write(code);
10469 file.Close()
10470 self.generated_cpp_filenames.append(file.filename)
10472 def WriteMojoGLES2Impl(self, filename):
10473 """Writes the Mojo GLES2 implementation."""
10474 file = CWriter(filename)
10475 file.Write(_LICENSE)
10476 file.Write(_DO_NOT_EDIT_WARNING)
10478 code = """
10479 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10481 #include "base/logging.h"
10482 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10483 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10484 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10485 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10486 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10487 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10488 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10489 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10490 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10492 namespace mojo {
10495 file.Write(code);
10496 for func in self.original_functions:
10497 func.WriteMojoGLES2Impl(file)
10498 code = """
10500 } // namespace mojo
10502 file.Write(code);
10503 file.Close()
10504 self.generated_cpp_filenames.append(file.filename)
10506 def WriteGLES2InterfaceStub(self, filename):
10507 """Writes the GLES2 interface stub header."""
10508 file = CHeaderWriter(
10509 filename,
10510 "// This file is included by gles2_interface_stub.h.\n")
10511 for func in self.original_functions:
10512 func.WriteGLES2InterfaceStub(file)
10513 file.Close()
10514 self.generated_cpp_filenames.append(file.filename)
10516 def WriteGLES2InterfaceStubImpl(self, filename):
10517 """Writes the GLES2 interface header."""
10518 file = CHeaderWriter(
10519 filename,
10520 "// This file is included by gles2_interface_stub.cc.\n")
10521 for func in self.original_functions:
10522 func.WriteGLES2InterfaceStubImpl(file)
10523 file.Close()
10524 self.generated_cpp_filenames.append(file.filename)
10526 def WriteGLES2ImplementationHeader(self, filename):
10527 """Writes the GLES2 Implementation header."""
10528 file = CHeaderWriter(
10529 filename,
10530 "// This file is included by gles2_implementation.h to declare the\n"
10531 "// GL api functions.\n")
10532 for func in self.original_functions:
10533 func.WriteGLES2ImplementationHeader(file)
10534 file.Close()
10535 self.generated_cpp_filenames.append(file.filename)
10537 def WriteGLES2Implementation(self, filename):
10538 """Writes the GLES2 Implementation."""
10539 file = CHeaderWriter(
10540 filename,
10541 "// This file is included by gles2_implementation.cc to define the\n"
10542 "// GL api functions.\n")
10543 for func in self.original_functions:
10544 func.WriteGLES2Implementation(file)
10545 file.Close()
10546 self.generated_cpp_filenames.append(file.filename)
10548 def WriteGLES2TraceImplementationHeader(self, filename):
10549 """Writes the GLES2 Trace Implementation header."""
10550 file = CHeaderWriter(
10551 filename,
10552 "// This file is included by gles2_trace_implementation.h\n")
10553 for func in self.original_functions:
10554 func.WriteGLES2TraceImplementationHeader(file)
10555 file.Close()
10556 self.generated_cpp_filenames.append(file.filename)
10558 def WriteGLES2TraceImplementation(self, filename):
10559 """Writes the GLES2 Trace Implementation."""
10560 file = CHeaderWriter(
10561 filename,
10562 "// This file is included by gles2_trace_implementation.cc\n")
10563 for func in self.original_functions:
10564 func.WriteGLES2TraceImplementation(file)
10565 file.Close()
10566 self.generated_cpp_filenames.append(file.filename)
10568 def WriteGLES2ImplementationUnitTests(self, filename):
10569 """Writes the GLES2 helper header."""
10570 file = CHeaderWriter(
10571 filename,
10572 "// This file is included by gles2_implementation.h to declare the\n"
10573 "// GL api functions.\n")
10574 for func in self.original_functions:
10575 func.WriteGLES2ImplementationUnitTest(file)
10576 file.Close()
10577 self.generated_cpp_filenames.append(file.filename)
10579 def WriteServiceUtilsHeader(self, filename):
10580 """Writes the gles2 auto generated utility header."""
10581 file = CHeaderWriter(filename)
10582 for name in sorted(_NAMED_TYPE_INFO.keys()):
10583 named_type = NamedType(_NAMED_TYPE_INFO[name])
10584 if named_type.IsConstant():
10585 continue
10586 file.Write("ValueValidator<%s> %s;\n" %
10587 (named_type.GetType(), ToUnderscore(name)))
10588 file.Write("\n")
10589 file.Close()
10590 self.generated_cpp_filenames.append(file.filename)
10592 def WriteServiceUtilsImplementation(self, filename):
10593 """Writes the gles2 auto generated utility implementation."""
10594 file = CHeaderWriter(filename)
10595 names = sorted(_NAMED_TYPE_INFO.keys())
10596 for name in names:
10597 named_type = NamedType(_NAMED_TYPE_INFO[name])
10598 if named_type.IsConstant():
10599 continue
10600 if named_type.GetValidValues():
10601 file.Write("static const %s valid_%s_table[] = {\n" %
10602 (named_type.GetType(), ToUnderscore(name)))
10603 for value in named_type.GetValidValues():
10604 file.Write(" %s,\n" % value)
10605 file.Write("};\n")
10606 file.Write("\n")
10607 if named_type.GetValidValuesES3():
10608 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10609 (named_type.GetType(), ToUnderscore(name)))
10610 for value in named_type.GetValidValuesES3():
10611 file.Write(" %s,\n" % value)
10612 file.Write("};\n")
10613 file.Write("\n")
10614 if named_type.GetDeprecatedValuesES3():
10615 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10616 (named_type.GetType(), ToUnderscore(name)))
10617 for value in named_type.GetDeprecatedValuesES3():
10618 file.Write(" %s,\n" % value)
10619 file.Write("};\n")
10620 file.Write("\n")
10621 file.Write("Validators::Validators()")
10622 pre = ' : '
10623 for count, name in enumerate(names):
10624 named_type = NamedType(_NAMED_TYPE_INFO[name])
10625 if named_type.IsConstant():
10626 continue
10627 if named_type.GetValidValues():
10628 code = """%(pre)s%(name)s(
10629 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10630 else:
10631 code = "%(pre)s%(name)s()"
10632 file.Write(code % {
10633 'name': ToUnderscore(name),
10634 'pre': pre,
10636 pre = ',\n '
10637 file.Write(" {\n");
10638 file.Write("}\n\n");
10640 file.Write("void Validators::UpdateValuesES3() {\n")
10641 for name in names:
10642 named_type = NamedType(_NAMED_TYPE_INFO[name])
10643 if named_type.GetDeprecatedValuesES3():
10644 code = """ %(name)s.RemoveValues(
10645 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10647 file.Write(code % {
10648 'name': ToUnderscore(name),
10650 if named_type.GetValidValuesES3():
10651 code = """ %(name)s.AddValues(
10652 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10654 file.Write(code % {
10655 'name': ToUnderscore(name),
10657 file.Write("}\n\n");
10658 file.Close()
10659 self.generated_cpp_filenames.append(file.filename)
10661 def WriteCommonUtilsHeader(self, filename):
10662 """Writes the gles2 common utility header."""
10663 file = CHeaderWriter(filename)
10664 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10665 for type_info in type_infos:
10666 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10667 file.Write("static std::string GetString%s(uint32_t value);\n" %
10668 type_info)
10669 file.Write("\n")
10670 file.Close()
10671 self.generated_cpp_filenames.append(file.filename)
10673 def WriteCommonUtilsImpl(self, filename):
10674 """Writes the gles2 common utility header."""
10675 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10676 dict = {}
10677 for fname in ['third_party/khronos/GLES2/gl2.h',
10678 'third_party/khronos/GLES2/gl2ext.h',
10679 'third_party/khronos/GLES3/gl3.h',
10680 'gpu/GLES2/gl2chromium.h',
10681 'gpu/GLES2/gl2extchromium.h']:
10682 lines = open(fname).readlines()
10683 for line in lines:
10684 m = enum_re.match(line)
10685 if m:
10686 name = m.group(1)
10687 value = m.group(2)
10688 if len(value) <= 10:
10689 if not value in dict:
10690 dict[value] = name
10691 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10692 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10693 dict[value].endswith('_CHROMIUM')):
10694 self.Error("code collision: %s and %s have the same code %s" %
10695 (dict[value], name, value))
10697 file = CHeaderWriter(filename)
10698 file.Write("static const GLES2Util::EnumToString "
10699 "enum_to_string_table[] = {\n")
10700 for value in dict:
10701 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
10702 file.Write("""};
10704 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10705 enum_to_string_table;
10706 const size_t GLES2Util::enum_to_string_table_len_ =
10707 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10709 """)
10711 enums = sorted(_NAMED_TYPE_INFO.keys())
10712 for enum in enums:
10713 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10714 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10715 enum)
10716 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10717 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10718 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10719 assert len(valid_list) == len(set(valid_list))
10720 if len(valid_list) > 0:
10721 file.Write(" static const EnumToString string_table[] = {\n")
10722 for value in valid_list:
10723 file.Write(' { %s, "%s" },\n' % (value, value))
10724 file.Write(""" };
10725 return GLES2Util::GetQualifiedEnumString(
10726 string_table, arraysize(string_table), value);
10729 """)
10730 else:
10731 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10732 NULL, 0, value);
10735 """)
10736 file.Close()
10737 self.generated_cpp_filenames.append(file.filename)
10739 def WritePepperGLES2Interface(self, filename, dev):
10740 """Writes the Pepper OpenGLES interface definition."""
10741 file = CWriter(filename)
10742 file.Write(_LICENSE)
10743 file.Write(_DO_NOT_EDIT_WARNING)
10745 file.Write("label Chrome {\n")
10746 file.Write(" M39 = 1.0\n")
10747 file.Write("};\n\n")
10749 if not dev:
10750 # Declare GL types.
10751 file.Write("[version=1.0]\n")
10752 file.Write("describe {\n")
10753 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10754 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10755 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10756 'GLubyte', 'GLuint', 'GLushort']:
10757 file.Write(" %s;\n" % gltype)
10758 file.Write(" %s_ptr_t;\n" % gltype)
10759 file.Write("};\n\n")
10761 # C level typedefs.
10762 file.Write("#inline c\n")
10763 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10764 if dev:
10765 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10766 else:
10767 file.Write("\n#ifndef __gl2_h_\n")
10768 for (k, v) in _GL_TYPES.iteritems():
10769 file.Write("typedef %s %s;\n" % (v, k))
10770 file.Write("#ifdef _WIN64\n")
10771 for (k, v) in _GL_TYPES_64.iteritems():
10772 file.Write("typedef %s %s;\n" % (v, k))
10773 file.Write("#else\n")
10774 for (k, v) in _GL_TYPES_32.iteritems():
10775 file.Write("typedef %s %s;\n" % (v, k))
10776 file.Write("#endif // _WIN64\n")
10777 file.Write("#endif // __gl2_h_\n\n")
10778 file.Write("#endinl\n")
10780 for interface in self.pepper_interfaces:
10781 if interface.dev != dev:
10782 continue
10783 # Historically, we provide OpenGLES2 interfaces with struct
10784 # namespace. Not to break code which uses the interface as
10785 # "struct OpenGLES2", we put it in struct namespace.
10786 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10787 interface.GetInterfaceName())
10788 file.Write("interface %s {\n" % interface.GetStructName())
10789 for func in self.original_functions:
10790 if not func.InPepperInterface(interface):
10791 continue
10793 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10794 is_for_return_type=True)
10795 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10796 file.Write(func_prefix)
10797 file.Write("[in] PP_Resource context")
10798 for arg in func.MakeTypedPepperIdlArgStrings():
10799 file.Write(",\n" + " " * len(func_prefix) + arg)
10800 file.Write(");\n")
10801 file.Write("};\n\n")
10804 file.Close()
10806 def WritePepperGLES2Implementation(self, filename):
10807 """Writes the Pepper OpenGLES interface implementation."""
10809 file = CWriter(filename)
10810 file.Write(_LICENSE)
10811 file.Write(_DO_NOT_EDIT_WARNING)
10813 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10814 file.Write("#include \"base/logging.h\"\n")
10815 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10816 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10817 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10819 file.Write("namespace ppapi {\n\n")
10820 file.Write("namespace {\n\n")
10822 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10823 " Enter3D;\n\n")
10825 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10826 " enter) {\n")
10827 file.Write(" DCHECK(enter);\n")
10828 file.Write(" DCHECK(enter->succeeded());\n")
10829 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10830 "gles2_impl();\n");
10831 file.Write("}\n\n");
10833 for func in self.original_functions:
10834 if not func.InAnyPepperExtension():
10835 continue
10837 original_arg = func.MakeTypedPepperArgString("")
10838 context_arg = "PP_Resource context_id"
10839 if len(original_arg):
10840 arg = context_arg + ", " + original_arg
10841 else:
10842 arg = context_arg
10843 file.Write("%s %s(%s) {\n" %
10844 (func.return_type, func.GetPepperName(), arg))
10845 file.Write(" Enter3D enter(context_id, true);\n")
10846 file.Write(" if (enter.succeeded()) {\n")
10848 return_str = "" if func.return_type == "void" else "return "
10849 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10850 (return_str, func.original_name,
10851 func.MakeOriginalArgString("")))
10852 file.Write(" }")
10853 if func.return_type == "void":
10854 file.Write("\n")
10855 else:
10856 file.Write(" else {\n")
10857 file.Write(" return %s;\n" % func.GetErrorReturnString())
10858 file.Write(" }\n")
10859 file.Write("}\n\n")
10861 file.Write("} // namespace\n")
10863 for interface in self.pepper_interfaces:
10864 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10865 (interface.GetStructName(), interface.GetName()))
10866 file.Write(" static const struct %s "
10867 "ppb_opengles2 = {\n" % interface.GetStructName())
10868 file.Write(" &")
10869 file.Write(",\n &".join(
10870 f.GetPepperName() for f in self.original_functions
10871 if f.InPepperInterface(interface)))
10872 file.Write("\n")
10874 file.Write(" };\n")
10875 file.Write(" return &ppb_opengles2;\n")
10876 file.Write("}\n")
10878 file.Write("} // namespace ppapi\n")
10879 file.Close()
10880 self.generated_cpp_filenames.append(file.filename)
10882 def WriteGLES2ToPPAPIBridge(self, filename):
10883 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10885 file = CWriter(filename)
10886 file.Write(_LICENSE)
10887 file.Write(_DO_NOT_EDIT_WARNING)
10889 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10890 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10891 file.Write("#endif\n")
10892 file.Write("#include <GLES2/gl2.h>\n")
10893 file.Write("#include <GLES2/gl2ext.h>\n")
10894 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10896 for func in self.original_functions:
10897 if not func.InAnyPepperExtension():
10898 continue
10900 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10902 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10903 (func.return_type, func.GetPepperName(),
10904 func.MakeTypedPepperArgString("")))
10905 return_str = "" if func.return_type == "void" else "return "
10906 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10907 original_arg = func.MakeOriginalArgString("")
10908 context_arg = "glGetCurrentContextPPAPI()"
10909 if len(original_arg):
10910 arg = context_arg + ", " + original_arg
10911 else:
10912 arg = context_arg
10913 if interface.GetName():
10914 file.Write(" const struct %s* ext = %s;\n" %
10915 (interface.GetStructName(), interface_str))
10916 file.Write(" if (ext)\n")
10917 file.Write(" %sext->%s(%s);\n" %
10918 (return_str, func.GetPepperName(), arg))
10919 if return_str:
10920 file.Write(" %s0;\n" % return_str)
10921 else:
10922 file.Write(" %s%s->%s(%s);\n" %
10923 (return_str, interface_str, func.GetPepperName(), arg))
10924 file.Write("}\n\n")
10925 file.Close()
10926 self.generated_cpp_filenames.append(file.filename)
10928 def WriteMojoGLCallVisitor(self, filename):
10929 """Provides the GL implementation for mojo"""
10930 file = CWriter(filename)
10931 file.Write(_LICENSE)
10932 file.Write(_DO_NOT_EDIT_WARNING)
10934 for func in self.original_functions:
10935 if not func.IsCoreGLFunction():
10936 continue
10937 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10938 (func.name, func.return_type,
10939 func.MakeTypedOriginalArgString(""),
10940 func.MakeOriginalArgString("")))
10942 file.Close()
10943 self.generated_cpp_filenames.append(file.filename)
10945 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10946 """Provides the GL implementation for mojo for a particular extension"""
10947 file = CWriter(filename)
10948 file.Write(_LICENSE)
10949 file.Write(_DO_NOT_EDIT_WARNING)
10951 for func in self.original_functions:
10952 if func.GetInfo("extension") != extension:
10953 continue
10954 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10955 (func.name, func.return_type,
10956 func.MakeTypedOriginalArgString(""),
10957 func.MakeOriginalArgString("")))
10959 file.Close()
10960 self.generated_cpp_filenames.append(file.filename)
10962 def Format(generated_files):
10963 formatter = "clang-format"
10964 if platform.system() == "Windows":
10965 formatter += ".bat"
10966 for filename in generated_files:
10967 call([formatter, "-i", "-style=chromium", filename])
10969 def main(argv):
10970 """This is the main function."""
10971 parser = OptionParser()
10972 parser.add_option(
10973 "--output-dir",
10974 help="base directory for resulting files, under chrome/src. default is "
10975 "empty. Use this if you want the result stored under gen.")
10976 parser.add_option(
10977 "-v", "--verbose", action="store_true",
10978 help="prints more output.")
10980 (options, args) = parser.parse_args(args=argv)
10982 # Add in states and capabilites to GLState
10983 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10984 for state_name in sorted(_STATES.keys()):
10985 state = _STATES[state_name]
10986 if 'extension_flag' in state:
10987 continue
10988 if 'enum' in state:
10989 if not state['enum'] in gl_state_valid:
10990 gl_state_valid.append(state['enum'])
10991 else:
10992 for item in state['states']:
10993 if 'extension_flag' in item:
10994 continue
10995 if not item['enum'] in gl_state_valid:
10996 gl_state_valid.append(item['enum'])
10997 for capability in _CAPABILITY_FLAGS:
10998 valid_value = "GL_%s" % capability['name'].upper()
10999 if not valid_value in gl_state_valid:
11000 gl_state_valid.append(valid_value)
11002 # This script lives under gpu/command_buffer, cd to base directory.
11003 os.chdir(os.path.dirname(__file__) + "/../..")
11004 base_dir = os.getcwd()
11005 gen = GLGenerator(options.verbose)
11006 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
11008 # Support generating files under gen/
11009 if options.output_dir != None:
11010 os.chdir(options.output_dir)
11012 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
11013 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
11014 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
11015 gen.WritePepperGLES2Implementation(
11016 "ppapi/shared_impl/ppb_opengles2_shared.cc")
11017 os.chdir(base_dir)
11018 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
11019 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
11020 gen.WriteFormatTest(
11021 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
11022 gen.WriteGLES2InterfaceHeader(
11023 "gpu/command_buffer/client/gles2_interface_autogen.h")
11024 gen.WriteMojoGLES2ImplHeader(
11025 "mojo/gpu/mojo_gles2_impl_autogen.h")
11026 gen.WriteMojoGLES2Impl(
11027 "mojo/gpu/mojo_gles2_impl_autogen.cc")
11028 gen.WriteGLES2InterfaceStub(
11029 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
11030 gen.WriteGLES2InterfaceStubImpl(
11031 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
11032 gen.WriteGLES2ImplementationHeader(
11033 "gpu/command_buffer/client/gles2_implementation_autogen.h")
11034 gen.WriteGLES2Implementation(
11035 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
11036 gen.WriteGLES2ImplementationUnitTests(
11037 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
11038 gen.WriteGLES2TraceImplementationHeader(
11039 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
11040 gen.WriteGLES2TraceImplementation(
11041 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
11042 gen.WriteGLES2CLibImplementation(
11043 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
11044 gen.WriteCmdHelperHeader(
11045 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
11046 gen.WriteServiceImplementation(
11047 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
11048 gen.WriteServiceContextStateHeader(
11049 "gpu/command_buffer/service/context_state_autogen.h")
11050 gen.WriteServiceContextStateImpl(
11051 "gpu/command_buffer/service/context_state_impl_autogen.h")
11052 gen.WriteClientContextStateHeader(
11053 "gpu/command_buffer/client/client_context_state_autogen.h")
11054 gen.WriteClientContextStateImpl(
11055 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
11056 gen.WriteServiceUnitTests(
11057 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
11058 gen.WriteServiceUnitTestsForExtensions(
11059 "gpu/command_buffer/service/"
11060 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11061 gen.WriteServiceUtilsHeader(
11062 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11063 gen.WriteServiceUtilsImplementation(
11064 "gpu/command_buffer/service/"
11065 "gles2_cmd_validation_implementation_autogen.h")
11066 gen.WriteCommonUtilsHeader(
11067 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11068 gen.WriteCommonUtilsImpl(
11069 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11070 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11071 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
11072 "gles2_call_visitor")
11073 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
11074 gen.WriteMojoGLCallVisitorForExtension(
11075 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
11076 "CHROMIUM_texture_mailbox")
11077 gen.WriteMojoGLCallVisitorForExtension(
11078 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
11079 "CHROMIUM_sync_point")
11080 gen.WriteMojoGLCallVisitorForExtension(
11081 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
11082 "CHROMIUM_sub_image")
11083 gen.WriteMojoGLCallVisitorForExtension(
11084 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
11085 "CHROMIUM_miscellaneous")
11086 gen.WriteMojoGLCallVisitorForExtension(
11087 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
11088 "occlusion_query_EXT")
11089 gen.WriteMojoGLCallVisitorForExtension(
11090 mojo_gles2_prefix + "_chromium_image_autogen.h",
11091 "CHROMIUM_image")
11092 gen.WriteMojoGLCallVisitorForExtension(
11093 mojo_gles2_prefix + "_chromium_copy_texture_autogen.h",
11094 "CHROMIUM_copy_texture")
11095 gen.WriteMojoGLCallVisitorForExtension(
11096 mojo_gles2_prefix + "_chromium_pixel_transfer_buffer_object_autogen.h",
11097 "CHROMIUM_pixel_transfer_buffer_object")
11099 Format(gen.generated_cpp_filenames)
11101 if gen.errors > 0:
11102 print "%d errors" % gen.errors
11103 return 1
11104 return 0
11107 if __name__ == '__main__':
11108 sys.exit(main(sys.argv[1:]))