Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob8ababfe5cb0b131294a17091fbea87ae732c64d8
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': 1,
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,
2099 'BufferSubData': {
2100 'type': 'Data',
2101 'client_test': False,
2102 'decoder_func': 'DoBufferSubData',
2103 'data_transfer_methods': ['shm'],
2105 'CheckFramebufferStatus': {
2106 'type': 'Is',
2107 'decoder_func': 'DoCheckFramebufferStatus',
2108 'gl_test_func': 'glCheckFramebufferStatusEXT',
2109 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2110 'result': ['GLenum'],
2112 'Clear': {
2113 'decoder_func': 'DoClear',
2114 'defer_draws': True,
2115 'trace_level': 1,
2117 'ClearBufferiv': {
2118 'type': 'PUT',
2119 'use_count_func': True,
2120 'count': 4,
2121 'unsafe': True,
2123 'ClearBufferuiv': {
2124 'type': 'PUT',
2125 'count': 4,
2126 'unsafe': True,
2128 'ClearBufferfv': {
2129 'type': 'PUT',
2130 'use_count_func': True,
2131 'count': 4,
2132 'unsafe': True,
2134 'ClearBufferfi': {
2135 'unsafe': True,
2137 'ClearColor': {
2138 'type': 'StateSet',
2139 'state': 'ClearColor',
2141 'ClearDepthf': {
2142 'type': 'StateSet',
2143 'state': 'ClearDepthf',
2144 'decoder_func': 'glClearDepth',
2145 'gl_test_func': 'glClearDepth',
2146 'valid_args': {
2147 '0': '0.5f'
2150 'ClientWaitSync': {
2151 'type': 'Custom',
2152 'data_transfer_methods': ['shm'],
2153 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2154 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2155 'unsafe': True,
2156 'result': ['GLenum'],
2158 'ColorMask': {
2159 'type': 'StateSet',
2160 'state': 'ColorMask',
2161 'no_gl': True,
2162 'expectation': False,
2164 'ConsumeTextureCHROMIUM': {
2165 'decoder_func': 'DoConsumeTextureCHROMIUM',
2166 'impl_func': False,
2167 'type': 'PUT',
2168 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2169 'unit_test': False,
2170 'client_test': False,
2171 'extension': "CHROMIUM_texture_mailbox",
2172 'chromium': True,
2173 'trace_level': 1,
2175 'CopyBufferSubData': {
2176 'unsafe': True,
2178 'CreateAndConsumeTextureCHROMIUM': {
2179 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2180 'impl_func': False,
2181 'type': 'HandWritten',
2182 'data_transfer_methods': ['immediate'],
2183 'unit_test': False,
2184 'client_test': False,
2185 'extension': "CHROMIUM_texture_mailbox",
2186 'chromium': True,
2188 'GenValuebuffersCHROMIUM': {
2189 'type': 'GENn',
2190 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2191 'resource_type': 'Valuebuffer',
2192 'resource_types': 'Valuebuffers',
2193 'unit_test': False,
2194 'extension': True,
2195 'chromium': True,
2197 'DeleteValuebuffersCHROMIUM': {
2198 'type': 'DELn',
2199 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2200 'resource_type': 'Valuebuffer',
2201 'resource_types': 'Valuebuffers',
2202 'unit_test': False,
2203 'extension': True,
2204 'chromium': True,
2206 'IsValuebufferCHROMIUM': {
2207 'type': 'Is',
2208 'decoder_func': 'DoIsValuebufferCHROMIUM',
2209 'expectation': False,
2210 'extension': True,
2211 'chromium': True,
2213 'BindValuebufferCHROMIUM': {
2214 'type': 'Bind',
2215 'decoder_func': 'DoBindValueBufferCHROMIUM',
2216 'gen_func': 'GenValueBuffersCHROMIUM',
2217 'unit_test': False,
2218 'extension': True,
2219 'chromium': True,
2221 'SubscribeValueCHROMIUM': {
2222 'decoder_func': 'DoSubscribeValueCHROMIUM',
2223 'unit_test': False,
2224 'extension': True,
2225 'chromium': True,
2227 'PopulateSubscribedValuesCHROMIUM': {
2228 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2229 'unit_test': False,
2230 'extension': True,
2231 'chromium': True,
2233 'UniformValuebufferCHROMIUM': {
2234 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2235 'unit_test': False,
2236 'extension': True,
2237 'chromium': True,
2239 'ClearStencil': {
2240 'type': 'StateSet',
2241 'state': 'ClearStencil',
2243 'EnableFeatureCHROMIUM': {
2244 'type': 'Custom',
2245 'data_transfer_methods': ['shm'],
2246 'decoder_func': 'DoEnableFeatureCHROMIUM',
2247 'expectation': False,
2248 'cmd_args': 'GLuint bucket_id, GLint* result',
2249 'result': ['GLint'],
2250 'extension': True,
2251 'chromium': True,
2252 'pepper_interface': 'ChromiumEnableFeature',
2254 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2255 'CompressedTexImage2D': {
2256 'type': 'Manual',
2257 'data_transfer_methods': ['bucket', 'shm'],
2259 'CompressedTexSubImage2D': {
2260 'type': 'Data',
2261 'data_transfer_methods': ['bucket', 'shm'],
2262 'decoder_func': 'DoCompressedTexSubImage2D',
2264 'CopyTexImage2D': {
2265 'decoder_func': 'DoCopyTexImage2D',
2266 'unit_test': False,
2267 'defer_reads': True,
2269 'CopyTexSubImage2D': {
2270 'decoder_func': 'DoCopyTexSubImage2D',
2271 'defer_reads': True,
2273 'CompressedTexImage3D': {
2274 'type': 'Manual',
2275 'data_transfer_methods': ['bucket', 'shm'],
2276 'unsafe': True,
2278 'CompressedTexSubImage3D': {
2279 'type': 'Data',
2280 'data_transfer_methods': ['bucket', 'shm'],
2281 'decoder_func': 'DoCompressedTexSubImage3D',
2282 'unsafe': True,
2284 'CopyTexSubImage3D': {
2285 'defer_reads': True,
2286 'unsafe': True,
2288 'CreateImageCHROMIUM': {
2289 'type': 'Manual',
2290 'cmd_args':
2291 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2292 'GLenum internalformat',
2293 'result': ['GLuint'],
2294 'client_test': False,
2295 'gen_cmd': False,
2296 'expectation': False,
2297 'extension': True,
2298 'chromium': True,
2300 'DestroyImageCHROMIUM': {
2301 'type': 'Manual',
2302 'client_test': False,
2303 'gen_cmd': False,
2304 'extension': True,
2305 'chromium': True,
2307 'CreateGpuMemoryBufferImageCHROMIUM': {
2308 'type': 'Manual',
2309 'cmd_args':
2310 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2311 'result': ['GLuint'],
2312 'client_test': False,
2313 'gen_cmd': False,
2314 'expectation': False,
2315 'extension': True,
2316 'chromium': True,
2318 'CreateProgram': {
2319 'type': 'Create',
2320 'client_test': False,
2322 'CreateShader': {
2323 'type': 'Create',
2324 'client_test': False,
2326 'BlendColor': {
2327 'type': 'StateSet',
2328 'state': 'BlendColor',
2330 'BlendEquation': {
2331 'type': 'StateSetRGBAlpha',
2332 'state': 'BlendEquation',
2333 'valid_args': {
2334 '0': 'GL_FUNC_SUBTRACT'
2337 'BlendEquationSeparate': {
2338 'type': 'StateSet',
2339 'state': 'BlendEquation',
2340 'valid_args': {
2341 '0': 'GL_FUNC_SUBTRACT'
2344 'BlendFunc': {
2345 'type': 'StateSetRGBAlpha',
2346 'state': 'BlendFunc',
2348 'BlendFuncSeparate': {
2349 'type': 'StateSet',
2350 'state': 'BlendFunc',
2352 'BlendBarrierKHR': {
2353 'gl_test_func': 'glBlendBarrierKHR',
2354 'extension': True,
2355 'extension_flag': 'blend_equation_advanced',
2356 'client_test': False,
2358 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2359 'StencilFunc': {
2360 'type': 'StateSetFrontBack',
2361 'state': 'StencilFunc',
2363 'StencilFuncSeparate': {
2364 'type': 'StateSetFrontBackSeparate',
2365 'state': 'StencilFunc',
2367 'StencilOp': {
2368 'type': 'StateSetFrontBack',
2369 'state': 'StencilOp',
2370 'valid_args': {
2371 '1': 'GL_INCR'
2374 'StencilOpSeparate': {
2375 'type': 'StateSetFrontBackSeparate',
2376 'state': 'StencilOp',
2377 'valid_args': {
2378 '1': 'GL_INCR'
2381 'Hint': {
2382 'type': 'StateSetNamedParameter',
2383 'state': 'Hint',
2385 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2386 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2387 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2388 'LineWidth': {
2389 'type': 'StateSet',
2390 'state': 'LineWidth',
2391 'valid_args': {
2392 '0': '0.5f'
2395 'PolygonOffset': {
2396 'type': 'StateSet',
2397 'state': 'PolygonOffset',
2399 'DeleteBuffers': {
2400 'type': 'DELn',
2401 'gl_test_func': 'glDeleteBuffersARB',
2402 'resource_type': 'Buffer',
2403 'resource_types': 'Buffers',
2405 'DeleteFramebuffers': {
2406 'type': 'DELn',
2407 'gl_test_func': 'glDeleteFramebuffersEXT',
2408 'resource_type': 'Framebuffer',
2409 'resource_types': 'Framebuffers',
2411 'DeleteProgram': { 'type': 'Delete' },
2412 'DeleteRenderbuffers': {
2413 'type': 'DELn',
2414 'gl_test_func': 'glDeleteRenderbuffersEXT',
2415 'resource_type': 'Renderbuffer',
2416 'resource_types': 'Renderbuffers',
2418 'DeleteSamplers': {
2419 'type': 'DELn',
2420 'resource_type': 'Sampler',
2421 'resource_types': 'Samplers',
2422 'unsafe': True,
2424 'DeleteShader': { 'type': 'Delete' },
2425 'DeleteSync': {
2426 'type': 'Delete',
2427 'cmd_args': 'GLuint sync',
2428 'resource_type': 'Sync',
2429 'unsafe': True,
2431 'DeleteTextures': {
2432 'type': 'DELn',
2433 'resource_type': 'Texture',
2434 'resource_types': 'Textures',
2436 'DeleteTransformFeedbacks': {
2437 'type': 'DELn',
2438 'resource_type': 'TransformFeedback',
2439 'resource_types': 'TransformFeedbacks',
2440 'unsafe': True,
2442 'DepthRangef': {
2443 'decoder_func': 'DoDepthRangef',
2444 'gl_test_func': 'glDepthRange',
2446 'DepthMask': {
2447 'type': 'StateSet',
2448 'state': 'DepthMask',
2449 'no_gl': True,
2450 'expectation': False,
2452 'DetachShader': {'decoder_func': 'DoDetachShader'},
2453 'Disable': {
2454 'decoder_func': 'DoDisable',
2455 'impl_func': False,
2456 'client_test': False,
2458 'DisableVertexAttribArray': {
2459 'decoder_func': 'DoDisableVertexAttribArray',
2460 'impl_decl': False,
2462 'DrawArrays': {
2463 'type': 'Manual',
2464 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2465 'defer_draws': True,
2466 'trace_level': 2,
2468 'DrawElements': {
2469 'type': 'Manual',
2470 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2471 'GLenumIndexType type, GLuint index_offset',
2472 'client_test': False,
2473 'defer_draws': True,
2474 'trace_level': 2,
2476 'DrawRangeElements': {
2477 'type': 'Manual',
2478 'gen_cmd': 'False',
2479 'unsafe': True,
2481 'Enable': {
2482 'decoder_func': 'DoEnable',
2483 'impl_func': False,
2484 'client_test': False,
2486 'EnableVertexAttribArray': {
2487 'decoder_func': 'DoEnableVertexAttribArray',
2488 'impl_decl': False,
2490 'FenceSync': {
2491 'type': 'Create',
2492 'client_test': False,
2493 'unsafe': True,
2495 'Finish': {
2496 'impl_func': False,
2497 'client_test': False,
2498 'decoder_func': 'DoFinish',
2499 'defer_reads': True,
2501 'Flush': {
2502 'impl_func': False,
2503 'decoder_func': 'DoFlush',
2505 'FramebufferRenderbuffer': {
2506 'decoder_func': 'DoFramebufferRenderbuffer',
2507 'gl_test_func': 'glFramebufferRenderbufferEXT',
2509 'FramebufferTexture2D': {
2510 'decoder_func': 'DoFramebufferTexture2D',
2511 'gl_test_func': 'glFramebufferTexture2DEXT',
2512 'trace_level': 1,
2514 'FramebufferTexture2DMultisampleEXT': {
2515 'decoder_func': 'DoFramebufferTexture2DMultisample',
2516 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2517 'expectation': False,
2518 'unit_test': False,
2519 'extension_flag': 'multisampled_render_to_texture',
2520 'trace_level': 1,
2522 'FramebufferTextureLayer': {
2523 'decoder_func': 'DoFramebufferTextureLayer',
2524 'unsafe': True,
2526 'GenerateMipmap': {
2527 'decoder_func': 'DoGenerateMipmap',
2528 'gl_test_func': 'glGenerateMipmapEXT',
2530 'GenBuffers': {
2531 'type': 'GENn',
2532 'gl_test_func': 'glGenBuffersARB',
2533 'resource_type': 'Buffer',
2534 'resource_types': 'Buffers',
2536 'GenMailboxCHROMIUM': {
2537 'type': 'HandWritten',
2538 'impl_func': False,
2539 'extension': "CHROMIUM_texture_mailbox",
2540 'chromium': True,
2542 'GenFramebuffers': {
2543 'type': 'GENn',
2544 'gl_test_func': 'glGenFramebuffersEXT',
2545 'resource_type': 'Framebuffer',
2546 'resource_types': 'Framebuffers',
2548 'GenRenderbuffers': {
2549 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2550 'resource_type': 'Renderbuffer',
2551 'resource_types': 'Renderbuffers',
2553 'GenSamplers': {
2554 'type': 'GENn',
2555 'gl_test_func': 'glGenSamplers',
2556 'resource_type': 'Sampler',
2557 'resource_types': 'Samplers',
2558 'unsafe': True,
2560 'GenTextures': {
2561 'type': 'GENn',
2562 'gl_test_func': 'glGenTextures',
2563 'resource_type': 'Texture',
2564 'resource_types': 'Textures',
2566 'GenTransformFeedbacks': {
2567 'type': 'GENn',
2568 'gl_test_func': 'glGenTransformFeedbacks',
2569 'resource_type': 'TransformFeedback',
2570 'resource_types': 'TransformFeedbacks',
2571 'unsafe': True,
2573 'GetActiveAttrib': {
2574 'type': 'Custom',
2575 'data_transfer_methods': ['shm'],
2576 'cmd_args':
2577 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2578 'void* result',
2579 'result': [
2580 'int32_t success',
2581 'int32_t size',
2582 'uint32_t type',
2585 'GetActiveUniform': {
2586 'type': 'Custom',
2587 'data_transfer_methods': ['shm'],
2588 'cmd_args':
2589 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2590 'void* result',
2591 'result': [
2592 'int32_t success',
2593 'int32_t size',
2594 'uint32_t type',
2597 'GetActiveUniformBlockiv': {
2598 'type': 'Custom',
2599 'data_transfer_methods': ['shm'],
2600 'result': ['SizedResult<GLint>'],
2601 'unsafe': True,
2603 'GetActiveUniformBlockName': {
2604 'type': 'Custom',
2605 'data_transfer_methods': ['shm'],
2606 'cmd_args':
2607 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2608 'void* result',
2609 'result': ['int32_t'],
2610 'unsafe': True,
2612 'GetActiveUniformsiv': {
2613 'type': 'Custom',
2614 'data_transfer_methods': ['shm'],
2615 'cmd_args':
2616 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2617 'GLint* params',
2618 'result': ['SizedResult<GLint>'],
2619 'unsafe': True,
2621 'GetAttachedShaders': {
2622 'type': 'Custom',
2623 'data_transfer_methods': ['shm'],
2624 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2625 'result': ['SizedResult<GLuint>'],
2627 'GetAttribLocation': {
2628 'type': 'Custom',
2629 'data_transfer_methods': ['shm'],
2630 'cmd_args':
2631 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2632 'result': ['GLint'],
2633 'error_return': -1,
2635 'GetFragDataLocation': {
2636 'type': 'Custom',
2637 'data_transfer_methods': ['shm'],
2638 'cmd_args':
2639 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2640 'result': ['GLint'],
2641 'error_return': -1,
2642 'unsafe': True,
2644 'GetBooleanv': {
2645 'type': 'GETn',
2646 'result': ['SizedResult<GLboolean>'],
2647 'decoder_func': 'DoGetBooleanv',
2648 'gl_test_func': 'glGetBooleanv',
2650 'GetBufferParameteriv': {
2651 'type': 'GETn',
2652 'result': ['SizedResult<GLint>'],
2653 'decoder_func': 'DoGetBufferParameteriv',
2654 'expectation': False,
2655 'shadowed': True,
2657 'GetError': {
2658 'type': 'Is',
2659 'decoder_func': 'GetErrorState()->GetGLError',
2660 'impl_func': False,
2661 'result': ['GLenum'],
2662 'client_test': False,
2664 'GetFloatv': {
2665 'type': 'GETn',
2666 'result': ['SizedResult<GLfloat>'],
2667 'decoder_func': 'DoGetFloatv',
2668 'gl_test_func': 'glGetFloatv',
2670 'GetFramebufferAttachmentParameteriv': {
2671 'type': 'GETn',
2672 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2673 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2674 'result': ['SizedResult<GLint>'],
2676 'GetInteger64v': {
2677 'type': 'GETn',
2678 'result': ['SizedResult<GLint64>'],
2679 'client_test': False,
2680 'decoder_func': 'DoGetInteger64v',
2681 'unsafe': True
2683 'GetIntegerv': {
2684 'type': 'GETn',
2685 'result': ['SizedResult<GLint>'],
2686 'decoder_func': 'DoGetIntegerv',
2687 'client_test': False,
2689 'GetInteger64i_v': {
2690 'type': 'GETn',
2691 'result': ['SizedResult<GLint64>'],
2692 'client_test': False,
2693 'unsafe': True
2695 'GetIntegeri_v': {
2696 'type': 'GETn',
2697 'result': ['SizedResult<GLint>'],
2698 'client_test': False,
2699 'unsafe': True
2701 'GetInternalformativ': {
2702 'type': 'GETn',
2703 'result': ['SizedResult<GLint>'],
2704 'unsafe': True,
2706 'GetMaxValueInBufferCHROMIUM': {
2707 'type': 'Is',
2708 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2709 'result': ['GLuint'],
2710 'unit_test': False,
2711 'client_test': False,
2712 'extension': True,
2713 'chromium': True,
2714 'impl_func': False,
2716 'GetProgramiv': {
2717 'type': 'GETn',
2718 'decoder_func': 'DoGetProgramiv',
2719 'result': ['SizedResult<GLint>'],
2720 'expectation': False,
2722 'GetProgramInfoCHROMIUM': {
2723 'type': 'Custom',
2724 'expectation': False,
2725 'impl_func': False,
2726 'extension': True,
2727 'chromium': True,
2728 'client_test': False,
2729 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2730 'result': [
2731 'uint32_t link_status',
2732 'uint32_t num_attribs',
2733 'uint32_t num_uniforms',
2736 'GetProgramInfoLog': {
2737 'type': 'STRn',
2738 'expectation': False,
2740 'GetRenderbufferParameteriv': {
2741 'type': 'GETn',
2742 'decoder_func': 'DoGetRenderbufferParameteriv',
2743 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2744 'result': ['SizedResult<GLint>'],
2746 'GetSamplerParameterfv': {
2747 'type': 'GETn',
2748 'result': ['SizedResult<GLfloat>'],
2749 'id_mapping': [ 'Sampler' ],
2750 'unsafe': True,
2752 'GetSamplerParameteriv': {
2753 'type': 'GETn',
2754 'result': ['SizedResult<GLint>'],
2755 'id_mapping': [ 'Sampler' ],
2756 'unsafe': True,
2758 'GetShaderiv': {
2759 'type': 'GETn',
2760 'decoder_func': 'DoGetShaderiv',
2761 'result': ['SizedResult<GLint>'],
2763 'GetShaderInfoLog': {
2764 'type': 'STRn',
2765 'get_len_func': 'glGetShaderiv',
2766 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2767 'unit_test': False,
2769 'GetShaderPrecisionFormat': {
2770 'type': 'Custom',
2771 'data_transfer_methods': ['shm'],
2772 'cmd_args':
2773 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2774 'void* result',
2775 'result': [
2776 'int32_t success',
2777 'int32_t min_range',
2778 'int32_t max_range',
2779 'int32_t precision',
2782 'GetShaderSource': {
2783 'type': 'STRn',
2784 'get_len_func': 'DoGetShaderiv',
2785 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2786 'unit_test': False,
2787 'client_test': False,
2789 'GetString': {
2790 'type': 'Custom',
2791 'client_test': False,
2792 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2794 'GetSynciv': {
2795 'type': 'GETn',
2796 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2797 'result': ['SizedResult<GLint>'],
2798 'id_mapping': ['Sync'],
2799 'unsafe': True,
2801 'GetTexParameterfv': {
2802 'type': 'GETn',
2803 'decoder_func': 'DoGetTexParameterfv',
2804 'result': ['SizedResult<GLfloat>']
2806 'GetTexParameteriv': {
2807 'type': 'GETn',
2808 'decoder_func': 'DoGetTexParameteriv',
2809 'result': ['SizedResult<GLint>']
2811 'GetTranslatedShaderSourceANGLE': {
2812 'type': 'STRn',
2813 'get_len_func': 'DoGetShaderiv',
2814 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2815 'unit_test': False,
2816 'extension': True,
2818 'GetUniformBlockIndex': {
2819 'type': 'Custom',
2820 'data_transfer_methods': ['shm'],
2821 'cmd_args':
2822 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2823 'result': ['GLuint'],
2824 'error_return': 'GL_INVALID_INDEX',
2825 'unsafe': True,
2827 'GetUniformBlocksCHROMIUM': {
2828 'type': 'Custom',
2829 'expectation': False,
2830 'impl_func': False,
2831 'extension': True,
2832 'chromium': True,
2833 'client_test': False,
2834 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2835 'result': ['uint32_t'],
2836 'unsafe': True,
2838 'GetUniformsES3CHROMIUM': {
2839 'type': 'Custom',
2840 'expectation': False,
2841 'impl_func': False,
2842 'extension': True,
2843 'chromium': True,
2844 'client_test': False,
2845 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2846 'result': ['uint32_t'],
2847 'unsafe': True,
2849 'GetTransformFeedbackVarying': {
2850 'type': 'Custom',
2851 'data_transfer_methods': ['shm'],
2852 'cmd_args':
2853 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2854 'void* result',
2855 'result': [
2856 'int32_t success',
2857 'int32_t size',
2858 'uint32_t type',
2860 'unsafe': True,
2862 'GetTransformFeedbackVaryingsCHROMIUM': {
2863 'type': 'Custom',
2864 'expectation': False,
2865 'impl_func': False,
2866 'extension': True,
2867 'chromium': True,
2868 'client_test': False,
2869 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2870 'result': ['uint32_t'],
2871 'unsafe': True,
2873 'GetUniformfv': {
2874 'type': 'Custom',
2875 'data_transfer_methods': ['shm'],
2876 'result': ['SizedResult<GLfloat>'],
2878 'GetUniformiv': {
2879 'type': 'Custom',
2880 'data_transfer_methods': ['shm'],
2881 'result': ['SizedResult<GLint>'],
2883 'GetUniformuiv': {
2884 'type': 'Custom',
2885 'data_transfer_methods': ['shm'],
2886 'result': ['SizedResult<GLuint>'],
2887 'unsafe': True,
2889 'GetUniformIndices': {
2890 'type': 'Custom',
2891 'data_transfer_methods': ['shm'],
2892 'result': ['SizedResult<GLuint>'],
2893 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2894 'GLuint* indices',
2895 'unsafe': True,
2897 'GetUniformLocation': {
2898 'type': 'Custom',
2899 'data_transfer_methods': ['shm'],
2900 'cmd_args':
2901 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2902 'result': ['GLint'],
2903 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2905 'GetVertexAttribfv': {
2906 'type': 'GETn',
2907 'result': ['SizedResult<GLfloat>'],
2908 'impl_decl': False,
2909 'decoder_func': 'DoGetVertexAttribfv',
2910 'expectation': False,
2911 'client_test': False,
2913 'GetVertexAttribiv': {
2914 'type': 'GETn',
2915 'result': ['SizedResult<GLint>'],
2916 'impl_decl': False,
2917 'decoder_func': 'DoGetVertexAttribiv',
2918 'expectation': False,
2919 'client_test': False,
2921 'GetVertexAttribIiv': {
2922 'type': 'GETn',
2923 'result': ['SizedResult<GLint>'],
2924 'impl_decl': False,
2925 'decoder_func': 'DoGetVertexAttribIiv',
2926 'expectation': False,
2927 'client_test': False,
2928 'unsafe': True,
2930 'GetVertexAttribIuiv': {
2931 'type': 'GETn',
2932 'result': ['SizedResult<GLuint>'],
2933 'impl_decl': False,
2934 'decoder_func': 'DoGetVertexAttribIuiv',
2935 'expectation': False,
2936 'client_test': False,
2937 'unsafe': True,
2939 'GetVertexAttribPointerv': {
2940 'type': 'Custom',
2941 'data_transfer_methods': ['shm'],
2942 'result': ['SizedResult<GLuint>'],
2943 'client_test': False,
2945 'InvalidateFramebuffer': {
2946 'type': 'PUTn',
2947 'count': 1,
2948 'client_test': False,
2949 'unit_test': False,
2950 'unsafe': True,
2952 'InvalidateSubFramebuffer': {
2953 'type': 'PUTn',
2954 'count': 1,
2955 'client_test': False,
2956 'unit_test': False,
2957 'unsafe': True,
2959 'IsBuffer': {
2960 'type': 'Is',
2961 'decoder_func': 'DoIsBuffer',
2962 'expectation': False,
2964 'IsEnabled': {
2965 'type': 'Is',
2966 'decoder_func': 'DoIsEnabled',
2967 'client_test': False,
2968 'impl_func': False,
2969 'expectation': False,
2971 'IsFramebuffer': {
2972 'type': 'Is',
2973 'decoder_func': 'DoIsFramebuffer',
2974 'expectation': False,
2976 'IsProgram': {
2977 'type': 'Is',
2978 'decoder_func': 'DoIsProgram',
2979 'expectation': False,
2981 'IsRenderbuffer': {
2982 'type': 'Is',
2983 'decoder_func': 'DoIsRenderbuffer',
2984 'expectation': False,
2986 'IsShader': {
2987 'type': 'Is',
2988 'decoder_func': 'DoIsShader',
2989 'expectation': False,
2991 'IsSampler': {
2992 'type': 'Is',
2993 'id_mapping': [ 'Sampler' ],
2994 'expectation': False,
2995 'unsafe': True,
2997 'IsSync': {
2998 'type': 'Is',
2999 'id_mapping': [ 'Sync' ],
3000 'cmd_args': 'GLuint sync',
3001 'expectation': False,
3002 'unsafe': True,
3004 'IsTexture': {
3005 'type': 'Is',
3006 'decoder_func': 'DoIsTexture',
3007 'expectation': False,
3009 'IsTransformFeedback': {
3010 'type': 'Is',
3011 'id_mapping': [ 'TransformFeedback' ],
3012 'expectation': False,
3013 'unsafe': True,
3015 'LinkProgram': {
3016 'decoder_func': 'DoLinkProgram',
3017 'impl_func': False,
3019 'MapBufferCHROMIUM': {
3020 'gen_cmd': False,
3021 'extension': True,
3022 'chromium': True,
3023 'client_test': False,
3025 'MapBufferSubDataCHROMIUM': {
3026 'gen_cmd': False,
3027 'extension': True,
3028 'chromium': True,
3029 'client_test': False,
3030 'pepper_interface': 'ChromiumMapSub',
3032 'MapTexSubImage2DCHROMIUM': {
3033 'gen_cmd': False,
3034 'extension': "CHROMIUM_sub_image",
3035 'chromium': True,
3036 'client_test': False,
3037 'pepper_interface': 'ChromiumMapSub',
3039 'MapBufferRange': {
3040 'type': 'Custom',
3041 'data_transfer_methods': ['shm'],
3042 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3043 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3044 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3045 'uint32_t result_shm_id, uint32_t result_shm_offset',
3046 'unsafe': True,
3047 'result': ['uint32_t'],
3049 'PauseTransformFeedback': {
3050 'unsafe': True,
3052 'PixelStorei': {'type': 'Manual'},
3053 'PostSubBufferCHROMIUM': {
3054 'type': 'Custom',
3055 'impl_func': False,
3056 'unit_test': False,
3057 'client_test': False,
3058 'extension': True,
3059 'chromium': True,
3061 'ProduceTextureCHROMIUM': {
3062 'decoder_func': 'DoProduceTextureCHROMIUM',
3063 'impl_func': False,
3064 'type': 'PUT',
3065 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3066 'unit_test': False,
3067 'client_test': False,
3068 'extension': "CHROMIUM_texture_mailbox",
3069 'chromium': True,
3070 'trace_level': 1,
3072 'ProduceTextureDirectCHROMIUM': {
3073 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3074 'impl_func': False,
3075 'type': 'PUT',
3076 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3077 'unit_test': False,
3078 'client_test': False,
3079 'extension': "CHROMIUM_texture_mailbox",
3080 'chromium': True,
3081 'trace_level': 1,
3083 'RenderbufferStorage': {
3084 'decoder_func': 'DoRenderbufferStorage',
3085 'gl_test_func': 'glRenderbufferStorageEXT',
3086 'expectation': False,
3088 'RenderbufferStorageMultisampleCHROMIUM': {
3089 'cmd_comment':
3090 '// GL_CHROMIUM_framebuffer_multisample\n',
3091 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3092 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3093 'expectation': False,
3094 'unit_test': False,
3095 'extension_flag': 'chromium_framebuffer_multisample',
3096 'pepper_interface': 'FramebufferMultisample',
3097 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3099 'RenderbufferStorageMultisampleEXT': {
3100 'cmd_comment':
3101 '// GL_EXT_multisampled_render_to_texture\n',
3102 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3103 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3104 'expectation': False,
3105 'unit_test': False,
3106 'extension_flag': 'multisampled_render_to_texture',
3108 'ReadBuffer': {
3109 'unsafe': True,
3111 'ReadPixels': {
3112 'cmd_comment':
3113 '// ReadPixels has the result separated from the pixel buffer so that\n'
3114 '// it is easier to specify the result going to some specific place\n'
3115 '// that exactly fits the rectangle of pixels.\n',
3116 'type': 'Custom',
3117 'data_transfer_methods': ['shm'],
3118 'impl_func': False,
3119 'client_test': False,
3120 'cmd_args':
3121 'GLint x, GLint y, GLsizei width, GLsizei height, '
3122 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3123 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3124 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3125 'GLboolean async',
3126 'result': ['uint32_t'],
3127 'defer_reads': True,
3129 'ReleaseShaderCompiler': {
3130 'decoder_func': 'DoReleaseShaderCompiler',
3131 'unit_test': False,
3133 'ResumeTransformFeedback': {
3134 'unsafe': True,
3136 'SamplerParameterf': {
3137 'valid_args': {
3138 '2': 'GL_NEAREST'
3140 'id_mapping': [ 'Sampler' ],
3141 'unsafe': True,
3143 'SamplerParameterfv': {
3144 'type': 'PUT',
3145 'data_value': 'GL_NEAREST',
3146 'count': 1,
3147 'gl_test_func': 'glSamplerParameterf',
3148 'decoder_func': 'DoSamplerParameterfv',
3149 'first_element_only': True,
3150 'id_mapping': [ 'Sampler' ],
3151 'unsafe': True,
3153 'SamplerParameteri': {
3154 'valid_args': {
3155 '2': 'GL_NEAREST'
3157 'id_mapping': [ 'Sampler' ],
3158 'unsafe': True,
3160 'SamplerParameteriv': {
3161 'type': 'PUT',
3162 'data_value': 'GL_NEAREST',
3163 'count': 1,
3164 'gl_test_func': 'glSamplerParameteri',
3165 'decoder_func': 'DoSamplerParameteriv',
3166 'first_element_only': True,
3167 'unsafe': True,
3169 'ShaderBinary': {
3170 'type': 'Custom',
3171 'client_test': False,
3173 'ShaderSource': {
3174 'type': 'PUTSTR',
3175 'decoder_func': 'DoShaderSource',
3176 'expectation': False,
3177 'data_transfer_methods': ['bucket'],
3178 'cmd_args':
3179 'GLuint shader, const char** str',
3180 'pepper_args':
3181 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3183 'StencilMask': {
3184 'type': 'StateSetFrontBack',
3185 'state': 'StencilMask',
3186 'no_gl': True,
3187 'expectation': False,
3189 'StencilMaskSeparate': {
3190 'type': 'StateSetFrontBackSeparate',
3191 'state': 'StencilMask',
3192 'no_gl': True,
3193 'expectation': False,
3195 'SwapBuffers': {
3196 'impl_func': False,
3197 'decoder_func': 'DoSwapBuffers',
3198 'unit_test': False,
3199 'client_test': False,
3200 'extension': True,
3201 'trace_level': 1,
3203 'SwapInterval': {
3204 'impl_func': False,
3205 'decoder_func': 'DoSwapInterval',
3206 'unit_test': False,
3207 'client_test': False,
3208 'extension': True,
3209 'trace_level': 1,
3211 'TexImage2D': {
3212 'type': 'Manual',
3213 'data_transfer_methods': ['shm'],
3214 'client_test': False,
3216 'TexImage3D': {
3217 'type': 'Manual',
3218 'data_transfer_methods': ['shm'],
3219 'client_test': False,
3220 'unsafe': True,
3222 'TexParameterf': {
3223 'decoder_func': 'DoTexParameterf',
3224 'valid_args': {
3225 '2': 'GL_NEAREST'
3228 'TexParameteri': {
3229 'decoder_func': 'DoTexParameteri',
3230 'valid_args': {
3231 '2': 'GL_NEAREST'
3234 'TexParameterfv': {
3235 'type': 'PUT',
3236 'data_value': 'GL_NEAREST',
3237 'count': 1,
3238 'decoder_func': 'DoTexParameterfv',
3239 'gl_test_func': 'glTexParameterf',
3240 'first_element_only': True,
3242 'TexParameteriv': {
3243 'type': 'PUT',
3244 'data_value': 'GL_NEAREST',
3245 'count': 1,
3246 'decoder_func': 'DoTexParameteriv',
3247 'gl_test_func': 'glTexParameteri',
3248 'first_element_only': True,
3250 'TexStorage3D': {
3251 'unsafe': True,
3253 'TexSubImage2D': {
3254 'type': 'Manual',
3255 'data_transfer_methods': ['shm'],
3256 'client_test': False,
3257 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3258 'GLint xoffset, GLint yoffset, '
3259 'GLsizei width, GLsizei height, '
3260 'GLenumTextureFormat format, GLenumPixelType type, '
3261 'const void* pixels, GLboolean internal'
3263 'TexSubImage3D': {
3264 'type': 'Manual',
3265 'data_transfer_methods': ['shm'],
3266 'client_test': False,
3267 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3268 'GLint xoffset, GLint yoffset, GLint zoffset, '
3269 'GLsizei width, GLsizei height, GLsizei depth, '
3270 'GLenumTextureFormat format, GLenumPixelType type, '
3271 'const void* pixels, GLboolean internal',
3272 'unsafe': True,
3274 'TransformFeedbackVaryings': {
3275 'type': 'PUTSTR',
3276 'data_transfer_methods': ['bucket'],
3277 'decoder_func': 'DoTransformFeedbackVaryings',
3278 'cmd_args':
3279 'GLuint program, const char** varyings, GLenum buffermode',
3280 'unsafe': True,
3282 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3283 'Uniform1fv': {
3284 'type': 'PUTn',
3285 'count': 1,
3286 'decoder_func': 'DoUniform1fv',
3288 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3289 'Uniform1iv': {
3290 'type': 'PUTn',
3291 'count': 1,
3292 'decoder_func': 'DoUniform1iv',
3293 'unit_test': False,
3295 'Uniform1ui': {
3296 'type': 'PUTXn',
3297 'count': 1,
3298 'unsafe': True,
3300 'Uniform1uiv': {
3301 'type': 'PUTn',
3302 'count': 1,
3303 'unsafe': True,
3305 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3306 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3307 'Uniform2fv': {
3308 'type': 'PUTn',
3309 'count': 2,
3310 'decoder_func': 'DoUniform2fv',
3312 'Uniform2iv': {
3313 'type': 'PUTn',
3314 'count': 2,
3315 'decoder_func': 'DoUniform2iv',
3317 'Uniform2ui': {
3318 'type': 'PUTXn',
3319 'count': 2,
3320 'unsafe': True,
3322 'Uniform2uiv': {
3323 'type': 'PUTn',
3324 'count': 2,
3325 'unsafe': True,
3327 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3328 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3329 'Uniform3fv': {
3330 'type': 'PUTn',
3331 'count': 3,
3332 'decoder_func': 'DoUniform3fv',
3334 'Uniform3iv': {
3335 'type': 'PUTn',
3336 'count': 3,
3337 'decoder_func': 'DoUniform3iv',
3339 'Uniform3ui': {
3340 'type': 'PUTXn',
3341 'count': 3,
3342 'unsafe': True,
3344 'Uniform3uiv': {
3345 'type': 'PUTn',
3346 'count': 3,
3347 'unsafe': True,
3349 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3350 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3351 'Uniform4fv': {
3352 'type': 'PUTn',
3353 'count': 4,
3354 'decoder_func': 'DoUniform4fv',
3356 'Uniform4iv': {
3357 'type': 'PUTn',
3358 'count': 4,
3359 'decoder_func': 'DoUniform4iv',
3361 'Uniform4ui': {
3362 'type': 'PUTXn',
3363 'count': 4,
3364 'unsafe': True,
3366 'Uniform4uiv': {
3367 'type': 'PUTn',
3368 'count': 4,
3369 'unsafe': True,
3371 'UniformMatrix2fv': {
3372 'type': 'PUTn',
3373 'count': 4,
3374 'decoder_func': 'DoUniformMatrix2fv',
3376 'UniformMatrix2x3fv': {
3377 'type': 'PUTn',
3378 'count': 6,
3379 'unsafe': True,
3381 'UniformMatrix2x4fv': {
3382 'type': 'PUTn',
3383 'count': 8,
3384 'unsafe': True,
3386 'UniformMatrix3fv': {
3387 'type': 'PUTn',
3388 'count': 9,
3389 'decoder_func': 'DoUniformMatrix3fv',
3391 'UniformMatrix3x2fv': {
3392 'type': 'PUTn',
3393 'count': 6,
3394 'unsafe': True,
3396 'UniformMatrix3x4fv': {
3397 'type': 'PUTn',
3398 'count': 12,
3399 'unsafe': True,
3401 'UniformMatrix4fv': {
3402 'type': 'PUTn',
3403 'count': 16,
3404 'decoder_func': 'DoUniformMatrix4fv',
3406 'UniformMatrix4x2fv': {
3407 'type': 'PUTn',
3408 'count': 8,
3409 'unsafe': True,
3411 'UniformMatrix4x3fv': {
3412 'type': 'PUTn',
3413 'count': 12,
3414 'unsafe': True,
3416 'UniformBlockBinding': {
3417 'type': 'Custom',
3418 'impl_func': False,
3419 'unsafe': True,
3421 'UnmapBufferCHROMIUM': {
3422 'gen_cmd': False,
3423 'extension': True,
3424 'chromium': True,
3425 'client_test': False,
3427 'UnmapBufferSubDataCHROMIUM': {
3428 'gen_cmd': False,
3429 'extension': True,
3430 'chromium': True,
3431 'client_test': False,
3432 'pepper_interface': 'ChromiumMapSub',
3434 'UnmapBuffer': {
3435 'type': 'Custom',
3436 'unsafe': True,
3438 'UnmapTexSubImage2DCHROMIUM': {
3439 'gen_cmd': False,
3440 'extension': "CHROMIUM_sub_image",
3441 'chromium': True,
3442 'client_test': False,
3443 'pepper_interface': 'ChromiumMapSub',
3445 'UseProgram': {
3446 'type': 'Bind',
3447 'decoder_func': 'DoUseProgram',
3449 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3450 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3451 'VertexAttrib1fv': {
3452 'type': 'PUT',
3453 'count': 1,
3454 'decoder_func': 'DoVertexAttrib1fv',
3456 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3457 'VertexAttrib2fv': {
3458 'type': 'PUT',
3459 'count': 2,
3460 'decoder_func': 'DoVertexAttrib2fv',
3462 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3463 'VertexAttrib3fv': {
3464 'type': 'PUT',
3465 'count': 3,
3466 'decoder_func': 'DoVertexAttrib3fv',
3468 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3469 'VertexAttrib4fv': {
3470 'type': 'PUT',
3471 'count': 4,
3472 'decoder_func': 'DoVertexAttrib4fv',
3474 'VertexAttribI4i': {
3475 'unsafe': True,
3476 'decoder_func': 'DoVertexAttribI4i',
3478 'VertexAttribI4iv': {
3479 'type': 'PUT',
3480 'count': 4,
3481 'unsafe': True,
3482 'decoder_func': 'DoVertexAttribI4iv',
3484 'VertexAttribI4ui': {
3485 'unsafe': True,
3486 'decoder_func': 'DoVertexAttribI4ui',
3488 'VertexAttribI4uiv': {
3489 'type': 'PUT',
3490 'count': 4,
3491 'unsafe': True,
3492 'decoder_func': 'DoVertexAttribI4uiv',
3494 'VertexAttribIPointer': {
3495 'type': 'Manual',
3496 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3497 'GLenumVertexAttribIType type, GLsizei stride, '
3498 'GLuint offset',
3499 'client_test': False,
3500 'unsafe': True,
3502 'VertexAttribPointer': {
3503 'type': 'Manual',
3504 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3505 'GLenumVertexAttribType type, GLboolean normalized, '
3506 'GLsizei stride, GLuint offset',
3507 'client_test': False,
3509 'WaitSync': {
3510 'type': 'Custom',
3511 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3512 'GLuint timeout_0, GLuint timeout_1',
3513 'impl_func': False,
3514 'client_test': False,
3515 'unsafe': True,
3517 'Scissor': {
3518 'type': 'StateSet',
3519 'state': 'Scissor',
3521 'Viewport': {
3522 'decoder_func': 'DoViewport',
3524 'ResizeCHROMIUM': {
3525 'type': 'Custom',
3526 'impl_func': False,
3527 'unit_test': False,
3528 'extension': True,
3529 'chromium': True,
3531 'GetRequestableExtensionsCHROMIUM': {
3532 'type': 'Custom',
3533 'impl_func': False,
3534 'cmd_args': 'uint32_t bucket_id',
3535 'extension': True,
3536 'chromium': True,
3538 'RequestExtensionCHROMIUM': {
3539 'type': 'Custom',
3540 'impl_func': False,
3541 'client_test': False,
3542 'cmd_args': 'uint32_t bucket_id',
3543 'extension': True,
3544 'chromium': True,
3546 'RateLimitOffscreenContextCHROMIUM': {
3547 'gen_cmd': False,
3548 'extension': True,
3549 'chromium': True,
3550 'client_test': False,
3552 'CreateStreamTextureCHROMIUM': {
3553 'type': 'HandWritten',
3554 'impl_func': False,
3555 'gen_cmd': False,
3556 'extension': True,
3557 'chromium': True,
3559 'TexImageIOSurface2DCHROMIUM': {
3560 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3561 'unit_test': False,
3562 'extension': True,
3563 'chromium': True,
3565 'CopyTextureCHROMIUM': {
3566 'decoder_func': 'DoCopyTextureCHROMIUM',
3567 'unit_test': False,
3568 'extension': True,
3569 'chromium': True,
3571 'CopySubTextureCHROMIUM': {
3572 'decoder_func': 'DoCopySubTextureCHROMIUM',
3573 'unit_test': False,
3574 'extension': True,
3575 'chromium': True,
3577 'TexStorage2DEXT': {
3578 'unit_test': False,
3579 'extension': True,
3580 'decoder_func': 'DoTexStorage2DEXT',
3582 'DrawArraysInstancedANGLE': {
3583 'type': 'Manual',
3584 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3585 'GLsizei primcount',
3586 'extension': True,
3587 'unit_test': False,
3588 'pepper_interface': 'InstancedArrays',
3589 'defer_draws': True,
3591 'DrawBuffersEXT': {
3592 'type': 'PUTn',
3593 'decoder_func': 'DoDrawBuffersEXT',
3594 'count': 1,
3595 'client_test': False,
3596 'unit_test': False,
3597 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3598 # work without.
3599 'extension': True,
3600 'pepper_interface': 'DrawBuffers',
3602 'DrawElementsInstancedANGLE': {
3603 'type': 'Manual',
3604 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3605 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3606 'extension': True,
3607 'unit_test': False,
3608 'client_test': False,
3609 'pepper_interface': 'InstancedArrays',
3610 'defer_draws': True,
3612 'VertexAttribDivisorANGLE': {
3613 'type': 'Manual',
3614 'cmd_args': 'GLuint index, GLuint divisor',
3615 'extension': True,
3616 'unit_test': False,
3617 'pepper_interface': 'InstancedArrays',
3619 'GenQueriesEXT': {
3620 'type': 'GENn',
3621 'gl_test_func': 'glGenQueriesARB',
3622 'resource_type': 'Query',
3623 'resource_types': 'Queries',
3624 'unit_test': False,
3625 'pepper_interface': 'Query',
3626 'not_shared': 'True',
3627 'extension': "occlusion_query_EXT",
3629 'DeleteQueriesEXT': {
3630 'type': 'DELn',
3631 'gl_test_func': 'glDeleteQueriesARB',
3632 'resource_type': 'Query',
3633 'resource_types': 'Queries',
3634 'unit_test': False,
3635 'pepper_interface': 'Query',
3636 'extension': "occlusion_query_EXT",
3638 'IsQueryEXT': {
3639 'gen_cmd': False,
3640 'client_test': False,
3641 'pepper_interface': 'Query',
3642 'extension': "occlusion_query_EXT",
3644 'BeginQueryEXT': {
3645 'type': 'Manual',
3646 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3647 'data_transfer_methods': ['shm'],
3648 'gl_test_func': 'glBeginQuery',
3649 'pepper_interface': 'Query',
3650 'extension': "occlusion_query_EXT",
3652 'BeginTransformFeedback': {
3653 'unsafe': True,
3655 'EndQueryEXT': {
3656 'type': 'Manual',
3657 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3658 'gl_test_func': 'glEndnQuery',
3659 'client_test': False,
3660 'pepper_interface': 'Query',
3661 'extension': "occlusion_query_EXT",
3663 'EndTransformFeedback': {
3664 'unsafe': True,
3666 'GetQueryivEXT': {
3667 'gen_cmd': False,
3668 'client_test': False,
3669 'gl_test_func': 'glGetQueryiv',
3670 'pepper_interface': 'Query',
3671 'extension': "occlusion_query_EXT",
3673 'GetQueryObjectuivEXT': {
3674 'gen_cmd': False,
3675 'client_test': False,
3676 'gl_test_func': 'glGetQueryObjectuiv',
3677 'pepper_interface': 'Query',
3678 'extension': "occlusion_query_EXT",
3680 'BindUniformLocationCHROMIUM': {
3681 'type': 'GLchar',
3682 'extension': True,
3683 'data_transfer_methods': ['bucket'],
3684 'needs_size': True,
3685 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3687 'InsertEventMarkerEXT': {
3688 'type': 'GLcharN',
3689 'decoder_func': 'DoInsertEventMarkerEXT',
3690 'expectation': False,
3691 'extension': True,
3693 'PushGroupMarkerEXT': {
3694 'type': 'GLcharN',
3695 'decoder_func': 'DoPushGroupMarkerEXT',
3696 'expectation': False,
3697 'extension': True,
3699 'PopGroupMarkerEXT': {
3700 'decoder_func': 'DoPopGroupMarkerEXT',
3701 'expectation': False,
3702 'extension': True,
3703 'impl_func': False,
3706 'GenVertexArraysOES': {
3707 'type': 'GENn',
3708 'extension': True,
3709 'gl_test_func': 'glGenVertexArraysOES',
3710 'resource_type': 'VertexArray',
3711 'resource_types': 'VertexArrays',
3712 'unit_test': False,
3713 'pepper_interface': 'VertexArrayObject',
3715 'BindVertexArrayOES': {
3716 'type': 'Bind',
3717 'extension': True,
3718 'gl_test_func': 'glBindVertexArrayOES',
3719 'decoder_func': 'DoBindVertexArrayOES',
3720 'gen_func': 'GenVertexArraysOES',
3721 'unit_test': False,
3722 'client_test': False,
3723 'pepper_interface': 'VertexArrayObject',
3725 'DeleteVertexArraysOES': {
3726 'type': 'DELn',
3727 'extension': True,
3728 'gl_test_func': 'glDeleteVertexArraysOES',
3729 'resource_type': 'VertexArray',
3730 'resource_types': 'VertexArrays',
3731 'unit_test': False,
3732 'pepper_interface': 'VertexArrayObject',
3734 'IsVertexArrayOES': {
3735 'type': 'Is',
3736 'extension': True,
3737 'gl_test_func': 'glIsVertexArrayOES',
3738 'decoder_func': 'DoIsVertexArrayOES',
3739 'expectation': False,
3740 'unit_test': False,
3741 'pepper_interface': 'VertexArrayObject',
3743 'BindTexImage2DCHROMIUM': {
3744 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3745 'unit_test': False,
3746 'extension': True,
3747 'chromium': True,
3749 'ReleaseTexImage2DCHROMIUM': {
3750 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3751 'unit_test': False,
3752 'extension': True,
3753 'chromium': True,
3755 'ShallowFinishCHROMIUM': {
3756 'impl_func': False,
3757 'gen_cmd': False,
3758 'extension': True,
3759 'chromium': True,
3760 'client_test': False,
3762 'ShallowFlushCHROMIUM': {
3763 'impl_func': False,
3764 'gen_cmd': False,
3765 'extension': "CHROMIUM_miscellaneous",
3766 'chromium': True,
3767 'client_test': False,
3769 'OrderingBarrierCHROMIUM': {
3770 'impl_func': False,
3771 'gen_cmd': False,
3772 'extension': True,
3773 'chromium': True,
3774 'client_test': False,
3776 'TraceBeginCHROMIUM': {
3777 'type': 'Custom',
3778 'impl_func': False,
3779 'client_test': False,
3780 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3781 'extension': True,
3782 'chromium': True,
3784 'TraceEndCHROMIUM': {
3785 'impl_func': False,
3786 'client_test': False,
3787 'decoder_func': 'DoTraceEndCHROMIUM',
3788 'unit_test': False,
3789 'extension': True,
3790 'chromium': True,
3792 'AsyncTexImage2DCHROMIUM': {
3793 'type': 'Manual',
3794 'data_transfer_methods': ['shm'],
3795 'client_test': False,
3796 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3797 'GLintTextureInternalFormat internalformat, '
3798 'GLsizei width, GLsizei height, '
3799 'GLintTextureBorder border, '
3800 'GLenumTextureFormat format, GLenumPixelType type, '
3801 'const void* pixels, '
3802 'uint32_t async_upload_token, '
3803 'void* sync_data',
3804 'extension': True,
3805 'chromium': True,
3807 'AsyncTexSubImage2DCHROMIUM': {
3808 'type': 'Manual',
3809 'data_transfer_methods': ['shm'],
3810 'client_test': False,
3811 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3812 'GLint xoffset, GLint yoffset, '
3813 'GLsizei width, GLsizei height, '
3814 'GLenumTextureFormat format, GLenumPixelType type, '
3815 'const void* data, '
3816 'uint32_t async_upload_token, '
3817 'void* sync_data',
3818 'extension': True,
3819 'chromium': True,
3821 'WaitAsyncTexImage2DCHROMIUM': {
3822 'type': 'Manual',
3823 'client_test': False,
3824 'extension': True,
3825 'chromium': True,
3827 'WaitAllAsyncTexImage2DCHROMIUM': {
3828 'type': 'Manual',
3829 'client_test': False,
3830 'extension': True,
3831 'chromium': True,
3833 'DiscardFramebufferEXT': {
3834 'type': 'PUTn',
3835 'count': 1,
3836 'decoder_func': 'DoDiscardFramebufferEXT',
3837 'unit_test': False,
3838 'client_test': False,
3839 'extension_flag': 'ext_discard_framebuffer',
3841 'LoseContextCHROMIUM': {
3842 'decoder_func': 'DoLoseContextCHROMIUM',
3843 'unit_test': False,
3844 'extension': True,
3845 'chromium': True,
3847 'InsertSyncPointCHROMIUM': {
3848 'type': 'HandWritten',
3849 'impl_func': False,
3850 'extension': "CHROMIUM_sync_point",
3851 'chromium': True,
3853 'WaitSyncPointCHROMIUM': {
3854 'type': 'Custom',
3855 'impl_func': True,
3856 'extension': "CHROMIUM_sync_point",
3857 'chromium': True,
3858 'trace_level': 1,
3860 'DiscardBackbufferCHROMIUM': {
3861 'type': 'Custom',
3862 'impl_func': True,
3863 'extension': True,
3864 'chromium': True,
3866 'ScheduleOverlayPlaneCHROMIUM': {
3867 'type': 'Custom',
3868 'impl_func': True,
3869 'unit_test': False,
3870 'client_test': False,
3871 'extension': True,
3872 'chromium': True,
3874 'MatrixLoadfCHROMIUM': {
3875 'type': 'PUT',
3876 'count': 16,
3877 'data_type': 'GLfloat',
3878 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3879 'gl_test_func': 'glMatrixLoadfEXT',
3880 'chromium': True,
3881 'extension': True,
3882 'extension_flag': 'chromium_path_rendering',
3884 'MatrixLoadIdentityCHROMIUM': {
3885 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3886 'gl_test_func': 'glMatrixLoadIdentityEXT',
3887 'chromium': True,
3888 'extension': True,
3889 'extension_flag': 'chromium_path_rendering',
3894 def Grouper(n, iterable, fillvalue=None):
3895 """Collect data into fixed-length chunks or blocks"""
3896 args = [iter(iterable)] * n
3897 return itertools.izip_longest(fillvalue=fillvalue, *args)
3900 def SplitWords(input_string):
3901 """Transforms a input_string into a list of lower-case components.
3903 Args:
3904 input_string: the input string.
3906 Returns:
3907 a list of lower-case words.
3909 if input_string.find('_') > -1:
3910 # 'some_TEXT_' -> 'some text'
3911 return input_string.replace('_', ' ').strip().lower().split()
3912 else:
3913 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
3914 # mixed case.
3915 # look for capitalization to cut input_strings
3916 # 'SomeText' -> 'Some Text'
3917 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
3918 # 'Vector3' -> 'Vector 3'
3919 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
3920 return input_string.lower().split()
3923 def Lower(words):
3924 """Makes a lower-case identifier from words.
3926 Args:
3927 words: a list of lower-case words.
3929 Returns:
3930 the lower-case identifier.
3932 return '_'.join(words)
3935 def ToUnderscore(input_string):
3936 """converts CamelCase to camel_case."""
3937 words = SplitWords(input_string)
3938 return Lower(words)
3940 def CachedStateName(item):
3941 if item.get('cached', False):
3942 return 'cached_' + item['name']
3943 return item['name']
3945 def ToGLExtensionString(extension_flag):
3946 """Returns GL-type extension string of a extension flag."""
3947 if extension_flag == "oes_compressed_etc1_rgb8_texture":
3948 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3949 # unfortunate.
3950 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3951 'egl', 'atc', 'etc1', 'angle']
3952 parts = extension_flag.split('_')
3953 return "_".join(
3954 [part.upper() if part in uppercase_words else part for part in parts])
3956 def ToCamelCase(input_string):
3957 """converts ABC_underscore_case to ABCUnderscoreCase."""
3958 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
3960 def GetGLGetTypeConversion(result_type, value_type, value):
3961 """Makes a gl compatible type conversion string for accessing state variables.
3963 Useful when accessing state variables through glGetXXX calls.
3964 glGet documetation (for example, the manual pages):
3965 [...] If glGetIntegerv is called, [...] most floating-point values are
3966 rounded to the nearest integer value. [...]
3968 Args:
3969 result_type: the gl type to be obtained
3970 value_type: the GL type of the state variable
3971 value: the name of the state variable
3973 Returns:
3974 String that converts the state variable to desired GL type according to GL
3975 rules.
3978 if result_type == 'GLint':
3979 if value_type == 'GLfloat':
3980 return 'static_cast<GLint>(round(%s))' % value
3981 return 'static_cast<%s>(%s)' % (result_type, value)
3983 class CWriter(object):
3984 """Writes to a file formatting it for Google's style guidelines."""
3986 def __init__(self, filename):
3987 self.filename = filename
3988 self.content = []
3990 def Write(self, string):
3991 """Writes a string to a file spliting if it's > 80 characters."""
3992 lines = string.splitlines()
3993 num_lines = len(lines)
3994 for ii in range(0, num_lines):
3995 self.content.append(lines[ii])
3996 if ii < (num_lines - 1) or string[-1] == '\n':
3997 self.content.append('\n')
3999 def Close(self):
4000 """Close the file."""
4001 content = "".join(self.content)
4002 write_file = True
4003 if os.path.exists(self.filename):
4004 old_file = open(self.filename, "rb");
4005 old_content = old_file.read()
4006 old_file.close();
4007 if content == old_content:
4008 write_file = False
4009 if write_file:
4010 file = open(self.filename, "wb")
4011 file.write(content)
4012 file.close()
4015 class CHeaderWriter(CWriter):
4016 """Writes a C Header file."""
4018 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
4020 def __init__(self, filename, file_comment = None):
4021 CWriter.__init__(self, filename)
4023 base = os.path.abspath(filename)
4024 while os.path.basename(base) != 'src':
4025 new_base = os.path.dirname(base)
4026 assert new_base != base # Prevent infinite loop.
4027 base = new_base
4029 hpath = os.path.relpath(filename, base)
4030 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
4032 self.Write(_LICENSE)
4033 self.Write(_DO_NOT_EDIT_WARNING)
4034 if not file_comment == None:
4035 self.Write(file_comment)
4036 self.Write("#ifndef %s\n" % self.guard)
4037 self.Write("#define %s\n\n" % self.guard)
4039 def Close(self):
4040 self.Write("#endif // %s\n\n" % self.guard)
4041 CWriter.Close(self)
4043 class TypeHandler(object):
4044 """This class emits code for a particular type of function."""
4046 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
4048 def __init__(self):
4049 pass
4051 def InitFunction(self, func):
4052 """Add or adjust anything type specific for this function."""
4053 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
4054 func.AddCmdArg(DataSizeArgument('data_size'))
4056 def NeedsDataTransferFunction(self, func):
4057 """Overriden from TypeHandler."""
4058 return func.num_pointer_args >= 1
4060 def WriteStruct(self, func, file):
4061 """Writes a structure that matches the arguments to a function."""
4062 comment = func.GetInfo('cmd_comment')
4063 if not comment == None:
4064 file.Write(comment)
4065 file.Write("struct %s {\n" % func.name)
4066 file.Write(" typedef %s ValueType;\n" % func.name)
4067 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
4068 func.WriteCmdArgFlag(file)
4069 func.WriteCmdFlag(file)
4070 file.Write("\n")
4071 result = func.GetInfo('result')
4072 if not result == None:
4073 if len(result) == 1:
4074 file.Write(" typedef %s Result;\n\n" % result[0])
4075 else:
4076 file.Write(" struct Result {\n")
4077 for line in result:
4078 file.Write(" %s;\n" % line)
4079 file.Write(" };\n\n")
4081 func.WriteCmdComputeSize(file)
4082 func.WriteCmdSetHeader(file)
4083 func.WriteCmdInit(file)
4084 func.WriteCmdSet(file)
4086 file.Write(" gpu::CommandHeader header;\n")
4087 args = func.GetCmdArgs()
4088 for arg in args:
4089 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
4091 consts = func.GetCmdConstants()
4092 for const in consts:
4093 file.Write(" static const %s %s = %s;\n" %
4094 (const.cmd_type, const.name, const.GetConstantValue()))
4096 file.Write("};\n")
4097 file.Write("\n")
4099 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
4100 file.Write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
4101 file.Write(" \"size of %s should be %d\");\n" %
4102 (func.name, size))
4103 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
4104 file.Write(" \"offset of %s header should be 0\");\n" %
4105 func.name)
4106 offset = _SIZE_OF_COMMAND_HEADER
4107 for arg in args:
4108 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
4109 (func.name, arg.name, offset))
4110 file.Write(" \"offset of %s %s should be %d\");\n" %
4111 (func.name, arg.name, offset))
4112 offset += _SIZE_OF_UINT32
4113 if not result == None and len(result) > 1:
4114 offset = 0;
4115 for line in result:
4116 parts = line.split()
4117 name = parts[-1]
4118 check = """
4119 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4120 "offset of %(cmd_name)s Result %(field_name)s should be "
4121 "%(offset)d");
4123 file.Write((check.strip() + "\n") % {
4124 'cmd_name': func.name,
4125 'field_name': name,
4126 'offset': offset,
4128 offset += _SIZE_OF_UINT32
4129 file.Write("\n")
4131 def WriteHandlerImplementation(self, func, file):
4132 """Writes the handler implementation for this command."""
4133 if func.IsUnsafe() and func.GetInfo('id_mapping'):
4134 code_no_gen = """ if (!group_->Get%(type)sServiceId(
4135 %(var)s, &%(service_var)s)) {
4136 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4137 return error::kNoError;
4140 code_gen = """ if (!group_->Get%(type)sServiceId(
4141 %(var)s, &%(service_var)s)) {
4142 if (!group_->bind_generates_resource()) {
4143 LOCAL_SET_GL_ERROR(
4144 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4145 return error::kNoError;
4147 GLuint client_id = %(var)s;
4148 gl%(gen_func)s(1, &%(service_var)s);
4149 Create%(type)s(client_id, %(service_var)s);
4152 gen_func = func.GetInfo('gen_func')
4153 for id_type in func.GetInfo('id_mapping'):
4154 service_var = id_type.lower()
4155 if id_type == 'Sync':
4156 service_var = "service_%s" % service_var
4157 file.Write(" GLsync %s = 0;\n" % service_var)
4158 if gen_func and id_type in gen_func:
4159 file.Write(code_gen % { 'type': id_type,
4160 'var': id_type.lower(),
4161 'service_var': service_var,
4162 'func': func.GetGLFunctionName(),
4163 'gen_func': gen_func })
4164 else:
4165 file.Write(code_no_gen % { 'type': id_type,
4166 'var': id_type.lower(),
4167 'service_var': service_var,
4168 'func': func.GetGLFunctionName() })
4169 args = []
4170 for arg in func.GetOriginalArgs():
4171 if arg.type == "GLsync":
4172 args.append("service_%s" % arg.name)
4173 elif arg.name.endswith("size") and arg.type == "GLsizei":
4174 args.append("num_%s" % func.GetLastOriginalArg().name)
4175 elif arg.name == "length":
4176 args.append("nullptr")
4177 else:
4178 args.append(arg.name)
4179 file.Write(" %s(%s);\n" %
4180 (func.GetGLFunctionName(), ", ".join(args)))
4182 def WriteCmdSizeTest(self, func, file):
4183 """Writes the size test for a command."""
4184 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4186 def WriteFormatTest(self, func, file):
4187 """Writes a format test for a command."""
4188 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4189 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4190 (func.name, func.name))
4191 file.Write(" void* next_cmd = cmd.Set(\n")
4192 file.Write(" &cmd")
4193 args = func.GetCmdArgs()
4194 for value, arg in enumerate(args):
4195 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4196 file.Write(");\n")
4197 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4198 func.name)
4199 file.Write(" cmd.header.command);\n")
4200 func.type_handler.WriteCmdSizeTest(func, file)
4201 for value, arg in enumerate(args):
4202 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4203 (arg.type, value + 11, arg.name))
4204 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4205 file.Write(" next_cmd, sizeof(cmd));\n")
4206 file.Write("}\n")
4207 file.Write("\n")
4209 def WriteImmediateFormatTest(self, func, file):
4210 """Writes a format test for an immediate version of a command."""
4211 pass
4213 def WriteBucketFormatTest(self, func, file):
4214 """Writes a format test for a bucket version of a command."""
4215 pass
4217 def WriteGetDataSizeCode(self, func, file):
4218 """Writes the code to set data_size used in validation"""
4219 pass
4221 def WriteImmediateCmdSizeTest(self, func, file):
4222 """Writes a size test for an immediate version of a command."""
4223 file.Write(" // TODO(gman): Compute correct size.\n")
4224 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4226 def __WriteIdMapping(self, func, file):
4227 """Writes client side / service side ID mapping."""
4228 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
4229 return
4230 for id_type in func.GetInfo('id_mapping'):
4231 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
4232 (id_type, id_type.lower(), id_type.lower()))
4234 def WriteImmediateHandlerImplementation (self, func, file):
4235 """Writes the handler impl for the immediate version of a command."""
4236 self.__WriteIdMapping(func, file)
4237 file.Write(" %s(%s);\n" %
4238 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4240 def WriteBucketHandlerImplementation (self, func, file):
4241 """Writes the handler impl for the bucket version of a command."""
4242 self.__WriteIdMapping(func, file)
4243 file.Write(" %s(%s);\n" %
4244 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4246 def WriteServiceHandlerFunctionHeader(self, func, file):
4247 """Writes function header for service implementation handlers."""
4248 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4249 uint32_t immediate_data_size, const void* cmd_data) {
4250 """ % {'name': func.name})
4251 if func.IsUnsafe():
4252 file.Write("""if (!unsafe_es3_apis_enabled())
4253 return error::kUnknownCommand;
4254 """)
4255 file.Write("""const gles2::cmds::%(name)s& c =
4256 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4257 (void)c;
4258 """ % {'name': func.name})
4260 def WriteServiceImplementation(self, func, file):
4261 """Writes the service implementation for a command."""
4262 self.WriteServiceHandlerFunctionHeader(func, file)
4263 self.WriteHandlerExtensionCheck(func, file)
4264 self.WriteHandlerDeferReadWrite(func, file);
4265 if len(func.GetOriginalArgs()) > 0:
4266 last_arg = func.GetLastOriginalArg()
4267 all_but_last_arg = func.GetOriginalArgs()[:-1]
4268 for arg in all_but_last_arg:
4269 arg.WriteGetCode(file)
4270 self.WriteGetDataSizeCode(func, file)
4271 last_arg.WriteGetCode(file)
4272 func.WriteHandlerValidation(file)
4273 func.WriteHandlerImplementation(file)
4274 file.Write(" return error::kNoError;\n")
4275 file.Write("}\n")
4276 file.Write("\n")
4278 def WriteImmediateServiceImplementation(self, func, file):
4279 """Writes the service implementation for an immediate version of command."""
4280 self.WriteServiceHandlerFunctionHeader(func, file)
4281 self.WriteHandlerExtensionCheck(func, file)
4282 self.WriteHandlerDeferReadWrite(func, file);
4283 for arg in func.GetOriginalArgs():
4284 if arg.IsPointer():
4285 self.WriteGetDataSizeCode(func, file)
4286 arg.WriteGetCode(file)
4287 func.WriteHandlerValidation(file)
4288 func.WriteHandlerImplementation(file)
4289 file.Write(" return error::kNoError;\n")
4290 file.Write("}\n")
4291 file.Write("\n")
4293 def WriteBucketServiceImplementation(self, func, file):
4294 """Writes the service implementation for a bucket version of command."""
4295 self.WriteServiceHandlerFunctionHeader(func, file)
4296 self.WriteHandlerExtensionCheck(func, file)
4297 self.WriteHandlerDeferReadWrite(func, file);
4298 for arg in func.GetCmdArgs():
4299 arg.WriteGetCode(file)
4300 func.WriteHandlerValidation(file)
4301 func.WriteHandlerImplementation(file)
4302 file.Write(" return error::kNoError;\n")
4303 file.Write("}\n")
4304 file.Write("\n")
4306 def WriteHandlerExtensionCheck(self, func, file):
4307 if func.GetInfo('extension_flag'):
4308 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
4309 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4310 " \"function not available\");\n" % func.original_name)
4311 file.Write(" return error::kNoError;")
4312 file.Write(" }\n\n")
4314 def WriteHandlerDeferReadWrite(self, func, file):
4315 """Writes the code to handle deferring reads or writes."""
4316 defer_draws = func.GetInfo('defer_draws')
4317 defer_reads = func.GetInfo('defer_reads')
4318 if defer_draws or defer_reads:
4319 file.Write(" error::Error error;\n")
4320 if defer_draws:
4321 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
4322 file.Write(" if (error != error::kNoError)\n")
4323 file.Write(" return error;\n")
4324 if defer_reads:
4325 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
4326 file.Write(" if (error != error::kNoError)\n")
4327 file.Write(" return error;\n")
4329 def WriteValidUnitTest(self, func, file, test, *extras):
4330 """Writes a valid unit test for the service implementation."""
4331 if func.GetInfo('expectation') == False:
4332 test = self._remove_expected_call_re.sub('', test)
4333 name = func.name
4334 arg_strings = [
4335 arg.GetValidArg(func) \
4336 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4338 gl_arg_strings = [
4339 arg.GetValidGLArg(func) \
4340 for arg in func.GetOriginalArgs()
4342 gl_func_name = func.GetGLTestFunctionName()
4343 vars = {
4344 'name':name,
4345 'gl_func_name': gl_func_name,
4346 'args': ", ".join(arg_strings),
4347 'gl_args': ", ".join(gl_arg_strings),
4349 for extra in extras:
4350 vars.update(extra)
4351 old_test = ""
4352 while (old_test != test):
4353 old_test = test
4354 test = test % vars
4355 file.Write(test % vars)
4357 def WriteInvalidUnitTest(self, func, file, test, *extras):
4358 """Writes an invalid unit test for the service implementation."""
4359 if func.IsUnsafe():
4360 return
4361 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4362 # Service implementation does not test constants, as they are not part of
4363 # the call in the service side.
4364 if invalid_arg.IsConstant():
4365 continue
4367 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4368 for value_index in range(0, num_invalid_values):
4369 arg_strings = []
4370 parse_result = "kNoError"
4371 gl_error = None
4372 for arg in func.GetOriginalArgs():
4373 if arg.IsConstant():
4374 continue
4375 if invalid_arg is arg:
4376 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4377 value_index)
4378 else:
4379 arg_string = arg.GetValidArg(func)
4380 arg_strings.append(arg_string)
4381 gl_arg_strings = []
4382 for arg in func.GetOriginalArgs():
4383 gl_arg_strings.append("_")
4384 gl_func_name = func.GetGLTestFunctionName()
4385 gl_error_test = ''
4386 if not gl_error == None:
4387 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4389 vars = {
4390 'name': func.name,
4391 'arg_index': invalid_arg_index,
4392 'value_index': value_index,
4393 'gl_func_name': gl_func_name,
4394 'args': ", ".join(arg_strings),
4395 'all_but_last_args': ", ".join(arg_strings[:-1]),
4396 'gl_args': ", ".join(gl_arg_strings),
4397 'parse_result': parse_result,
4398 'gl_error_test': gl_error_test,
4400 for extra in extras:
4401 vars.update(extra)
4402 file.Write(test % vars)
4404 def WriteServiceUnitTest(self, func, file, *extras):
4405 """Writes the service unit test for a command."""
4407 if func.name == 'Enable':
4408 valid_test = """
4409 TEST_P(%(test_name)s, %(name)sValidArgs) {
4410 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4411 SpecializedSetup<cmds::%(name)s, 0>(true);
4412 cmds::%(name)s cmd;
4413 cmd.Init(%(args)s);"""
4414 elif func.name == 'Disable':
4415 valid_test = """
4416 TEST_P(%(test_name)s, %(name)sValidArgs) {
4417 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4418 SpecializedSetup<cmds::%(name)s, 0>(true);
4419 cmds::%(name)s cmd;
4420 cmd.Init(%(args)s);"""
4421 else:
4422 valid_test = """
4423 TEST_P(%(test_name)s, %(name)sValidArgs) {
4424 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4425 SpecializedSetup<cmds::%(name)s, 0>(true);
4426 cmds::%(name)s cmd;
4427 cmd.Init(%(args)s);"""
4428 if func.IsUnsafe():
4429 valid_test += """
4430 decoder_->set_unsafe_es3_apis_enabled(true);
4431 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4432 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4433 decoder_->set_unsafe_es3_apis_enabled(false);
4434 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4437 else:
4438 valid_test += """
4439 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4440 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4443 self.WriteValidUnitTest(func, file, valid_test, *extras)
4445 if not func.IsUnsafe():
4446 invalid_test = """
4447 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4448 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4449 SpecializedSetup<cmds::%(name)s, 0>(false);
4450 cmds::%(name)s cmd;
4451 cmd.Init(%(args)s);
4452 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4455 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4457 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4458 """Writes the service unit test for an immediate command."""
4459 file.Write("// TODO(gman): %s\n" % func.name)
4461 def WriteImmediateValidationCode(self, func, file):
4462 """Writes the validation code for an immediate version of a command."""
4463 pass
4465 def WriteBucketServiceUnitTest(self, func, file, *extras):
4466 """Writes the service unit test for a bucket command."""
4467 file.Write("// TODO(gman): %s\n" % func.name)
4469 def WriteBucketValidationCode(self, func, file):
4470 """Writes the validation code for a bucket version of a command."""
4471 file.Write("// TODO(gman): %s\n" % func.name)
4473 def WriteGLES2ImplementationDeclaration(self, func, file):
4474 """Writes the GLES2 Implemention declaration."""
4475 impl_decl = func.GetInfo('impl_decl')
4476 if impl_decl == None or impl_decl == True:
4477 file.Write("%s %s(%s) override;\n" %
4478 (func.return_type, func.original_name,
4479 func.MakeTypedOriginalArgString("")))
4480 file.Write("\n")
4482 def WriteGLES2CLibImplementation(self, func, file):
4483 file.Write("%s GLES2%s(%s) {\n" %
4484 (func.return_type, func.name,
4485 func.MakeTypedOriginalArgString("")))
4486 result_string = "return "
4487 if func.return_type == "void":
4488 result_string = ""
4489 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4490 (result_string, func.original_name,
4491 func.MakeOriginalArgString("")))
4492 file.Write("}\n")
4494 def WriteGLES2Header(self, func, file):
4495 """Writes a re-write macro for GLES"""
4496 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4498 def WriteClientGLCallLog(self, func, file):
4499 """Writes a logging macro for the client side code."""
4500 comma = ""
4501 if len(func.GetOriginalArgs()):
4502 comma = " << "
4503 file.Write(
4504 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4505 (func.original_name, comma, func.MakeLogArgString()))
4507 def WriteClientGLReturnLog(self, func, file):
4508 """Writes the return value logging code."""
4509 if func.return_type != "void":
4510 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4512 def WriteGLES2ImplementationHeader(self, func, file):
4513 """Writes the GLES2 Implemention."""
4514 self.WriteGLES2ImplementationDeclaration(func, file)
4516 def WriteGLES2TraceImplementationHeader(self, func, file):
4517 """Writes the GLES2 Trace Implemention header."""
4518 file.Write("%s %s(%s) override;\n" %
4519 (func.return_type, func.original_name,
4520 func.MakeTypedOriginalArgString("")))
4522 def WriteGLES2TraceImplementation(self, func, file):
4523 """Writes the GLES2 Trace Implemention."""
4524 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4525 (func.return_type, func.original_name,
4526 func.MakeTypedOriginalArgString("")))
4527 result_string = "return "
4528 if func.return_type == "void":
4529 result_string = ""
4530 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4531 func.name)
4532 file.Write(" %sgl_->%s(%s);\n" %
4533 (result_string, func.name, func.MakeOriginalArgString("")))
4534 file.Write("}\n")
4535 file.Write("\n")
4537 def WriteGLES2Implementation(self, func, file):
4538 """Writes the GLES2 Implemention."""
4539 impl_func = func.GetInfo('impl_func')
4540 impl_decl = func.GetInfo('impl_decl')
4541 gen_cmd = func.GetInfo('gen_cmd')
4542 if (func.can_auto_generate and
4543 (impl_func == None or impl_func == True) and
4544 (impl_decl == None or impl_decl == True) and
4545 (gen_cmd == None or gen_cmd == True)):
4546 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4547 (func.return_type, func.original_name,
4548 func.MakeTypedOriginalArgString("")))
4549 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4550 self.WriteClientGLCallLog(func, file)
4551 func.WriteDestinationInitalizationValidation(file)
4552 for arg in func.GetOriginalArgs():
4553 arg.WriteClientSideValidationCode(file, func)
4554 file.Write(" helper_->%s(%s);\n" %
4555 (func.name, func.MakeHelperArgString("")))
4556 file.Write(" CheckGLError();\n")
4557 self.WriteClientGLReturnLog(func, file)
4558 file.Write("}\n")
4559 file.Write("\n")
4561 def WriteGLES2InterfaceHeader(self, func, file):
4562 """Writes the GLES2 Interface."""
4563 file.Write("virtual %s %s(%s) = 0;\n" %
4564 (func.return_type, func.original_name,
4565 func.MakeTypedOriginalArgString("")))
4567 def WriteMojoGLES2ImplHeader(self, func, file):
4568 """Writes the Mojo GLES2 implementation header."""
4569 file.Write("%s %s(%s) override;\n" %
4570 (func.return_type, func.original_name,
4571 func.MakeTypedOriginalArgString("")))
4573 def WriteMojoGLES2Impl(self, func, file):
4574 """Writes the Mojo GLES2 implementation."""
4575 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4576 (func.return_type, func.original_name,
4577 func.MakeTypedOriginalArgString("")))
4578 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4579 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4580 "occlusion_query_EXT"]
4581 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4582 file.Write("MojoGLES2MakeCurrent(context_);");
4583 func_return = "gl" + func.original_name + "(" + \
4584 func.MakeOriginalArgString("") + ");"
4585 if func.return_type == "void":
4586 file.Write(func_return);
4587 else:
4588 file.Write("return " + func_return);
4589 else:
4590 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4591 func.original_name);
4592 if func.return_type != "void":
4593 file.Write("return 0;")
4594 file.Write("}")
4596 def WriteGLES2InterfaceStub(self, func, file):
4597 """Writes the GLES2 Interface stub declaration."""
4598 file.Write("%s %s(%s) override;\n" %
4599 (func.return_type, func.original_name,
4600 func.MakeTypedOriginalArgString("")))
4602 def WriteGLES2InterfaceStubImpl(self, func, file):
4603 """Writes the GLES2 Interface stub declaration."""
4604 args = func.GetOriginalArgs()
4605 arg_string = ", ".join(
4606 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4607 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4608 (func.return_type, func.original_name, arg_string))
4609 if func.return_type != "void":
4610 file.Write(" return 0;\n")
4611 file.Write("}\n")
4613 def WriteGLES2ImplementationUnitTest(self, func, file):
4614 """Writes the GLES2 Implemention unit test."""
4615 client_test = func.GetInfo('client_test')
4616 if (func.can_auto_generate and
4617 (client_test == None or client_test == True)):
4618 code = """
4619 TEST_F(GLES2ImplementationTest, %(name)s) {
4620 struct Cmds {
4621 cmds::%(name)s cmd;
4623 Cmds expected;
4624 expected.cmd.Init(%(cmd_args)s);
4626 gl_->%(name)s(%(args)s);
4627 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4630 cmd_arg_strings = [
4631 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4634 gl_arg_strings = [
4635 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4638 file.Write(code % {
4639 'name': func.name,
4640 'args': ", ".join(gl_arg_strings),
4641 'cmd_args': ", ".join(cmd_arg_strings),
4644 # Test constants for invalid values, as they are not tested by the
4645 # service.
4646 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4647 if constants:
4648 code = """
4649 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4650 gl_->%(name)s(%(args)s);
4651 EXPECT_TRUE(NoCommandsWritten());
4652 EXPECT_EQ(%(gl_error)s, CheckError());
4655 for invalid_arg in constants:
4656 gl_arg_strings = []
4657 invalid = invalid_arg.GetInvalidArg(func)
4658 for arg in func.GetOriginalArgs():
4659 if arg is invalid_arg:
4660 gl_arg_strings.append(invalid[0])
4661 else:
4662 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4664 file.Write(code % {
4665 'name': func.name,
4666 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4667 'args': ", ".join(gl_arg_strings),
4668 'gl_error': invalid[2],
4670 else:
4671 if client_test != False:
4672 file.Write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4674 def WriteDestinationInitalizationValidation(self, func, file):
4675 """Writes the client side destintion initialization validation."""
4676 for arg in func.GetOriginalArgs():
4677 arg.WriteDestinationInitalizationValidation(file, func)
4679 def WriteTraceEvent(self, func, file):
4680 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4681 func.original_name)
4683 def WriteImmediateCmdComputeSize(self, func, file):
4684 """Writes the size computation code for the immediate version of a cmd."""
4685 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4686 file.Write(" return static_cast<uint32_t>(\n")
4687 file.Write(" sizeof(ValueType) + // NOLINT\n")
4688 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4689 file.Write(" }\n")
4690 file.Write("\n")
4692 def WriteImmediateCmdSetHeader(self, func, file):
4693 """Writes the SetHeader function for the immediate version of a cmd."""
4694 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4695 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4696 file.Write(" }\n")
4697 file.Write("\n")
4699 def WriteImmediateCmdInit(self, func, file):
4700 """Writes the Init function for the immediate version of a command."""
4701 raise NotImplementedError(func.name)
4703 def WriteImmediateCmdSet(self, func, file):
4704 """Writes the Set function for the immediate version of a command."""
4705 raise NotImplementedError(func.name)
4707 def WriteCmdHelper(self, func, file):
4708 """Writes the cmd helper definition for a cmd."""
4709 code = """ void %(name)s(%(typed_args)s) {
4710 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4711 if (c) {
4712 c->Init(%(args)s);
4717 file.Write(code % {
4718 "name": func.name,
4719 "typed_args": func.MakeTypedCmdArgString(""),
4720 "args": func.MakeCmdArgString(""),
4723 def WriteImmediateCmdHelper(self, func, file):
4724 """Writes the cmd helper definition for the immediate version of a cmd."""
4725 code = """ void %(name)s(%(typed_args)s) {
4726 const uint32_t s = 0; // TODO(gman): compute correct size
4727 gles2::cmds::%(name)s* c =
4728 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4729 if (c) {
4730 c->Init(%(args)s);
4735 file.Write(code % {
4736 "name": func.name,
4737 "typed_args": func.MakeTypedCmdArgString(""),
4738 "args": func.MakeCmdArgString(""),
4742 class StateSetHandler(TypeHandler):
4743 """Handler for commands that simply set state."""
4745 def __init__(self):
4746 TypeHandler.__init__(self)
4748 def WriteHandlerImplementation(self, func, file):
4749 """Overrriden from TypeHandler."""
4750 state_name = func.GetInfo('state')
4751 state = _STATES[state_name]
4752 states = state['states']
4753 args = func.GetOriginalArgs()
4754 for ndx,item in enumerate(states):
4755 code = []
4756 if 'range_checks' in item:
4757 for range_check in item['range_checks']:
4758 code.append("%s %s" % (args[ndx].name, range_check['check']))
4759 if 'nan_check' in item:
4760 # Drivers might generate an INVALID_VALUE error when a value is set
4761 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4762 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4763 # Make this behavior consistent within Chromium, and avoid leaking GL
4764 # errors by generating the error in the command buffer instead of
4765 # letting the GL driver generate it.
4766 code.append("std::isnan(%s)" % args[ndx].name)
4767 if len(code):
4768 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4769 file.Write(
4770 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4771 ' "%s", "%s out of range");\n' %
4772 (func.name, args[ndx].name))
4773 file.Write(" return error::kNoError;\n")
4774 file.Write(" }\n")
4775 code = []
4776 for ndx,item in enumerate(states):
4777 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4778 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4779 for ndx,item in enumerate(states):
4780 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4781 if 'state_flag' in state:
4782 file.Write(" %s = true;\n" % state['state_flag'])
4783 if not func.GetInfo("no_gl"):
4784 for ndx,item in enumerate(states):
4785 if item.get('cached', False):
4786 file.Write(" state_.%s = %s;\n" %
4787 (CachedStateName(item), args[ndx].name))
4788 file.Write(" %s(%s);\n" %
4789 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4790 file.Write(" }\n")
4792 def WriteServiceUnitTest(self, func, file, *extras):
4793 """Overrriden from TypeHandler."""
4794 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
4795 state_name = func.GetInfo('state')
4796 state = _STATES[state_name]
4797 states = state['states']
4798 for ndx,item in enumerate(states):
4799 if 'range_checks' in item:
4800 for check_ndx, range_check in enumerate(item['range_checks']):
4801 valid_test = """
4802 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4803 SpecializedSetup<cmds::%(name)s, 0>(false);
4804 cmds::%(name)s cmd;
4805 cmd.Init(%(args)s);
4806 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4807 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4810 name = func.name
4811 arg_strings = [
4812 arg.GetValidArg(func) \
4813 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4816 arg_strings[ndx] = range_check['test_value']
4817 vars = {
4818 'name': name,
4819 'ndx': ndx,
4820 'check_ndx': check_ndx,
4821 'args': ", ".join(arg_strings),
4823 for extra in extras:
4824 vars.update(extra)
4825 file.Write(valid_test % vars)
4826 if 'nan_check' in item:
4827 valid_test = """
4828 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4829 SpecializedSetup<cmds::%(name)s, 0>(false);
4830 cmds::%(name)s cmd;
4831 cmd.Init(%(args)s);
4832 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4833 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4836 name = func.name
4837 arg_strings = [
4838 arg.GetValidArg(func) \
4839 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4842 arg_strings[ndx] = 'nanf("")'
4843 vars = {
4844 'name': name,
4845 'ndx': ndx,
4846 'args': ", ".join(arg_strings),
4848 for extra in extras:
4849 vars.update(extra)
4850 file.Write(valid_test % vars)
4853 class StateSetRGBAlphaHandler(TypeHandler):
4854 """Handler for commands that simply set state that have rgb/alpha."""
4856 def __init__(self):
4857 TypeHandler.__init__(self)
4859 def WriteHandlerImplementation(self, func, file):
4860 """Overrriden from TypeHandler."""
4861 state_name = func.GetInfo('state')
4862 state = _STATES[state_name]
4863 states = state['states']
4864 args = func.GetOriginalArgs()
4865 num_args = len(args)
4866 code = []
4867 for ndx,item in enumerate(states):
4868 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
4869 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4870 for ndx, item in enumerate(states):
4871 file.Write(" state_.%s = %s;\n" %
4872 (item['name'], args[ndx % num_args].name))
4873 if 'state_flag' in state:
4874 file.Write(" %s = true;\n" % state['state_flag'])
4875 if not func.GetInfo("no_gl"):
4876 file.Write(" %s(%s);\n" %
4877 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4878 file.Write(" }\n")
4881 class StateSetFrontBackSeparateHandler(TypeHandler):
4882 """Handler for commands that simply set state that have front/back."""
4884 def __init__(self):
4885 TypeHandler.__init__(self)
4887 def WriteHandlerImplementation(self, func, file):
4888 """Overrriden from TypeHandler."""
4889 state_name = func.GetInfo('state')
4890 state = _STATES[state_name]
4891 states = state['states']
4892 args = func.GetOriginalArgs()
4893 face = args[0].name
4894 num_args = len(args)
4895 file.Write(" bool changed = false;\n")
4896 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4897 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4898 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4899 code = []
4900 for ndx, item in enumerate(group):
4901 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
4902 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
4903 file.Write(" }\n")
4904 file.Write(" if (changed) {\n")
4905 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4906 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4907 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4908 for ndx, item in enumerate(group):
4909 file.Write(" state_.%s = %s;\n" %
4910 (item['name'], args[ndx + 1].name))
4911 file.Write(" }\n")
4912 if 'state_flag' in state:
4913 file.Write(" %s = true;\n" % state['state_flag'])
4914 if not func.GetInfo("no_gl"):
4915 file.Write(" %s(%s);\n" %
4916 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4917 file.Write(" }\n")
4920 class StateSetFrontBackHandler(TypeHandler):
4921 """Handler for commands that simply set state that set both front/back."""
4923 def __init__(self):
4924 TypeHandler.__init__(self)
4926 def WriteHandlerImplementation(self, func, file):
4927 """Overrriden from TypeHandler."""
4928 state_name = func.GetInfo('state')
4929 state = _STATES[state_name]
4930 states = state['states']
4931 args = func.GetOriginalArgs()
4932 num_args = len(args)
4933 code = []
4934 for group_ndx, group in enumerate(Grouper(num_args, states)):
4935 for ndx, item in enumerate(group):
4936 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4937 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4938 for group_ndx, group in enumerate(Grouper(num_args, states)):
4939 for ndx, item in enumerate(group):
4940 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4941 if 'state_flag' in state:
4942 file.Write(" %s = true;\n" % state['state_flag'])
4943 if not func.GetInfo("no_gl"):
4944 file.Write(" %s(%s);\n" %
4945 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4946 file.Write(" }\n")
4949 class StateSetNamedParameter(TypeHandler):
4950 """Handler for commands that set a state chosen with an enum parameter."""
4952 def __init__(self):
4953 TypeHandler.__init__(self)
4955 def WriteHandlerImplementation(self, func, file):
4956 """Overridden from TypeHandler."""
4957 state_name = func.GetInfo('state')
4958 state = _STATES[state_name]
4959 states = state['states']
4960 args = func.GetOriginalArgs()
4961 num_args = len(args)
4962 assert num_args == 2
4963 file.Write(" switch (%s) {\n" % args[0].name)
4964 for state in states:
4965 file.Write(" case %s:\n" % state['enum'])
4966 file.Write(" if (state_.%s != %s) {\n" %
4967 (state['name'], args[1].name))
4968 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
4969 if not func.GetInfo("no_gl"):
4970 file.Write(" %s(%s);\n" %
4971 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4972 file.Write(" }\n")
4973 file.Write(" break;\n")
4974 file.Write(" default:\n")
4975 file.Write(" NOTREACHED();\n")
4976 file.Write(" }\n")
4979 class CustomHandler(TypeHandler):
4980 """Handler for commands that are auto-generated but require minor tweaks."""
4982 def __init__(self):
4983 TypeHandler.__init__(self)
4985 def WriteServiceImplementation(self, func, file):
4986 """Overrriden from TypeHandler."""
4987 pass
4989 def WriteImmediateServiceImplementation(self, func, file):
4990 """Overrriden from TypeHandler."""
4991 pass
4993 def WriteBucketServiceImplementation(self, func, file):
4994 """Overrriden from TypeHandler."""
4995 pass
4997 def WriteServiceUnitTest(self, func, file, *extras):
4998 """Overrriden from TypeHandler."""
4999 file.Write("// TODO(gman): %s\n\n" % func.name)
5001 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5002 """Overrriden from TypeHandler."""
5003 file.Write("// TODO(gman): %s\n\n" % func.name)
5005 def WriteImmediateCmdGetTotalSize(self, func, file):
5006 """Overrriden from TypeHandler."""
5007 file.Write(
5008 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5010 def WriteImmediateCmdInit(self, func, file):
5011 """Overrriden from TypeHandler."""
5012 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5013 self.WriteImmediateCmdGetTotalSize(func, file)
5014 file.Write(" SetHeader(total_size);\n")
5015 args = func.GetCmdArgs()
5016 for arg in args:
5017 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5018 file.Write(" }\n")
5019 file.Write("\n")
5021 def WriteImmediateCmdSet(self, func, file):
5022 """Overrriden from TypeHandler."""
5023 copy_args = func.MakeCmdArgString("_", False)
5024 file.Write(" void* Set(void* cmd%s) {\n" %
5025 func.MakeTypedCmdArgString("_", True))
5026 self.WriteImmediateCmdGetTotalSize(func, file)
5027 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5028 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5029 "cmd, total_size);\n")
5030 file.Write(" }\n")
5031 file.Write("\n")
5034 class TodoHandler(CustomHandler):
5035 """Handle for commands that are not yet implemented."""
5037 def NeedsDataTransferFunction(self, func):
5038 """Overriden from TypeHandler."""
5039 return False
5041 def WriteImmediateFormatTest(self, func, file):
5042 """Overrriden from TypeHandler."""
5043 pass
5045 def WriteGLES2ImplementationUnitTest(self, func, file):
5046 """Overrriden from TypeHandler."""
5047 pass
5049 def WriteGLES2Implementation(self, func, file):
5050 """Overrriden from TypeHandler."""
5051 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5052 (func.return_type, func.original_name,
5053 func.MakeTypedOriginalArgString("")))
5054 file.Write(" // TODO: for now this is a no-op\n")
5055 file.Write(
5056 " SetGLError("
5057 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5058 func.name)
5059 if func.return_type != "void":
5060 file.Write(" return 0;\n")
5061 file.Write("}\n")
5062 file.Write("\n")
5064 def WriteServiceImplementation(self, func, file):
5065 """Overrriden from TypeHandler."""
5066 self.WriteServiceHandlerFunctionHeader(func, file)
5067 file.Write(" // TODO: for now this is a no-op\n")
5068 file.Write(
5069 " LOCAL_SET_GL_ERROR("
5070 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5071 func.name)
5072 file.Write(" return error::kNoError;\n")
5073 file.Write("}\n")
5074 file.Write("\n")
5077 class HandWrittenHandler(CustomHandler):
5078 """Handler for comands where everything must be written by hand."""
5080 def InitFunction(self, func):
5081 """Add or adjust anything type specific for this function."""
5082 CustomHandler.InitFunction(self, func)
5083 func.can_auto_generate = False
5085 def NeedsDataTransferFunction(self, func):
5086 """Overriden from TypeHandler."""
5087 # If specified explicitly, force the data transfer method.
5088 if func.GetInfo('data_transfer_methods'):
5089 return True
5090 return False
5092 def WriteStruct(self, func, file):
5093 """Overrriden from TypeHandler."""
5094 pass
5096 def WriteDocs(self, func, file):
5097 """Overrriden from TypeHandler."""
5098 pass
5100 def WriteServiceUnitTest(self, func, file, *extras):
5101 """Overrriden from TypeHandler."""
5102 file.Write("// TODO(gman): %s\n\n" % func.name)
5104 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5105 """Overrriden from TypeHandler."""
5106 file.Write("// TODO(gman): %s\n\n" % func.name)
5108 def WriteBucketServiceUnitTest(self, func, file, *extras):
5109 """Overrriden from TypeHandler."""
5110 file.Write("// TODO(gman): %s\n\n" % func.name)
5112 def WriteServiceImplementation(self, func, file):
5113 """Overrriden from TypeHandler."""
5114 pass
5116 def WriteImmediateServiceImplementation(self, func, file):
5117 """Overrriden from TypeHandler."""
5118 pass
5120 def WriteBucketServiceImplementation(self, func, file):
5121 """Overrriden from TypeHandler."""
5122 pass
5124 def WriteImmediateCmdHelper(self, func, file):
5125 """Overrriden from TypeHandler."""
5126 pass
5128 def WriteCmdHelper(self, func, file):
5129 """Overrriden from TypeHandler."""
5130 pass
5132 def WriteFormatTest(self, func, file):
5133 """Overrriden from TypeHandler."""
5134 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5136 def WriteImmediateFormatTest(self, func, file):
5137 """Overrriden from TypeHandler."""
5138 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5140 def WriteBucketFormatTest(self, func, file):
5141 """Overrriden from TypeHandler."""
5142 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5146 class ManualHandler(CustomHandler):
5147 """Handler for commands who's handlers must be written by hand."""
5149 def __init__(self):
5150 CustomHandler.__init__(self)
5152 def InitFunction(self, func):
5153 """Overrriden from TypeHandler."""
5154 if (func.name == 'CompressedTexImage2DBucket' or
5155 func.name == 'CompressedTexImage3DBucket'):
5156 func.cmd_args = func.cmd_args[:-1]
5157 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5158 else:
5159 CustomHandler.InitFunction(self, func)
5161 def WriteServiceImplementation(self, func, file):
5162 """Overrriden from TypeHandler."""
5163 pass
5165 def WriteBucketServiceImplementation(self, func, file):
5166 """Overrriden from TypeHandler."""
5167 pass
5169 def WriteServiceUnitTest(self, func, file, *extras):
5170 """Overrriden from TypeHandler."""
5171 file.Write("// TODO(gman): %s\n\n" % func.name)
5173 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5174 """Overrriden from TypeHandler."""
5175 file.Write("// TODO(gman): %s\n\n" % func.name)
5177 def WriteImmediateServiceImplementation(self, func, file):
5178 """Overrriden from TypeHandler."""
5179 pass
5181 def WriteImmediateFormatTest(self, func, file):
5182 """Overrriden from TypeHandler."""
5183 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
5185 def WriteGLES2Implementation(self, func, file):
5186 """Overrriden from TypeHandler."""
5187 if func.GetInfo('impl_func'):
5188 super(ManualHandler, self).WriteGLES2Implementation(func, file)
5190 def WriteGLES2ImplementationHeader(self, func, file):
5191 """Overrriden from TypeHandler."""
5192 file.Write("%s %s(%s) override;\n" %
5193 (func.return_type, func.original_name,
5194 func.MakeTypedOriginalArgString("")))
5195 file.Write("\n")
5197 def WriteImmediateCmdGetTotalSize(self, func, file):
5198 """Overrriden from TypeHandler."""
5199 # TODO(gman): Move this data to _FUNCTION_INFO?
5200 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
5203 class DataHandler(TypeHandler):
5204 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5205 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5206 def __init__(self):
5207 TypeHandler.__init__(self)
5209 def InitFunction(self, func):
5210 """Overrriden from TypeHandler."""
5211 if (func.name == 'CompressedTexSubImage2DBucket' or
5212 func.name == 'CompressedTexSubImage3DBucket'):
5213 func.cmd_args = func.cmd_args[:-1]
5214 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5216 def WriteGetDataSizeCode(self, func, file):
5217 """Overrriden from TypeHandler."""
5218 # TODO(gman): Move this data to _FUNCTION_INFO?
5219 name = func.name
5220 if name.endswith("Immediate"):
5221 name = name[0:-9]
5222 if name == 'BufferData' or name == 'BufferSubData':
5223 file.Write(" uint32_t data_size = size;\n")
5224 elif (name == 'CompressedTexImage2D' or
5225 name == 'CompressedTexSubImage2D' or
5226 name == 'CompressedTexImage3D' or
5227 name == 'CompressedTexSubImage3D'):
5228 file.Write(" uint32_t data_size = imageSize;\n")
5229 elif (name == 'CompressedTexSubImage2DBucket' or
5230 name == 'CompressedTexSubImage3DBucket'):
5231 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5232 file.Write(" uint32_t data_size = bucket->size();\n")
5233 file.Write(" GLsizei imageSize = data_size;\n")
5234 elif name == 'TexImage2D' or name == 'TexSubImage2D':
5235 code = """ uint32_t data_size;
5236 if (!GLES2Util::ComputeImageDataSize(
5237 width, height, format, type, unpack_alignment_, &data_size)) {
5238 return error::kOutOfBounds;
5241 file.Write(code)
5242 else:
5243 file.Write(
5244 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5246 def WriteImmediateCmdGetTotalSize(self, func, file):
5247 """Overrriden from TypeHandler."""
5248 pass
5250 def WriteImmediateCmdSizeTest(self, func, file):
5251 """Overrriden from TypeHandler."""
5252 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5254 def WriteImmediateCmdInit(self, func, file):
5255 """Overrriden from TypeHandler."""
5256 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5257 self.WriteImmediateCmdGetTotalSize(func, file)
5258 file.Write(" SetHeader(total_size);\n")
5259 args = func.GetCmdArgs()
5260 for arg in args:
5261 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5262 file.Write(" }\n")
5263 file.Write("\n")
5265 def WriteImmediateCmdSet(self, func, file):
5266 """Overrriden from TypeHandler."""
5267 copy_args = func.MakeCmdArgString("_", False)
5268 file.Write(" void* Set(void* cmd%s) {\n" %
5269 func.MakeTypedCmdArgString("_", True))
5270 self.WriteImmediateCmdGetTotalSize(func, file)
5271 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5272 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5273 "cmd, total_size);\n")
5274 file.Write(" }\n")
5275 file.Write("\n")
5277 def WriteImmediateFormatTest(self, func, file):
5278 """Overrriden from TypeHandler."""
5279 # TODO(gman): Remove this exception.
5280 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
5281 return
5283 def WriteServiceUnitTest(self, func, file, *extras):
5284 """Overrriden from TypeHandler."""
5285 file.Write("// TODO(gman): %s\n\n" % func.name)
5287 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5288 """Overrriden from TypeHandler."""
5289 file.Write("// TODO(gman): %s\n\n" % func.name)
5291 def WriteBucketServiceImplementation(self, func, file):
5292 """Overrriden from TypeHandler."""
5293 if ((not func.name == 'CompressedTexSubImage2DBucket') and
5294 (not func.name == 'CompressedTexSubImage3DBucket')):
5295 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
5298 class BindHandler(TypeHandler):
5299 """Handler for glBind___ type functions."""
5301 def __init__(self):
5302 TypeHandler.__init__(self)
5304 def WriteServiceUnitTest(self, func, file, *extras):
5305 """Overrriden from TypeHandler."""
5307 if len(func.GetOriginalArgs()) == 1:
5308 valid_test = """
5309 TEST_P(%(test_name)s, %(name)sValidArgs) {
5310 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5311 SpecializedSetup<cmds::%(name)s, 0>(true);
5312 cmds::%(name)s cmd;
5313 cmd.Init(%(args)s);"""
5314 if func.IsUnsafe():
5315 valid_test += """
5316 decoder_->set_unsafe_es3_apis_enabled(true);
5317 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5318 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5319 decoder_->set_unsafe_es3_apis_enabled(false);
5320 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5323 else:
5324 valid_test += """
5325 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5326 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5329 if func.GetInfo("gen_func"):
5330 valid_test += """
5331 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5332 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5333 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5334 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5335 SpecializedSetup<cmds::%(name)s, 0>(true);
5336 cmds::%(name)s cmd;
5337 cmd.Init(kNewClientId);
5338 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5339 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5340 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5343 self.WriteValidUnitTest(func, file, valid_test, {
5344 'resource_type': func.GetOriginalArgs()[0].resource_type,
5345 'gl_gen_func_name': func.GetInfo("gen_func"),
5346 }, *extras)
5347 else:
5348 valid_test = """
5349 TEST_P(%(test_name)s, %(name)sValidArgs) {
5350 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5351 SpecializedSetup<cmds::%(name)s, 0>(true);
5352 cmds::%(name)s cmd;
5353 cmd.Init(%(args)s);"""
5354 if func.IsUnsafe():
5355 valid_test += """
5356 decoder_->set_unsafe_es3_apis_enabled(true);
5357 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5358 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5359 decoder_->set_unsafe_es3_apis_enabled(false);
5360 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5363 else:
5364 valid_test += """
5365 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5366 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5369 if func.GetInfo("gen_func"):
5370 valid_test += """
5371 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5372 EXPECT_CALL(*gl_,
5373 %(gl_func_name)s(%(gl_args_with_new_id)s));
5374 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5375 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5376 SpecializedSetup<cmds::%(name)s, 0>(true);
5377 cmds::%(name)s cmd;
5378 cmd.Init(%(args_with_new_id)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 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5385 decoder_->set_unsafe_es3_apis_enabled(false);
5386 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5389 else:
5390 valid_test += """
5391 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5392 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5393 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5397 gl_args_with_new_id = []
5398 args_with_new_id = []
5399 for arg in func.GetOriginalArgs():
5400 if hasattr(arg, 'resource_type'):
5401 gl_args_with_new_id.append('kNewServiceId')
5402 args_with_new_id.append('kNewClientId')
5403 else:
5404 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5405 args_with_new_id.append(arg.GetValidArg(func))
5406 self.WriteValidUnitTest(func, file, valid_test, {
5407 'args_with_new_id': ", ".join(args_with_new_id),
5408 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5409 'resource_type': func.GetResourceIdArg().resource_type,
5410 'gl_gen_func_name': func.GetInfo("gen_func"),
5411 }, *extras)
5413 invalid_test = """
5414 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5415 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5416 SpecializedSetup<cmds::%(name)s, 0>(false);
5417 cmds::%(name)s cmd;
5418 cmd.Init(%(args)s);
5419 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5422 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
5424 def WriteGLES2Implementation(self, func, file):
5425 """Writes the GLES2 Implemention."""
5427 impl_func = func.GetInfo('impl_func')
5428 impl_decl = func.GetInfo('impl_decl')
5430 if (func.can_auto_generate and
5431 (impl_func == None or impl_func == True) and
5432 (impl_decl == None or impl_decl == True)):
5434 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5435 (func.return_type, func.original_name,
5436 func.MakeTypedOriginalArgString("")))
5437 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5438 func.WriteDestinationInitalizationValidation(file)
5439 self.WriteClientGLCallLog(func, file)
5440 for arg in func.GetOriginalArgs():
5441 arg.WriteClientSideValidationCode(file, func)
5443 code = """ if (Is%(type)sReservedId(%(id)s)) {
5444 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5445 return;
5447 %(name)sHelper(%(arg_string)s);
5448 CheckGLError();
5452 name_arg = func.GetResourceIdArg()
5453 file.Write(code % {
5454 'name': func.name,
5455 'arg_string': func.MakeOriginalArgString(""),
5456 'id': name_arg.name,
5457 'type': name_arg.resource_type,
5458 'lc_type': name_arg.resource_type.lower(),
5461 def WriteGLES2ImplementationUnitTest(self, func, file):
5462 """Overrriden from TypeHandler."""
5463 client_test = func.GetInfo('client_test')
5464 if client_test == False:
5465 return
5466 code = """
5467 TEST_F(GLES2ImplementationTest, %(name)s) {
5468 struct Cmds {
5469 cmds::%(name)s cmd;
5471 Cmds expected;
5472 expected.cmd.Init(%(cmd_args)s);
5474 gl_->%(name)s(%(args)s);
5475 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5476 if not func.IsUnsafe():
5477 code += """
5478 ClearCommands();
5479 gl_->%(name)s(%(args)s);
5480 EXPECT_TRUE(NoCommandsWritten());"""
5481 code += """
5484 cmd_arg_strings = [
5485 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5487 gl_arg_strings = [
5488 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5491 file.Write(code % {
5492 'name': func.name,
5493 'args': ", ".join(gl_arg_strings),
5494 'cmd_args': ", ".join(cmd_arg_strings),
5498 class GENnHandler(TypeHandler):
5499 """Handler for glGen___ type functions."""
5501 def __init__(self):
5502 TypeHandler.__init__(self)
5504 def InitFunction(self, func):
5505 """Overrriden from TypeHandler."""
5506 pass
5508 def WriteGetDataSizeCode(self, func, file):
5509 """Overrriden from TypeHandler."""
5510 code = """ uint32_t data_size;
5511 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5512 return error::kOutOfBounds;
5515 file.Write(code)
5517 def WriteHandlerImplementation (self, func, file):
5518 """Overrriden from TypeHandler."""
5519 file.Write(" if (!%sHelper(n, %s)) {\n"
5520 " return error::kInvalidArguments;\n"
5521 " }\n" %
5522 (func.name, func.GetLastOriginalArg().name))
5524 def WriteImmediateHandlerImplementation(self, func, file):
5525 """Overrriden from TypeHandler."""
5526 if func.IsUnsafe():
5527 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5528 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5529 return error::kInvalidArguments;
5532 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5533 gl%(func_name)s(n, service_ids.get());
5534 for (GLsizei ii = 0; ii < n; ++ii) {
5535 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5537 """ % { 'func_name': func.original_name,
5538 'last_arg_name': func.GetLastOriginalArg().name,
5539 'resource_name': func.GetInfo('resource_type') })
5540 else:
5541 file.Write(" if (!%sHelper(n, %s)) {\n"
5542 " return error::kInvalidArguments;\n"
5543 " }\n" %
5544 (func.original_name, func.GetLastOriginalArg().name))
5546 def WriteGLES2Implementation(self, func, file):
5547 """Overrriden from TypeHandler."""
5548 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5549 for (GLsizei i = 0; i < n; ++i) {
5550 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5552 });""" % func.GetOriginalArgs()[1].name)
5553 args = {
5554 'log_code': log_code,
5555 'return_type': func.return_type,
5556 'name': func.original_name,
5557 'typed_args': func.MakeTypedOriginalArgString(""),
5558 'args': func.MakeOriginalArgString(""),
5559 'resource_types': func.GetInfo('resource_types'),
5560 'count_name': func.GetOriginalArgs()[0].name,
5562 file.Write(
5563 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5564 args)
5565 func.WriteDestinationInitalizationValidation(file)
5566 self.WriteClientGLCallLog(func, file)
5567 for arg in func.GetOriginalArgs():
5568 arg.WriteClientSideValidationCode(file, func)
5569 not_shared = func.GetInfo('not_shared')
5570 if not_shared:
5571 alloc_code = (
5573 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5574 for (GLsizei ii = 0; ii < n; ++ii)
5575 %s[ii] = id_allocator->AllocateID();""" %
5576 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5577 else:
5578 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5579 MakeIds(this, 0, %(args)s);""" % args)
5580 args['alloc_code'] = alloc_code
5582 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5583 %(alloc_code)s
5584 %(name)sHelper(%(args)s);
5585 helper_->%(name)sImmediate(%(args)s);
5586 if (share_group_->bind_generates_resource())
5587 helper_->CommandBufferHelper::Flush();
5588 %(log_code)s
5589 CheckGLError();
5593 file.Write(code % args)
5595 def WriteGLES2ImplementationUnitTest(self, func, file):
5596 """Overrriden from TypeHandler."""
5597 code = """
5598 TEST_F(GLES2ImplementationTest, %(name)s) {
5599 GLuint ids[2] = { 0, };
5600 struct Cmds {
5601 cmds::%(name)sImmediate gen;
5602 GLuint data[2];
5604 Cmds expected;
5605 expected.gen.Init(arraysize(ids), &ids[0]);
5606 expected.data[0] = k%(types)sStartId;
5607 expected.data[1] = k%(types)sStartId + 1;
5608 gl_->%(name)s(arraysize(ids), &ids[0]);
5609 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5610 EXPECT_EQ(k%(types)sStartId, ids[0]);
5611 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5614 file.Write(code % {
5615 'name': func.name,
5616 'types': func.GetInfo('resource_types'),
5619 def WriteServiceUnitTest(self, func, file, *extras):
5620 """Overrriden from TypeHandler."""
5621 valid_test = """
5622 TEST_P(%(test_name)s, %(name)sValidArgs) {
5623 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5624 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5625 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5626 SpecializedSetup<cmds::%(name)s, 0>(true);
5627 cmds::%(name)s cmd;
5628 cmd.Init(%(args)s);
5629 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5630 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5631 if func.IsUnsafe():
5632 valid_test += """
5633 GLuint service_id;
5634 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5635 EXPECT_EQ(kNewServiceId, service_id)
5638 else:
5639 valid_test += """
5640 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5643 self.WriteValidUnitTest(func, file, valid_test, {
5644 'resource_name': func.GetInfo('resource_type'),
5645 }, *extras)
5646 invalid_test = """
5647 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5648 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5649 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5650 SpecializedSetup<cmds::%(name)s, 0>(false);
5651 cmds::%(name)s cmd;
5652 cmd.Init(%(args)s);
5653 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5656 self.WriteValidUnitTest(func, file, invalid_test, {
5657 'resource_name': func.GetInfo('resource_type').lower(),
5658 }, *extras)
5660 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5661 """Overrriden from TypeHandler."""
5662 valid_test = """
5663 TEST_P(%(test_name)s, %(name)sValidArgs) {
5664 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5665 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5666 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5667 GLuint temp = kNewClientId;
5668 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5669 if func.IsUnsafe():
5670 valid_test += """
5671 decoder_->set_unsafe_es3_apis_enabled(true);"""
5672 valid_test += """
5673 cmd->Init(1, &temp);
5674 EXPECT_EQ(error::kNoError,
5675 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5676 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5677 if func.IsUnsafe():
5678 valid_test += """
5679 GLuint service_id;
5680 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5681 EXPECT_EQ(kNewServiceId, service_id);
5682 decoder_->set_unsafe_es3_apis_enabled(false);
5683 EXPECT_EQ(error::kUnknownCommand,
5684 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5687 else:
5688 valid_test += """
5689 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5692 self.WriteValidUnitTest(func, file, valid_test, {
5693 'resource_name': func.GetInfo('resource_type'),
5694 }, *extras)
5695 invalid_test = """
5696 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5697 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5698 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5699 SpecializedSetup<cmds::%(name)s, 0>(false);
5700 cmd->Init(1, &client_%(resource_name)s_id_);"""
5701 if func.IsUnsafe():
5702 invalid_test += """
5703 decoder_->set_unsafe_es3_apis_enabled(true);
5704 EXPECT_EQ(error::kInvalidArguments,
5705 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5706 decoder_->set_unsafe_es3_apis_enabled(false);
5709 else:
5710 invalid_test += """
5711 EXPECT_EQ(error::kInvalidArguments,
5712 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5715 self.WriteValidUnitTest(func, file, invalid_test, {
5716 'resource_name': func.GetInfo('resource_type').lower(),
5717 }, *extras)
5719 def WriteImmediateCmdComputeSize(self, func, file):
5720 """Overrriden from TypeHandler."""
5721 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5722 file.Write(
5723 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5724 file.Write(" }\n")
5725 file.Write("\n")
5726 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5727 file.Write(" return static_cast<uint32_t>(\n")
5728 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5729 file.Write(" }\n")
5730 file.Write("\n")
5732 def WriteImmediateCmdSetHeader(self, func, file):
5733 """Overrriden from TypeHandler."""
5734 file.Write(" void SetHeader(GLsizei n) {\n")
5735 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5736 file.Write(" }\n")
5737 file.Write("\n")
5739 def WriteImmediateCmdInit(self, func, file):
5740 """Overrriden from TypeHandler."""
5741 last_arg = func.GetLastOriginalArg()
5742 file.Write(" void Init(%s, %s _%s) {\n" %
5743 (func.MakeTypedCmdArgString("_"),
5744 last_arg.type, last_arg.name))
5745 file.Write(" SetHeader(_n);\n")
5746 args = func.GetCmdArgs()
5747 for arg in args:
5748 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5749 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5750 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5751 file.Write(" }\n")
5752 file.Write("\n")
5754 def WriteImmediateCmdSet(self, func, file):
5755 """Overrriden from TypeHandler."""
5756 last_arg = func.GetLastOriginalArg()
5757 copy_args = func.MakeCmdArgString("_", False)
5758 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5759 (func.MakeTypedCmdArgString("_", True),
5760 last_arg.type, last_arg.name))
5761 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5762 (copy_args, last_arg.name))
5763 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5764 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5765 "cmd, size);\n")
5766 file.Write(" }\n")
5767 file.Write("\n")
5769 def WriteImmediateCmdHelper(self, func, file):
5770 """Overrriden from TypeHandler."""
5771 code = """ void %(name)s(%(typed_args)s) {
5772 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5773 gles2::cmds::%(name)s* c =
5774 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5775 if (c) {
5776 c->Init(%(args)s);
5781 file.Write(code % {
5782 "name": func.name,
5783 "typed_args": func.MakeTypedOriginalArgString(""),
5784 "args": func.MakeOriginalArgString(""),
5787 def WriteImmediateFormatTest(self, func, file):
5788 """Overrriden from TypeHandler."""
5789 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5790 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5791 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5792 (func.name, func.name))
5793 file.Write(" void* next_cmd = cmd.Set(\n")
5794 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5795 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5796 func.name)
5797 file.Write(" cmd.header.command);\n")
5798 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5799 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5800 file.Write(" cmd.header.size * 4u);\n")
5801 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5802 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5803 file.Write(" next_cmd, sizeof(cmd) +\n")
5804 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5805 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5806 file.Write("}\n")
5807 file.Write("\n")
5810 class CreateHandler(TypeHandler):
5811 """Handler for glCreate___ type functions."""
5813 def __init__(self):
5814 TypeHandler.__init__(self)
5816 def InitFunction(self, func):
5817 """Overrriden from TypeHandler."""
5818 func.AddCmdArg(Argument("client_id", 'uint32_t'))
5820 def __GetResourceType(self, func):
5821 if func.return_type == "GLsync":
5822 return "Sync"
5823 else:
5824 return func.name[6:] # Create*
5826 def WriteServiceUnitTest(self, func, file, *extras):
5827 """Overrriden from TypeHandler."""
5828 valid_test = """
5829 TEST_P(%(test_name)s, %(name)sValidArgs) {
5830 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5831 .WillOnce(Return(%(const_service_id)s));
5832 SpecializedSetup<cmds::%(name)s, 0>(true);
5833 cmds::%(name)s cmd;
5834 cmd.Init(%(args)s%(comma)skNewClientId);"""
5835 if func.IsUnsafe():
5836 valid_test += """
5837 decoder_->set_unsafe_es3_apis_enabled(true);"""
5838 valid_test += """
5839 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5840 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5841 if func.IsUnsafe():
5842 valid_test += """
5843 %(return_type)s service_id = 0;
5844 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5845 EXPECT_EQ(%(const_service_id)s, service_id);
5846 decoder_->set_unsafe_es3_apis_enabled(false);
5847 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5850 else:
5851 valid_test += """
5852 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5855 comma = ""
5856 cmd_arg_count = 0
5857 for arg in func.GetOriginalArgs():
5858 if not arg.IsConstant():
5859 cmd_arg_count += 1
5860 if cmd_arg_count:
5861 comma = ", "
5862 if func.return_type == 'GLsync':
5863 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5864 "<GLsync>(kNewServiceId);\n ")
5865 const_service_id = "kNewServiceIdGLuint"
5866 else:
5867 id_type_cast = ""
5868 const_service_id = "kNewServiceId"
5869 self.WriteValidUnitTest(func, file, valid_test, {
5870 'comma': comma,
5871 'resource_type': self.__GetResourceType(func),
5872 'return_type': func.return_type,
5873 'id_type_cast': id_type_cast,
5874 'const_service_id': const_service_id,
5875 }, *extras)
5876 invalid_test = """
5877 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5878 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5879 SpecializedSetup<cmds::%(name)s, 0>(false);
5880 cmds::%(name)s cmd;
5881 cmd.Init(%(args)s%(comma)skNewClientId);
5882 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5885 self.WriteInvalidUnitTest(func, file, invalid_test, {
5886 'comma': comma,
5887 }, *extras)
5889 def WriteHandlerImplementation (self, func, file):
5890 """Overrriden from TypeHandler."""
5891 if func.IsUnsafe():
5892 code = """ uint32_t client_id = c.client_id;
5893 %(return_type)s service_id = 0;
5894 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5895 return error::kInvalidArguments;
5897 service_id = %(gl_func_name)s(%(gl_args)s);
5898 if (service_id) {
5899 group_->Add%(resource_name)sId(client_id, service_id);
5902 else:
5903 code = """ uint32_t client_id = c.client_id;
5904 if (Get%(resource_name)s(client_id)) {
5905 return error::kInvalidArguments;
5907 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5908 if (service_id) {
5909 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5912 file.Write(code % {
5913 'resource_name': self.__GetResourceType(func),
5914 'return_type': func.return_type,
5915 'gl_func_name': func.GetGLFunctionName(),
5916 'gl_args': func.MakeOriginalArgString(""),
5917 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
5919 def WriteGLES2Implementation(self, func, file):
5920 """Overrriden from TypeHandler."""
5921 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5922 (func.return_type, func.original_name,
5923 func.MakeTypedOriginalArgString("")))
5924 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5925 func.WriteDestinationInitalizationValidation(file)
5926 self.WriteClientGLCallLog(func, file)
5927 for arg in func.GetOriginalArgs():
5928 arg.WriteClientSideValidationCode(file, func)
5929 file.Write(" GLuint client_id;\n")
5930 if func.return_type == "GLsync":
5931 file.Write(
5932 " GetIdHandler(id_namespaces::kSyncs)->\n")
5933 else:
5934 file.Write(
5935 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5936 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5937 file.Write(" helper_->%s(%s);\n" %
5938 (func.name, func.MakeCmdArgString("")))
5939 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5940 file.Write(" CheckGLError();\n")
5941 if func.return_type == "GLsync":
5942 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5943 else:
5944 file.Write(" return client_id;\n")
5945 file.Write("}\n")
5946 file.Write("\n")
5949 class DeleteHandler(TypeHandler):
5950 """Handler for glDelete___ single resource type functions."""
5952 def __init__(self):
5953 TypeHandler.__init__(self)
5955 def WriteServiceImplementation(self, func, file):
5956 """Overrriden from TypeHandler."""
5957 if func.IsUnsafe():
5958 TypeHandler.WriteServiceImplementation(self, func, file)
5959 # HandleDeleteShader and HandleDeleteProgram are manually written.
5960 pass
5962 def WriteGLES2Implementation(self, func, file):
5963 """Overrriden from TypeHandler."""
5964 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5965 (func.return_type, func.original_name,
5966 func.MakeTypedOriginalArgString("")))
5967 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5968 func.WriteDestinationInitalizationValidation(file)
5969 self.WriteClientGLCallLog(func, file)
5970 for arg in func.GetOriginalArgs():
5971 arg.WriteClientSideValidationCode(file, func)
5972 file.Write(
5973 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
5974 file.Write(" %sHelper(%s);\n" %
5975 (func.original_name, func.GetOriginalArgs()[-1].name))
5976 file.Write(" CheckGLError();\n")
5977 file.Write("}\n")
5978 file.Write("\n")
5980 def WriteHandlerImplementation (self, func, file):
5981 """Overrriden from TypeHandler."""
5982 assert len(func.GetOriginalArgs()) == 1
5983 arg = func.GetOriginalArgs()[0]
5984 if func.IsUnsafe():
5985 file.Write(""" %(arg_type)s service_id = 0;
5986 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5987 glDelete%(resource_type)s(service_id);
5988 group_->Remove%(resource_type)sId(%(arg_name)s);
5989 } else {
5990 LOCAL_SET_GL_ERROR(
5991 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5993 """ % { 'resource_type': func.GetInfo('resource_type'),
5994 'arg_name': arg.name,
5995 'arg_type': arg.type,
5996 'func_name': func.original_name })
5997 else:
5998 file.Write(" %sHelper(%s);\n" % (func.original_name, arg.name))
6000 class DELnHandler(TypeHandler):
6001 """Handler for glDelete___ type functions."""
6003 def __init__(self):
6004 TypeHandler.__init__(self)
6006 def WriteGetDataSizeCode(self, func, file):
6007 """Overrriden from TypeHandler."""
6008 code = """ uint32_t data_size;
6009 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6010 return error::kOutOfBounds;
6013 file.Write(code)
6015 def WriteGLES2ImplementationUnitTest(self, func, file):
6016 """Overrriden from TypeHandler."""
6017 code = """
6018 TEST_F(GLES2ImplementationTest, %(name)s) {
6019 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6020 struct Cmds {
6021 cmds::%(name)sImmediate del;
6022 GLuint data[2];
6024 Cmds expected;
6025 expected.del.Init(arraysize(ids), &ids[0]);
6026 expected.data[0] = k%(types)sStartId;
6027 expected.data[1] = k%(types)sStartId + 1;
6028 gl_->%(name)s(arraysize(ids), &ids[0]);
6029 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6032 file.Write(code % {
6033 'name': func.name,
6034 'types': func.GetInfo('resource_types'),
6037 def WriteServiceUnitTest(self, func, file, *extras):
6038 """Overrriden from TypeHandler."""
6039 valid_test = """
6040 TEST_P(%(test_name)s, %(name)sValidArgs) {
6041 EXPECT_CALL(
6042 *gl_,
6043 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6044 .Times(1);
6045 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6046 SpecializedSetup<cmds::%(name)s, 0>(true);
6047 cmds::%(name)s cmd;
6048 cmd.Init(%(args)s);
6049 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6050 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6051 EXPECT_TRUE(
6052 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6055 self.WriteValidUnitTest(func, file, valid_test, {
6056 'resource_name': func.GetInfo('resource_type').lower(),
6057 'upper_resource_name': func.GetInfo('resource_type'),
6058 }, *extras)
6059 invalid_test = """
6060 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6061 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6062 SpecializedSetup<cmds::%(name)s, 0>(false);
6063 cmds::%(name)s cmd;
6064 cmd.Init(%(args)s);
6065 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6068 self.WriteValidUnitTest(func, file, invalid_test, *extras)
6070 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6071 """Overrriden from TypeHandler."""
6072 valid_test = """
6073 TEST_P(%(test_name)s, %(name)sValidArgs) {
6074 EXPECT_CALL(
6075 *gl_,
6076 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6077 .Times(1);
6078 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6079 SpecializedSetup<cmds::%(name)s, 0>(true);
6080 cmd.Init(1, &client_%(resource_name)s_id_);"""
6081 if func.IsUnsafe():
6082 valid_test += """
6083 decoder_->set_unsafe_es3_apis_enabled(true);"""
6084 valid_test += """
6085 EXPECT_EQ(error::kNoError,
6086 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6087 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6088 if func.IsUnsafe():
6089 valid_test += """
6090 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6091 client_%(resource_name)s_id_, NULL));
6092 decoder_->set_unsafe_es3_apis_enabled(false);
6093 EXPECT_EQ(error::kUnknownCommand,
6094 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6097 else:
6098 valid_test += """
6099 EXPECT_TRUE(
6100 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6103 self.WriteValidUnitTest(func, file, valid_test, {
6104 'resource_name': func.GetInfo('resource_type').lower(),
6105 'upper_resource_name': func.GetInfo('resource_type'),
6106 }, *extras)
6107 invalid_test = """
6108 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6109 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6110 SpecializedSetup<cmds::%(name)s, 0>(false);
6111 GLuint temp = kInvalidClientId;
6112 cmd.Init(1, &temp);"""
6113 if func.IsUnsafe():
6114 invalid_test += """
6115 decoder_->set_unsafe_es3_apis_enabled(true);
6116 EXPECT_EQ(error::kNoError,
6117 ExecuteImmediateCmd(cmd, sizeof(temp)));
6118 decoder_->set_unsafe_es3_apis_enabled(false);
6119 EXPECT_EQ(error::kUnknownCommand,
6120 ExecuteImmediateCmd(cmd, sizeof(temp)));
6123 else:
6124 invalid_test += """
6125 EXPECT_EQ(error::kNoError,
6126 ExecuteImmediateCmd(cmd, sizeof(temp)));
6129 self.WriteValidUnitTest(func, file, invalid_test, *extras)
6131 def WriteHandlerImplementation (self, func, file):
6132 """Overrriden from TypeHandler."""
6133 file.Write(" %sHelper(n, %s);\n" %
6134 (func.name, func.GetLastOriginalArg().name))
6136 def WriteImmediateHandlerImplementation (self, func, file):
6137 """Overrriden from TypeHandler."""
6138 if func.IsUnsafe():
6139 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6140 GLuint service_id = 0;
6141 if (group_->Get%(resource_type)sServiceId(
6142 %(last_arg_name)s[ii], &service_id)) {
6143 glDelete%(resource_type)ss(1, &service_id);
6144 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6147 """ % { 'resource_type': func.GetInfo('resource_type'),
6148 'last_arg_name': func.GetLastOriginalArg().name })
6149 else:
6150 file.Write(" %sHelper(n, %s);\n" %
6151 (func.original_name, func.GetLastOriginalArg().name))
6153 def WriteGLES2Implementation(self, func, file):
6154 """Overrriden from TypeHandler."""
6155 impl_decl = func.GetInfo('impl_decl')
6156 if impl_decl == None or impl_decl == True:
6157 args = {
6158 'return_type': func.return_type,
6159 'name': func.original_name,
6160 'typed_args': func.MakeTypedOriginalArgString(""),
6161 'args': func.MakeOriginalArgString(""),
6162 'resource_type': func.GetInfo('resource_type').lower(),
6163 'count_name': func.GetOriginalArgs()[0].name,
6165 file.Write(
6166 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6167 args)
6168 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6169 func.WriteDestinationInitalizationValidation(file)
6170 self.WriteClientGLCallLog(func, file)
6171 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6172 for (GLsizei i = 0; i < n; ++i) {
6173 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6176 """ % func.GetOriginalArgs()[1].name)
6177 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6178 for (GLsizei i = 0; i < n; ++i) {
6179 DCHECK(%s[i] != 0);
6182 """ % func.GetOriginalArgs()[1].name)
6183 for arg in func.GetOriginalArgs():
6184 arg.WriteClientSideValidationCode(file, func)
6185 code = """ %(name)sHelper(%(args)s);
6186 CheckGLError();
6190 file.Write(code % args)
6192 def WriteImmediateCmdComputeSize(self, func, file):
6193 """Overrriden from TypeHandler."""
6194 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6195 file.Write(
6196 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6197 file.Write(" }\n")
6198 file.Write("\n")
6199 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
6200 file.Write(" return static_cast<uint32_t>(\n")
6201 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6202 file.Write(" }\n")
6203 file.Write("\n")
6205 def WriteImmediateCmdSetHeader(self, func, file):
6206 """Overrriden from TypeHandler."""
6207 file.Write(" void SetHeader(GLsizei n) {\n")
6208 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6209 file.Write(" }\n")
6210 file.Write("\n")
6212 def WriteImmediateCmdInit(self, func, file):
6213 """Overrriden from TypeHandler."""
6214 last_arg = func.GetLastOriginalArg()
6215 file.Write(" void Init(%s, %s _%s) {\n" %
6216 (func.MakeTypedCmdArgString("_"),
6217 last_arg.type, last_arg.name))
6218 file.Write(" SetHeader(_n);\n")
6219 args = func.GetCmdArgs()
6220 for arg in args:
6221 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6222 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6223 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
6224 file.Write(" }\n")
6225 file.Write("\n")
6227 def WriteImmediateCmdSet(self, func, file):
6228 """Overrriden from TypeHandler."""
6229 last_arg = func.GetLastOriginalArg()
6230 copy_args = func.MakeCmdArgString("_", False)
6231 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6232 (func.MakeTypedCmdArgString("_", True),
6233 last_arg.type, last_arg.name))
6234 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6235 (copy_args, last_arg.name))
6236 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6237 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6238 "cmd, size);\n")
6239 file.Write(" }\n")
6240 file.Write("\n")
6242 def WriteImmediateCmdHelper(self, func, file):
6243 """Overrriden from TypeHandler."""
6244 code = """ void %(name)s(%(typed_args)s) {
6245 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6246 gles2::cmds::%(name)s* c =
6247 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6248 if (c) {
6249 c->Init(%(args)s);
6254 file.Write(code % {
6255 "name": func.name,
6256 "typed_args": func.MakeTypedOriginalArgString(""),
6257 "args": func.MakeOriginalArgString(""),
6260 def WriteImmediateFormatTest(self, func, file):
6261 """Overrriden from TypeHandler."""
6262 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6263 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6264 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6265 (func.name, func.name))
6266 file.Write(" void* next_cmd = cmd.Set(\n")
6267 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6268 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6269 func.name)
6270 file.Write(" cmd.header.command);\n")
6271 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6272 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6273 file.Write(" cmd.header.size * 4u);\n")
6274 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6275 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6276 file.Write(" next_cmd, sizeof(cmd) +\n")
6277 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6278 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6279 file.Write("}\n")
6280 file.Write("\n")
6283 class GETnHandler(TypeHandler):
6284 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6286 def __init__(self):
6287 TypeHandler.__init__(self)
6289 def NeedsDataTransferFunction(self, func):
6290 """Overriden from TypeHandler."""
6291 return False
6293 def WriteServiceImplementation(self, func, file):
6294 """Overrriden from TypeHandler."""
6295 self.WriteServiceHandlerFunctionHeader(func, file)
6296 last_arg = func.GetLastOriginalArg()
6297 # All except shm_id and shm_offset.
6298 all_but_last_args = func.GetCmdArgs()[:-2]
6299 for arg in all_but_last_args:
6300 arg.WriteGetCode(file)
6302 code = """ typedef cmds::%(func_name)s::Result Result;
6303 GLsizei num_values = 0;
6304 GetNumValuesReturnedForGLGet(pname, &num_values);
6305 Result* result = GetSharedMemoryAs<Result*>(
6306 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6307 Result::ComputeSize(num_values));
6308 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6310 file.Write(code % {
6311 'last_arg_type': last_arg.type,
6312 'last_arg_name': last_arg.name,
6313 'func_name': func.name,
6315 func.WriteHandlerValidation(file)
6316 code = """ // Check that the client initialized the result.
6317 if (result->size != 0) {
6318 return error::kInvalidArguments;
6321 shadowed = func.GetInfo('shadowed')
6322 if not shadowed:
6323 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
6324 file.Write(code)
6325 func.WriteHandlerImplementation(file)
6326 if shadowed:
6327 code = """ result->SetNumResults(num_values);
6328 return error::kNoError;
6331 else:
6332 code = """ GLenum error = glGetError();
6333 if (error == GL_NO_ERROR) {
6334 result->SetNumResults(num_values);
6335 } else {
6336 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
6338 return error::kNoError;
6342 file.Write(code % {'func_name': func.name})
6344 def WriteGLES2Implementation(self, func, file):
6345 """Overrriden from TypeHandler."""
6346 impl_decl = func.GetInfo('impl_decl')
6347 if impl_decl == None or impl_decl == True:
6348 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6349 (func.return_type, func.original_name,
6350 func.MakeTypedOriginalArgString("")))
6351 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6352 func.WriteDestinationInitalizationValidation(file)
6353 self.WriteClientGLCallLog(func, file)
6354 for arg in func.GetOriginalArgs():
6355 arg.WriteClientSideValidationCode(file, func)
6356 all_but_last_args = func.GetOriginalArgs()[:-1]
6357 args = []
6358 has_length_arg = False
6359 for arg in all_but_last_args:
6360 if arg.type == 'GLsync':
6361 args.append('ToGLuint(%s)' % arg.name)
6362 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6363 continue
6364 elif arg.name == 'length':
6365 has_length_arg = True
6366 continue
6367 else:
6368 args.append(arg.name)
6369 arg_string = ", ".join(args)
6370 all_arg_string = (
6371 ", ".join([
6372 "%s" % arg.name
6373 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6374 self.WriteTraceEvent(func, file)
6375 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6376 return;
6378 typedef cmds::%(func_name)s::Result Result;
6379 Result* result = GetResultAs<Result*>();
6380 if (!result) {
6381 return;
6383 result->SetNumResults(0);
6384 helper_->%(func_name)s(%(arg_string)s,
6385 GetResultShmId(), GetResultShmOffset());
6386 WaitForCmd();
6387 result->CopyResult(%(last_arg_name)s);
6388 GPU_CLIENT_LOG_CODE_BLOCK({
6389 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6390 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6392 });"""
6393 if has_length_arg:
6394 code += """
6395 if (length) {
6396 *length = result->GetNumResults();
6397 }"""
6398 code += """
6399 CheckGLError();
6402 file.Write(code % {
6403 'func_name': func.name,
6404 'arg_string': arg_string,
6405 'all_arg_string': all_arg_string,
6406 'last_arg_name': func.GetLastOriginalArg().name,
6409 def WriteGLES2ImplementationUnitTest(self, func, file):
6410 """Writes the GLES2 Implemention unit test."""
6411 code = """
6412 TEST_F(GLES2ImplementationTest, %(name)s) {
6413 struct Cmds {
6414 cmds::%(name)s cmd;
6416 typedef cmds::%(name)s::Result::Type ResultType;
6417 ResultType result = 0;
6418 Cmds expected;
6419 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6420 sizeof(uint32_t) + sizeof(ResultType));
6421 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6422 EXPECT_CALL(*command_buffer(), OnFlush())
6423 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6424 .RetiresOnSaturation();
6425 gl_->%(name)s(%(args)s, &result);
6426 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6427 EXPECT_EQ(static_cast<ResultType>(1), result);
6430 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6431 if not first_cmd_arg:
6432 return
6434 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6435 func)
6437 cmd_arg_strings = [first_cmd_arg]
6438 for arg in func.GetCmdArgs()[1:-2]:
6439 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6440 gl_arg_strings = [first_gl_arg]
6441 for arg in func.GetOriginalArgs()[1:-1]:
6442 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6444 file.Write(code % {
6445 'name': func.name,
6446 'args': ", ".join(gl_arg_strings),
6447 'cmd_args': ", ".join(cmd_arg_strings),
6450 def WriteServiceUnitTest(self, func, file, *extras):
6451 """Overrriden from TypeHandler."""
6452 valid_test = """
6453 TEST_P(%(test_name)s, %(name)sValidArgs) {
6454 EXPECT_CALL(*gl_, GetError())
6455 .WillOnce(Return(GL_NO_ERROR))
6456 .WillOnce(Return(GL_NO_ERROR))
6457 .RetiresOnSaturation();
6458 SpecializedSetup<cmds::%(name)s, 0>(true);
6459 typedef cmds::%(name)s::Result Result;
6460 Result* result = static_cast<Result*>(shared_memory_address_);
6461 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6462 result->size = 0;
6463 cmds::%(name)s cmd;
6464 cmd.Init(%(cmd_args)s);"""
6465 if func.IsUnsafe():
6466 valid_test += """
6467 decoder_->set_unsafe_es3_apis_enabled(true);"""
6468 valid_test += """
6469 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6470 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6471 %(valid_pname)s),
6472 result->GetNumResults());
6473 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6474 if func.IsUnsafe():
6475 valid_test += """
6476 decoder_->set_unsafe_es3_apis_enabled(false);
6477 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6478 valid_test += """
6481 gl_arg_strings = []
6482 cmd_arg_strings = []
6483 valid_pname = ''
6484 for arg in func.GetOriginalArgs()[:-1]:
6485 if arg.name == 'length':
6486 gl_arg_value = 'nullptr'
6487 elif arg.name.endswith('size'):
6488 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6489 valid_pname)
6490 elif arg.type == 'GLsync':
6491 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6492 else:
6493 gl_arg_value = arg.GetValidGLArg(func)
6494 gl_arg_strings.append(gl_arg_value)
6495 if arg.name == 'pname':
6496 valid_pname = gl_arg_value
6497 if arg.name.endswith('size') or arg.name == 'length':
6498 continue
6499 if arg.type == 'GLsync':
6500 arg_value = 'client_sync_id_'
6501 else:
6502 arg_value = arg.GetValidArg(func)
6503 cmd_arg_strings.append(arg_value)
6504 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6505 gl_arg_strings.append("_")
6506 else:
6507 gl_arg_strings.append("result->GetData()")
6508 cmd_arg_strings.append("shared_memory_id_")
6509 cmd_arg_strings.append("shared_memory_offset_")
6511 self.WriteValidUnitTest(func, file, valid_test, {
6512 'local_gl_args': ", ".join(gl_arg_strings),
6513 'cmd_args': ", ".join(cmd_arg_strings),
6514 'valid_pname': valid_pname,
6515 }, *extras)
6517 if not func.IsUnsafe():
6518 invalid_test = """
6519 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6520 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6521 SpecializedSetup<cmds::%(name)s, 0>(false);
6522 cmds::%(name)s::Result* result =
6523 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6524 result->size = 0;
6525 cmds::%(name)s cmd;
6526 cmd.Init(%(args)s);
6527 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6528 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6531 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
6533 class ArrayArgTypeHandler(TypeHandler):
6534 """Base class for type handlers that handle args that are arrays"""
6536 def __init__(self):
6537 TypeHandler.__init__(self)
6539 def GetArrayType(self, func):
6540 """Returns the type of the element in the element array being PUT to."""
6541 for arg in func.GetOriginalArgs():
6542 if arg.IsPointer():
6543 element_type = arg.GetPointedType()
6544 return element_type
6546 # Special case: array type handler is used for a function that is forwarded
6547 # to the actual array type implementation
6548 element_type = func.GetOriginalArgs()[-1].type
6549 assert all(arg.type == element_type \
6550 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6551 return element_type
6553 def GetArrayCount(self, func):
6554 """Returns the count of the elements in the array being PUT to."""
6555 return func.GetInfo('count')
6557 class PUTHandler(ArrayArgTypeHandler):
6558 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6560 def __init__(self):
6561 ArrayArgTypeHandler.__init__(self)
6563 def WriteServiceUnitTest(self, func, file, *extras):
6564 """Writes the service unit test for a command."""
6565 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6566 if func.GetInfo("first_element_only"):
6567 gl_arg_strings = [
6568 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6570 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6571 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6572 ", ".join(gl_arg_strings))
6573 valid_test = """
6574 TEST_P(%(test_name)s, %(name)sValidArgs) {
6575 SpecializedSetup<cmds::%(name)s, 0>(true);
6576 cmds::%(name)s cmd;
6577 cmd.Init(%(args)s);
6578 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6579 %(expected_call)s
6580 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6581 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6584 extra = {
6585 'data_type': self.GetArrayType(func),
6586 'data_value': func.GetInfo('data_value') or '0',
6587 'expected_call': expected_call,
6589 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6591 invalid_test = """
6592 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6593 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6594 SpecializedSetup<cmds::%(name)s, 0>(false);
6595 cmds::%(name)s cmd;
6596 cmd.Init(%(args)s);
6597 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6598 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6601 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6603 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6604 """Writes the service unit test for a command."""
6605 valid_test = """
6606 TEST_P(%(test_name)s, %(name)sValidArgs) {
6607 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6608 SpecializedSetup<cmds::%(name)s, 0>(true);
6609 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6610 cmd.Init(%(gl_args)s, &temp[0]);
6611 EXPECT_CALL(
6612 *gl_,
6613 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6614 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6615 if func.IsUnsafe():
6616 valid_test += """
6617 decoder_->set_unsafe_es3_apis_enabled(true);"""
6618 valid_test += """
6619 EXPECT_EQ(error::kNoError,
6620 ExecuteImmediateCmd(cmd, sizeof(temp)));
6621 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6622 if func.IsUnsafe():
6623 valid_test += """
6624 decoder_->set_unsafe_es3_apis_enabled(false);
6625 EXPECT_EQ(error::kUnknownCommand,
6626 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6627 valid_test += """
6630 gl_arg_strings = [
6631 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6633 gl_any_strings = ["_"] * len(gl_arg_strings)
6635 extra = {
6636 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6637 'data_type': self.GetArrayType(func),
6638 'data_count': self.GetArrayCount(func),
6639 'data_value': func.GetInfo('data_value') or '0',
6640 'gl_args': ", ".join(gl_arg_strings),
6641 'gl_any_args': ", ".join(gl_any_strings),
6643 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6645 invalid_test = """
6646 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6647 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6648 if func.IsUnsafe():
6649 invalid_test += """
6650 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6652 else:
6653 invalid_test += """
6654 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6656 invalid_test += """
6657 SpecializedSetup<cmds::%(name)s, 0>(false);
6658 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6659 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6660 if func.IsUnsafe():
6661 invalid_test += """
6662 decoder_->set_unsafe_es3_apis_enabled(true);
6663 EXPECT_EQ(error::%(parse_result)s,
6664 ExecuteImmediateCmd(cmd, sizeof(temp)));
6665 decoder_->set_unsafe_es3_apis_enabled(false);
6668 else:
6669 invalid_test += """
6670 EXPECT_EQ(error::%(parse_result)s,
6671 ExecuteImmediateCmd(cmd, sizeof(temp)));
6672 %(gl_error_test)s
6675 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6677 def WriteGetDataSizeCode(self, func, file):
6678 """Overrriden from TypeHandler."""
6679 code = """ uint32_t data_size;
6680 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6681 return error::kOutOfBounds;
6684 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6685 if func.IsImmediate():
6686 file.Write(" if (data_size > immediate_data_size) {\n")
6687 file.Write(" return error::kOutOfBounds;\n")
6688 file.Write(" }\n")
6690 def __NeedsToCalcDataCount(self, func):
6691 use_count_func = func.GetInfo('use_count_func')
6692 return use_count_func != None and use_count_func != False
6694 def WriteGLES2Implementation(self, func, file):
6695 """Overrriden from TypeHandler."""
6696 impl_func = func.GetInfo('impl_func')
6697 if (impl_func != None and impl_func != True):
6698 return;
6699 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6700 (func.return_type, func.original_name,
6701 func.MakeTypedOriginalArgString("")))
6702 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6703 func.WriteDestinationInitalizationValidation(file)
6704 self.WriteClientGLCallLog(func, file)
6706 if self.__NeedsToCalcDataCount(func):
6707 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6708 (func.name, func.GetOriginalArgs()[0].name))
6709 file.Write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6710 else:
6711 file.Write(" size_t count = %d;" % self.GetArrayCount(func))
6712 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6713 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6714 func.GetLastOriginalArg().name)
6715 for arg in func.GetOriginalArgs():
6716 arg.WriteClientSideValidationCode(file, func)
6717 file.Write(" helper_->%sImmediate(%s);\n" %
6718 (func.name, func.MakeOriginalArgString("")))
6719 file.Write(" CheckGLError();\n")
6720 file.Write("}\n")
6721 file.Write("\n")
6723 def WriteGLES2ImplementationUnitTest(self, func, file):
6724 """Writes the GLES2 Implemention unit test."""
6725 client_test = func.GetInfo('client_test')
6726 if (client_test != None and client_test != True):
6727 return;
6728 code = """
6729 TEST_F(GLES2ImplementationTest, %(name)s) {
6730 %(type)s data[%(count)d] = {0};
6731 struct Cmds {
6732 cmds::%(name)sImmediate cmd;
6733 %(type)s data[%(count)d];
6736 for (int jj = 0; jj < %(count)d; ++jj) {
6737 data[jj] = static_cast<%(type)s>(jj);
6739 Cmds expected;
6740 expected.cmd.Init(%(cmd_args)s, &data[0]);
6741 gl_->%(name)s(%(args)s, &data[0]);
6742 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6745 cmd_arg_strings = [
6746 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6748 gl_arg_strings = [
6749 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6752 file.Write(code % {
6753 'name': func.name,
6754 'type': self.GetArrayType(func),
6755 'count': self.GetArrayCount(func),
6756 'args': ", ".join(gl_arg_strings),
6757 'cmd_args': ", ".join(cmd_arg_strings),
6760 def WriteImmediateCmdComputeSize(self, func, file):
6761 """Overrriden from TypeHandler."""
6762 file.Write(" static uint32_t ComputeDataSize() {\n")
6763 file.Write(" return static_cast<uint32_t>(\n")
6764 file.Write(" sizeof(%s) * %d);\n" %
6765 (self.GetArrayType(func), self.GetArrayCount(func)))
6766 file.Write(" }\n")
6767 file.Write("\n")
6768 if self.__NeedsToCalcDataCount(func):
6769 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6770 (func.GetOriginalArgs()[0].type,
6771 func.GetOriginalArgs()[0].name))
6772 file.Write(" return static_cast<uint32_t>(\n")
6773 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6774 (self.GetArrayType(func), func.original_name,
6775 func.GetOriginalArgs()[0].name))
6776 file.Write(" }\n")
6777 file.Write("\n")
6778 file.Write(" static uint32_t ComputeSize() {\n")
6779 file.Write(" return static_cast<uint32_t>(\n")
6780 file.Write(
6781 " sizeof(ValueType) + ComputeDataSize());\n")
6782 file.Write(" }\n")
6783 file.Write("\n")
6785 def WriteImmediateCmdSetHeader(self, func, file):
6786 """Overrriden from TypeHandler."""
6787 file.Write(" void SetHeader() {\n")
6788 file.Write(
6789 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6790 file.Write(" }\n")
6791 file.Write("\n")
6793 def WriteImmediateCmdInit(self, func, file):
6794 """Overrriden from TypeHandler."""
6795 last_arg = func.GetLastOriginalArg()
6796 file.Write(" void Init(%s, %s _%s) {\n" %
6797 (func.MakeTypedCmdArgString("_"),
6798 last_arg.type, last_arg.name))
6799 file.Write(" SetHeader();\n")
6800 args = func.GetCmdArgs()
6801 for arg in args:
6802 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6803 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6804 if self.__NeedsToCalcDataCount(func):
6805 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6806 (last_arg.name, func.GetOriginalArgs()[0].name))
6807 file.Write("""
6808 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6809 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6810 ComputeEffectiveDataSize(%(arg)s);
6811 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6812 """ % { 'arg': func.GetOriginalArgs()[0].name, })
6813 else:
6814 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
6815 file.Write(" }\n")
6816 file.Write("\n")
6818 def WriteImmediateCmdSet(self, func, file):
6819 """Overrriden from TypeHandler."""
6820 last_arg = func.GetLastOriginalArg()
6821 copy_args = func.MakeCmdArgString("_", False)
6822 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6823 (func.MakeTypedCmdArgString("_", True),
6824 last_arg.type, last_arg.name))
6825 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6826 (copy_args, last_arg.name))
6827 file.Write(" const uint32_t size = ComputeSize();\n")
6828 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6829 "cmd, size);\n")
6830 file.Write(" }\n")
6831 file.Write("\n")
6833 def WriteImmediateCmdHelper(self, func, file):
6834 """Overrriden from TypeHandler."""
6835 code = """ void %(name)s(%(typed_args)s) {
6836 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6837 gles2::cmds::%(name)s* c =
6838 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6839 if (c) {
6840 c->Init(%(args)s);
6845 file.Write(code % {
6846 "name": func.name,
6847 "typed_args": func.MakeTypedOriginalArgString(""),
6848 "args": func.MakeOriginalArgString(""),
6851 def WriteImmediateFormatTest(self, func, file):
6852 """Overrriden from TypeHandler."""
6853 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6854 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6855 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6856 for v in range(0, self.GetArrayCount(func)):
6857 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6858 (self.GetArrayType(func), v))
6859 file.Write(" };\n")
6860 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6861 (func.name, func.name))
6862 file.Write(" void* next_cmd = cmd.Set(\n")
6863 file.Write(" &cmd")
6864 args = func.GetCmdArgs()
6865 for value, arg in enumerate(args):
6866 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
6867 file.Write(",\n data);\n")
6868 args = func.GetCmdArgs()
6869 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6870 % func.name)
6871 file.Write(" cmd.header.command);\n")
6872 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6873 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6874 file.Write(" cmd.header.size * 4u);\n")
6875 for value, arg in enumerate(args):
6876 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6877 (arg.type, value + 11, arg.name))
6878 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6879 file.Write(" next_cmd, sizeof(cmd) +\n")
6880 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6881 file.Write(" // TODO(gman): Check that data was inserted;\n")
6882 file.Write("}\n")
6883 file.Write("\n")
6886 class PUTnHandler(ArrayArgTypeHandler):
6887 """Handler for PUTn 'glUniform__v' type functions."""
6889 def __init__(self):
6890 ArrayArgTypeHandler.__init__(self)
6892 def WriteServiceUnitTest(self, func, file, *extras):
6893 """Overridden from TypeHandler."""
6894 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
6896 valid_test = """
6897 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6898 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6899 SpecializedSetup<cmds::%(name)s, 0>(true);
6900 cmds::%(name)s cmd;
6901 cmd.Init(%(args)s);
6902 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6903 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6906 gl_arg_strings = []
6907 arg_strings = []
6908 for count, arg in enumerate(func.GetOriginalArgs()):
6909 # hardcoded to match unit tests.
6910 if count == 0:
6911 # the location of the second element of the 2nd uniform.
6912 # defined in GLES2DecoderBase::SetupShaderForUniform
6913 gl_arg_strings.append("3")
6914 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
6915 elif count == 1:
6916 # the number of elements that gl will be called with.
6917 gl_arg_strings.append("3")
6918 # the number of elements requested in the command.
6919 arg_strings.append("5")
6920 else:
6921 gl_arg_strings.append(arg.GetValidGLArg(func))
6922 if not arg.IsConstant():
6923 arg_strings.append(arg.GetValidArg(func))
6924 extra = {
6925 'gl_args': ", ".join(gl_arg_strings),
6926 'args': ", ".join(arg_strings),
6928 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6930 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6931 """Overridden from TypeHandler."""
6932 valid_test = """
6933 TEST_P(%(test_name)s, %(name)sValidArgs) {
6934 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6935 EXPECT_CALL(
6936 *gl_,
6937 %(gl_func_name)s(%(gl_args)s,
6938 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6939 SpecializedSetup<cmds::%(name)s, 0>(true);
6940 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6941 cmd.Init(%(args)s, &temp[0]);"""
6942 if func.IsUnsafe():
6943 valid_test += """
6944 decoder_->set_unsafe_es3_apis_enabled(true);"""
6945 valid_test += """
6946 EXPECT_EQ(error::kNoError,
6947 ExecuteImmediateCmd(cmd, sizeof(temp)));
6948 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6949 if func.IsUnsafe():
6950 valid_test += """
6951 decoder_->set_unsafe_es3_apis_enabled(false);
6952 EXPECT_EQ(error::kUnknownCommand,
6953 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6954 valid_test += """
6957 gl_arg_strings = []
6958 gl_any_strings = []
6959 arg_strings = []
6960 for arg in func.GetOriginalArgs()[0:-1]:
6961 gl_arg_strings.append(arg.GetValidGLArg(func))
6962 gl_any_strings.append("_")
6963 if not arg.IsConstant():
6964 arg_strings.append(arg.GetValidArg(func))
6965 extra = {
6966 'data_type': self.GetArrayType(func),
6967 'data_count': self.GetArrayCount(func),
6968 'args': ", ".join(arg_strings),
6969 'gl_args': ", ".join(gl_arg_strings),
6970 'gl_any_args': ", ".join(gl_any_strings),
6972 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6974 invalid_test = """
6975 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6976 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6977 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6978 SpecializedSetup<cmds::%(name)s, 0>(false);
6979 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6980 cmd.Init(%(all_but_last_args)s, &temp[0]);
6981 EXPECT_EQ(error::%(parse_result)s,
6982 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6985 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6987 def WriteGetDataSizeCode(self, func, file):
6988 """Overrriden from TypeHandler."""
6989 code = """ uint32_t data_size;
6990 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6991 return error::kOutOfBounds;
6994 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6995 if func.IsImmediate():
6996 file.Write(" if (data_size > immediate_data_size) {\n")
6997 file.Write(" return error::kOutOfBounds;\n")
6998 file.Write(" }\n")
7000 def WriteGLES2Implementation(self, func, file):
7001 """Overrriden from TypeHandler."""
7002 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7003 (func.return_type, func.original_name,
7004 func.MakeTypedOriginalArgString("")))
7005 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7006 func.WriteDestinationInitalizationValidation(file)
7007 self.WriteClientGLCallLog(func, file)
7008 last_pointer_name = func.GetLastOriginalPointerArg().name
7009 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7010 for (GLsizei i = 0; i < count; ++i) {
7011 """)
7012 values_str = ' << ", " << '.join(
7013 ["%s[%d + i * %d]" % (
7014 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
7015 0, self.GetArrayCount(func))])
7016 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
7017 file.Write(" }\n });\n")
7018 for arg in func.GetOriginalArgs():
7019 arg.WriteClientSideValidationCode(file, func)
7020 file.Write(" helper_->%sImmediate(%s);\n" %
7021 (func.name, func.MakeInitString("")))
7022 file.Write(" CheckGLError();\n")
7023 file.Write("}\n")
7024 file.Write("\n")
7026 def WriteGLES2ImplementationUnitTest(self, func, file):
7027 """Writes the GLES2 Implemention unit test."""
7028 code = """
7029 TEST_F(GLES2ImplementationTest, %(name)s) {
7030 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7031 struct Cmds {
7032 cmds::%(name)sImmediate cmd;
7033 %(type)s data[%(count_param)d][%(count)d];
7036 Cmds expected;
7037 for (int ii = 0; ii < %(count_param)d; ++ii) {
7038 for (int jj = 0; jj < %(count)d; ++jj) {
7039 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7042 expected.cmd.Init(%(cmd_args)s);
7043 gl_->%(name)s(%(args)s);
7044 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7047 cmd_arg_strings = []
7048 for arg in func.GetCmdArgs():
7049 if arg.name.endswith("_shm_id"):
7050 cmd_arg_strings.append("&data[0][0]")
7051 elif arg.name.endswith("_shm_offset"):
7052 continue
7053 else:
7054 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
7055 gl_arg_strings = []
7056 count_param = 0
7057 for arg in func.GetOriginalArgs():
7058 if arg.IsPointer():
7059 valid_value = "&data[0][0]"
7060 else:
7061 valid_value = arg.GetValidClientSideArg(func)
7062 gl_arg_strings.append(valid_value)
7063 if arg.name == "count":
7064 count_param = int(valid_value)
7065 file.Write(code % {
7066 'name': func.name,
7067 'type': self.GetArrayType(func),
7068 'count': self.GetArrayCount(func),
7069 'args': ", ".join(gl_arg_strings),
7070 'cmd_args': ", ".join(cmd_arg_strings),
7071 'count_param': count_param,
7074 # Test constants for invalid values, as they are not tested by the
7075 # service.
7076 constants = [
7077 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
7079 if not constants:
7080 return
7082 code = """
7083 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7084 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7085 for (int ii = 0; ii < %(count_param)d; ++ii) {
7086 for (int jj = 0; jj < %(count)d; ++jj) {
7087 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7090 gl_->%(name)s(%(args)s);
7091 EXPECT_TRUE(NoCommandsWritten());
7092 EXPECT_EQ(%(gl_error)s, CheckError());
7095 for invalid_arg in constants:
7096 gl_arg_strings = []
7097 invalid = invalid_arg.GetInvalidArg(func)
7098 for arg in func.GetOriginalArgs():
7099 if arg is invalid_arg:
7100 gl_arg_strings.append(invalid[0])
7101 elif arg.IsPointer():
7102 gl_arg_strings.append("&data[0][0]")
7103 else:
7104 valid_value = arg.GetValidClientSideArg(func)
7105 gl_arg_strings.append(valid_value)
7106 if arg.name == "count":
7107 count_param = int(valid_value)
7109 file.Write(code % {
7110 'name': func.name,
7111 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
7112 'type': self.GetArrayType(func),
7113 'count': self.GetArrayCount(func),
7114 'args': ", ".join(gl_arg_strings),
7115 'gl_error': invalid[2],
7116 'count_param': count_param,
7120 def WriteImmediateCmdComputeSize(self, func, file):
7121 """Overrriden from TypeHandler."""
7122 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7123 file.Write(" return static_cast<uint32_t>(\n")
7124 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
7125 (self.GetArrayType(func), self.GetArrayCount(func)))
7126 file.Write(" }\n")
7127 file.Write("\n")
7128 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
7129 file.Write(" return static_cast<uint32_t>(\n")
7130 file.Write(
7131 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7132 file.Write(" }\n")
7133 file.Write("\n")
7135 def WriteImmediateCmdSetHeader(self, func, file):
7136 """Overrriden from TypeHandler."""
7137 file.Write(" void SetHeader(GLsizei count) {\n")
7138 file.Write(
7139 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7140 file.Write(" }\n")
7141 file.Write("\n")
7143 def WriteImmediateCmdInit(self, func, file):
7144 """Overrriden from TypeHandler."""
7145 file.Write(" void Init(%s) {\n" %
7146 func.MakeTypedInitString("_"))
7147 file.Write(" SetHeader(_count);\n")
7148 args = func.GetCmdArgs()
7149 for arg in args:
7150 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
7151 file.Write(" memcpy(ImmediateDataAddress(this),\n")
7152 pointer_arg = func.GetLastOriginalPointerArg()
7153 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
7154 file.Write(" }\n")
7155 file.Write("\n")
7157 def WriteImmediateCmdSet(self, func, file):
7158 """Overrriden from TypeHandler."""
7159 file.Write(" void* Set(void* cmd%s) {\n" %
7160 func.MakeTypedInitString("_", True))
7161 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7162 func.MakeInitString("_"))
7163 file.Write(" const uint32_t size = ComputeSize(_count);\n")
7164 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7165 "cmd, size);\n")
7166 file.Write(" }\n")
7167 file.Write("\n")
7169 def WriteImmediateCmdHelper(self, func, file):
7170 """Overrriden from TypeHandler."""
7171 code = """ void %(name)s(%(typed_args)s) {
7172 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7173 gles2::cmds::%(name)s* c =
7174 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7175 if (c) {
7176 c->Init(%(args)s);
7181 file.Write(code % {
7182 "name": func.name,
7183 "typed_args": func.MakeTypedInitString(""),
7184 "args": func.MakeInitString("")
7187 def WriteImmediateFormatTest(self, func, file):
7188 """Overrriden from TypeHandler."""
7189 args = func.GetOriginalArgs()
7190 count_param = 0
7191 for arg in args:
7192 if arg.name == "count":
7193 count_param = int(arg.GetValidClientSideCmdArg(func))
7194 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7195 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
7196 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
7197 for v in range(0, self.GetArrayCount(func) * count_param):
7198 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7199 (self.GetArrayType(func), v))
7200 file.Write(" };\n")
7201 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7202 (func.name, func.name))
7203 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
7204 file.Write(" const size_t kExpectedCmdSize =\n")
7205 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7206 (self.GetArrayType(func), self.GetArrayCount(func)))
7207 file.Write(" void* next_cmd = cmd.Set(\n")
7208 file.Write(" &cmd")
7209 for value, arg in enumerate(args):
7210 if arg.IsPointer():
7211 file.Write(",\n data")
7212 elif arg.IsConstant():
7213 continue
7214 else:
7215 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
7216 file.Write(");\n")
7217 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7218 func.name)
7219 file.Write(" cmd.header.command);\n")
7220 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7221 for value, arg in enumerate(args):
7222 if arg.IsPointer() or arg.IsConstant():
7223 continue
7224 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7225 (arg.type, value + 1, arg.name))
7226 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7227 file.Write(" next_cmd, sizeof(cmd) +\n")
7228 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7229 file.Write(" // TODO(gman): Check that data was inserted;\n")
7230 file.Write("}\n")
7231 file.Write("\n")
7233 class PUTSTRHandler(ArrayArgTypeHandler):
7234 """Handler for functions that pass a string array."""
7236 def __init__(self):
7237 ArrayArgTypeHandler.__init__(self)
7239 def __GetDataArg(self, func):
7240 """Return the argument that points to the 2D char arrays"""
7241 for arg in func.GetOriginalArgs():
7242 if arg.IsPointer2D():
7243 return arg
7244 return None
7246 def __GetLengthArg(self, func):
7247 """Return the argument that holds length for each char array"""
7248 for arg in func.GetOriginalArgs():
7249 if arg.IsPointer() and not arg.IsPointer2D():
7250 return arg
7251 return None
7253 def WriteGLES2Implementation(self, func, file):
7254 """Overrriden from TypeHandler."""
7255 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7256 (func.return_type, func.original_name,
7257 func.MakeTypedOriginalArgString("")))
7258 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7259 func.WriteDestinationInitalizationValidation(file)
7260 self.WriteClientGLCallLog(func, file)
7261 data_arg = self.__GetDataArg(func)
7262 length_arg = self.__GetLengthArg(func)
7263 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
7264 for (GLsizei ii = 0; ii < count; ++ii) {
7265 if (%(data)s[ii]) {"""
7266 if length_arg == None:
7267 log_code_block += """
7268 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7269 else:
7270 log_code_block += """
7271 if (%(length)s && %(length)s[ii] >= 0) {
7272 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7273 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7274 } else {
7275 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7276 }"""
7277 log_code_block += """
7278 } else {
7279 GPU_CLIENT_LOG(" " << ii << ": NULL");
7284 file.Write(log_code_block % {
7285 'data': data_arg.name,
7286 'length': length_arg.name if not length_arg == None else ''
7288 for arg in func.GetOriginalArgs():
7289 arg.WriteClientSideValidationCode(file, func)
7291 bucket_args = []
7292 for arg in func.GetOriginalArgs():
7293 if arg.name == 'count' or arg == self.__GetLengthArg(func):
7294 continue
7295 if arg == self.__GetDataArg(func):
7296 bucket_args.append('kResultBucketId')
7297 else:
7298 bucket_args.append(arg.name)
7299 code_block = """
7300 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7301 return;
7303 helper_->%(func_name)sBucket(%(bucket_args)s);
7304 helper_->SetBucketSize(kResultBucketId, 0);
7305 CheckGLError();
7309 file.Write(code_block % {
7310 'data': data_arg.name,
7311 'length': length_arg.name if not length_arg == None else 'NULL',
7312 'func_name': func.name,
7313 'bucket_args': ', '.join(bucket_args),
7316 def WriteGLES2ImplementationUnitTest(self, func, file):
7317 """Overrriden from TypeHandler."""
7318 code = """
7319 TEST_F(GLES2ImplementationTest, %(name)s) {
7320 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7321 const char* kString1 = "happy";
7322 const char* kString2 = "ending";
7323 const size_t kString1Size = ::strlen(kString1) + 1;
7324 const size_t kString2Size = ::strlen(kString2) + 1;
7325 const size_t kHeaderSize = sizeof(GLint) * 3;
7326 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7327 const size_t kPaddedHeaderSize =
7328 transfer_buffer_->RoundToAlignment(kHeaderSize);
7329 const size_t kPaddedString1Size =
7330 transfer_buffer_->RoundToAlignment(kString1Size);
7331 const size_t kPaddedString2Size =
7332 transfer_buffer_->RoundToAlignment(kString2Size);
7333 struct Cmds {
7334 cmd::SetBucketSize set_bucket_size;
7335 cmd::SetBucketData set_bucket_header;
7336 cmd::SetToken set_token1;
7337 cmd::SetBucketData set_bucket_data1;
7338 cmd::SetToken set_token2;
7339 cmd::SetBucketData set_bucket_data2;
7340 cmd::SetToken set_token3;
7341 cmds::%(name)sBucket cmd_bucket;
7342 cmd::SetBucketSize clear_bucket_size;
7345 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7346 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7347 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7349 Cmds expected;
7350 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7351 expected.set_bucket_header.Init(
7352 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7353 expected.set_token1.Init(GetNextToken());
7354 expected.set_bucket_data1.Init(
7355 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7356 expected.set_token2.Init(GetNextToken());
7357 expected.set_bucket_data2.Init(
7358 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7359 mem2.offset);
7360 expected.set_token3.Init(GetNextToken());
7361 expected.cmd_bucket.Init(%(bucket_args)s);
7362 expected.clear_bucket_size.Init(kBucketId, 0);
7363 const char* kStrings[] = { kString1, kString2 };
7364 gl_->%(name)s(%(gl_args)s);
7365 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7368 gl_args = []
7369 bucket_args = []
7370 for arg in func.GetOriginalArgs():
7371 if arg == self.__GetDataArg(func):
7372 gl_args.append('kStrings')
7373 bucket_args.append('kBucketId')
7374 elif arg == self.__GetLengthArg(func):
7375 gl_args.append('NULL')
7376 elif arg.name == 'count':
7377 gl_args.append('2')
7378 else:
7379 gl_args.append(arg.GetValidClientSideArg(func))
7380 bucket_args.append(arg.GetValidClientSideArg(func))
7381 file.Write(code % {
7382 'name': func.name,
7383 'gl_args': ", ".join(gl_args),
7384 'bucket_args': ", ".join(bucket_args),
7387 if self.__GetLengthArg(func) == None:
7388 return
7389 code = """
7390 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7391 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7392 const char* kString = "foobar******";
7393 const size_t kStringSize = 6; // We only need "foobar".
7394 const size_t kHeaderSize = sizeof(GLint) * 2;
7395 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7396 const size_t kPaddedHeaderSize =
7397 transfer_buffer_->RoundToAlignment(kHeaderSize);
7398 const size_t kPaddedStringSize =
7399 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7400 struct Cmds {
7401 cmd::SetBucketSize set_bucket_size;
7402 cmd::SetBucketData set_bucket_header;
7403 cmd::SetToken set_token1;
7404 cmd::SetBucketData set_bucket_data;
7405 cmd::SetToken set_token2;
7406 cmds::ShaderSourceBucket shader_source_bucket;
7407 cmd::SetBucketSize clear_bucket_size;
7410 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7411 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7413 Cmds expected;
7414 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7415 expected.set_bucket_header.Init(
7416 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7417 expected.set_token1.Init(GetNextToken());
7418 expected.set_bucket_data.Init(
7419 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7420 expected.set_token2.Init(GetNextToken());
7421 expected.shader_source_bucket.Init(%(bucket_args)s);
7422 expected.clear_bucket_size.Init(kBucketId, 0);
7423 const char* kStrings[] = { kString };
7424 const GLint kLength[] = { kStringSize };
7425 gl_->%(name)s(%(gl_args)s);
7426 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7429 gl_args = []
7430 for arg in func.GetOriginalArgs():
7431 if arg == self.__GetDataArg(func):
7432 gl_args.append('kStrings')
7433 elif arg == self.__GetLengthArg(func):
7434 gl_args.append('kLength')
7435 elif arg.name == 'count':
7436 gl_args.append('1')
7437 else:
7438 gl_args.append(arg.GetValidClientSideArg(func))
7439 file.Write(code % {
7440 'name': func.name,
7441 'gl_args': ", ".join(gl_args),
7442 'bucket_args': ", ".join(bucket_args),
7445 def WriteBucketServiceUnitTest(self, func, file, *extras):
7446 """Overrriden from TypeHandler."""
7447 cmd_args = []
7448 cmd_args_with_invalid_id = []
7449 gl_args = []
7450 for index, arg in enumerate(func.GetOriginalArgs()):
7451 if arg == self.__GetLengthArg(func):
7452 gl_args.append('_')
7453 elif arg.name == 'count':
7454 gl_args.append('1')
7455 elif arg == self.__GetDataArg(func):
7456 cmd_args.append('kBucketId')
7457 cmd_args_with_invalid_id.append('kBucketId')
7458 gl_args.append('_')
7459 elif index == 0: # Resource ID arg
7460 cmd_args.append(arg.GetValidArg(func))
7461 cmd_args_with_invalid_id.append('kInvalidClientId')
7462 gl_args.append(arg.GetValidGLArg(func))
7463 else:
7464 cmd_args.append(arg.GetValidArg(func))
7465 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7466 gl_args.append(arg.GetValidGLArg(func))
7468 test = """
7469 TEST_P(%(test_name)s, %(name)sValidArgs) {
7470 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7471 const uint32 kBucketId = 123;
7472 const char kSource0[] = "hello";
7473 const char* kSource[] = { kSource0 };
7474 const char kValidStrEnd = 0;
7475 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7476 cmds::%(name)s cmd;
7477 cmd.Init(%(cmd_args)s);
7478 decoder_->set_unsafe_es3_apis_enabled(true);
7479 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7480 if func.IsUnsafe():
7481 test += """
7482 decoder_->set_unsafe_es3_apis_enabled(false);
7483 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7485 test += """
7488 self.WriteValidUnitTest(func, file, test, {
7489 'cmd_args': ", ".join(cmd_args),
7490 'gl_args': ", ".join(gl_args),
7491 }, *extras)
7493 test = """
7494 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7495 const uint32 kBucketId = 123;
7496 const char kSource0[] = "hello";
7497 const char* kSource[] = { kSource0 };
7498 const char kValidStrEnd = 0;
7499 decoder_->set_unsafe_es3_apis_enabled(true);
7500 cmds::%(name)s cmd;
7501 // Test no bucket.
7502 cmd.Init(%(cmd_args)s);
7503 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7504 // Test invalid client.
7505 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7506 cmd.Init(%(cmd_args_with_invalid_id)s);
7507 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7508 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7511 self.WriteValidUnitTest(func, file, test, {
7512 'cmd_args': ", ".join(cmd_args),
7513 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7514 }, *extras)
7516 test = """
7517 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7518 const uint32 kBucketId = 123;
7519 const char kSource0[] = "hello";
7520 const char* kSource[] = { kSource0 };
7521 const char kValidStrEnd = 0;
7522 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7523 const GLsizei kTests[] = {
7524 kCount + 1,
7526 std::numeric_limits<GLsizei>::max(),
7529 decoder_->set_unsafe_es3_apis_enabled(true);
7530 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7531 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7532 cmds::%(name)s cmd;
7533 cmd.Init(%(cmd_args)s);
7534 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7538 self.WriteValidUnitTest(func, file, test, {
7539 'cmd_args': ", ".join(cmd_args),
7540 }, *extras)
7542 test = """
7543 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7544 const uint32 kBucketId = 123;
7545 const char kSource0[] = "hello";
7546 const char* kSource[] = { kSource0 };
7547 const char kInvalidStrEnd = '*';
7548 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7549 cmds::%(name)s cmd;
7550 cmd.Init(%(cmd_args)s);
7551 decoder_->set_unsafe_es3_apis_enabled(true);
7552 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7555 self.WriteValidUnitTest(func, file, test, {
7556 'cmd_args': ", ".join(cmd_args),
7557 }, *extras)
7560 class PUTXnHandler(ArrayArgTypeHandler):
7561 """Handler for glUniform?f functions."""
7562 def __init__(self):
7563 ArrayArgTypeHandler.__init__(self)
7565 def WriteHandlerImplementation(self, func, file):
7566 """Overrriden from TypeHandler."""
7567 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7568 if func.IsUnsafe():
7569 code += """
7570 gl%(name)sv(%(location)s, 1, &temp[0]);
7572 else:
7573 code += """
7574 Do%(name)sv(%(location)s, 1, &temp[0]);
7576 values = ""
7577 args = func.GetOriginalArgs()
7578 count = int(self.GetArrayCount(func))
7579 num_args = len(args)
7580 for ii in range(count):
7581 values += "%s, " % args[len(args) - count + ii].name
7583 file.Write(code % {
7584 'name': func.name,
7585 'count': self.GetArrayCount(func),
7586 'type': self.GetArrayType(func),
7587 'location': args[0].name,
7588 'args': func.MakeOriginalArgString(""),
7589 'values': values,
7592 def WriteServiceUnitTest(self, func, file, *extras):
7593 """Overrriden from TypeHandler."""
7594 valid_test = """
7595 TEST_P(%(test_name)s, %(name)sValidArgs) {
7596 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7597 SpecializedSetup<cmds::%(name)s, 0>(true);
7598 cmds::%(name)s cmd;
7599 cmd.Init(%(args)s);"""
7600 if func.IsUnsafe():
7601 valid_test += """
7602 decoder_->set_unsafe_es3_apis_enabled(true);"""
7603 valid_test += """
7604 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7605 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7606 if func.IsUnsafe():
7607 valid_test += """
7608 decoder_->set_unsafe_es3_apis_enabled(false);
7609 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7610 valid_test += """
7613 args = func.GetOriginalArgs()
7614 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7615 self.WriteValidUnitTest(func, file, valid_test, {
7616 'name': func.name,
7617 'count': self.GetArrayCount(func),
7618 'local_args': local_args,
7619 }, *extras)
7621 invalid_test = """
7622 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7623 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7624 SpecializedSetup<cmds::%(name)s, 0>(false);
7625 cmds::%(name)s cmd;
7626 cmd.Init(%(args)s);
7627 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7630 self.WriteInvalidUnitTest(func, file, invalid_test, {
7631 'name': func.GetInfo('name'),
7632 'count': self.GetArrayCount(func),
7636 class GLcharHandler(CustomHandler):
7637 """Handler for functions that pass a single string ."""
7639 def __init__(self):
7640 CustomHandler.__init__(self)
7642 def WriteImmediateCmdComputeSize(self, func, file):
7643 """Overrriden from TypeHandler."""
7644 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7645 file.Write(" return static_cast<uint32_t>(\n")
7646 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7647 file.Write(" }\n")
7649 def WriteImmediateCmdSetHeader(self, func, file):
7650 """Overrriden from TypeHandler."""
7651 code = """
7652 void SetHeader(uint32_t data_size) {
7653 header.SetCmdBySize<ValueType>(data_size);
7656 file.Write(code)
7658 def WriteImmediateCmdInit(self, func, file):
7659 """Overrriden from TypeHandler."""
7660 last_arg = func.GetLastOriginalArg()
7661 args = func.GetCmdArgs()
7662 set_code = []
7663 for arg in args:
7664 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7665 code = """
7666 void Init(%(typed_args)s, uint32_t _data_size) {
7667 SetHeader(_data_size);
7668 %(set_code)s
7669 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7673 file.Write(code % {
7674 "typed_args": func.MakeTypedArgString("_"),
7675 "set_code": "\n".join(set_code),
7676 "last_arg": last_arg.name
7679 def WriteImmediateCmdSet(self, func, file):
7680 """Overrriden from TypeHandler."""
7681 last_arg = func.GetLastOriginalArg()
7682 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7683 func.MakeTypedCmdArgString("_", True))
7684 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7685 func.MakeCmdArgString("_"))
7686 file.Write(" return NextImmediateCmdAddress<ValueType>("
7687 "cmd, _data_size);\n")
7688 file.Write(" }\n")
7689 file.Write("\n")
7691 def WriteImmediateCmdHelper(self, func, file):
7692 """Overrriden from TypeHandler."""
7693 code = """ void %(name)s(%(typed_args)s) {
7694 const uint32_t data_size = strlen(name);
7695 gles2::cmds::%(name)s* c =
7696 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7697 if (c) {
7698 c->Init(%(args)s, data_size);
7703 file.Write(code % {
7704 "name": func.name,
7705 "typed_args": func.MakeTypedOriginalArgString(""),
7706 "args": func.MakeOriginalArgString(""),
7710 def WriteImmediateFormatTest(self, func, file):
7711 """Overrriden from TypeHandler."""
7712 init_code = []
7713 check_code = []
7714 all_but_last_arg = func.GetCmdArgs()[:-1]
7715 for value, arg in enumerate(all_but_last_arg):
7716 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7717 for value, arg in enumerate(all_but_last_arg):
7718 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7719 (arg.type, value + 11, arg.name))
7720 code = """
7721 TEST_F(GLES2FormatTest, %(func_name)s) {
7722 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7723 static const char* const test_str = \"test string\";
7724 void* next_cmd = cmd.Set(
7725 &cmd,
7726 %(init_code)s
7727 test_str,
7728 strlen(test_str));
7729 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7730 cmd.header.command);
7731 EXPECT_EQ(sizeof(cmd) +
7732 RoundSizeToMultipleOfEntries(strlen(test_str)),
7733 cmd.header.size * 4u);
7734 EXPECT_EQ(static_cast<char*>(next_cmd),
7735 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7736 RoundSizeToMultipleOfEntries(strlen(test_str)));
7737 %(check_code)s
7738 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7739 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7740 CheckBytesWritten(
7741 next_cmd,
7742 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7743 sizeof(cmd) + strlen(test_str));
7747 file.Write(code % {
7748 'func_name': func.name,
7749 'init_code': "\n".join(init_code),
7750 'check_code': "\n".join(check_code),
7754 class GLcharNHandler(CustomHandler):
7755 """Handler for functions that pass a single string with an optional len."""
7757 def __init__(self):
7758 CustomHandler.__init__(self)
7760 def InitFunction(self, func):
7761 """Overrriden from TypeHandler."""
7762 func.cmd_args = []
7763 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7765 def NeedsDataTransferFunction(self, func):
7766 """Overriden from TypeHandler."""
7767 return False
7769 def AddBucketFunction(self, generator, func):
7770 """Overrriden from TypeHandler."""
7771 pass
7773 def WriteServiceImplementation(self, func, file):
7774 """Overrriden from TypeHandler."""
7775 self.WriteServiceHandlerFunctionHeader(func, file)
7776 file.Write("""
7777 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7778 Bucket* bucket = GetBucket(bucket_id);
7779 if (!bucket || bucket->size() == 0) {
7780 return error::kInvalidArguments;
7782 std::string str;
7783 if (!bucket->GetAsString(&str)) {
7784 return error::kInvalidArguments;
7786 %(gl_func_name)s(0, str.c_str());
7787 return error::kNoError;
7790 """ % {
7791 'name': func.name,
7792 'gl_func_name': func.GetGLFunctionName(),
7793 'bucket_id': func.cmd_args[0].name,
7797 class IsHandler(TypeHandler):
7798 """Handler for glIs____ type and glGetError functions."""
7800 def __init__(self):
7801 TypeHandler.__init__(self)
7803 def InitFunction(self, func):
7804 """Overrriden from TypeHandler."""
7805 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7806 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7807 if func.GetInfo('result') == None:
7808 func.AddInfo('result', ['uint32_t'])
7810 def WriteServiceUnitTest(self, func, file, *extras):
7811 """Overrriden from TypeHandler."""
7812 valid_test = """
7813 TEST_P(%(test_name)s, %(name)sValidArgs) {
7814 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7815 SpecializedSetup<cmds::%(name)s, 0>(true);
7816 cmds::%(name)s cmd;
7817 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7818 if func.IsUnsafe():
7819 valid_test += """
7820 decoder_->set_unsafe_es3_apis_enabled(true);"""
7821 valid_test += """
7822 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7823 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7824 if func.IsUnsafe():
7825 valid_test += """
7826 decoder_->set_unsafe_es3_apis_enabled(false);
7827 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7828 valid_test += """
7831 comma = ""
7832 if len(func.GetOriginalArgs()):
7833 comma =", "
7834 self.WriteValidUnitTest(func, file, valid_test, {
7835 'comma': comma,
7836 }, *extras)
7838 invalid_test = """
7839 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7840 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7841 SpecializedSetup<cmds::%(name)s, 0>(false);
7842 cmds::%(name)s cmd;
7843 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7844 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7847 self.WriteInvalidUnitTest(func, file, invalid_test, {
7848 'comma': comma,
7849 }, *extras)
7851 invalid_test = """
7852 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7853 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7854 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7855 if func.IsUnsafe():
7856 invalid_test += """
7857 decoder_->set_unsafe_es3_apis_enabled(true);"""
7858 invalid_test += """
7859 cmds::%(name)s cmd;
7860 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7861 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7862 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7863 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7864 if func.IsUnsafe():
7865 invalid_test += """
7866 decoder_->set_unsafe_es3_apis_enabled(true);"""
7867 invalid_test += """
7870 self.WriteValidUnitTest(func, file, invalid_test, {
7871 'comma': comma,
7872 }, *extras)
7874 def WriteServiceImplementation(self, func, file):
7875 """Overrriden from TypeHandler."""
7876 self.WriteServiceHandlerFunctionHeader(func, file)
7877 args = func.GetOriginalArgs()
7878 for arg in args:
7879 arg.WriteGetCode(file)
7881 code = """ typedef cmds::%(func_name)s::Result Result;
7882 Result* result_dst = GetSharedMemoryAs<Result*>(
7883 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7884 if (!result_dst) {
7885 return error::kOutOfBounds;
7888 file.Write(code % {'func_name': func.name})
7889 func.WriteHandlerValidation(file)
7890 if func.IsUnsafe():
7891 assert func.GetInfo('id_mapping')
7892 assert len(func.GetInfo('id_mapping')) == 1
7893 assert len(args) == 1
7894 id_type = func.GetInfo('id_mapping')[0]
7895 file.Write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
7896 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7897 (id_type, id_type.lower(), id_type.lower()))
7898 else:
7899 file.Write(" *result_dst = %s(%s);\n" %
7900 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
7901 file.Write(" return error::kNoError;\n")
7902 file.Write("}\n")
7903 file.Write("\n")
7905 def WriteGLES2Implementation(self, func, file):
7906 """Overrriden from TypeHandler."""
7907 impl_func = func.GetInfo('impl_func')
7908 if impl_func == None or impl_func == True:
7909 error_value = func.GetInfo("error_value") or "GL_FALSE"
7910 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7911 (func.return_type, func.original_name,
7912 func.MakeTypedOriginalArgString("")))
7913 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7914 self.WriteTraceEvent(func, file)
7915 func.WriteDestinationInitalizationValidation(file)
7916 self.WriteClientGLCallLog(func, file)
7917 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
7918 file.Write(" Result* result = GetResultAs<Result*>();\n")
7919 file.Write(" if (!result) {\n")
7920 file.Write(" return %s;\n" % error_value)
7921 file.Write(" }\n")
7922 file.Write(" *result = 0;\n")
7923 assert len(func.GetOriginalArgs()) == 1
7924 id_arg = func.GetOriginalArgs()[0]
7925 if id_arg.type == 'GLsync':
7926 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
7927 else:
7928 arg_string = func.MakeOriginalArgString("")
7929 file.Write(
7930 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7931 (func.name, arg_string))
7932 file.Write(" WaitForCmd();\n")
7933 file.Write(" %s result_value = *result" % func.return_type)
7934 if func.return_type == "GLboolean":
7935 file.Write(" != 0")
7936 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
7937 file.Write(" CheckGLError();\n")
7938 file.Write(" return result_value;\n")
7939 file.Write("}\n")
7940 file.Write("\n")
7942 def WriteGLES2ImplementationUnitTest(self, func, file):
7943 """Overrriden from TypeHandler."""
7944 client_test = func.GetInfo('client_test')
7945 if client_test == None or client_test == True:
7946 code = """
7947 TEST_F(GLES2ImplementationTest, %(name)s) {
7948 struct Cmds {
7949 cmds::%(name)s cmd;
7952 Cmds expected;
7953 ExpectedMemoryInfo result1 =
7954 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
7955 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
7957 EXPECT_CALL(*command_buffer(), OnFlush())
7958 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
7959 .RetiresOnSaturation();
7961 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
7962 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7963 EXPECT_TRUE(result);
7966 args = func.GetOriginalArgs()
7967 assert len(args) == 1
7968 file.Write(code % {
7969 'name': func.name,
7970 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
7971 'gl_id_value': args[0].GetValidClientSideArg(func) })
7974 class STRnHandler(TypeHandler):
7975 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
7976 GetTranslatedShaderSourceANGLE."""
7978 def __init__(self):
7979 TypeHandler.__init__(self)
7981 def InitFunction(self, func):
7982 """Overrriden from TypeHandler."""
7983 # remove all but the first cmd args.
7984 cmd_args = func.GetCmdArgs()
7985 func.ClearCmdArgs()
7986 func.AddCmdArg(cmd_args[0])
7987 # add on a bucket id.
7988 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
7990 def WriteGLES2Implementation(self, func, file):
7991 """Overrriden from TypeHandler."""
7992 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
7993 GPU_CLIENT_SINGLE_THREAD_CHECK();
7995 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
7996 << "] gl%(func_name)s" << "("
7997 << %(arg0)s << ", "
7998 << %(arg1)s << ", "
7999 << static_cast<void*>(%(arg2)s) << ", "
8000 << static_cast<void*>(%(arg3)s) << ")");
8001 helper_->SetBucketSize(kResultBucketId, 0);
8002 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8003 std::string str;
8004 GLsizei max_size = 0;
8005 if (GetBucketAsString(kResultBucketId, &str)) {
8006 if (bufsize > 0) {
8007 max_size =
8008 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8009 memcpy(%(dest_name)s, str.c_str(), max_size);
8010 %(dest_name)s[max_size] = '\\0';
8011 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8014 if (%(length_name)s != NULL) {
8015 *%(length_name)s = max_size;
8017 CheckGLError();
8020 args = func.GetOriginalArgs()
8021 str_args = {
8022 'return_type': func.return_type,
8023 'func_name': func.original_name,
8024 'args': func.MakeTypedOriginalArgString(""),
8025 'id_name': args[0].name,
8026 'bufsize_name': args[1].name,
8027 'length_name': args[2].name,
8028 'dest_name': args[3].name,
8029 'arg0': args[0].name,
8030 'arg1': args[1].name,
8031 'arg2': args[2].name,
8032 'arg3': args[3].name,
8034 file.Write(code_1 % str_args)
8035 func.WriteDestinationInitalizationValidation(file)
8036 file.Write(code_2 % str_args)
8038 def WriteServiceUnitTest(self, func, file, *extras):
8039 """Overrriden from TypeHandler."""
8040 valid_test = """
8041 TEST_P(%(test_name)s, %(name)sValidArgs) {
8042 const char* kInfo = "hello";
8043 const uint32_t kBucketId = 123;
8044 SpecializedSetup<cmds::%(name)s, 0>(true);
8045 %(expect_len_code)s
8046 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8047 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8048 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8049 cmds::%(name)s cmd;
8050 cmd.Init(%(args)s);
8051 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8052 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8053 ASSERT_TRUE(bucket != NULL);
8054 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8055 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8056 bucket->size()));
8057 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8060 args = func.GetOriginalArgs()
8061 id_name = args[0].GetValidGLArg(func)
8062 get_len_func = func.GetInfo('get_len_func')
8063 get_len_enum = func.GetInfo('get_len_enum')
8064 sub = {
8065 'id_name': id_name,
8066 'get_len_func': get_len_func,
8067 'get_len_enum': get_len_enum,
8068 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8069 args[0].GetValidGLArg(func),
8070 'args': '%s, kBucketId' % args[0].GetValidArg(func),
8071 'expect_len_code': '',
8073 if get_len_func and get_len_func[0:2] == 'gl':
8074 sub['expect_len_code'] = (
8075 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8076 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8077 get_len_func[2:], id_name, get_len_enum)
8078 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
8080 invalid_test = """
8081 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8082 const uint32_t kBucketId = 123;
8083 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8084 .Times(0);
8085 cmds::%(name)s cmd;
8086 cmd.Init(kInvalidClientId, kBucketId);
8087 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8088 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8091 self.WriteValidUnitTest(func, file, invalid_test, *extras)
8093 def WriteServiceImplementation(self, func, file):
8094 """Overrriden from TypeHandler."""
8095 pass
8097 class NamedType(object):
8098 """A class that represents a type of an argument in a client function.
8100 A type of an argument that is to be passed through in the command buffer
8101 command. Currently used only for the arguments that are specificly named in
8102 the 'cmd_buffer_functions.txt' file, mostly enums.
8105 def __init__(self, info):
8106 assert not 'is_complete' in info or info['is_complete'] == True
8107 self.info = info
8108 self.valid = info['valid']
8109 if 'invalid' in info:
8110 self.invalid = info['invalid']
8111 else:
8112 self.invalid = []
8113 if 'valid_es3' in info:
8114 self.valid_es3 = info['valid_es3']
8115 else:
8116 self.valid_es3 = []
8117 if 'deprecated_es3' in info:
8118 self.deprecated_es3 = info['deprecated_es3']
8119 else:
8120 self.deprecated_es3 = []
8122 def GetType(self):
8123 return self.info['type']
8125 def GetInvalidValues(self):
8126 return self.invalid
8128 def GetValidValues(self):
8129 return self.valid
8131 def GetValidValuesES3(self):
8132 return self.valid_es3
8134 def GetDeprecatedValuesES3(self):
8135 return self.deprecated_es3
8137 def IsConstant(self):
8138 if not 'is_complete' in self.info:
8139 return False
8141 return len(self.GetValidValues()) == 1
8143 def GetConstantValue(self):
8144 return self.GetValidValues()[0]
8146 class Argument(object):
8147 """A class that represents a function argument."""
8149 cmd_type_map_ = {
8150 'GLenum': 'uint32_t',
8151 'GLint': 'int32_t',
8152 'GLintptr': 'int32_t',
8153 'GLsizei': 'int32_t',
8154 'GLsizeiptr': 'int32_t',
8155 'GLfloat': 'float',
8156 'GLclampf': 'float',
8158 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8160 def __init__(self, name, type):
8161 self.name = name
8162 self.optional = type.endswith("Optional*")
8163 if self.optional:
8164 type = type[:-9] + "*"
8165 self.type = type
8167 if type in self.cmd_type_map_:
8168 self.cmd_type = self.cmd_type_map_[type]
8169 else:
8170 self.cmd_type = 'uint32_t'
8172 def IsPointer(self):
8173 """Returns true if argument is a pointer."""
8174 return False
8176 def IsPointer2D(self):
8177 """Returns true if argument is a 2D pointer."""
8178 return False
8180 def IsConstant(self):
8181 """Returns true if the argument has only one valid value."""
8182 return False
8184 def AddCmdArgs(self, args):
8185 """Adds command arguments for this argument to the given list."""
8186 if not self.IsConstant():
8187 return args.append(self)
8189 def AddInitArgs(self, args):
8190 """Adds init arguments for this argument to the given list."""
8191 if not self.IsConstant():
8192 return args.append(self)
8194 def GetValidArg(self, func):
8195 """Gets a valid value for this argument."""
8196 valid_arg = func.GetValidArg(self)
8197 if valid_arg != None:
8198 return valid_arg
8200 index = func.GetOriginalArgs().index(self)
8201 return str(index + 1)
8203 def GetValidClientSideArg(self, func):
8204 """Gets a valid value for this argument."""
8205 valid_arg = func.GetValidArg(self)
8206 if valid_arg != None:
8207 return valid_arg
8209 if self.IsPointer():
8210 return 'nullptr'
8211 index = func.GetOriginalArgs().index(self)
8212 if self.type == 'GLsync':
8213 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
8214 return str(index + 1)
8216 def GetValidClientSideCmdArg(self, func):
8217 """Gets a valid value for this argument."""
8218 valid_arg = func.GetValidArg(self)
8219 if valid_arg != None:
8220 return valid_arg
8221 try:
8222 index = func.GetOriginalArgs().index(self)
8223 return str(index + 1)
8224 except ValueError:
8225 pass
8226 index = func.GetCmdArgs().index(self)
8227 return str(index + 1)
8229 def GetValidGLArg(self, func):
8230 """Gets a valid GL value for this argument."""
8231 value = self.GetValidArg(func)
8232 if self.type == 'GLsync':
8233 return ("reinterpret_cast<GLsync>(%s)" % value)
8234 return value
8236 def GetValidNonCachedClientSideArg(self, func):
8237 """Returns a valid value for this argument in a GL call.
8238 Using the value will produce a command buffer service invocation.
8239 Returns None if there is no such value."""
8240 value = '123'
8241 if self.type == 'GLsync':
8242 return ("reinterpret_cast<GLsync>(%s)" % value)
8243 return value
8245 def GetValidNonCachedClientSideCmdArg(self, func):
8246 """Returns a valid value for this argument in a command buffer command.
8247 Calling the GL function with the value returned by
8248 GetValidNonCachedClientSideArg will result in a command buffer command
8249 that contains the value returned by this function. """
8250 return '123'
8252 def GetNumInvalidValues(self, func):
8253 """returns the number of invalid values to be tested."""
8254 return 0
8256 def GetInvalidArg(self, index):
8257 """returns an invalid value and expected parse result by index."""
8258 return ("---ERROR0---", "---ERROR2---", None)
8260 def GetLogArg(self):
8261 """Get argument appropriate for LOG macro."""
8262 if self.type == 'GLboolean':
8263 return 'GLES2Util::GetStringBool(%s)' % self.name
8264 if self.type == 'GLenum':
8265 return 'GLES2Util::GetStringEnum(%s)' % self.name
8266 return self.name
8268 def WriteGetCode(self, file):
8269 """Writes the code to get an argument from a command structure."""
8270 if self.type == 'GLsync':
8271 my_type = 'GLuint'
8272 else:
8273 my_type = self.type
8274 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
8275 (my_type, self.name, my_type, self.name))
8277 def WriteValidationCode(self, file, func):
8278 """Writes the validation code for an argument."""
8279 pass
8281 def WriteClientSideValidationCode(self, file, func):
8282 """Writes the validation code for an argument."""
8283 pass
8285 def WriteDestinationInitalizationValidation(self, file, func):
8286 """Writes the client side destintion initialization validation."""
8287 pass
8289 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
8290 """Writes the client side destintion initialization validation if needed."""
8291 parts = self.type.split(" ")
8292 if len(parts) > 1:
8293 return
8294 if parts[0] in self.need_validation_:
8295 file.Write(
8296 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8297 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
8300 def WriteGetAddress(self, file):
8301 """Writes the code to get the address this argument refers to."""
8302 pass
8304 def GetImmediateVersion(self):
8305 """Gets the immediate version of this argument."""
8306 return self
8308 def GetBucketVersion(self):
8309 """Gets the bucket version of this argument."""
8310 return self
8313 class BoolArgument(Argument):
8314 """class for GLboolean"""
8316 def __init__(self, name, type):
8317 Argument.__init__(self, name, 'GLboolean')
8319 def GetValidArg(self, func):
8320 """Gets a valid value for this argument."""
8321 return 'true'
8323 def GetValidClientSideArg(self, func):
8324 """Gets a valid value for this argument."""
8325 return 'true'
8327 def GetValidClientSideCmdArg(self, func):
8328 """Gets a valid value for this argument."""
8329 return 'true'
8331 def GetValidGLArg(self, func):
8332 """Gets a valid GL value for this argument."""
8333 return 'true'
8336 class UniformLocationArgument(Argument):
8337 """class for uniform locations."""
8339 def __init__(self, name):
8340 Argument.__init__(self, name, "GLint")
8342 def WriteGetCode(self, file):
8343 """Writes the code to get an argument from a command structure."""
8344 code = """ %s %s = static_cast<%s>(c.%s);
8346 file.Write(code % (self.type, self.name, self.type, self.name))
8348 class DataSizeArgument(Argument):
8349 """class for data_size which Bucket commands do not need."""
8351 def __init__(self, name):
8352 Argument.__init__(self, name, "uint32_t")
8354 def GetBucketVersion(self):
8355 return None
8358 class SizeArgument(Argument):
8359 """class for GLsizei and GLsizeiptr."""
8361 def __init__(self, name, type):
8362 Argument.__init__(self, name, type)
8364 def GetNumInvalidValues(self, func):
8365 """overridden from Argument."""
8366 if func.IsImmediate():
8367 return 0
8368 return 1
8370 def GetInvalidArg(self, index):
8371 """overridden from Argument."""
8372 return ("-1", "kNoError", "GL_INVALID_VALUE")
8374 def WriteValidationCode(self, file, func):
8375 """overridden from Argument."""
8376 if func.IsUnsafe():
8377 return
8378 code = """ if (%(var_name)s < 0) {
8379 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8380 return error::kNoError;
8383 file.Write(code % {
8384 "var_name": self.name,
8385 "func_name": func.original_name,
8388 def WriteClientSideValidationCode(self, file, func):
8389 """overridden from Argument."""
8390 code = """ if (%(var_name)s < 0) {
8391 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8392 return;
8395 file.Write(code % {
8396 "var_name": self.name,
8397 "func_name": func.original_name,
8401 class SizeNotNegativeArgument(SizeArgument):
8402 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8404 def __init__(self, name, type, gl_type):
8405 SizeArgument.__init__(self, name, gl_type)
8407 def GetInvalidArg(self, index):
8408 """overridden from SizeArgument."""
8409 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8411 def WriteValidationCode(self, file, func):
8412 """overridden from SizeArgument."""
8413 pass
8416 class EnumBaseArgument(Argument):
8417 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8418 ValidatedBoolArgument."""
8420 def __init__(self, name, gl_type, type, gl_error):
8421 Argument.__init__(self, name, gl_type)
8423 self.local_type = type
8424 self.gl_error = gl_error
8425 name = type[len(gl_type):]
8426 self.type_name = name
8427 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8429 def IsConstant(self):
8430 return self.named_type.IsConstant()
8432 def GetConstantValue(self):
8433 return self.named_type.GetConstantValue()
8435 def WriteValidationCode(self, file, func):
8436 if func.IsUnsafe():
8437 return
8438 if self.named_type.IsConstant():
8439 return
8440 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8441 (ToUnderscore(self.type_name), self.name))
8442 if self.gl_error == "GL_INVALID_ENUM":
8443 file.Write(
8444 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8445 (func.original_name, self.name, self.name))
8446 else:
8447 file.Write(
8448 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8449 (self.gl_error, func.original_name, self.name, self.gl_error))
8450 file.Write(" return error::kNoError;\n")
8451 file.Write(" }\n")
8453 def WriteClientSideValidationCode(self, file, func):
8454 if not self.named_type.IsConstant():
8455 return
8456 file.Write(" if (%s != %s) {" % (self.name,
8457 self.GetConstantValue()))
8458 file.Write(
8459 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8460 (self.gl_error, func.original_name, self.name, self.gl_error))
8461 if func.return_type == "void":
8462 file.Write(" return;\n")
8463 else:
8464 file.Write(" return %s;\n" % func.GetErrorReturnString())
8465 file.Write(" }\n")
8467 def GetValidArg(self, func):
8468 valid_arg = func.GetValidArg(self)
8469 if valid_arg != None:
8470 return valid_arg
8471 valid = self.named_type.GetValidValues()
8472 if valid:
8473 num_valid = len(valid)
8474 return valid[0]
8476 index = func.GetOriginalArgs().index(self)
8477 return str(index + 1)
8479 def GetValidClientSideArg(self, func):
8480 """Gets a valid value for this argument."""
8481 return self.GetValidArg(func)
8483 def GetValidClientSideCmdArg(self, func):
8484 """Gets a valid value for this argument."""
8485 valid_arg = func.GetValidArg(self)
8486 if valid_arg != None:
8487 return valid_arg
8489 valid = self.named_type.GetValidValues()
8490 if valid:
8491 num_valid = len(valid)
8492 return valid[0]
8494 try:
8495 index = func.GetOriginalArgs().index(self)
8496 return str(index + 1)
8497 except ValueError:
8498 pass
8499 index = func.GetCmdArgs().index(self)
8500 return str(index + 1)
8502 def GetValidGLArg(self, func):
8503 """Gets a valid value for this argument."""
8504 return self.GetValidArg(func)
8506 def GetNumInvalidValues(self, func):
8507 """returns the number of invalid values to be tested."""
8508 return len(self.named_type.GetInvalidValues())
8510 def GetInvalidArg(self, index):
8511 """returns an invalid value by index."""
8512 invalid = self.named_type.GetInvalidValues()
8513 if invalid:
8514 num_invalid = len(invalid)
8515 if index >= num_invalid:
8516 index = num_invalid - 1
8517 return (invalid[index], "kNoError", self.gl_error)
8518 return ("---ERROR1---", "kNoError", self.gl_error)
8521 class EnumArgument(EnumBaseArgument):
8522 """A class that represents a GLenum argument"""
8524 def __init__(self, name, type):
8525 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8527 def GetLogArg(self):
8528 """Overridden from Argument."""
8529 return ("GLES2Util::GetString%s(%s)" %
8530 (self.type_name, self.name))
8533 class IntArgument(EnumBaseArgument):
8534 """A class for a GLint argument that can only accept specific values.
8536 For example glTexImage2D takes a GLint for its internalformat
8537 argument instead of a GLenum.
8540 def __init__(self, name, type):
8541 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8544 class ValidatedBoolArgument(EnumBaseArgument):
8545 """A class for a GLboolean argument that can only accept specific values.
8547 For example glUniformMatrix takes a GLboolean for it's transpose but it
8548 must be false.
8551 def __init__(self, name, type):
8552 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8554 def GetLogArg(self):
8555 """Overridden from Argument."""
8556 return 'GLES2Util::GetStringBool(%s)' % self.name
8559 class BitFieldArgument(EnumBaseArgument):
8560 """A class for a GLbitfield argument that can only accept specific values.
8562 For example glFenceSync takes a GLbitfield for its flags argument bit it
8563 must be 0.
8566 def __init__(self, name, type):
8567 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8568 "GL_INVALID_VALUE")
8571 class ImmediatePointerArgument(Argument):
8572 """A class that represents an immediate argument to a function.
8574 An immediate argument is one where the data follows the command.
8577 def __init__(self, name, type):
8578 Argument.__init__(self, name, type)
8580 def IsPointer(self):
8581 return True
8583 def GetPointedType(self):
8584 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8585 assert match
8586 return match.groupdict()['element_type']
8588 def AddCmdArgs(self, args):
8589 """Overridden from Argument."""
8590 pass
8592 def WriteGetCode(self, file):
8593 """Overridden from Argument."""
8594 file.Write(
8595 " %s %s = GetImmediateDataAs<%s>(\n" %
8596 (self.type, self.name, self.type))
8597 file.Write(" c, data_size, immediate_data_size);\n")
8599 def WriteValidationCode(self, file, func):
8600 """Overridden from Argument."""
8601 if self.optional:
8602 return
8603 file.Write(" if (%s == NULL) {\n" % self.name)
8604 file.Write(" return error::kOutOfBounds;\n")
8605 file.Write(" }\n")
8607 def GetImmediateVersion(self):
8608 """Overridden from Argument."""
8609 return None
8611 def WriteDestinationInitalizationValidation(self, file, func):
8612 """Overridden from Argument."""
8613 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8615 def GetLogArg(self):
8616 """Overridden from Argument."""
8617 return "static_cast<const void*>(%s)" % self.name
8620 class PointerArgument(Argument):
8621 """A class that represents a pointer argument to a function."""
8623 def __init__(self, name, type):
8624 Argument.__init__(self, name, type)
8626 def IsPointer(self):
8627 """Overridden from Argument."""
8628 return True
8630 def IsPointer2D(self):
8631 """Overridden from Argument."""
8632 return self.type.count('*') == 2
8634 def GetPointedType(self):
8635 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8636 assert match
8637 return match.groupdict()['element_type']
8639 def GetValidArg(self, func):
8640 """Overridden from Argument."""
8641 return "shared_memory_id_, shared_memory_offset_"
8643 def GetValidGLArg(self, func):
8644 """Overridden from Argument."""
8645 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8647 def GetNumInvalidValues(self, func):
8648 """Overridden from Argument."""
8649 return 2
8651 def GetInvalidArg(self, index):
8652 """Overridden from Argument."""
8653 if index == 0:
8654 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8655 else:
8656 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8657 "kOutOfBounds", None)
8659 def GetLogArg(self):
8660 """Overridden from Argument."""
8661 return "static_cast<const void*>(%s)" % self.name
8663 def AddCmdArgs(self, args):
8664 """Overridden from Argument."""
8665 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8666 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8668 def WriteGetCode(self, file):
8669 """Overridden from Argument."""
8670 file.Write(
8671 " %s %s = GetSharedMemoryAs<%s>(\n" %
8672 (self.type, self.name, self.type))
8673 file.Write(
8674 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8675 (self.name, self.name))
8677 def WriteGetAddress(self, file):
8678 """Overridden from Argument."""
8679 file.Write(
8680 " %s %s = GetSharedMemoryAs<%s>(\n" %
8681 (self.type, self.name, self.type))
8682 file.Write(
8683 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8684 (self.name, self.name, self.name))
8686 def WriteValidationCode(self, file, func):
8687 """Overridden from Argument."""
8688 if self.optional:
8689 return
8690 file.Write(" if (%s == NULL) {\n" % self.name)
8691 file.Write(" return error::kOutOfBounds;\n")
8692 file.Write(" }\n")
8694 def GetImmediateVersion(self):
8695 """Overridden from Argument."""
8696 return ImmediatePointerArgument(self.name, self.type)
8698 def GetBucketVersion(self):
8699 """Overridden from Argument."""
8700 if self.type.find('char') >= 0:
8701 if self.IsPointer2D():
8702 return InputStringArrayBucketArgument(self.name, self.type)
8703 return InputStringBucketArgument(self.name, self.type)
8704 return BucketPointerArgument(self.name, self.type)
8706 def WriteDestinationInitalizationValidation(self, file, func):
8707 """Overridden from Argument."""
8708 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8711 class BucketPointerArgument(PointerArgument):
8712 """A class that represents an bucket argument to a function."""
8714 def __init__(self, name, type):
8715 Argument.__init__(self, name, type)
8717 def AddCmdArgs(self, args):
8718 """Overridden from Argument."""
8719 pass
8721 def WriteGetCode(self, file):
8722 """Overridden from Argument."""
8723 file.Write(
8724 " %s %s = bucket->GetData(0, data_size);\n" %
8725 (self.type, self.name))
8727 def WriteValidationCode(self, file, func):
8728 """Overridden from Argument."""
8729 pass
8731 def GetImmediateVersion(self):
8732 """Overridden from Argument."""
8733 return None
8735 def WriteDestinationInitalizationValidation(self, file, func):
8736 """Overridden from Argument."""
8737 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8739 def GetLogArg(self):
8740 """Overridden from Argument."""
8741 return "static_cast<const void*>(%s)" % self.name
8744 class InputStringBucketArgument(Argument):
8745 """A string input argument where the string is passed in a bucket."""
8747 def __init__(self, name, type):
8748 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8750 def IsPointer(self):
8751 """Overridden from Argument."""
8752 return True
8754 def IsPointer2D(self):
8755 """Overridden from Argument."""
8756 return False
8759 class InputStringArrayBucketArgument(Argument):
8760 """A string array input argument where the strings are passed in a bucket."""
8762 def __init__(self, name, type):
8763 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8764 self._original_name = name
8766 def WriteGetCode(self, file):
8767 """Overridden from Argument."""
8768 code = """
8769 Bucket* bucket = GetBucket(c.%(name)s);
8770 if (!bucket) {
8771 return error::kInvalidArguments;
8773 GLsizei count = 0;
8774 std::vector<char*> strs;
8775 std::vector<GLint> len;
8776 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8777 return error::kInvalidArguments;
8779 const char** %(original_name)s =
8780 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8781 const GLint* length =
8782 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8783 (void)length;
8785 file.Write(code % {
8786 'name': self.name,
8787 'original_name': self._original_name,
8790 def GetValidArg(self, func):
8791 return "kNameBucketId"
8793 def GetValidGLArg(self, func):
8794 return "_"
8796 def IsPointer(self):
8797 """Overridden from Argument."""
8798 return True
8800 def IsPointer2D(self):
8801 """Overridden from Argument."""
8802 return True
8805 class ResourceIdArgument(Argument):
8806 """A class that represents a resource id argument to a function."""
8808 def __init__(self, name, type):
8809 match = re.match("(GLid\w+)", type)
8810 self.resource_type = match.group(1)[4:]
8811 if self.resource_type == "Sync":
8812 type = type.replace(match.group(1), "GLsync")
8813 else:
8814 type = type.replace(match.group(1), "GLuint")
8815 Argument.__init__(self, name, type)
8817 def WriteGetCode(self, file):
8818 """Overridden from Argument."""
8819 if self.type == "GLsync":
8820 my_type = "GLuint"
8821 else:
8822 my_type = self.type
8823 file.Write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8825 def GetValidArg(self, func):
8826 return "client_%s_id_" % self.resource_type.lower()
8828 def GetValidGLArg(self, func):
8829 if self.resource_type == "Sync":
8830 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8831 return "kService%sId" % self.resource_type
8834 class ResourceIdBindArgument(Argument):
8835 """Represents a resource id argument to a bind function."""
8837 def __init__(self, name, type):
8838 match = re.match("(GLidBind\w+)", type)
8839 self.resource_type = match.group(1)[8:]
8840 type = type.replace(match.group(1), "GLuint")
8841 Argument.__init__(self, name, type)
8843 def WriteGetCode(self, file):
8844 """Overridden from Argument."""
8845 code = """ %(type)s %(name)s = c.%(name)s;
8847 file.Write(code % {'type': self.type, 'name': self.name})
8849 def GetValidArg(self, func):
8850 return "client_%s_id_" % self.resource_type.lower()
8852 def GetValidGLArg(self, func):
8853 return "kService%sId" % self.resource_type
8856 class ResourceIdZeroArgument(Argument):
8857 """Represents a resource id argument to a function that can be zero."""
8859 def __init__(self, name, type):
8860 match = re.match("(GLidZero\w+)", type)
8861 self.resource_type = match.group(1)[8:]
8862 type = type.replace(match.group(1), "GLuint")
8863 Argument.__init__(self, name, type)
8865 def WriteGetCode(self, file):
8866 """Overridden from Argument."""
8867 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
8869 def GetValidArg(self, func):
8870 return "client_%s_id_" % self.resource_type.lower()
8872 def GetValidGLArg(self, func):
8873 return "kService%sId" % self.resource_type
8875 def GetNumInvalidValues(self, func):
8876 """returns the number of invalid values to be tested."""
8877 return 1
8879 def GetInvalidArg(self, index):
8880 """returns an invalid value by index."""
8881 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8884 class Function(object):
8885 """A class that represents a function."""
8887 type_handlers = {
8888 '': TypeHandler(),
8889 'Bind': BindHandler(),
8890 'Create': CreateHandler(),
8891 'Custom': CustomHandler(),
8892 'Data': DataHandler(),
8893 'Delete': DeleteHandler(),
8894 'DELn': DELnHandler(),
8895 'GENn': GENnHandler(),
8896 'GETn': GETnHandler(),
8897 'GLchar': GLcharHandler(),
8898 'GLcharN': GLcharNHandler(),
8899 'HandWritten': HandWrittenHandler(),
8900 'Is': IsHandler(),
8901 'Manual': ManualHandler(),
8902 'PUT': PUTHandler(),
8903 'PUTn': PUTnHandler(),
8904 'PUTSTR': PUTSTRHandler(),
8905 'PUTXn': PUTXnHandler(),
8906 'StateSet': StateSetHandler(),
8907 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8908 'StateSetFrontBack': StateSetFrontBackHandler(),
8909 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8910 'StateSetNamedParameter': StateSetNamedParameter(),
8911 'STRn': STRnHandler(),
8912 'Todo': TodoHandler(),
8915 def __init__(self, name, info):
8916 self.name = name
8917 self.original_name = info['original_name']
8919 self.original_args = self.ParseArgs(info['original_args'])
8921 if 'cmd_args' in info:
8922 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
8923 else:
8924 self.args_for_cmds = self.original_args[:]
8926 self.return_type = info['return_type']
8927 if self.return_type != 'void':
8928 self.return_arg = CreateArg(info['return_type'] + " result")
8929 else:
8930 self.return_arg = None
8932 self.num_pointer_args = sum(
8933 [1 for arg in self.args_for_cmds if arg.IsPointer()])
8934 if self.num_pointer_args > 0:
8935 for arg in reversed(self.original_args):
8936 if arg.IsPointer():
8937 self.last_original_pointer_arg = arg
8938 break
8939 else:
8940 self.last_original_pointer_arg = None
8941 self.info = info
8942 self.type_handler = self.type_handlers[info['type']]
8943 self.can_auto_generate = (self.num_pointer_args == 0 and
8944 info['return_type'] == "void")
8945 self.InitFunction()
8947 def ParseArgs(self, arg_string):
8948 """Parses a function arg string."""
8949 args = []
8950 parts = arg_string.split(',')
8951 for arg_string in parts:
8952 arg = CreateArg(arg_string)
8953 if arg:
8954 args.append(arg)
8955 return args
8957 def IsType(self, type_name):
8958 """Returns true if function is a certain type."""
8959 return self.info['type'] == type_name
8961 def InitFunction(self):
8962 """Creates command args and calls the init function for the type handler.
8964 Creates argument lists for command buffer commands, eg. self.cmd_args and
8965 self.init_args.
8966 Calls the type function initialization.
8967 Override to create different kind of command buffer command argument lists.
8969 self.cmd_args = []
8970 for arg in self.args_for_cmds:
8971 arg.AddCmdArgs(self.cmd_args)
8973 self.init_args = []
8974 for arg in self.args_for_cmds:
8975 arg.AddInitArgs(self.init_args)
8977 if self.return_arg:
8978 self.init_args.append(self.return_arg)
8980 self.type_handler.InitFunction(self)
8982 def IsImmediate(self):
8983 """Returns whether the function is immediate data function or not."""
8984 return False
8986 def IsUnsafe(self):
8987 """Returns whether the function has service side validation or not."""
8988 return self.GetInfo('unsafe', False)
8990 def GetInfo(self, name, default = None):
8991 """Returns a value from the function info for this function."""
8992 if name in self.info:
8993 return self.info[name]
8994 return default
8996 def GetValidArg(self, arg):
8997 """Gets a valid argument value for the parameter arg from the function info
8998 if one exists."""
8999 try:
9000 index = self.GetOriginalArgs().index(arg)
9001 except ValueError:
9002 return None
9004 valid_args = self.GetInfo('valid_args')
9005 if valid_args and str(index) in valid_args:
9006 return valid_args[str(index)]
9007 return None
9009 def AddInfo(self, name, value):
9010 """Adds an info."""
9011 self.info[name] = value
9013 def IsExtension(self):
9014 return self.GetInfo('extension') or self.GetInfo('extension_flag')
9016 def IsCoreGLFunction(self):
9017 return (not self.IsExtension() and
9018 not self.GetInfo('pepper_interface') and
9019 not self.IsUnsafe())
9021 def InPepperInterface(self, interface):
9022 ext = self.GetInfo('pepper_interface')
9023 if not interface.GetName():
9024 return self.IsCoreGLFunction()
9025 return ext == interface.GetName()
9027 def InAnyPepperExtension(self):
9028 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
9030 def GetErrorReturnString(self):
9031 if self.GetInfo("error_return"):
9032 return self.GetInfo("error_return")
9033 elif self.return_type == "GLboolean":
9034 return "GL_FALSE"
9035 elif "*" in self.return_type:
9036 return "NULL"
9037 return "0"
9039 def GetGLFunctionName(self):
9040 """Gets the function to call to execute GL for this command."""
9041 if self.GetInfo('decoder_func'):
9042 return self.GetInfo('decoder_func')
9043 return "gl%s" % self.original_name
9045 def GetGLTestFunctionName(self):
9046 gl_func_name = self.GetInfo('gl_test_func')
9047 if gl_func_name == None:
9048 gl_func_name = self.GetGLFunctionName()
9049 if gl_func_name.startswith("gl"):
9050 gl_func_name = gl_func_name[2:]
9051 else:
9052 gl_func_name = self.original_name
9053 return gl_func_name
9055 def GetDataTransferMethods(self):
9056 return self.GetInfo('data_transfer_methods',
9057 ['immediate' if self.num_pointer_args == 1 else 'shm'])
9059 def AddCmdArg(self, arg):
9060 """Adds a cmd argument to this function."""
9061 self.cmd_args.append(arg)
9063 def GetCmdArgs(self):
9064 """Gets the command args for this function."""
9065 return self.cmd_args
9067 def ClearCmdArgs(self):
9068 """Clears the command args for this function."""
9069 self.cmd_args = []
9071 def GetCmdConstants(self):
9072 """Gets the constants for this function."""
9073 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
9075 def GetInitArgs(self):
9076 """Gets the init args for this function."""
9077 return self.init_args
9079 def GetOriginalArgs(self):
9080 """Gets the original arguments to this function."""
9081 return self.original_args
9083 def GetLastOriginalArg(self):
9084 """Gets the last original argument to this function."""
9085 return self.original_args[len(self.original_args) - 1]
9087 def GetLastOriginalPointerArg(self):
9088 return self.last_original_pointer_arg
9090 def GetResourceIdArg(self):
9091 for arg in self.original_args:
9092 if hasattr(arg, 'resource_type'):
9093 return arg
9094 return None
9096 def _MaybePrependComma(self, arg_string, add_comma):
9097 """Adds a comma if arg_string is not empty and add_comma is true."""
9098 comma = ""
9099 if add_comma and len(arg_string):
9100 comma = ", "
9101 return "%s%s" % (comma, arg_string)
9103 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
9104 """Gets a list of arguments as they are in GL."""
9105 args = self.GetOriginalArgs()
9106 arg_string = ", ".join(
9107 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9108 return self._MaybePrependComma(arg_string, add_comma)
9110 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9111 """Gets the list of arguments as they are in GL."""
9112 args = self.GetOriginalArgs()
9113 arg_string = separator.join(
9114 ["%s%s" % (prefix, arg.name) for arg in args])
9115 return self._MaybePrependComma(arg_string, add_comma)
9117 def MakeTypedHelperArgString(self, prefix, add_comma = False):
9118 """Gets a list of typed GL arguments after removing unneeded arguments."""
9119 args = self.GetOriginalArgs()
9120 arg_string = ", ".join(
9121 ["%s %s%s" % (
9122 arg.type,
9123 prefix,
9124 arg.name,
9125 ) for arg in args if not arg.IsConstant()])
9126 return self._MaybePrependComma(arg_string, add_comma)
9128 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
9129 """Gets a list of GL arguments after removing unneeded arguments."""
9130 args = self.GetOriginalArgs()
9131 arg_string = separator.join(
9132 ["%s%s" % (prefix, arg.name)
9133 for arg in args if not arg.IsConstant()])
9134 return self._MaybePrependComma(arg_string, add_comma)
9136 def MakeTypedPepperArgString(self, prefix):
9137 """Gets a list of arguments as they need to be for Pepper."""
9138 if self.GetInfo("pepper_args"):
9139 return self.GetInfo("pepper_args")
9140 else:
9141 return self.MakeTypedOriginalArgString(prefix, False)
9143 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
9144 """Converts a C type name to the corresponding Pepper IDL type."""
9145 idltype = {
9146 'char*': '[out] str_t',
9147 'const GLchar* const*': '[out] cstr_t',
9148 'const char*': 'cstr_t',
9149 'const void*': 'mem_t',
9150 'void*': '[out] mem_t',
9151 'void**': '[out] mem_ptr_t',
9152 }.get(ctype, ctype)
9153 # We use "GLxxx_ptr_t" for "GLxxx*".
9154 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
9155 if matched:
9156 idltype = matched.group(2) + '_ptr_t'
9157 if not matched.group(1):
9158 idltype = '[out] ' + idltype
9159 # If an in/out specifier is not specified yet, prepend [in].
9160 if idltype[0] != '[':
9161 idltype = '[in] ' + idltype
9162 # Strip the in/out specifier for a return type.
9163 if is_for_return_type:
9164 idltype = re.sub(r'\[\w+\] ', '', idltype)
9165 return idltype
9167 def MakeTypedPepperIdlArgStrings(self):
9168 """Gets a list of arguments as they need to be for Pepper IDL."""
9169 args = self.GetOriginalArgs()
9170 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
9171 for arg in args]
9173 def GetPepperName(self):
9174 if self.GetInfo("pepper_name"):
9175 return self.GetInfo("pepper_name")
9176 return self.name
9178 def MakeTypedCmdArgString(self, prefix, add_comma = False):
9179 """Gets a typed list of arguments as they need to be for command buffers."""
9180 args = self.GetCmdArgs()
9181 arg_string = ", ".join(
9182 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9183 return self._MaybePrependComma(arg_string, add_comma)
9185 def MakeCmdArgString(self, prefix, add_comma = False):
9186 """Gets the list of arguments as they need to be for command buffers."""
9187 args = self.GetCmdArgs()
9188 arg_string = ", ".join(
9189 ["%s%s" % (prefix, arg.name) for arg in args])
9190 return self._MaybePrependComma(arg_string, add_comma)
9192 def MakeTypedInitString(self, prefix, add_comma = False):
9193 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9194 args = self.GetInitArgs()
9195 arg_string = ", ".join(
9196 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9197 return self._MaybePrependComma(arg_string, add_comma)
9199 def MakeInitString(self, prefix, add_comma = False):
9200 """Gets the list of arguments as they need to be for cmd Init/Set."""
9201 args = self.GetInitArgs()
9202 arg_string = ", ".join(
9203 ["%s%s" % (prefix, arg.name) for arg in args])
9204 return self._MaybePrependComma(arg_string, add_comma)
9206 def MakeLogArgString(self):
9207 """Makes a string of the arguments for the LOG macros"""
9208 args = self.GetOriginalArgs()
9209 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
9211 def WriteCommandDescription(self, file):
9212 """Writes a description of the command."""
9213 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
9215 def WriteHandlerValidation(self, file):
9216 """Writes validation code for the function."""
9217 for arg in self.GetOriginalArgs():
9218 arg.WriteValidationCode(file, self)
9219 self.WriteValidationCode(file)
9221 def WriteHandlerImplementation(self, file):
9222 """Writes the handler implementation for this command."""
9223 self.type_handler.WriteHandlerImplementation(self, file)
9225 def WriteValidationCode(self, file):
9226 """Writes the validation code for a command."""
9227 pass
9229 def WriteCmdFlag(self, file):
9230 """Writes the cmd cmd_flags constant."""
9231 flags = []
9232 # By default trace only at the highest level 3.
9233 trace_level = int(self.GetInfo('trace_level', default = 3))
9234 if trace_level not in xrange(0, 4):
9235 raise KeyError("Unhandled trace_level: %d" % trace_level)
9237 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
9239 if len(flags) > 0:
9240 cmd_flags = ' | '.join(flags)
9241 else:
9242 cmd_flags = 0
9244 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
9247 def WriteCmdArgFlag(self, file):
9248 """Writes the cmd kArgFlags constant."""
9249 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9251 def WriteCmdComputeSize(self, file):
9252 """Writes the ComputeSize function for the command."""
9253 file.Write(" static uint32_t ComputeSize() {\n")
9254 file.Write(
9255 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9256 file.Write(" }\n")
9257 file.Write("\n")
9259 def WriteCmdSetHeader(self, file):
9260 """Writes the cmd's SetHeader function."""
9261 file.Write(" void SetHeader() {\n")
9262 file.Write(" header.SetCmd<ValueType>();\n")
9263 file.Write(" }\n")
9264 file.Write("\n")
9266 def WriteCmdInit(self, file):
9267 """Writes the cmd's Init function."""
9268 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
9269 file.Write(" SetHeader();\n")
9270 args = self.GetCmdArgs()
9271 for arg in args:
9272 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
9273 file.Write(" }\n")
9274 file.Write("\n")
9276 def WriteCmdSet(self, file):
9277 """Writes the cmd's Set function."""
9278 copy_args = self.MakeCmdArgString("_", False)
9279 file.Write(" void* Set(void* cmd%s) {\n" %
9280 self.MakeTypedCmdArgString("_", True))
9281 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
9282 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
9283 file.Write(" }\n")
9284 file.Write("\n")
9286 def WriteStruct(self, file):
9287 self.type_handler.WriteStruct(self, file)
9289 def WriteDocs(self, file):
9290 self.type_handler.WriteDocs(self, file)
9292 def WriteCmdHelper(self, file):
9293 """Writes the cmd's helper."""
9294 self.type_handler.WriteCmdHelper(self, file)
9296 def WriteServiceImplementation(self, file):
9297 """Writes the service implementation for a command."""
9298 self.type_handler.WriteServiceImplementation(self, file)
9300 def WriteServiceUnitTest(self, file, *extras):
9301 """Writes the service implementation for a command."""
9302 self.type_handler.WriteServiceUnitTest(self, file, *extras)
9304 def WriteGLES2CLibImplementation(self, file):
9305 """Writes the GLES2 C Lib Implemention."""
9306 self.type_handler.WriteGLES2CLibImplementation(self, file)
9308 def WriteGLES2InterfaceHeader(self, file):
9309 """Writes the GLES2 Interface declaration."""
9310 self.type_handler.WriteGLES2InterfaceHeader(self, file)
9312 def WriteMojoGLES2ImplHeader(self, file):
9313 """Writes the Mojo GLES2 implementation header declaration."""
9314 self.type_handler.WriteMojoGLES2ImplHeader(self, file)
9316 def WriteMojoGLES2Impl(self, file):
9317 """Writes the Mojo GLES2 implementation declaration."""
9318 self.type_handler.WriteMojoGLES2Impl(self, file)
9320 def WriteGLES2InterfaceStub(self, file):
9321 """Writes the GLES2 Interface Stub declaration."""
9322 self.type_handler.WriteGLES2InterfaceStub(self, file)
9324 def WriteGLES2InterfaceStubImpl(self, file):
9325 """Writes the GLES2 Interface Stub declaration."""
9326 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
9328 def WriteGLES2ImplementationHeader(self, file):
9329 """Writes the GLES2 Implemention declaration."""
9330 self.type_handler.WriteGLES2ImplementationHeader(self, file)
9332 def WriteGLES2Implementation(self, file):
9333 """Writes the GLES2 Implemention definition."""
9334 self.type_handler.WriteGLES2Implementation(self, file)
9336 def WriteGLES2TraceImplementationHeader(self, file):
9337 """Writes the GLES2 Trace Implemention declaration."""
9338 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
9340 def WriteGLES2TraceImplementation(self, file):
9341 """Writes the GLES2 Trace Implemention definition."""
9342 self.type_handler.WriteGLES2TraceImplementation(self, file)
9344 def WriteGLES2Header(self, file):
9345 """Writes the GLES2 Implemention unit test."""
9346 self.type_handler.WriteGLES2Header(self, file)
9348 def WriteGLES2ImplementationUnitTest(self, file):
9349 """Writes the GLES2 Implemention unit test."""
9350 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
9352 def WriteDestinationInitalizationValidation(self, file):
9353 """Writes the client side destintion initialization validation."""
9354 self.type_handler.WriteDestinationInitalizationValidation(self, file)
9356 def WriteFormatTest(self, file):
9357 """Writes the cmd's format test."""
9358 self.type_handler.WriteFormatTest(self, file)
9361 class PepperInterface(object):
9362 """A class that represents a function."""
9364 def __init__(self, info):
9365 self.name = info["name"]
9366 self.dev = info["dev"]
9368 def GetName(self):
9369 return self.name
9371 def GetInterfaceName(self):
9372 upperint = ""
9373 dev = ""
9374 if self.name:
9375 upperint = "_" + self.name.upper()
9376 if self.dev:
9377 dev = "_DEV"
9378 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9380 def GetInterfaceString(self):
9381 dev = ""
9382 if self.dev:
9383 dev = "(Dev)"
9384 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9386 def GetStructName(self):
9387 dev = ""
9388 if self.dev:
9389 dev = "_Dev"
9390 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9393 class ImmediateFunction(Function):
9394 """A class that represnets an immediate function command."""
9396 def __init__(self, func):
9397 Function.__init__(
9398 self,
9399 "%sImmediate" % func.name,
9400 func.info)
9402 def InitFunction(self):
9403 # Override args in original_args and args_for_cmds with immediate versions
9404 # of the args.
9406 new_original_args = []
9407 for arg in self.original_args:
9408 new_arg = arg.GetImmediateVersion()
9409 if new_arg:
9410 new_original_args.append(new_arg)
9411 self.original_args = new_original_args
9413 new_args_for_cmds = []
9414 for arg in self.args_for_cmds:
9415 new_arg = arg.GetImmediateVersion()
9416 if new_arg:
9417 new_args_for_cmds.append(new_arg)
9419 self.args_for_cmds = new_args_for_cmds
9421 Function.InitFunction(self)
9423 def IsImmediate(self):
9424 return True
9426 def WriteCommandDescription(self, file):
9427 """Overridden from Function"""
9428 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9429 self.original_name)
9431 def WriteServiceImplementation(self, file):
9432 """Overridden from Function"""
9433 self.type_handler.WriteImmediateServiceImplementation(self, file)
9435 def WriteHandlerImplementation(self, file):
9436 """Overridden from Function"""
9437 self.type_handler.WriteImmediateHandlerImplementation(self, file)
9439 def WriteServiceUnitTest(self, file, *extras):
9440 """Writes the service implementation for a command."""
9441 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
9443 def WriteValidationCode(self, file):
9444 """Overridden from Function"""
9445 self.type_handler.WriteImmediateValidationCode(self, file)
9447 def WriteCmdArgFlag(self, file):
9448 """Overridden from Function"""
9449 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9451 def WriteCmdComputeSize(self, file):
9452 """Overridden from Function"""
9453 self.type_handler.WriteImmediateCmdComputeSize(self, file)
9455 def WriteCmdSetHeader(self, file):
9456 """Overridden from Function"""
9457 self.type_handler.WriteImmediateCmdSetHeader(self, file)
9459 def WriteCmdInit(self, file):
9460 """Overridden from Function"""
9461 self.type_handler.WriteImmediateCmdInit(self, file)
9463 def WriteCmdSet(self, file):
9464 """Overridden from Function"""
9465 self.type_handler.WriteImmediateCmdSet(self, file)
9467 def WriteCmdHelper(self, file):
9468 """Overridden from Function"""
9469 self.type_handler.WriteImmediateCmdHelper(self, file)
9471 def WriteFormatTest(self, file):
9472 """Overridden from Function"""
9473 self.type_handler.WriteImmediateFormatTest(self, file)
9476 class BucketFunction(Function):
9477 """A class that represnets a bucket version of a function command."""
9479 def __init__(self, func):
9480 Function.__init__(
9481 self,
9482 "%sBucket" % func.name,
9483 func.info)
9485 def InitFunction(self):
9486 # Override args in original_args and args_for_cmds with bucket versions
9487 # of the args.
9489 new_original_args = []
9490 for arg in self.original_args:
9491 new_arg = arg.GetBucketVersion()
9492 if new_arg:
9493 new_original_args.append(new_arg)
9494 self.original_args = new_original_args
9496 new_args_for_cmds = []
9497 for arg in self.args_for_cmds:
9498 new_arg = arg.GetBucketVersion()
9499 if new_arg:
9500 new_args_for_cmds.append(new_arg)
9502 self.args_for_cmds = new_args_for_cmds
9504 Function.InitFunction(self)
9506 def WriteCommandDescription(self, file):
9507 """Overridden from Function"""
9508 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9509 self.original_name)
9511 def WriteServiceImplementation(self, file):
9512 """Overridden from Function"""
9513 self.type_handler.WriteBucketServiceImplementation(self, file)
9515 def WriteHandlerImplementation(self, file):
9516 """Overridden from Function"""
9517 self.type_handler.WriteBucketHandlerImplementation(self, file)
9519 def WriteServiceUnitTest(self, file, *extras):
9520 """Overridden from Function"""
9521 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
9523 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9524 """Overridden from Function"""
9525 args = self.GetOriginalArgs()
9526 arg_string = separator.join(
9527 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9528 else arg.name) for arg in args])
9529 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9532 def CreateArg(arg_string):
9533 """Creates an Argument."""
9534 arg_parts = arg_string.split()
9535 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9536 return None
9537 # Is this a pointer argument?
9538 elif arg_string.find('*') >= 0:
9539 return PointerArgument(
9540 arg_parts[-1],
9541 " ".join(arg_parts[0:-1]))
9542 # Is this a resource argument? Must come after pointer check.
9543 elif arg_parts[0].startswith('GLidBind'):
9544 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9545 elif arg_parts[0].startswith('GLidZero'):
9546 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9547 elif arg_parts[0].startswith('GLid'):
9548 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9549 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9550 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9551 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9552 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9553 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9554 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9555 elif arg_parts[0].startswith('GLboolean'):
9556 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9557 elif arg_parts[0].startswith('GLintUniformLocation'):
9558 return UniformLocationArgument(arg_parts[-1])
9559 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9560 not arg_parts[0].startswith('GLintptr')):
9561 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9562 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9563 arg_parts[0].startswith('GLintptrNotNegative')):
9564 return SizeNotNegativeArgument(arg_parts[-1],
9565 " ".join(arg_parts[0:-1]),
9566 arg_parts[0][0:-11])
9567 elif arg_parts[0].startswith('GLsize'):
9568 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9569 else:
9570 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9573 class GLGenerator(object):
9574 """A class to generate GL command buffers."""
9576 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9578 def __init__(self, verbose):
9579 self.original_functions = []
9580 self.functions = []
9581 self.verbose = verbose
9582 self.errors = 0
9583 self.pepper_interfaces = []
9584 self.interface_info = {}
9585 self.generated_cpp_filenames = []
9587 for interface in _PEPPER_INTERFACES:
9588 interface = PepperInterface(interface)
9589 self.pepper_interfaces.append(interface)
9590 self.interface_info[interface.GetName()] = interface
9592 def AddFunction(self, func):
9593 """Adds a function."""
9594 self.functions.append(func)
9596 def GetFunctionInfo(self, name):
9597 """Gets a type info for the given function name."""
9598 if name in _FUNCTION_INFO:
9599 func_info = _FUNCTION_INFO[name].copy()
9600 else:
9601 func_info = {}
9603 if not 'type' in func_info:
9604 func_info['type'] = ''
9606 return func_info
9608 def Log(self, msg):
9609 """Prints something if verbose is true."""
9610 if self.verbose:
9611 print msg
9613 def Error(self, msg):
9614 """Prints an error."""
9615 print "Error: %s" % msg
9616 self.errors += 1
9618 def WriteLicense(self, file):
9619 """Writes the license."""
9620 file.Write(_LICENSE)
9622 def WriteNamespaceOpen(self, file):
9623 """Writes the code for the namespace."""
9624 file.Write("namespace gpu {\n")
9625 file.Write("namespace gles2 {\n")
9626 file.Write("\n")
9628 def WriteNamespaceClose(self, file):
9629 """Writes the code to close the namespace."""
9630 file.Write("} // namespace gles2\n")
9631 file.Write("} // namespace gpu\n")
9632 file.Write("\n")
9634 def ParseGLH(self, filename):
9635 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9636 f = open(filename, "r")
9637 functions = f.read()
9638 f.close()
9639 for line in functions.splitlines():
9640 match = self._function_re.match(line)
9641 if match:
9642 func_name = match.group(2)[2:]
9643 func_info = self.GetFunctionInfo(func_name)
9644 if func_info['type'] == 'Noop':
9645 continue
9647 parsed_func_info = {
9648 'original_name': func_name,
9649 'original_args': match.group(3),
9650 'return_type': match.group(1).strip(),
9653 for k in parsed_func_info.keys():
9654 if not k in func_info:
9655 func_info[k] = parsed_func_info[k]
9657 f = Function(func_name, func_info)
9658 self.original_functions.append(f)
9660 #for arg in f.GetOriginalArgs():
9661 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9662 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9664 gen_cmd = f.GetInfo('gen_cmd')
9665 if gen_cmd == True or gen_cmd == None:
9666 if f.type_handler.NeedsDataTransferFunction(f):
9667 methods = f.GetDataTransferMethods()
9668 if 'immediate' in methods:
9669 self.AddFunction(ImmediateFunction(f))
9670 if 'bucket' in methods:
9671 self.AddFunction(BucketFunction(f))
9672 if 'shm' in methods:
9673 self.AddFunction(f)
9674 else:
9675 self.AddFunction(f)
9677 self.Log("Auto Generated Functions : %d" %
9678 len([f for f in self.functions if f.can_auto_generate or
9679 (not f.IsType('') and not f.IsType('Custom') and
9680 not f.IsType('Todo'))]))
9682 funcs = [f for f in self.functions if not f.can_auto_generate and
9683 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9684 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9686 for f in funcs:
9687 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9689 def WriteCommandIds(self, filename):
9690 """Writes the command buffer format"""
9691 file = CHeaderWriter(filename)
9692 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9693 id = 256
9694 for func in self.functions:
9695 file.Write(" %-60s /* %d */ \\\n" %
9696 ("OP(%s)" % func.name, id))
9697 id += 1
9698 file.Write("\n")
9700 file.Write("enum CommandId {\n")
9701 file.Write(" kStartPoint = cmd::kLastCommonId, "
9702 "// All GLES2 commands start after this.\n")
9703 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9704 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9705 file.Write("#undef GLES2_CMD_OP\n")
9706 file.Write(" kNumCommands\n")
9707 file.Write("};\n")
9708 file.Write("\n")
9709 file.Close()
9710 self.generated_cpp_filenames.append(file.filename)
9712 def WriteFormat(self, filename):
9713 """Writes the command buffer format"""
9714 file = CHeaderWriter(filename)
9715 # Forward declaration of a few enums used in constant argument
9716 # to avoid including GL header files.
9717 enum_defines = {
9718 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9719 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9721 file.Write('\n')
9722 for enum in enum_defines:
9723 file.Write("#define %s %s\n" % (enum, enum_defines[enum]))
9724 file.Write('\n')
9725 for func in self.functions:
9726 if True:
9727 #gen_cmd = func.GetInfo('gen_cmd')
9728 #if gen_cmd == True or gen_cmd == None:
9729 func.WriteStruct(file)
9730 file.Write("\n")
9731 file.Close()
9732 self.generated_cpp_filenames.append(file.filename)
9734 def WriteDocs(self, filename):
9735 """Writes the command buffer doc version of the commands"""
9736 file = CWriter(filename)
9737 for func in self.functions:
9738 if True:
9739 #gen_cmd = func.GetInfo('gen_cmd')
9740 #if gen_cmd == True or gen_cmd == None:
9741 func.WriteDocs(file)
9742 file.Write("\n")
9743 file.Close()
9744 self.generated_cpp_filenames.append(file.filename)
9746 def WriteFormatTest(self, filename):
9747 """Writes the command buffer format test."""
9748 file = CHeaderWriter(
9749 filename,
9750 "// This file contains unit tests for gles2 commmands\n"
9751 "// It is included by gles2_cmd_format_test.cc\n"
9752 "\n")
9754 for func in self.functions:
9755 if True:
9756 #gen_cmd = func.GetInfo('gen_cmd')
9757 #if gen_cmd == True or gen_cmd == None:
9758 func.WriteFormatTest(file)
9760 file.Close()
9761 self.generated_cpp_filenames.append(file.filename)
9763 def WriteCmdHelperHeader(self, filename):
9764 """Writes the gles2 command helper."""
9765 file = CHeaderWriter(filename)
9767 for func in self.functions:
9768 if True:
9769 #gen_cmd = func.GetInfo('gen_cmd')
9770 #if gen_cmd == True or gen_cmd == None:
9771 func.WriteCmdHelper(file)
9773 file.Close()
9774 self.generated_cpp_filenames.append(file.filename)
9776 def WriteServiceContextStateHeader(self, filename):
9777 """Writes the service context state header."""
9778 file = CHeaderWriter(
9779 filename,
9780 "// It is included by context_state.h\n")
9781 file.Write("struct EnableFlags {\n")
9782 file.Write(" EnableFlags();\n")
9783 for capability in _CAPABILITY_FLAGS:
9784 file.Write(" bool %s;\n" % capability['name'])
9785 file.Write(" bool cached_%s;\n" % capability['name'])
9786 file.Write("};\n\n")
9788 for state_name in sorted(_STATES.keys()):
9789 state = _STATES[state_name]
9790 for item in state['states']:
9791 if isinstance(item['default'], list):
9792 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
9793 len(item['default'])))
9794 else:
9795 file.Write("%s %s;\n" % (item['type'], item['name']))
9797 if item.get('cached', False):
9798 if isinstance(item['default'], list):
9799 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9800 len(item['default'])))
9801 else:
9802 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
9804 file.Write("\n")
9806 file.Write("""
9807 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9808 switch (cap) {
9809 """)
9810 for capability in _CAPABILITY_FLAGS:
9811 file.Write("""\
9812 case GL_%s:
9813 """ % capability['name'].upper())
9814 file.Write("""\
9815 if (enable_flags.cached_%(name)s == enable &&
9816 !ignore_cached_state)
9817 return;
9818 enable_flags.cached_%(name)s = enable;
9819 break;
9820 """ % capability)
9822 file.Write("""\
9823 default:
9824 NOTREACHED();
9825 return;
9827 if (enable)
9828 glEnable(cap);
9829 else
9830 glDisable(cap);
9832 """)
9834 file.Close()
9835 self.generated_cpp_filenames.append(file.filename)
9837 def WriteClientContextStateHeader(self, filename):
9838 """Writes the client context state header."""
9839 file = CHeaderWriter(
9840 filename,
9841 "// It is included by client_context_state.h\n")
9842 file.Write("struct EnableFlags {\n")
9843 file.Write(" EnableFlags();\n")
9844 for capability in _CAPABILITY_FLAGS:
9845 file.Write(" bool %s;\n" % capability['name'])
9846 file.Write("};\n\n")
9848 file.Close()
9849 self.generated_cpp_filenames.append(file.filename)
9851 def WriteContextStateGetters(self, file, class_name):
9852 """Writes the state getters."""
9853 for gl_type in ["GLint", "GLfloat"]:
9854 file.Write("""
9855 bool %s::GetStateAs%s(
9856 GLenum pname, %s* params, GLsizei* num_written) const {
9857 switch (pname) {
9858 """ % (class_name, gl_type, gl_type))
9859 for state_name in sorted(_STATES.keys()):
9860 state = _STATES[state_name]
9861 if 'enum' in state:
9862 file.Write(" case %s:\n" % state['enum'])
9863 file.Write(" *num_written = %d;\n" % len(state['states']))
9864 file.Write(" if (params) {\n")
9865 for ndx,item in enumerate(state['states']):
9866 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9867 (ndx, gl_type, item['name']))
9868 file.Write(" }\n")
9869 file.Write(" return true;\n")
9870 else:
9871 for item in state['states']:
9872 file.Write(" case %s:\n" % item['enum'])
9873 if isinstance(item['default'], list):
9874 item_len = len(item['default'])
9875 file.Write(" *num_written = %d;\n" % item_len)
9876 file.Write(" if (params) {\n")
9877 if item['type'] == gl_type:
9878 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9879 (item['name'], item['type'], item_len))
9880 else:
9881 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9882 item_len)
9883 file.Write(" params[i] = %s;\n" %
9884 (GetGLGetTypeConversion(gl_type, item['type'],
9885 "%s[i]" % item['name'])))
9886 file.Write(" }\n");
9887 else:
9888 file.Write(" *num_written = 1;\n")
9889 file.Write(" if (params) {\n")
9890 file.Write(" params[0] = %s;\n" %
9891 (GetGLGetTypeConversion(gl_type, item['type'],
9892 item['name'])))
9893 file.Write(" }\n")
9894 file.Write(" return true;\n")
9895 for capability in _CAPABILITY_FLAGS:
9896 file.Write(" case GL_%s:\n" % capability['name'].upper())
9897 file.Write(" *num_written = 1;\n")
9898 file.Write(" if (params) {\n")
9899 file.Write(
9900 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9901 (gl_type, capability['name']))
9902 file.Write(" }\n")
9903 file.Write(" return true;\n")
9904 file.Write(""" default:
9905 return false;
9908 """)
9910 def WriteServiceContextStateImpl(self, filename):
9911 """Writes the context state service implementation."""
9912 file = CHeaderWriter(
9913 filename,
9914 "// It is included by context_state.cc\n")
9915 code = []
9916 for capability in _CAPABILITY_FLAGS:
9917 code.append("%s(%s)" %
9918 (capability['name'],
9919 ('false', 'true')['default' in capability]))
9920 code.append("cached_%s(%s)" %
9921 (capability['name'],
9922 ('false', 'true')['default' in capability]))
9923 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9924 ",\n ".join(code))
9925 file.Write("\n")
9927 file.Write("void ContextState::Initialize() {\n")
9928 for state_name in sorted(_STATES.keys()):
9929 state = _STATES[state_name]
9930 for item in state['states']:
9931 if isinstance(item['default'], list):
9932 for ndx, value in enumerate(item['default']):
9933 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
9934 else:
9935 file.Write(" %s = %s;\n" % (item['name'], item['default']))
9936 if item.get('cached', False):
9937 if isinstance(item['default'], list):
9938 for ndx, value in enumerate(item['default']):
9939 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
9940 else:
9941 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
9942 file.Write("}\n")
9944 file.Write("""
9945 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9946 """)
9947 def WriteCapabilities(test_prev, es3_caps):
9948 for capability in _CAPABILITY_FLAGS:
9949 capability_name = capability['name']
9950 capability_es3 = 'es3' in capability and capability['es3'] == True
9951 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
9952 continue
9953 if test_prev:
9954 file.Write(""" if (prev_state->enable_flags.cached_%s !=
9955 enable_flags.cached_%s) {\n""" %
9956 (capability_name, capability_name))
9957 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
9958 (capability_name.upper(), capability_name))
9959 if test_prev:
9960 file.Write(" }")
9962 file.Write(" if (prev_state) {")
9963 WriteCapabilities(True, False)
9964 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9965 WriteCapabilities(True, True)
9966 file.Write(" }\n")
9967 file.Write(" } else {")
9968 WriteCapabilities(False, False)
9969 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9970 WriteCapabilities(False, True)
9971 file.Write(" }\n")
9972 file.Write(" }")
9974 file.Write("""}
9976 void ContextState::InitState(const ContextState *prev_state) const {
9977 """)
9979 def WriteStates(test_prev):
9980 # We need to sort the keys so the expectations match
9981 for state_name in sorted(_STATES.keys()):
9982 state = _STATES[state_name]
9983 if state['type'] == 'FrontBack':
9984 num_states = len(state['states'])
9985 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9986 if test_prev:
9987 file.Write(" if (")
9988 args = []
9989 for place, item in enumerate(group):
9990 item_name = CachedStateName(item)
9991 args.append('%s' % item_name)
9992 if test_prev:
9993 if place > 0:
9994 file.Write(' ||\n')
9995 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
9996 if test_prev:
9997 file.Write(")\n")
9998 file.Write(
9999 " gl%s(%s, %s);\n" %
10000 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10001 elif state['type'] == 'NamedParameter':
10002 for item in state['states']:
10003 item_name = CachedStateName(item)
10005 if 'extension_flag' in item:
10006 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
10007 item['extension_flag'])
10008 if test_prev:
10009 if isinstance(item['default'], list):
10010 file.Write(" if (memcmp(prev_state->%s, %s, "
10011 "sizeof(%s) * %d)) {\n" %
10012 (item_name, item_name, item['type'],
10013 len(item['default'])))
10014 else:
10015 file.Write(" if (prev_state->%s != %s) {\n " %
10016 (item_name, item_name))
10017 if 'gl_version_flag' in item:
10018 item_name = item['gl_version_flag']
10019 inverted = ''
10020 if item_name[0] == '!':
10021 inverted = '!'
10022 item_name = item_name[1:]
10023 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10024 (inverted, item_name))
10025 file.Write(" gl%s(%s, %s);\n" %
10026 (state['func'],
10027 (item['enum_set']
10028 if 'enum_set' in item else item['enum']),
10029 item['name']))
10030 if 'gl_version_flag' in item:
10031 file.Write(" }\n")
10032 if test_prev:
10033 if 'extension_flag' in item:
10034 file.Write(" ")
10035 file.Write(" }")
10036 if 'extension_flag' in item:
10037 file.Write(" }")
10038 else:
10039 if 'extension_flag' in state:
10040 file.Write(" if (feature_info_->feature_flags().%s)\n " %
10041 state['extension_flag'])
10042 if test_prev:
10043 file.Write(" if (")
10044 args = []
10045 for place, item in enumerate(state['states']):
10046 item_name = CachedStateName(item)
10047 args.append('%s' % item_name)
10048 if test_prev:
10049 if place > 0:
10050 file.Write(' ||\n')
10051 file.Write("(%s != prev_state->%s)" %
10052 (item_name, item_name))
10053 if test_prev:
10054 file.Write(" )\n")
10055 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
10057 file.Write(" if (prev_state) {")
10058 WriteStates(True)
10059 file.Write(" } else {")
10060 WriteStates(False)
10061 file.Write(" }")
10062 file.Write("}\n")
10064 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
10065 switch (cap) {
10066 """)
10067 for capability in _CAPABILITY_FLAGS:
10068 file.Write(" case GL_%s:\n" % capability['name'].upper())
10069 file.Write(" return enable_flags.%s;\n" % capability['name'])
10070 file.Write(""" default:
10071 NOTREACHED();
10072 return false;
10075 """)
10077 self.WriteContextStateGetters(file, "ContextState")
10078 file.Close()
10079 self.generated_cpp_filenames.append(file.filename)
10081 def WriteClientContextStateImpl(self, filename):
10082 """Writes the context state client side implementation."""
10083 file = CHeaderWriter(
10084 filename,
10085 "// It is included by client_context_state.cc\n")
10086 code = []
10087 for capability in _CAPABILITY_FLAGS:
10088 code.append("%s(%s)" %
10089 (capability['name'],
10090 ('false', 'true')['default' in capability]))
10091 file.Write(
10092 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10093 ",\n ".join(code))
10094 file.Write("\n")
10096 file.Write("""
10097 bool ClientContextState::SetCapabilityState(
10098 GLenum cap, bool enabled, bool* changed) {
10099 *changed = false;
10100 switch (cap) {
10101 """)
10102 for capability in _CAPABILITY_FLAGS:
10103 file.Write(" case GL_%s:\n" % capability['name'].upper())
10104 file.Write(""" if (enable_flags.%(name)s != enabled) {
10105 *changed = true;
10106 enable_flags.%(name)s = enabled;
10108 return true;
10109 """ % capability)
10110 file.Write(""" default:
10111 return false;
10114 """)
10115 file.Write("""bool ClientContextState::GetEnabled(
10116 GLenum cap, bool* enabled) const {
10117 switch (cap) {
10118 """)
10119 for capability in _CAPABILITY_FLAGS:
10120 file.Write(" case GL_%s:\n" % capability['name'].upper())
10121 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
10122 file.Write(" return true;\n")
10123 file.Write(""" default:
10124 return false;
10127 """)
10128 file.Close()
10129 self.generated_cpp_filenames.append(file.filename)
10131 def WriteServiceImplementation(self, filename):
10132 """Writes the service decorder implementation."""
10133 file = CHeaderWriter(
10134 filename,
10135 "// It is included by gles2_cmd_decoder.cc\n")
10137 for func in self.functions:
10138 if True:
10139 #gen_cmd = func.GetInfo('gen_cmd')
10140 #if gen_cmd == True or gen_cmd == None:
10141 func.WriteServiceImplementation(file)
10143 file.Write("""
10144 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10145 switch (cap) {
10146 """)
10147 for capability in _CAPABILITY_FLAGS:
10148 file.Write(" case GL_%s:\n" % capability['name'].upper())
10149 if 'state_flag' in capability:
10151 file.Write("""\
10152 state_.enable_flags.%(name)s = enabled;
10153 if (state_.enable_flags.cached_%(name)s != enabled
10154 || state_.ignore_cached_state) {
10155 %(state_flag)s = true;
10157 return false;
10158 """ % capability)
10159 else:
10160 file.Write("""\
10161 state_.enable_flags.%(name)s = enabled;
10162 if (state_.enable_flags.cached_%(name)s != enabled
10163 || state_.ignore_cached_state) {
10164 state_.enable_flags.cached_%(name)s = enabled;
10165 return true;
10167 return false;
10168 """ % capability)
10169 file.Write(""" default:
10170 NOTREACHED();
10171 return false;
10174 """)
10175 file.Close()
10176 self.generated_cpp_filenames.append(file.filename)
10178 def WriteServiceUnitTests(self, filename):
10179 """Writes the service decorder unit tests."""
10180 num_tests = len(self.functions)
10181 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
10182 count = 0
10183 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
10184 count += 1
10185 name = filename % count
10186 file = CHeaderWriter(
10187 name,
10188 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
10189 test_name = 'GLES2DecoderTest%d' % count
10190 end = test_num + FUNCTIONS_PER_FILE
10191 if end > num_tests:
10192 end = num_tests
10193 for idx in range(test_num, end):
10194 func = self.functions[idx]
10196 # Do any filtering of the functions here, so that the functions
10197 # will not move between the numbered files if filtering properties
10198 # are changed.
10199 if func.GetInfo('extension_flag'):
10200 continue
10202 if True:
10203 #gen_cmd = func.GetInfo('gen_cmd')
10204 #if gen_cmd == True or gen_cmd == None:
10205 if func.GetInfo('unit_test') == False:
10206 file.Write("// TODO(gman): %s\n" % func.name)
10207 else:
10208 func.WriteServiceUnitTest(file, {
10209 'test_name': test_name
10211 file.Close()
10212 self.generated_cpp_filenames.append(file.filename)
10213 file = CHeaderWriter(
10214 filename % 0,
10215 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
10216 file.Write(
10217 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10218 bool es3_capable) {""")
10219 for capability in _CAPABILITY_FLAGS:
10220 capability_es3 = 'es3' in capability and capability['es3'] == True
10221 if not capability_es3:
10222 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10223 (capability['name'].upper(),
10224 ('false', 'true')['default' in capability]))
10226 file.Write(" if (es3_capable) {")
10227 for capability in _CAPABILITY_FLAGS:
10228 capability_es3 = 'es3' in capability and capability['es3'] == True
10229 if capability_es3:
10230 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10231 (capability['name'].upper(),
10232 ('false', 'true')['default' in capability]))
10233 file.Write(""" }
10236 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10237 """)
10239 # We need to sort the keys so the expectations match
10240 for state_name in sorted(_STATES.keys()):
10241 state = _STATES[state_name]
10242 if state['type'] == 'FrontBack':
10243 num_states = len(state['states'])
10244 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10245 args = []
10246 for item in group:
10247 if 'expected' in item:
10248 args.append(item['expected'])
10249 else:
10250 args.append(item['default'])
10251 file.Write(
10252 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10253 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10254 file.Write(" .Times(1)\n")
10255 file.Write(" .RetiresOnSaturation();\n")
10256 elif state['type'] == 'NamedParameter':
10257 for item in state['states']:
10258 if 'extension_flag' in item:
10259 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10260 item['extension_flag'])
10261 file.Write(" ")
10262 expect_value = item['default']
10263 if isinstance(expect_value, list):
10264 # TODO: Currently we do not check array values.
10265 expect_value = "_"
10267 file.Write(
10268 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10269 (state['func'],
10270 (item['enum_set']
10271 if 'enum_set' in item else item['enum']),
10272 expect_value))
10273 file.Write(" .Times(1)\n")
10274 file.Write(" .RetiresOnSaturation();\n")
10275 if 'extension_flag' in item:
10276 file.Write(" }\n")
10277 else:
10278 if 'extension_flag' in state:
10279 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10280 state['extension_flag'])
10281 file.Write(" ")
10282 args = []
10283 for item in state['states']:
10284 if 'expected' in item:
10285 args.append(item['expected'])
10286 else:
10287 args.append(item['default'])
10288 # TODO: Currently we do not check array values.
10289 args = ["_" if isinstance(arg, list) else arg for arg in args]
10290 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10291 (state['func'], ", ".join(args)))
10292 file.Write(" .Times(1)\n")
10293 file.Write(" .RetiresOnSaturation();\n")
10294 if 'extension_flag' in state:
10295 file.Write(" }\n")
10296 file.Write("""}
10297 """)
10298 file.Close()
10299 self.generated_cpp_filenames.append(file.filename)
10301 def WriteServiceUnitTestsForExtensions(self, filename):
10302 """Writes the service decorder unit tests for functions with extension_flag.
10304 The functions are special in that they need a specific unit test
10305 baseclass to turn on the extension.
10307 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
10308 file = CHeaderWriter(
10309 filename,
10310 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
10311 for func in functions:
10312 if True:
10313 if func.GetInfo('unit_test') == False:
10314 file.Write("// TODO(gman): %s\n" % func.name)
10315 else:
10316 extension = ToCamelCase(
10317 ToGLExtensionString(func.GetInfo('extension_flag')))
10318 func.WriteServiceUnitTest(file, {
10319 'test_name': 'GLES2DecoderTestWith%s' % extension
10322 file.Close()
10323 self.generated_cpp_filenames.append(file.filename)
10325 def WriteGLES2Header(self, filename):
10326 """Writes the GLES2 header."""
10327 file = CHeaderWriter(
10328 filename,
10329 "// This file contains Chromium-specific GLES2 declarations.\n\n")
10331 for func in self.original_functions:
10332 func.WriteGLES2Header(file)
10334 file.Write("\n")
10335 file.Close()
10336 self.generated_cpp_filenames.append(file.filename)
10338 def WriteGLES2CLibImplementation(self, filename):
10339 """Writes the GLES2 c lib implementation."""
10340 file = CHeaderWriter(
10341 filename,
10342 "// These functions emulate GLES2 over command buffers.\n")
10344 for func in self.original_functions:
10345 func.WriteGLES2CLibImplementation(file)
10347 file.Write("""
10348 namespace gles2 {
10350 extern const NameToFunc g_gles2_function_table[] = {
10351 """)
10352 for func in self.original_functions:
10353 file.Write(
10354 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10355 (func.name, func.name))
10356 file.Write(""" { NULL, NULL, },
10359 } // namespace gles2
10360 """)
10361 file.Close()
10362 self.generated_cpp_filenames.append(file.filename)
10364 def WriteGLES2InterfaceHeader(self, filename):
10365 """Writes the GLES2 interface header."""
10366 file = CHeaderWriter(
10367 filename,
10368 "// This file is included by gles2_interface.h to declare the\n"
10369 "// GL api functions.\n")
10370 for func in self.original_functions:
10371 func.WriteGLES2InterfaceHeader(file)
10372 file.Close()
10373 self.generated_cpp_filenames.append(file.filename)
10375 def WriteMojoGLES2ImplHeader(self, filename):
10376 """Writes the Mojo GLES2 implementation header."""
10377 file = CHeaderWriter(
10378 filename,
10379 "// This file is included by gles2_interface.h to declare the\n"
10380 "// GL api functions.\n")
10382 code = """
10383 #include "gpu/command_buffer/client/gles2_interface.h"
10384 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10386 namespace mojo {
10388 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10389 public:
10390 explicit MojoGLES2Impl(MojoGLES2Context context) {
10391 context_ = context;
10393 ~MojoGLES2Impl() override {}
10395 file.Write(code);
10396 for func in self.original_functions:
10397 func.WriteMojoGLES2ImplHeader(file)
10398 code = """
10399 private:
10400 MojoGLES2Context context_;
10403 } // namespace mojo
10405 file.Write(code);
10406 file.Close()
10407 self.generated_cpp_filenames.append(file.filename)
10409 def WriteMojoGLES2Impl(self, filename):
10410 """Writes the Mojo GLES2 implementation."""
10411 file = CWriter(filename)
10412 file.Write(_LICENSE)
10413 file.Write(_DO_NOT_EDIT_WARNING)
10415 code = """
10416 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10418 #include "base/logging.h"
10419 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10420 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10421 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10422 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10423 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10424 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10426 namespace mojo {
10429 file.Write(code);
10430 for func in self.original_functions:
10431 func.WriteMojoGLES2Impl(file)
10432 code = """
10434 } // namespace mojo
10436 file.Write(code);
10437 file.Close()
10438 self.generated_cpp_filenames.append(file.filename)
10440 def WriteGLES2InterfaceStub(self, filename):
10441 """Writes the GLES2 interface stub header."""
10442 file = CHeaderWriter(
10443 filename,
10444 "// This file is included by gles2_interface_stub.h.\n")
10445 for func in self.original_functions:
10446 func.WriteGLES2InterfaceStub(file)
10447 file.Close()
10448 self.generated_cpp_filenames.append(file.filename)
10450 def WriteGLES2InterfaceStubImpl(self, filename):
10451 """Writes the GLES2 interface header."""
10452 file = CHeaderWriter(
10453 filename,
10454 "// This file is included by gles2_interface_stub.cc.\n")
10455 for func in self.original_functions:
10456 func.WriteGLES2InterfaceStubImpl(file)
10457 file.Close()
10458 self.generated_cpp_filenames.append(file.filename)
10460 def WriteGLES2ImplementationHeader(self, filename):
10461 """Writes the GLES2 Implementation header."""
10462 file = CHeaderWriter(
10463 filename,
10464 "// This file is included by gles2_implementation.h to declare the\n"
10465 "// GL api functions.\n")
10466 for func in self.original_functions:
10467 func.WriteGLES2ImplementationHeader(file)
10468 file.Close()
10469 self.generated_cpp_filenames.append(file.filename)
10471 def WriteGLES2Implementation(self, filename):
10472 """Writes the GLES2 Implementation."""
10473 file = CHeaderWriter(
10474 filename,
10475 "// This file is included by gles2_implementation.cc to define the\n"
10476 "// GL api functions.\n")
10477 for func in self.original_functions:
10478 func.WriteGLES2Implementation(file)
10479 file.Close()
10480 self.generated_cpp_filenames.append(file.filename)
10482 def WriteGLES2TraceImplementationHeader(self, filename):
10483 """Writes the GLES2 Trace Implementation header."""
10484 file = CHeaderWriter(
10485 filename,
10486 "// This file is included by gles2_trace_implementation.h\n")
10487 for func in self.original_functions:
10488 func.WriteGLES2TraceImplementationHeader(file)
10489 file.Close()
10490 self.generated_cpp_filenames.append(file.filename)
10492 def WriteGLES2TraceImplementation(self, filename):
10493 """Writes the GLES2 Trace Implementation."""
10494 file = CHeaderWriter(
10495 filename,
10496 "// This file is included by gles2_trace_implementation.cc\n")
10497 for func in self.original_functions:
10498 func.WriteGLES2TraceImplementation(file)
10499 file.Close()
10500 self.generated_cpp_filenames.append(file.filename)
10502 def WriteGLES2ImplementationUnitTests(self, filename):
10503 """Writes the GLES2 helper header."""
10504 file = CHeaderWriter(
10505 filename,
10506 "// This file is included by gles2_implementation.h to declare the\n"
10507 "// GL api functions.\n")
10508 for func in self.original_functions:
10509 func.WriteGLES2ImplementationUnitTest(file)
10510 file.Close()
10511 self.generated_cpp_filenames.append(file.filename)
10513 def WriteServiceUtilsHeader(self, filename):
10514 """Writes the gles2 auto generated utility header."""
10515 file = CHeaderWriter(filename)
10516 for name in sorted(_NAMED_TYPE_INFO.keys()):
10517 named_type = NamedType(_NAMED_TYPE_INFO[name])
10518 if named_type.IsConstant():
10519 continue
10520 file.Write("ValueValidator<%s> %s;\n" %
10521 (named_type.GetType(), ToUnderscore(name)))
10522 file.Write("\n")
10523 file.Close()
10524 self.generated_cpp_filenames.append(file.filename)
10526 def WriteServiceUtilsImplementation(self, filename):
10527 """Writes the gles2 auto generated utility implementation."""
10528 file = CHeaderWriter(filename)
10529 names = sorted(_NAMED_TYPE_INFO.keys())
10530 for name in names:
10531 named_type = NamedType(_NAMED_TYPE_INFO[name])
10532 if named_type.IsConstant():
10533 continue
10534 if named_type.GetValidValues():
10535 file.Write("static const %s valid_%s_table[] = {\n" %
10536 (named_type.GetType(), ToUnderscore(name)))
10537 for value in named_type.GetValidValues():
10538 file.Write(" %s,\n" % value)
10539 file.Write("};\n")
10540 file.Write("\n")
10541 if named_type.GetValidValuesES3():
10542 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10543 (named_type.GetType(), ToUnderscore(name)))
10544 for value in named_type.GetValidValuesES3():
10545 file.Write(" %s,\n" % value)
10546 file.Write("};\n")
10547 file.Write("\n")
10548 if named_type.GetDeprecatedValuesES3():
10549 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10550 (named_type.GetType(), ToUnderscore(name)))
10551 for value in named_type.GetDeprecatedValuesES3():
10552 file.Write(" %s,\n" % value)
10553 file.Write("};\n")
10554 file.Write("\n")
10555 file.Write("Validators::Validators()")
10556 pre = ' : '
10557 for count, name in enumerate(names):
10558 named_type = NamedType(_NAMED_TYPE_INFO[name])
10559 if named_type.IsConstant():
10560 continue
10561 if named_type.GetValidValues():
10562 code = """%(pre)s%(name)s(
10563 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10564 else:
10565 code = "%(pre)s%(name)s()"
10566 file.Write(code % {
10567 'name': ToUnderscore(name),
10568 'pre': pre,
10570 pre = ',\n '
10571 file.Write(" {\n");
10572 file.Write("}\n\n");
10574 file.Write("void Validators::UpdateValuesES3() {\n")
10575 for name in names:
10576 named_type = NamedType(_NAMED_TYPE_INFO[name])
10577 if named_type.GetDeprecatedValuesES3():
10578 code = """ %(name)s.RemoveValues(
10579 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10581 file.Write(code % {
10582 'name': ToUnderscore(name),
10584 if named_type.GetValidValuesES3():
10585 code = """ %(name)s.AddValues(
10586 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10588 file.Write(code % {
10589 'name': ToUnderscore(name),
10591 file.Write("}\n\n");
10592 file.Close()
10593 self.generated_cpp_filenames.append(file.filename)
10595 def WriteCommonUtilsHeader(self, filename):
10596 """Writes the gles2 common utility header."""
10597 file = CHeaderWriter(filename)
10598 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10599 for type_info in type_infos:
10600 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10601 file.Write("static std::string GetString%s(uint32_t value);\n" %
10602 type_info)
10603 file.Write("\n")
10604 file.Close()
10605 self.generated_cpp_filenames.append(file.filename)
10607 def WriteCommonUtilsImpl(self, filename):
10608 """Writes the gles2 common utility header."""
10609 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10610 dict = {}
10611 for fname in ['third_party/khronos/GLES2/gl2.h',
10612 'third_party/khronos/GLES2/gl2ext.h',
10613 'third_party/khronos/GLES3/gl3.h',
10614 'gpu/GLES2/gl2chromium.h',
10615 'gpu/GLES2/gl2extchromium.h']:
10616 lines = open(fname).readlines()
10617 for line in lines:
10618 m = enum_re.match(line)
10619 if m:
10620 name = m.group(1)
10621 value = m.group(2)
10622 if len(value) <= 10:
10623 if not value in dict:
10624 dict[value] = name
10625 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10626 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10627 dict[value].endswith('_CHROMIUM')):
10628 self.Error("code collision: %s and %s have the same code %s" %
10629 (dict[value], name, value))
10631 file = CHeaderWriter(filename)
10632 file.Write("static const GLES2Util::EnumToString "
10633 "enum_to_string_table[] = {\n")
10634 for value in dict:
10635 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
10636 file.Write("""};
10638 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10639 enum_to_string_table;
10640 const size_t GLES2Util::enum_to_string_table_len_ =
10641 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10643 """)
10645 enums = sorted(_NAMED_TYPE_INFO.keys())
10646 for enum in enums:
10647 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10648 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10649 enum)
10650 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10651 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10652 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10653 assert len(valid_list) == len(set(valid_list))
10654 if len(valid_list) > 0:
10655 file.Write(" static const EnumToString string_table[] = {\n")
10656 for value in valid_list:
10657 file.Write(' { %s, "%s" },\n' % (value, value))
10658 file.Write(""" };
10659 return GLES2Util::GetQualifiedEnumString(
10660 string_table, arraysize(string_table), value);
10663 """)
10664 else:
10665 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10666 NULL, 0, value);
10669 """)
10670 file.Close()
10671 self.generated_cpp_filenames.append(file.filename)
10673 def WritePepperGLES2Interface(self, filename, dev):
10674 """Writes the Pepper OpenGLES interface definition."""
10675 file = CWriter(filename)
10676 file.Write(_LICENSE)
10677 file.Write(_DO_NOT_EDIT_WARNING)
10679 file.Write("label Chrome {\n")
10680 file.Write(" M39 = 1.0\n")
10681 file.Write("};\n\n")
10683 if not dev:
10684 # Declare GL types.
10685 file.Write("[version=1.0]\n")
10686 file.Write("describe {\n")
10687 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10688 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10689 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10690 'GLubyte', 'GLuint', 'GLushort']:
10691 file.Write(" %s;\n" % gltype)
10692 file.Write(" %s_ptr_t;\n" % gltype)
10693 file.Write("};\n\n")
10695 # C level typedefs.
10696 file.Write("#inline c\n")
10697 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10698 if dev:
10699 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10700 else:
10701 file.Write("\n#ifndef __gl2_h_\n")
10702 for (k, v) in _GL_TYPES.iteritems():
10703 file.Write("typedef %s %s;\n" % (v, k))
10704 file.Write("#ifdef _WIN64\n")
10705 for (k, v) in _GL_TYPES_64.iteritems():
10706 file.Write("typedef %s %s;\n" % (v, k))
10707 file.Write("#else\n")
10708 for (k, v) in _GL_TYPES_32.iteritems():
10709 file.Write("typedef %s %s;\n" % (v, k))
10710 file.Write("#endif // _WIN64\n")
10711 file.Write("#endif // __gl2_h_\n\n")
10712 file.Write("#endinl\n")
10714 for interface in self.pepper_interfaces:
10715 if interface.dev != dev:
10716 continue
10717 # Historically, we provide OpenGLES2 interfaces with struct
10718 # namespace. Not to break code which uses the interface as
10719 # "struct OpenGLES2", we put it in struct namespace.
10720 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10721 interface.GetInterfaceName())
10722 file.Write("interface %s {\n" % interface.GetStructName())
10723 for func in self.original_functions:
10724 if not func.InPepperInterface(interface):
10725 continue
10727 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10728 is_for_return_type=True)
10729 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10730 file.Write(func_prefix)
10731 file.Write("[in] PP_Resource context")
10732 for arg in func.MakeTypedPepperIdlArgStrings():
10733 file.Write(",\n" + " " * len(func_prefix) + arg)
10734 file.Write(");\n")
10735 file.Write("};\n\n")
10738 file.Close()
10740 def WritePepperGLES2Implementation(self, filename):
10741 """Writes the Pepper OpenGLES interface implementation."""
10743 file = CWriter(filename)
10744 file.Write(_LICENSE)
10745 file.Write(_DO_NOT_EDIT_WARNING)
10747 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10748 file.Write("#include \"base/logging.h\"\n")
10749 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10750 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10751 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10753 file.Write("namespace ppapi {\n\n")
10754 file.Write("namespace {\n\n")
10756 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10757 " Enter3D;\n\n")
10759 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10760 " enter) {\n")
10761 file.Write(" DCHECK(enter);\n")
10762 file.Write(" DCHECK(enter->succeeded());\n")
10763 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10764 "gles2_impl();\n");
10765 file.Write("}\n\n");
10767 for func in self.original_functions:
10768 if not func.InAnyPepperExtension():
10769 continue
10771 original_arg = func.MakeTypedPepperArgString("")
10772 context_arg = "PP_Resource context_id"
10773 if len(original_arg):
10774 arg = context_arg + ", " + original_arg
10775 else:
10776 arg = context_arg
10777 file.Write("%s %s(%s) {\n" %
10778 (func.return_type, func.GetPepperName(), arg))
10779 file.Write(" Enter3D enter(context_id, true);\n")
10780 file.Write(" if (enter.succeeded()) {\n")
10782 return_str = "" if func.return_type == "void" else "return "
10783 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10784 (return_str, func.original_name,
10785 func.MakeOriginalArgString("")))
10786 file.Write(" }")
10787 if func.return_type == "void":
10788 file.Write("\n")
10789 else:
10790 file.Write(" else {\n")
10791 file.Write(" return %s;\n" % func.GetErrorReturnString())
10792 file.Write(" }\n")
10793 file.Write("}\n\n")
10795 file.Write("} // namespace\n")
10797 for interface in self.pepper_interfaces:
10798 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10799 (interface.GetStructName(), interface.GetName()))
10800 file.Write(" static const struct %s "
10801 "ppb_opengles2 = {\n" % interface.GetStructName())
10802 file.Write(" &")
10803 file.Write(",\n &".join(
10804 f.GetPepperName() for f in self.original_functions
10805 if f.InPepperInterface(interface)))
10806 file.Write("\n")
10808 file.Write(" };\n")
10809 file.Write(" return &ppb_opengles2;\n")
10810 file.Write("}\n")
10812 file.Write("} // namespace ppapi\n")
10813 file.Close()
10814 self.generated_cpp_filenames.append(file.filename)
10816 def WriteGLES2ToPPAPIBridge(self, filename):
10817 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10819 file = CWriter(filename)
10820 file.Write(_LICENSE)
10821 file.Write(_DO_NOT_EDIT_WARNING)
10823 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10824 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10825 file.Write("#endif\n")
10826 file.Write("#include <GLES2/gl2.h>\n")
10827 file.Write("#include <GLES2/gl2ext.h>\n")
10828 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10830 for func in self.original_functions:
10831 if not func.InAnyPepperExtension():
10832 continue
10834 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10836 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10837 (func.return_type, func.GetPepperName(),
10838 func.MakeTypedPepperArgString("")))
10839 return_str = "" if func.return_type == "void" else "return "
10840 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10841 original_arg = func.MakeOriginalArgString("")
10842 context_arg = "glGetCurrentContextPPAPI()"
10843 if len(original_arg):
10844 arg = context_arg + ", " + original_arg
10845 else:
10846 arg = context_arg
10847 if interface.GetName():
10848 file.Write(" const struct %s* ext = %s;\n" %
10849 (interface.GetStructName(), interface_str))
10850 file.Write(" if (ext)\n")
10851 file.Write(" %sext->%s(%s);\n" %
10852 (return_str, func.GetPepperName(), arg))
10853 if return_str:
10854 file.Write(" %s0;\n" % return_str)
10855 else:
10856 file.Write(" %s%s->%s(%s);\n" %
10857 (return_str, interface_str, func.GetPepperName(), arg))
10858 file.Write("}\n\n")
10859 file.Close()
10860 self.generated_cpp_filenames.append(file.filename)
10862 def WriteMojoGLCallVisitor(self, filename):
10863 """Provides the GL implementation for mojo"""
10864 file = CWriter(filename)
10865 file.Write(_LICENSE)
10866 file.Write(_DO_NOT_EDIT_WARNING)
10868 for func in self.original_functions:
10869 if not func.IsCoreGLFunction():
10870 continue
10871 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10872 (func.name, func.return_type,
10873 func.MakeTypedOriginalArgString(""),
10874 func.MakeOriginalArgString("")))
10876 file.Close()
10877 self.generated_cpp_filenames.append(file.filename)
10879 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10880 """Provides the GL implementation for mojo for a particular extension"""
10881 file = CWriter(filename)
10882 file.Write(_LICENSE)
10883 file.Write(_DO_NOT_EDIT_WARNING)
10885 for func in self.original_functions:
10886 if func.GetInfo("extension") != extension:
10887 continue
10888 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10889 (func.name, func.return_type,
10890 func.MakeTypedOriginalArgString(""),
10891 func.MakeOriginalArgString("")))
10893 file.Close()
10894 self.generated_cpp_filenames.append(file.filename)
10896 def Format(generated_files):
10897 formatter = "clang-format"
10898 if platform.system() == "Windows":
10899 formatter += ".bat"
10900 for filename in generated_files:
10901 call([formatter, "-i", "-style=chromium", filename])
10903 def main(argv):
10904 """This is the main function."""
10905 parser = OptionParser()
10906 parser.add_option(
10907 "--output-dir",
10908 help="base directory for resulting files, under chrome/src. default is "
10909 "empty. Use this if you want the result stored under gen.")
10910 parser.add_option(
10911 "-v", "--verbose", action="store_true",
10912 help="prints more output.")
10914 (options, args) = parser.parse_args(args=argv)
10916 # Add in states and capabilites to GLState
10917 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10918 for state_name in sorted(_STATES.keys()):
10919 state = _STATES[state_name]
10920 if 'extension_flag' in state:
10921 continue
10922 if 'enum' in state:
10923 if not state['enum'] in gl_state_valid:
10924 gl_state_valid.append(state['enum'])
10925 else:
10926 for item in state['states']:
10927 if 'extension_flag' in item:
10928 continue
10929 if not item['enum'] in gl_state_valid:
10930 gl_state_valid.append(item['enum'])
10931 for capability in _CAPABILITY_FLAGS:
10932 valid_value = "GL_%s" % capability['name'].upper()
10933 if not valid_value in gl_state_valid:
10934 gl_state_valid.append(valid_value)
10936 # This script lives under gpu/command_buffer, cd to base directory.
10937 os.chdir(os.path.dirname(__file__) + "/../..")
10938 base_dir = os.getcwd()
10939 gen = GLGenerator(options.verbose)
10940 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10942 # Support generating files under gen/
10943 if options.output_dir != None:
10944 os.chdir(options.output_dir)
10946 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10947 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10948 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10949 gen.WritePepperGLES2Implementation(
10950 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10951 os.chdir(base_dir)
10952 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10953 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10954 gen.WriteFormatTest(
10955 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10956 gen.WriteGLES2InterfaceHeader(
10957 "gpu/command_buffer/client/gles2_interface_autogen.h")
10958 gen.WriteMojoGLES2ImplHeader(
10959 "mojo/gpu/mojo_gles2_impl_autogen.h")
10960 gen.WriteMojoGLES2Impl(
10961 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10962 gen.WriteGLES2InterfaceStub(
10963 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10964 gen.WriteGLES2InterfaceStubImpl(
10965 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10966 gen.WriteGLES2ImplementationHeader(
10967 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10968 gen.WriteGLES2Implementation(
10969 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10970 gen.WriteGLES2ImplementationUnitTests(
10971 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10972 gen.WriteGLES2TraceImplementationHeader(
10973 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10974 gen.WriteGLES2TraceImplementation(
10975 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10976 gen.WriteGLES2CLibImplementation(
10977 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10978 gen.WriteCmdHelperHeader(
10979 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10980 gen.WriteServiceImplementation(
10981 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10982 gen.WriteServiceContextStateHeader(
10983 "gpu/command_buffer/service/context_state_autogen.h")
10984 gen.WriteServiceContextStateImpl(
10985 "gpu/command_buffer/service/context_state_impl_autogen.h")
10986 gen.WriteClientContextStateHeader(
10987 "gpu/command_buffer/client/client_context_state_autogen.h")
10988 gen.WriteClientContextStateImpl(
10989 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10990 gen.WriteServiceUnitTests(
10991 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10992 gen.WriteServiceUnitTestsForExtensions(
10993 "gpu/command_buffer/service/"
10994 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10995 gen.WriteServiceUtilsHeader(
10996 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10997 gen.WriteServiceUtilsImplementation(
10998 "gpu/command_buffer/service/"
10999 "gles2_cmd_validation_implementation_autogen.h")
11000 gen.WriteCommonUtilsHeader(
11001 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11002 gen.WriteCommonUtilsImpl(
11003 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11004 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11005 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
11006 "gles2_call_visitor")
11007 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
11008 gen.WriteMojoGLCallVisitorForExtension(
11009 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
11010 "CHROMIUM_texture_mailbox")
11011 gen.WriteMojoGLCallVisitorForExtension(
11012 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
11013 "CHROMIUM_sync_point")
11014 gen.WriteMojoGLCallVisitorForExtension(
11015 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
11016 "CHROMIUM_sub_image")
11017 gen.WriteMojoGLCallVisitorForExtension(
11018 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
11019 "CHROMIUM_miscellaneous")
11020 gen.WriteMojoGLCallVisitorForExtension(
11021 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
11022 "occlusion_query_EXT")
11024 Format(gen.generated_cpp_filenames)
11026 if gen.errors > 0:
11027 print "%d errors" % gen.errors
11028 return 1
11029 return 0
11032 if __name__ == '__main__':
11033 sys.exit(main(sys.argv[1:]))