Format generated gpu files using clang-format.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob0acd6a3ddca53b31de1074b159be6f8b6487b3d9
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 from optparse import OptionParser
14 from subprocess import call
16 _SIZE_OF_UINT32 = 4
17 _SIZE_OF_COMMAND_HEADER = 4
18 _FIRST_SPECIFIC_COMMAND_ID = 256
20 _LICENSE = """// Copyright (c) 2014 The Chromium Authors. All rights reserved.
21 // Use of this source code is governed by a BSD-style license that can be
22 // found in the LICENSE file.
24 """
26 _DO_NOT_EDIT_WARNING = """// This file is auto-generated from
27 // gpu/command_buffer/build_gles2_cmd_buffer.py
28 // It's formatted by clang-format using chromium coding style:
29 // clang-format -i -style=chromium filename
30 // DO NOT EDIT!
32 """
34 # This string is copied directly out of the gl2.h file from GLES2.0
36 # Edits:
38 # *) Any argument that is a resourceID has been changed to GLid<Type>.
39 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
40 # If it's allowed to not exist it's GLidBind<Type>
42 # *) All GLenums have been changed to GLenumTypeOfEnum
44 _GL_TYPES = {
45 'GLenum': 'unsigned int',
46 'GLboolean': 'unsigned char',
47 'GLbitfield': 'unsigned int',
48 'GLbyte': 'signed char',
49 'GLshort': 'short',
50 'GLint': 'int',
51 'GLsizei': 'int',
52 'GLubyte': 'unsigned char',
53 'GLushort': 'unsigned short',
54 'GLuint': 'unsigned int',
55 'GLfloat': 'float',
56 'GLclampf': 'float',
57 'GLvoid': 'void',
58 'GLfixed': 'int',
59 'GLclampx': 'int'
62 _GL_TYPES_32 = {
63 'GLintptr': 'long int',
64 'GLsizeiptr': 'long int'
67 _GL_TYPES_64 = {
68 'GLintptr': 'long long int',
69 'GLsizeiptr': 'long long int'
72 # Capabilites selected with glEnable
73 _CAPABILITY_FLAGS = [
74 {'name': 'blend'},
75 {'name': 'cull_face'},
76 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
77 {'name': 'dither', 'default': True},
78 {'name': 'polygon_offset_fill'},
79 {'name': 'sample_alpha_to_coverage'},
80 {'name': 'sample_coverage'},
81 {'name': 'scissor_test',
82 'state_flag': 'framebuffer_state_.clear_state_dirty'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
87 _STATES = {
88 'ClearColor': {
89 'type': 'Normal',
90 'func': 'ClearColor',
91 'enum': 'GL_COLOR_CLEAR_VALUE',
92 'states': [
93 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
94 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
99 'ClearDepthf': {
100 'type': 'Normal',
101 'func': 'ClearDepth',
102 'enum': 'GL_DEPTH_CLEAR_VALUE',
103 'states': [
104 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
107 'ColorMask': {
108 'type': 'Normal',
109 'func': 'ColorMask',
110 'enum': 'GL_COLOR_WRITEMASK',
111 'states': [
112 {'name': 'color_mask_red', 'type': 'GLboolean', 'default': 'true'},
113 {'name': 'color_mask_green', 'type': 'GLboolean', 'default': 'true'},
114 {'name': 'color_mask_blue', 'type': 'GLboolean', 'default': 'true'},
115 {'name': 'color_mask_alpha', 'type': 'GLboolean', 'default': 'true'},
117 'state_flag': 'framebuffer_state_.clear_state_dirty',
119 'ClearStencil': {
120 'type': 'Normal',
121 'func': 'ClearStencil',
122 'enum': 'GL_STENCIL_CLEAR_VALUE',
123 'states': [
124 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
127 'BlendColor': {
128 'type': 'Normal',
129 'func': 'BlendColor',
130 'enum': 'GL_BLEND_COLOR',
131 'states': [
132 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
133 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
134 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
135 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
138 'BlendEquation': {
139 'type': 'SrcDst',
140 'func': 'BlendEquationSeparate',
141 'states': [
143 'name': 'blend_equation_rgb',
144 'type': 'GLenum',
145 'enum': 'GL_BLEND_EQUATION_RGB',
146 'default': 'GL_FUNC_ADD',
149 'name': 'blend_equation_alpha',
150 'type': 'GLenum',
151 'enum': 'GL_BLEND_EQUATION_ALPHA',
152 'default': 'GL_FUNC_ADD',
156 'BlendFunc': {
157 'type': 'SrcDst',
158 'func': 'BlendFuncSeparate',
159 'states': [
161 'name': 'blend_source_rgb',
162 'type': 'GLenum',
163 'enum': 'GL_BLEND_SRC_RGB',
164 'default': 'GL_ONE',
167 'name': 'blend_dest_rgb',
168 'type': 'GLenum',
169 'enum': 'GL_BLEND_DST_RGB',
170 'default': 'GL_ZERO',
173 'name': 'blend_source_alpha',
174 'type': 'GLenum',
175 'enum': 'GL_BLEND_SRC_ALPHA',
176 'default': 'GL_ONE',
179 'name': 'blend_dest_alpha',
180 'type': 'GLenum',
181 'enum': 'GL_BLEND_DST_ALPHA',
182 'default': 'GL_ZERO',
186 'PolygonOffset': {
187 'type': 'Normal',
188 'func': 'PolygonOffset',
189 'states': [
191 'name': 'polygon_offset_factor',
192 'type': 'GLfloat',
193 'enum': 'GL_POLYGON_OFFSET_FACTOR',
194 'default': '0.0f',
197 'name': 'polygon_offset_units',
198 'type': 'GLfloat',
199 'enum': 'GL_POLYGON_OFFSET_UNITS',
200 'default': '0.0f',
204 'CullFace': {
205 'type': 'Normal',
206 'func': 'CullFace',
207 'enum': 'GL_CULL_FACE_MODE',
208 'states': [
210 'name': 'cull_mode',
211 'type': 'GLenum',
212 'default': 'GL_BACK',
216 'FrontFace': {
217 'type': 'Normal',
218 'func': 'FrontFace',
219 'enum': 'GL_FRONT_FACE',
220 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
222 'DepthFunc': {
223 'type': 'Normal',
224 'func': 'DepthFunc',
225 'enum': 'GL_DEPTH_FUNC',
226 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
228 'DepthRange': {
229 'type': 'Normal',
230 'func': 'DepthRange',
231 'enum': 'GL_DEPTH_RANGE',
232 'states': [
233 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
234 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
237 'SampleCoverage': {
238 'type': 'Normal',
239 'func': 'SampleCoverage',
240 'states': [
242 'name': 'sample_coverage_value',
243 'type': 'GLclampf',
244 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
245 'default': '1.0f',
248 'name': 'sample_coverage_invert',
249 'type': 'GLboolean',
250 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
251 'default': 'false',
255 'StencilMask': {
256 'type': 'FrontBack',
257 'func': 'StencilMaskSeparate',
258 'state_flag': 'framebuffer_state_.clear_state_dirty',
259 'states': [
261 'name': 'stencil_front_writemask',
262 'type': 'GLuint',
263 'enum': 'GL_STENCIL_WRITEMASK',
264 'default': '0xFFFFFFFFU',
267 'name': 'stencil_back_writemask',
268 'type': 'GLuint',
269 'enum': 'GL_STENCIL_BACK_WRITEMASK',
270 'default': '0xFFFFFFFFU',
274 'StencilOp': {
275 'type': 'FrontBack',
276 'func': 'StencilOpSeparate',
277 'states': [
279 'name': 'stencil_front_fail_op',
280 'type': 'GLenum',
281 'enum': 'GL_STENCIL_FAIL',
282 'default': 'GL_KEEP',
285 'name': 'stencil_front_z_fail_op',
286 'type': 'GLenum',
287 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
288 'default': 'GL_KEEP',
291 'name': 'stencil_front_z_pass_op',
292 'type': 'GLenum',
293 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
294 'default': 'GL_KEEP',
297 'name': 'stencil_back_fail_op',
298 'type': 'GLenum',
299 'enum': 'GL_STENCIL_BACK_FAIL',
300 'default': 'GL_KEEP',
303 'name': 'stencil_back_z_fail_op',
304 'type': 'GLenum',
305 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_back_z_pass_op',
310 'type': 'GLenum',
311 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
312 'default': 'GL_KEEP',
316 'StencilFunc': {
317 'type': 'FrontBack',
318 'func': 'StencilFuncSeparate',
319 'states': [
321 'name': 'stencil_front_func',
322 'type': 'GLenum',
323 'enum': 'GL_STENCIL_FUNC',
324 'default': 'GL_ALWAYS',
327 'name': 'stencil_front_ref',
328 'type': 'GLint',
329 'enum': 'GL_STENCIL_REF',
330 'default': '0',
333 'name': 'stencil_front_mask',
334 'type': 'GLuint',
335 'enum': 'GL_STENCIL_VALUE_MASK',
336 'default': '0xFFFFFFFFU',
339 'name': 'stencil_back_func',
340 'type': 'GLenum',
341 'enum': 'GL_STENCIL_BACK_FUNC',
342 'default': 'GL_ALWAYS',
345 'name': 'stencil_back_ref',
346 'type': 'GLint',
347 'enum': 'GL_STENCIL_BACK_REF',
348 'default': '0',
351 'name': 'stencil_back_mask',
352 'type': 'GLuint',
353 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
354 'default': '0xFFFFFFFFU',
358 'Hint': {
359 'type': 'NamedParameter',
360 'func': 'Hint',
361 'states': [
363 'name': 'hint_generate_mipmap',
364 'type': 'GLenum',
365 'enum': 'GL_GENERATE_MIPMAP_HINT',
366 'default': 'GL_DONT_CARE'
369 'name': 'hint_fragment_shader_derivative',
370 'type': 'GLenum',
371 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
372 'default': 'GL_DONT_CARE',
373 'extension_flag': 'oes_standard_derivatives'
377 'PixelStore': {
378 'type': 'NamedParameter',
379 'func': 'PixelStorei',
380 'states': [
382 'name': 'pack_alignment',
383 'type': 'GLint',
384 'enum': 'GL_PACK_ALIGNMENT',
385 'default': '4'
388 'name': 'unpack_alignment',
389 'type': 'GLint',
390 'enum': 'GL_UNPACK_ALIGNMENT',
391 'default': '4'
395 # TODO: Consider implemenenting these states
396 # GL_ACTIVE_TEXTURE
397 'LineWidth': {
398 'type': 'Normal',
399 'func': 'LineWidth',
400 'enum': 'GL_LINE_WIDTH',
401 'states': [
403 'name': 'line_width',
404 'type': 'GLfloat',
405 'default': '1.0f',
406 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
409 'DepthMask': {
410 'type': 'Normal',
411 'func': 'DepthMask',
412 'enum': 'GL_DEPTH_WRITEMASK',
413 'states': [
414 {'name': 'depth_mask', 'type': 'GLboolean', 'default': 'true'},
416 'state_flag': 'framebuffer_state_.clear_state_dirty',
418 'Scissor': {
419 'type': 'Normal',
420 'func': 'Scissor',
421 'enum': 'GL_SCISSOR_BOX',
422 'states': [
423 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
425 'name': 'scissor_x',
426 'type': 'GLint',
427 'default': '0',
428 'expected': 'kViewportX',
431 'name': 'scissor_y',
432 'type': 'GLint',
433 'default': '0',
434 'expected': 'kViewportY',
437 'name': 'scissor_width',
438 'type': 'GLsizei',
439 'default': '1',
440 'expected': 'kViewportWidth',
443 'name': 'scissor_height',
444 'type': 'GLsizei',
445 'default': '1',
446 'expected': 'kViewportHeight',
450 'Viewport': {
451 'type': 'Normal',
452 'func': 'Viewport',
453 'enum': 'GL_VIEWPORT',
454 'states': [
455 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
457 'name': 'viewport_x',
458 'type': 'GLint',
459 'default': '0',
460 'expected': 'kViewportX',
463 'name': 'viewport_y',
464 'type': 'GLint',
465 'default': '0',
466 'expected': 'kViewportY',
469 'name': 'viewport_width',
470 'type': 'GLsizei',
471 'default': '1',
472 'expected': 'kViewportWidth',
475 'name': 'viewport_height',
476 'type': 'GLsizei',
477 'default': '1',
478 'expected': 'kViewportHeight',
484 # This is a list of enum names and their valid values. It is used to map
485 # GLenum arguments to a specific set of valid values.
486 _ENUM_LISTS = {
487 'BlitFilter': {
488 'type': 'GLenum',
489 'valid': [
490 'GL_NEAREST',
491 'GL_LINEAR',
493 'invalid': [
494 'GL_LINEAR_MIPMAP_LINEAR',
497 'FrameBufferTarget': {
498 'type': 'GLenum',
499 'valid': [
500 'GL_FRAMEBUFFER',
502 'invalid': [
503 'GL_DRAW_FRAMEBUFFER' ,
504 'GL_READ_FRAMEBUFFER' ,
507 'RenderBufferTarget': {
508 'type': 'GLenum',
509 'valid': [
510 'GL_RENDERBUFFER',
512 'invalid': [
513 'GL_FRAMEBUFFER',
516 'BufferTarget': {
517 'type': 'GLenum',
518 'valid': [
519 'GL_ARRAY_BUFFER',
520 'GL_ELEMENT_ARRAY_BUFFER',
522 'invalid': [
523 'GL_RENDERBUFFER',
526 'BufferUsage': {
527 'type': 'GLenum',
528 'valid': [
529 'GL_STREAM_DRAW',
530 'GL_STATIC_DRAW',
531 'GL_DYNAMIC_DRAW',
533 'invalid': [
534 'GL_STATIC_READ',
537 'CompressedTextureFormat': {
538 'type': 'GLenum',
539 'valid': [
542 'GLState': {
543 'type': 'GLenum',
544 'valid': [
545 # NOTE: State an Capability entries added later.
546 'GL_ACTIVE_TEXTURE',
547 'GL_ALIASED_LINE_WIDTH_RANGE',
548 'GL_ALIASED_POINT_SIZE_RANGE',
549 'GL_ALPHA_BITS',
550 'GL_ARRAY_BUFFER_BINDING',
551 'GL_BLUE_BITS',
552 'GL_COMPRESSED_TEXTURE_FORMATS',
553 'GL_CURRENT_PROGRAM',
554 'GL_DEPTH_BITS',
555 'GL_DEPTH_RANGE',
556 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
557 'GL_FRAMEBUFFER_BINDING',
558 'GL_GENERATE_MIPMAP_HINT',
559 'GL_GREEN_BITS',
560 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
561 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
562 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
563 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
564 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
565 'GL_MAX_RENDERBUFFER_SIZE',
566 'GL_MAX_TEXTURE_IMAGE_UNITS',
567 'GL_MAX_TEXTURE_SIZE',
568 'GL_MAX_VARYING_VECTORS',
569 'GL_MAX_VERTEX_ATTRIBS',
570 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
571 'GL_MAX_VERTEX_UNIFORM_VECTORS',
572 'GL_MAX_VIEWPORT_DIMS',
573 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
574 'GL_NUM_SHADER_BINARY_FORMATS',
575 'GL_PACK_ALIGNMENT',
576 'GL_RED_BITS',
577 'GL_RENDERBUFFER_BINDING',
578 'GL_SAMPLE_BUFFERS',
579 'GL_SAMPLE_COVERAGE_INVERT',
580 'GL_SAMPLE_COVERAGE_VALUE',
581 'GL_SAMPLES',
582 'GL_SCISSOR_BOX',
583 'GL_SHADER_BINARY_FORMATS',
584 'GL_SHADER_COMPILER',
585 'GL_SUBPIXEL_BITS',
586 'GL_STENCIL_BITS',
587 'GL_TEXTURE_BINDING_2D',
588 'GL_TEXTURE_BINDING_CUBE_MAP',
589 'GL_UNPACK_ALIGNMENT',
590 'GL_UNPACK_FLIP_Y_CHROMIUM',
591 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
592 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
593 # we can add this because we emulate it if the driver does not support it.
594 'GL_VERTEX_ARRAY_BINDING_OES',
595 'GL_VIEWPORT',
597 'invalid': [
598 'GL_FOG_HINT',
601 'GetTexParamTarget': {
602 'type': 'GLenum',
603 'valid': [
604 'GL_TEXTURE_2D',
605 'GL_TEXTURE_CUBE_MAP',
607 'invalid': [
608 'GL_PROXY_TEXTURE_CUBE_MAP',
611 'TextureTarget': {
612 'type': 'GLenum',
613 'valid': [
614 'GL_TEXTURE_2D',
615 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
616 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
617 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
618 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
619 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
620 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
622 'invalid': [
623 'GL_PROXY_TEXTURE_CUBE_MAP',
626 'TextureBindTarget': {
627 'type': 'GLenum',
628 'valid': [
629 'GL_TEXTURE_2D',
630 'GL_TEXTURE_CUBE_MAP',
632 'invalid': [
633 'GL_TEXTURE_1D',
634 'GL_TEXTURE_3D',
637 'ShaderType': {
638 'type': 'GLenum',
639 'valid': [
640 'GL_VERTEX_SHADER',
641 'GL_FRAGMENT_SHADER',
643 'invalid': [
644 'GL_GEOMETRY_SHADER',
647 'FaceType': {
648 'type': 'GLenum',
649 'valid': [
650 'GL_FRONT',
651 'GL_BACK',
652 'GL_FRONT_AND_BACK',
655 'FaceMode': {
656 'type': 'GLenum',
657 'valid': [
658 'GL_CW',
659 'GL_CCW',
662 'CmpFunction': {
663 'type': 'GLenum',
664 'valid': [
665 'GL_NEVER',
666 'GL_LESS',
667 'GL_EQUAL',
668 'GL_LEQUAL',
669 'GL_GREATER',
670 'GL_NOTEQUAL',
671 'GL_GEQUAL',
672 'GL_ALWAYS',
675 'Equation': {
676 'type': 'GLenum',
677 'valid': [
678 'GL_FUNC_ADD',
679 'GL_FUNC_SUBTRACT',
680 'GL_FUNC_REVERSE_SUBTRACT',
682 'invalid': [
683 'GL_MIN',
684 'GL_MAX',
687 'SrcBlendFactor': {
688 'type': 'GLenum',
689 'valid': [
690 'GL_ZERO',
691 'GL_ONE',
692 'GL_SRC_COLOR',
693 'GL_ONE_MINUS_SRC_COLOR',
694 'GL_DST_COLOR',
695 'GL_ONE_MINUS_DST_COLOR',
696 'GL_SRC_ALPHA',
697 'GL_ONE_MINUS_SRC_ALPHA',
698 'GL_DST_ALPHA',
699 'GL_ONE_MINUS_DST_ALPHA',
700 'GL_CONSTANT_COLOR',
701 'GL_ONE_MINUS_CONSTANT_COLOR',
702 'GL_CONSTANT_ALPHA',
703 'GL_ONE_MINUS_CONSTANT_ALPHA',
704 'GL_SRC_ALPHA_SATURATE',
707 'DstBlendFactor': {
708 'type': 'GLenum',
709 'valid': [
710 'GL_ZERO',
711 'GL_ONE',
712 'GL_SRC_COLOR',
713 'GL_ONE_MINUS_SRC_COLOR',
714 'GL_DST_COLOR',
715 'GL_ONE_MINUS_DST_COLOR',
716 'GL_SRC_ALPHA',
717 'GL_ONE_MINUS_SRC_ALPHA',
718 'GL_DST_ALPHA',
719 'GL_ONE_MINUS_DST_ALPHA',
720 'GL_CONSTANT_COLOR',
721 'GL_ONE_MINUS_CONSTANT_COLOR',
722 'GL_CONSTANT_ALPHA',
723 'GL_ONE_MINUS_CONSTANT_ALPHA',
726 'Capability': {
727 'type': 'GLenum',
728 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS],
729 'invalid': [
730 'GL_CLIP_PLANE0',
731 'GL_POINT_SPRITE',
734 'DrawMode': {
735 'type': 'GLenum',
736 'valid': [
737 'GL_POINTS',
738 'GL_LINE_STRIP',
739 'GL_LINE_LOOP',
740 'GL_LINES',
741 'GL_TRIANGLE_STRIP',
742 'GL_TRIANGLE_FAN',
743 'GL_TRIANGLES',
745 'invalid': [
746 'GL_QUADS',
747 'GL_POLYGON',
750 'IndexType': {
751 'type': 'GLenum',
752 'valid': [
753 'GL_UNSIGNED_BYTE',
754 'GL_UNSIGNED_SHORT',
756 'invalid': [
757 'GL_UNSIGNED_INT',
758 'GL_INT',
761 'GetMaxIndexType': {
762 'type': 'GLenum',
763 'valid': [
764 'GL_UNSIGNED_BYTE',
765 'GL_UNSIGNED_SHORT',
766 'GL_UNSIGNED_INT',
768 'invalid': [
769 'GL_INT',
772 'Attachment': {
773 'type': 'GLenum',
774 'valid': [
775 'GL_COLOR_ATTACHMENT0',
776 'GL_DEPTH_ATTACHMENT',
777 'GL_STENCIL_ATTACHMENT',
780 'BackbufferAttachment': {
781 'type': 'GLenum',
782 'valid': [
783 'GL_COLOR_EXT',
784 'GL_DEPTH_EXT',
785 'GL_STENCIL_EXT',
788 'BufferParameter': {
789 'type': 'GLenum',
790 'valid': [
791 'GL_BUFFER_SIZE',
792 'GL_BUFFER_USAGE',
794 'invalid': [
795 'GL_PIXEL_PACK_BUFFER',
798 'FrameBufferParameter': {
799 'type': 'GLenum',
800 'valid': [
801 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
802 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
803 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
804 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
807 'ProgramParameter': {
808 'type': 'GLenum',
809 'valid': [
810 'GL_DELETE_STATUS',
811 'GL_LINK_STATUS',
812 'GL_VALIDATE_STATUS',
813 'GL_INFO_LOG_LENGTH',
814 'GL_ATTACHED_SHADERS',
815 'GL_ACTIVE_ATTRIBUTES',
816 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
817 'GL_ACTIVE_UNIFORMS',
818 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
821 'QueryObjectParameter': {
822 'type': 'GLenum',
823 'valid': [
824 'GL_QUERY_RESULT_EXT',
825 'GL_QUERY_RESULT_AVAILABLE_EXT',
828 'QueryParameter': {
829 'type': 'GLenum',
830 'valid': [
831 'GL_CURRENT_QUERY_EXT',
834 'QueryTarget': {
835 'type': 'GLenum',
836 'valid': [
837 'GL_ANY_SAMPLES_PASSED_EXT',
838 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
839 'GL_COMMANDS_ISSUED_CHROMIUM',
840 'GL_LATENCY_QUERY_CHROMIUM',
841 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
842 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
845 'RenderBufferParameter': {
846 'type': 'GLenum',
847 'valid': [
848 'GL_RENDERBUFFER_RED_SIZE',
849 'GL_RENDERBUFFER_GREEN_SIZE',
850 'GL_RENDERBUFFER_BLUE_SIZE',
851 'GL_RENDERBUFFER_ALPHA_SIZE',
852 'GL_RENDERBUFFER_DEPTH_SIZE',
853 'GL_RENDERBUFFER_STENCIL_SIZE',
854 'GL_RENDERBUFFER_WIDTH',
855 'GL_RENDERBUFFER_HEIGHT',
856 'GL_RENDERBUFFER_INTERNAL_FORMAT',
859 'ShaderParameter': {
860 'type': 'GLenum',
861 'valid': [
862 'GL_SHADER_TYPE',
863 'GL_DELETE_STATUS',
864 'GL_COMPILE_STATUS',
865 'GL_INFO_LOG_LENGTH',
866 'GL_SHADER_SOURCE_LENGTH',
867 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
870 'ShaderPrecision': {
871 'type': 'GLenum',
872 'valid': [
873 'GL_LOW_FLOAT',
874 'GL_MEDIUM_FLOAT',
875 'GL_HIGH_FLOAT',
876 'GL_LOW_INT',
877 'GL_MEDIUM_INT',
878 'GL_HIGH_INT',
881 'StringType': {
882 'type': 'GLenum',
883 'valid': [
884 'GL_VENDOR',
885 'GL_RENDERER',
886 'GL_VERSION',
887 'GL_SHADING_LANGUAGE_VERSION',
888 'GL_EXTENSIONS',
891 'TextureParameter': {
892 'type': 'GLenum',
893 'valid': [
894 'GL_TEXTURE_MAG_FILTER',
895 'GL_TEXTURE_MIN_FILTER',
896 'GL_TEXTURE_POOL_CHROMIUM',
897 'GL_TEXTURE_WRAP_S',
898 'GL_TEXTURE_WRAP_T',
900 'invalid': [
901 'GL_GENERATE_MIPMAP',
904 'TexturePool': {
905 'type': 'GLenum',
906 'valid': [
907 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
908 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
911 'TextureWrapMode': {
912 'type': 'GLenum',
913 'valid': [
914 'GL_CLAMP_TO_EDGE',
915 'GL_MIRRORED_REPEAT',
916 'GL_REPEAT',
919 'TextureMinFilterMode': {
920 'type': 'GLenum',
921 'valid': [
922 'GL_NEAREST',
923 'GL_LINEAR',
924 'GL_NEAREST_MIPMAP_NEAREST',
925 'GL_LINEAR_MIPMAP_NEAREST',
926 'GL_NEAREST_MIPMAP_LINEAR',
927 'GL_LINEAR_MIPMAP_LINEAR',
930 'TextureMagFilterMode': {
931 'type': 'GLenum',
932 'valid': [
933 'GL_NEAREST',
934 'GL_LINEAR',
937 'TextureUsage': {
938 'type': 'GLenum',
939 'valid': [
940 'GL_NONE',
941 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
944 'VertexAttribute': {
945 'type': 'GLenum',
946 'valid': [
947 # some enum that the decoder actually passes through to GL needs
948 # to be the first listed here since it's used in unit tests.
949 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
950 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
951 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
952 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
953 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
954 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
955 'GL_CURRENT_VERTEX_ATTRIB',
958 'VertexPointer': {
959 'type': 'GLenum',
960 'valid': [
961 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
964 'HintTarget': {
965 'type': 'GLenum',
966 'valid': [
967 'GL_GENERATE_MIPMAP_HINT',
969 'invalid': [
970 'GL_PERSPECTIVE_CORRECTION_HINT',
973 'HintMode': {
974 'type': 'GLenum',
975 'valid': [
976 'GL_FASTEST',
977 'GL_NICEST',
978 'GL_DONT_CARE',
981 'PixelStore': {
982 'type': 'GLenum',
983 'valid': [
984 'GL_PACK_ALIGNMENT',
985 'GL_UNPACK_ALIGNMENT',
986 'GL_UNPACK_FLIP_Y_CHROMIUM',
987 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
988 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
990 'invalid': [
991 'GL_PACK_SWAP_BYTES',
992 'GL_UNPACK_SWAP_BYTES',
995 'PixelStoreAlignment': {
996 'type': 'GLint',
997 'valid': [
998 '1',
999 '2',
1000 '4',
1001 '8',
1003 'invalid': [
1004 '3',
1005 '9',
1008 'ReadPixelFormat': {
1009 'type': 'GLenum',
1010 'valid': [
1011 'GL_ALPHA',
1012 'GL_RGB',
1013 'GL_RGBA',
1016 'PixelType': {
1017 'type': 'GLenum',
1018 'valid': [
1019 'GL_UNSIGNED_BYTE',
1020 'GL_UNSIGNED_SHORT_5_6_5',
1021 'GL_UNSIGNED_SHORT_4_4_4_4',
1022 'GL_UNSIGNED_SHORT_5_5_5_1',
1024 'invalid': [
1025 'GL_SHORT',
1026 'GL_INT',
1029 'ReadPixelType': {
1030 'type': 'GLenum',
1031 'valid': [
1032 'GL_UNSIGNED_BYTE',
1033 'GL_UNSIGNED_SHORT_5_6_5',
1034 'GL_UNSIGNED_SHORT_4_4_4_4',
1035 'GL_UNSIGNED_SHORT_5_5_5_1',
1037 'invalid': [
1038 'GL_SHORT',
1039 'GL_INT',
1042 'RenderBufferFormat': {
1043 'type': 'GLenum',
1044 'valid': [
1045 'GL_RGBA4',
1046 'GL_RGB565',
1047 'GL_RGB5_A1',
1048 'GL_DEPTH_COMPONENT16',
1049 'GL_STENCIL_INDEX8',
1052 'ShaderBinaryFormat': {
1053 'type': 'GLenum',
1054 'valid': [
1057 'StencilOp': {
1058 'type': 'GLenum',
1059 'valid': [
1060 'GL_KEEP',
1061 'GL_ZERO',
1062 'GL_REPLACE',
1063 'GL_INCR',
1064 'GL_INCR_WRAP',
1065 'GL_DECR',
1066 'GL_DECR_WRAP',
1067 'GL_INVERT',
1070 'TextureFormat': {
1071 'type': 'GLenum',
1072 'valid': [
1073 'GL_ALPHA',
1074 'GL_LUMINANCE',
1075 'GL_LUMINANCE_ALPHA',
1076 'GL_RGB',
1077 'GL_RGBA',
1079 'invalid': [
1080 'GL_BGRA',
1081 'GL_BGR',
1084 'TextureInternalFormat': {
1085 'type': 'GLenum',
1086 'valid': [
1087 'GL_ALPHA',
1088 'GL_LUMINANCE',
1089 'GL_LUMINANCE_ALPHA',
1090 'GL_RGB',
1091 'GL_RGBA',
1093 'invalid': [
1094 'GL_BGRA',
1095 'GL_BGR',
1098 'TextureInternalFormatStorage': {
1099 'type': 'GLenum',
1100 'valid': [
1101 'GL_RGB565',
1102 'GL_RGBA4',
1103 'GL_RGB5_A1',
1104 'GL_ALPHA8_EXT',
1105 'GL_LUMINANCE8_EXT',
1106 'GL_LUMINANCE8_ALPHA8_EXT',
1107 'GL_RGB8_OES',
1108 'GL_RGBA8_OES',
1111 'VertexAttribType': {
1112 'type': 'GLenum',
1113 'valid': [
1114 'GL_BYTE',
1115 'GL_UNSIGNED_BYTE',
1116 'GL_SHORT',
1117 'GL_UNSIGNED_SHORT',
1118 # 'GL_FIXED', // This is not available on Desktop GL.
1119 'GL_FLOAT',
1121 'invalid': [
1122 'GL_DOUBLE',
1125 'TextureBorder': {
1126 'type': 'GLint',
1127 'valid': [
1128 '0',
1130 'invalid': [
1131 '1',
1134 'VertexAttribSize': {
1135 'type': 'GLint',
1136 'valid': [
1137 '1',
1138 '2',
1139 '3',
1140 '4',
1142 'invalid': [
1143 '0',
1144 '5',
1147 'ZeroOnly': {
1148 'type': 'GLint',
1149 'valid': [
1150 '0',
1152 'invalid': [
1153 '1',
1156 'FalseOnly': {
1157 'type': 'GLboolean',
1158 'valid': [
1159 'false',
1161 'invalid': [
1162 'true',
1165 'ResetStatus': {
1166 'type': 'GLenum',
1167 'valid': [
1168 'GL_GUILTY_CONTEXT_RESET_ARB',
1169 'GL_INNOCENT_CONTEXT_RESET_ARB',
1170 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1175 # This table specifies the different pepper interfaces that are supported for
1176 # GL commands. 'dev' is true if it's a dev interface.
1177 _PEPPER_INTERFACES = [
1178 {'name': '', 'dev': False},
1179 {'name': 'InstancedArrays', 'dev': False},
1180 {'name': 'FramebufferBlit', 'dev': False},
1181 {'name': 'FramebufferMultisample', 'dev': False},
1182 {'name': 'ChromiumEnableFeature', 'dev': False},
1183 {'name': 'ChromiumMapSub', 'dev': False},
1184 {'name': 'Query', 'dev': False},
1187 # This table specifies types and other special data for the commands that
1188 # will be generated.
1190 # Must match function names specified in "cmd_buffer_functions.txt".
1192 # cmd_comment: A comment added to the cmd format.
1193 # type: defines which handler will be used to generate code.
1194 # decoder_func: defines which function to call in the decoder to execute the
1195 # corresponding GL command. If not specified the GL command will
1196 # be called directly.
1197 # gl_test_func: GL function that is expected to be called when testing.
1198 # cmd_args: The arguments to use for the command. This overrides generating
1199 # them based on the GL function arguments.
1200 # a NonImmediate type is a type that stays a pointer even in
1201 # and immediate version of acommand.
1202 # gen_cmd: Whether or not this function geneates a command. Default = True.
1203 # immediate: Whether or not to generate an immediate command for the GL
1204 # function. The default is if there is exactly 1 pointer argument
1205 # in the GL function an immediate command is generated.
1206 # bucket: True to generate a bucket version of the command.
1207 # impl_func: Whether or not to generate the GLES2Implementation part of this
1208 # command.
1209 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1210 # for this command.
1211 # needs_size: If true a data_size field is added to the command.
1212 # data_type: The type of data the command uses. For PUTn or PUT types.
1213 # count: The number of units per element. For PUTn or PUT types.
1214 # unit_test: If False no service side unit test will be generated.
1215 # client_test: If False no client side unit test will be generated.
1216 # expectation: If False the unit test will have no expected calls.
1217 # gen_func: Name of function that generates GL resource for corresponding
1218 # bind function.
1219 # states: array of states that get set by this function corresponding to
1220 # the given arguments
1221 # state_flag: name of flag that is set to true when function is called.
1222 # no_gl: no GL function is called.
1223 # valid_args: A dictionary of argument indices to args to use in unit tests
1224 # when they can not be automatically determined.
1225 # pepper_interface: The pepper interface that is used for this extension
1226 # pepper_name: The name of the function as exposed to pepper.
1227 # pepper_args: A string representing the argument list (what would appear in
1228 # C/C++ between the parentheses for the function declaration)
1229 # that the Pepper API expects for this function. Use this only if
1230 # the stable Pepper API differs from the GLES2 argument list.
1231 # invalid_test: False if no invalid test needed.
1232 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1233 # first_element_only: For PUT types, True if only the first element of an
1234 # array is used and we end up calling the single value
1235 # corresponding function. eg. TexParameteriv -> TexParameteri
1237 _FUNCTION_INFO = {
1238 'ActiveTexture': {
1239 'decoder_func': 'DoActiveTexture',
1240 'unit_test': False,
1241 'impl_func': False,
1242 'client_test': False,
1244 'AttachShader': {'decoder_func': 'DoAttachShader'},
1245 'BindAttribLocation': {
1246 'type': 'GLchar',
1247 'bucket': True,
1248 'needs_size': True,
1249 'immediate': False,
1251 'BindBuffer': {
1252 'type': 'Bind',
1253 'decoder_func': 'DoBindBuffer',
1254 'gen_func': 'GenBuffersARB',
1256 'BindFramebuffer': {
1257 'type': 'Bind',
1258 'decoder_func': 'DoBindFramebuffer',
1259 'gl_test_func': 'glBindFramebufferEXT',
1260 'gen_func': 'GenFramebuffersEXT',
1261 'trace_level': 1,
1263 'BindRenderbuffer': {
1264 'type': 'Bind',
1265 'decoder_func': 'DoBindRenderbuffer',
1266 'gl_test_func': 'glBindRenderbufferEXT',
1267 'gen_func': 'GenRenderbuffersEXT',
1269 'BindTexture': {
1270 'type': 'Bind',
1271 'decoder_func': 'DoBindTexture',
1272 'gen_func': 'GenTextures',
1273 # TODO(gman): remove this once client side caching works.
1274 'client_test': False,
1275 'trace_level': 1,
1277 'BlitFramebufferCHROMIUM': {
1278 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1279 'unit_test': False,
1280 'extension': True,
1281 'pepper_interface': 'FramebufferBlit',
1282 'pepper_name': 'BlitFramebufferEXT',
1283 'defer_reads': True,
1284 'defer_draws': True,
1285 'trace_level': 1,
1287 'BufferData': {
1288 'type': 'Manual',
1289 'immediate': False,
1290 'client_test': False,
1292 'BufferSubData': {
1293 'type': 'Data',
1294 'client_test': False,
1295 'decoder_func': 'DoBufferSubData',
1296 'immediate': False,
1298 'CheckFramebufferStatus': {
1299 'type': 'Is',
1300 'decoder_func': 'DoCheckFramebufferStatus',
1301 'gl_test_func': 'glCheckFramebufferStatusEXT',
1302 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1303 'result': ['GLenum'],
1305 'Clear': {
1306 'decoder_func': 'DoClear',
1307 'defer_draws': True,
1308 'trace_level': 1,
1310 'ClearColor': {
1311 'type': 'StateSet',
1312 'state': 'ClearColor',
1314 'ClearDepthf': {
1315 'type': 'StateSet',
1316 'state': 'ClearDepthf',
1317 'decoder_func': 'glClearDepth',
1318 'gl_test_func': 'glClearDepth',
1319 'valid_args': {
1320 '0': '0.5f'
1323 'ColorMask': {
1324 'type': 'StateSet',
1325 'state': 'ColorMask',
1326 'no_gl': True,
1327 'expectation': False,
1329 'ConsumeTextureCHROMIUM': {
1330 'decoder_func': 'DoConsumeTextureCHROMIUM',
1331 'impl_func': False,
1332 'type': 'PUT',
1333 'data_type': 'GLbyte',
1334 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1335 'unit_test': False,
1336 'client_test': False,
1337 'extension': True,
1338 'chromium': True,
1339 'trace_level': 1,
1341 'ClearStencil': {
1342 'type': 'StateSet',
1343 'state': 'ClearStencil',
1345 'EnableFeatureCHROMIUM': {
1346 'type': 'Custom',
1347 'immediate': False,
1348 'decoder_func': 'DoEnableFeatureCHROMIUM',
1349 'expectation': False,
1350 'cmd_args': 'GLuint bucket_id, GLint* result',
1351 'result': ['GLint'],
1352 'extension': True,
1353 'chromium': True,
1354 'pepper_interface': 'ChromiumEnableFeature',
1356 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1357 'CompressedTexImage2D': {
1358 'type': 'Manual',
1359 'immediate': False,
1360 'bucket': True,
1362 'CompressedTexSubImage2D': {
1363 'type': 'Data',
1364 'bucket': True,
1365 'decoder_func': 'DoCompressedTexSubImage2D',
1366 'immediate': False,
1368 'CopyTexImage2D': {
1369 'decoder_func': 'DoCopyTexImage2D',
1370 'unit_test': False,
1371 'defer_reads': True,
1373 'CopyTexSubImage2D': {
1374 'decoder_func': 'DoCopyTexSubImage2D',
1375 'defer_reads': True,
1377 'CreateImageCHROMIUM': {
1378 'type': 'Manual',
1379 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1380 'result': ['GLuint'],
1381 'client_test': False,
1382 'gen_cmd': False,
1383 'expectation': False,
1384 'extension': True,
1385 'chromium': True,
1387 'DestroyImageCHROMIUM': {
1388 'type': 'Manual',
1389 'immediate': False,
1390 'client_test': False,
1391 'gen_cmd': False,
1392 'extension': True,
1393 'chromium': True,
1395 'GetImageParameterivCHROMIUM': {
1396 'type': 'Manual',
1397 'client_test': False,
1398 'gen_cmd': False,
1399 'expectation': False,
1400 'extension': True,
1401 'chromium': True,
1403 'CreateProgram': {
1404 'type': 'Create',
1405 'client_test': False,
1407 'CreateShader': {
1408 'type': 'Create',
1409 'client_test': False,
1411 'BlendColor': {
1412 'type': 'StateSet',
1413 'state': 'BlendColor',
1415 'BlendEquation': {
1416 'type': 'StateSetRGBAlpha',
1417 'state': 'BlendEquation',
1418 'valid_args': {
1419 '0': 'GL_FUNC_SUBTRACT'
1422 'BlendEquationSeparate': {
1423 'type': 'StateSet',
1424 'state': 'BlendEquation',
1425 'valid_args': {
1426 '0': 'GL_FUNC_SUBTRACT'
1429 'BlendFunc': {
1430 'type': 'StateSetRGBAlpha',
1431 'state': 'BlendFunc',
1433 'BlendFuncSeparate': {
1434 'type': 'StateSet',
1435 'state': 'BlendFunc',
1437 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1438 'StencilFunc': {
1439 'type': 'StateSetFrontBack',
1440 'state': 'StencilFunc',
1442 'StencilFuncSeparate': {
1443 'type': 'StateSetFrontBackSeparate',
1444 'state': 'StencilFunc',
1446 'StencilOp': {
1447 'type': 'StateSetFrontBack',
1448 'state': 'StencilOp',
1449 'valid_args': {
1450 '1': 'GL_INCR'
1453 'StencilOpSeparate': {
1454 'type': 'StateSetFrontBackSeparate',
1455 'state': 'StencilOp',
1456 'valid_args': {
1457 '1': 'GL_INCR'
1460 'Hint': {
1461 'type': 'StateSetNamedParameter',
1462 'state': 'Hint',
1464 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1465 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1466 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1467 'LineWidth': {
1468 'type': 'StateSet',
1469 'state': 'LineWidth',
1470 'valid_args': {
1471 '0': '0.5f'
1474 'PolygonOffset': {
1475 'type': 'StateSet',
1476 'state': 'PolygonOffset',
1478 'DeleteBuffers': {
1479 'type': 'DELn',
1480 'gl_test_func': 'glDeleteBuffersARB',
1481 'resource_type': 'Buffer',
1482 'resource_types': 'Buffers',
1484 'DeleteFramebuffers': {
1485 'type': 'DELn',
1486 'gl_test_func': 'glDeleteFramebuffersEXT',
1487 'resource_type': 'Framebuffer',
1488 'resource_types': 'Framebuffers',
1490 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1491 'DeleteRenderbuffers': {
1492 'type': 'DELn',
1493 'gl_test_func': 'glDeleteRenderbuffersEXT',
1494 'resource_type': 'Renderbuffer',
1495 'resource_types': 'Renderbuffers',
1497 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1498 'DeleteSharedIdsCHROMIUM': {
1499 'type': 'Custom',
1500 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1501 'impl_func': False,
1502 'expectation': False,
1503 'immediate': False,
1504 'extension': True,
1505 'chromium': True,
1507 'DeleteTextures': {
1508 'type': 'DELn',
1509 'resource_type': 'Texture',
1510 'resource_types': 'Textures',
1512 'DepthRangef': {
1513 'decoder_func': 'DoDepthRangef',
1514 'gl_test_func': 'glDepthRange',
1516 'DepthMask': {
1517 'type': 'StateSet',
1518 'state': 'DepthMask',
1519 'no_gl': True,
1520 'expectation': False,
1522 'DetachShader': {'decoder_func': 'DoDetachShader'},
1523 'Disable': {
1524 'decoder_func': 'DoDisable',
1525 'impl_func': False,
1526 'client_test': False,
1528 'DisableVertexAttribArray': {
1529 'decoder_func': 'DoDisableVertexAttribArray',
1530 'impl_decl': False,
1532 'DrawArrays': {
1533 'type': 'Manual',
1534 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1535 'defer_draws': True,
1536 'trace_level': 2,
1538 'DrawElements': {
1539 'type': 'Manual',
1540 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1541 'GLenumIndexType type, GLuint index_offset',
1542 'client_test': False,
1543 'defer_draws': True,
1544 'trace_level': 2,
1546 'Enable': {
1547 'decoder_func': 'DoEnable',
1548 'impl_func': False,
1549 'client_test': False,
1551 'EnableVertexAttribArray': {
1552 'decoder_func': 'DoEnableVertexAttribArray',
1553 'impl_decl': False,
1555 'Finish': {
1556 'impl_func': False,
1557 'client_test': False,
1558 'decoder_func': 'DoFinish',
1559 'defer_reads': True,
1561 'Flush': {
1562 'impl_func': False,
1563 'decoder_func': 'DoFlush',
1565 'FramebufferRenderbuffer': {
1566 'decoder_func': 'DoFramebufferRenderbuffer',
1567 'gl_test_func': 'glFramebufferRenderbufferEXT',
1569 'FramebufferTexture2D': {
1570 'decoder_func': 'DoFramebufferTexture2D',
1571 'gl_test_func': 'glFramebufferTexture2DEXT',
1572 'trace_level': 1,
1574 'FramebufferTexture2DMultisampleEXT': {
1575 'decoder_func': 'DoFramebufferTexture2DMultisample',
1576 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1577 'expectation': False,
1578 'unit_test': False,
1579 'extension': True,
1580 'trace_level': 1,
1582 'GenerateMipmap': {
1583 'decoder_func': 'DoGenerateMipmap',
1584 'gl_test_func': 'glGenerateMipmapEXT',
1586 'GenBuffers': {
1587 'type': 'GENn',
1588 'gl_test_func': 'glGenBuffersARB',
1589 'resource_type': 'Buffer',
1590 'resource_types': 'Buffers',
1592 'GenMailboxCHROMIUM': {
1593 'type': 'HandWritten',
1594 'immediate': False,
1595 'impl_func': False,
1596 'extension': True,
1597 'chromium': True,
1599 'GenFramebuffers': {
1600 'type': 'GENn',
1601 'gl_test_func': 'glGenFramebuffersEXT',
1602 'resource_type': 'Framebuffer',
1603 'resource_types': 'Framebuffers',
1605 'GenRenderbuffers': {
1606 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1607 'resource_type': 'Renderbuffer',
1608 'resource_types': 'Renderbuffers',
1610 'GenTextures': {
1611 'type': 'GENn',
1612 'gl_test_func': 'glGenTextures',
1613 'resource_type': 'Texture',
1614 'resource_types': 'Textures',
1616 'GenSharedIdsCHROMIUM': {
1617 'type': 'Custom',
1618 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1619 'impl_func': False,
1620 'expectation': False,
1621 'immediate': False,
1622 'extension': True,
1623 'chromium': True,
1625 'GetActiveAttrib': {
1626 'type': 'Custom',
1627 'immediate': False,
1628 'cmd_args':
1629 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1630 'void* result',
1631 'result': [
1632 'int32 success',
1633 'int32 size',
1634 'uint32 type',
1637 'GetActiveUniform': {
1638 'type': 'Custom',
1639 'immediate': False,
1640 'cmd_args':
1641 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1642 'void* result',
1643 'result': [
1644 'int32 success',
1645 'int32 size',
1646 'uint32 type',
1649 'GetAttachedShaders': {
1650 'type': 'Custom',
1651 'immediate': False,
1652 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1653 'result': ['SizedResult<GLuint>'],
1655 'GetAttribLocation': {
1656 'type': 'HandWritten',
1657 'immediate': False,
1658 'bucket': True,
1659 'needs_size': True,
1660 'cmd_args':
1661 'GLidProgram program, const char* name, NonImmediate GLint* location',
1662 'result': ['GLint'],
1663 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1665 'GetBooleanv': {
1666 'type': 'GETn',
1667 'result': ['SizedResult<GLboolean>'],
1668 'decoder_func': 'DoGetBooleanv',
1669 'gl_test_func': 'glGetBooleanv',
1671 'GetBufferParameteriv': {
1672 'type': 'GETn',
1673 'result': ['SizedResult<GLint>'],
1674 'decoder_func': 'DoGetBufferParameteriv',
1675 'expectation': False,
1676 'shadowed': True,
1678 'GetError': {
1679 'type': 'Is',
1680 'decoder_func': 'GetErrorState()->GetGLError',
1681 'impl_func': False,
1682 'result': ['GLenum'],
1683 'client_test': False,
1685 'GetFloatv': {
1686 'type': 'GETn',
1687 'result': ['SizedResult<GLfloat>'],
1688 'decoder_func': 'DoGetFloatv',
1689 'gl_test_func': 'glGetFloatv',
1691 'GetFramebufferAttachmentParameteriv': {
1692 'type': 'GETn',
1693 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1694 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1695 'result': ['SizedResult<GLint>'],
1697 'GetIntegerv': {
1698 'type': 'GETn',
1699 'result': ['SizedResult<GLint>'],
1700 'decoder_func': 'DoGetIntegerv',
1701 'client_test': False,
1703 'GetMaxValueInBufferCHROMIUM': {
1704 'type': 'Is',
1705 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1706 'result': ['GLuint'],
1707 'unit_test': False,
1708 'client_test': False,
1709 'extension': True,
1710 'chromium': True,
1711 'impl_func': False,
1713 'GetMultipleIntegervCHROMIUM': {
1714 'type': 'Custom',
1715 'immediate': False,
1716 'expectation': False,
1717 'extension': True,
1718 'chromium': True,
1719 'client_test': False,
1721 'GetProgramiv': {
1722 'type': 'GETn',
1723 'decoder_func': 'DoGetProgramiv',
1724 'result': ['SizedResult<GLint>'],
1725 'expectation': False,
1727 'GetProgramInfoCHROMIUM': {
1728 'type': 'Custom',
1729 'immediate': False,
1730 'expectation': False,
1731 'impl_func': False,
1732 'extension': True,
1733 'chromium': True,
1734 'client_test': False,
1735 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1736 'result': [
1737 'uint32 link_status',
1738 'uint32 num_attribs',
1739 'uint32 num_uniforms',
1742 'GetProgramInfoLog': {
1743 'type': 'STRn',
1744 'expectation': False,
1746 'GetRenderbufferParameteriv': {
1747 'type': 'GETn',
1748 'decoder_func': 'DoGetRenderbufferParameteriv',
1749 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1750 'result': ['SizedResult<GLint>'],
1752 'GetShaderiv': {
1753 'type': 'GETn',
1754 'decoder_func': 'DoGetShaderiv',
1755 'result': ['SizedResult<GLint>'],
1757 'GetShaderInfoLog': {
1758 'type': 'STRn',
1759 'get_len_func': 'glGetShaderiv',
1760 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1761 'unit_test': False,
1763 'GetShaderPrecisionFormat': {
1764 'type': 'Custom',
1765 'immediate': False,
1766 'cmd_args':
1767 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1768 'void* result',
1769 'result': [
1770 'int32 success',
1771 'int32 min_range',
1772 'int32 max_range',
1773 'int32 precision',
1776 'GetShaderSource': {
1777 'type': 'STRn',
1778 'get_len_func': 'DoGetShaderiv',
1779 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1780 'unit_test': False,
1781 'client_test': False,
1783 'GetString': {
1784 'type': 'Custom',
1785 'client_test': False,
1786 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1788 'GetTexParameterfv': {
1789 'type': 'GETn',
1790 'decoder_func': 'DoGetTexParameterfv',
1791 'result': ['SizedResult<GLfloat>']
1793 'GetTexParameteriv': {
1794 'type': 'GETn',
1795 'decoder_func': 'DoGetTexParameteriv',
1796 'result': ['SizedResult<GLint>']
1798 'GetTranslatedShaderSourceANGLE': {
1799 'type': 'STRn',
1800 'get_len_func': 'DoGetShaderiv',
1801 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1802 'unit_test': False,
1803 'extension': True,
1805 'GetUniformfv': {
1806 'type': 'Custom',
1807 'immediate': False,
1808 'result': ['SizedResult<GLfloat>'],
1810 'GetUniformiv': {
1811 'type': 'Custom',
1812 'immediate': False,
1813 'result': ['SizedResult<GLint>'],
1815 'GetUniformLocation': {
1816 'type': 'HandWritten',
1817 'immediate': False,
1818 'bucket': True,
1819 'needs_size': True,
1820 'cmd_args':
1821 'GLidProgram program, const char* name, NonImmediate GLint* location',
1822 'result': ['GLint'],
1823 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1825 'GetVertexAttribfv': {
1826 'type': 'GETn',
1827 'result': ['SizedResult<GLfloat>'],
1828 'impl_decl': False,
1829 'decoder_func': 'DoGetVertexAttribfv',
1830 'expectation': False,
1831 'client_test': False,
1833 'GetVertexAttribiv': {
1834 'type': 'GETn',
1835 'result': ['SizedResult<GLint>'],
1836 'impl_decl': False,
1837 'decoder_func': 'DoGetVertexAttribiv',
1838 'expectation': False,
1839 'client_test': False,
1841 'GetVertexAttribPointerv': {
1842 'type': 'Custom',
1843 'immediate': False,
1844 'result': ['SizedResult<GLuint>'],
1845 'client_test': False,
1847 'IsBuffer': {
1848 'type': 'Is',
1849 'decoder_func': 'DoIsBuffer',
1850 'expectation': False,
1852 'IsEnabled': {
1853 'type': 'Is',
1854 'decoder_func': 'DoIsEnabled',
1855 'impl_func': False,
1856 'expectation': False,
1858 'IsFramebuffer': {
1859 'type': 'Is',
1860 'decoder_func': 'DoIsFramebuffer',
1861 'expectation': False,
1863 'IsProgram': {
1864 'type': 'Is',
1865 'decoder_func': 'DoIsProgram',
1866 'expectation': False,
1868 'IsRenderbuffer': {
1869 'type': 'Is',
1870 'decoder_func': 'DoIsRenderbuffer',
1871 'expectation': False,
1873 'IsShader': {
1874 'type': 'Is',
1875 'decoder_func': 'DoIsShader',
1876 'expectation': False,
1878 'IsTexture': {
1879 'type': 'Is',
1880 'decoder_func': 'DoIsTexture',
1881 'expectation': False,
1883 'LinkProgram': {
1884 'decoder_func': 'DoLinkProgram',
1885 'impl_func': False,
1887 'MapBufferCHROMIUM': {
1888 'gen_cmd': False,
1889 'extension': True,
1890 'chromium': True,
1891 'client_test': False,
1893 'MapBufferSubDataCHROMIUM': {
1894 'gen_cmd': False,
1895 'extension': True,
1896 'chromium': True,
1897 'client_test': False,
1898 'pepper_interface': 'ChromiumMapSub',
1900 'MapImageCHROMIUM': {
1901 'gen_cmd': False,
1902 'extension': True,
1903 'chromium': True,
1904 'client_test': False,
1906 'MapTexSubImage2DCHROMIUM': {
1907 'gen_cmd': False,
1908 'extension': True,
1909 'chromium': True,
1910 'client_test': False,
1911 'pepper_interface': 'ChromiumMapSub',
1913 'PixelStorei': {'type': 'Manual'},
1914 'PostSubBufferCHROMIUM': {
1915 'type': 'Custom',
1916 'impl_func': False,
1917 'unit_test': False,
1918 'client_test': False,
1919 'extension': True,
1920 'chromium': True,
1922 'ProduceTextureCHROMIUM': {
1923 'decoder_func': 'DoProduceTextureCHROMIUM',
1924 'impl_func': False,
1925 'type': 'PUT',
1926 'data_type': 'GLbyte',
1927 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1928 'unit_test': False,
1929 'client_test': False,
1930 'extension': True,
1931 'chromium': True,
1932 'trace_level': 1,
1934 'RenderbufferStorage': {
1935 'decoder_func': 'DoRenderbufferStorage',
1936 'gl_test_func': 'glRenderbufferStorageEXT',
1937 'expectation': False,
1939 'RenderbufferStorageMultisampleCHROMIUM': {
1940 'cmd_comment':
1941 '// GL_CHROMIUM_framebuffer_multisample\n',
1942 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
1943 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
1944 'expectation': False,
1945 'unit_test': False,
1946 'extension': True,
1947 'pepper_interface': 'FramebufferMultisample',
1948 'pepper_name': 'RenderbufferStorageMultisampleEXT',
1950 'RenderbufferStorageMultisampleEXT': {
1951 'cmd_comment':
1952 '// GL_EXT_multisampled_render_to_texture\n',
1953 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
1954 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1955 'expectation': False,
1956 'unit_test': False,
1957 'extension': True,
1959 'ReadPixels': {
1960 'cmd_comment':
1961 '// ReadPixels has the result separated from the pixel buffer so that\n'
1962 '// it is easier to specify the result going to some specific place\n'
1963 '// that exactly fits the rectangle of pixels.\n',
1964 'type': 'Custom',
1965 'immediate': False,
1966 'impl_func': False,
1967 'client_test': False,
1968 'cmd_args':
1969 'GLint x, GLint y, GLsizei width, GLsizei height, '
1970 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1971 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1972 'uint32 result_shm_id, uint32 result_shm_offset, '
1973 'GLboolean async',
1974 'result': ['uint32'],
1975 'defer_reads': True,
1977 'RegisterSharedIdsCHROMIUM': {
1978 'type': 'Custom',
1979 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1980 'impl_func': False,
1981 'expectation': False,
1982 'immediate': False,
1983 'extension': True,
1984 'chromium': True,
1986 'ReleaseShaderCompiler': {
1987 'decoder_func': 'DoReleaseShaderCompiler',
1988 'unit_test': False,
1990 'ShaderBinary': {
1991 'type': 'Custom',
1992 'client_test': False,
1994 'ShaderSource': {
1995 'type': 'Manual',
1996 'immediate': False,
1997 'bucket': True,
1998 'needs_size': True,
1999 'client_test': False,
2000 'cmd_args':
2001 'GLuint shader, const char* data',
2002 'pepper_args':
2003 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2005 'StencilMask': {
2006 'type': 'StateSetFrontBack',
2007 'state': 'StencilMask',
2008 'no_gl': True,
2009 'expectation': False,
2011 'StencilMaskSeparate': {
2012 'type': 'StateSetFrontBackSeparate',
2013 'state': 'StencilMask',
2014 'no_gl': True,
2015 'expectation': False,
2017 'SwapBuffers': {
2018 'impl_func': False,
2019 'decoder_func': 'DoSwapBuffers',
2020 'unit_test': False,
2021 'client_test': False,
2022 'extension': True,
2023 'trace_level': 1,
2025 'TexImage2D': {
2026 'type': 'Manual',
2027 'immediate': False,
2028 'client_test': False,
2030 'TexParameterf': {
2031 'decoder_func': 'DoTexParameterf',
2032 'gl_test_func': 'glTexParameteri',
2033 'valid_args': {
2034 '2': 'GL_NEAREST'
2037 'TexParameteri': {
2038 'decoder_func': 'DoTexParameteri',
2039 'valid_args': {
2040 '2': 'GL_NEAREST'
2043 'TexParameterfv': {
2044 'type': 'PUT',
2045 'data_type': 'GLfloat',
2046 'data_value': 'GL_NEAREST',
2047 'count': 1,
2048 'decoder_func': 'DoTexParameterfv',
2049 'gl_test_func': 'glTexParameteri',
2050 'first_element_only': True,
2052 'TexParameteriv': {
2053 'type': 'PUT',
2054 'data_type': 'GLint',
2055 'data_value': 'GL_NEAREST',
2056 'count': 1,
2057 'decoder_func': 'DoTexParameteriv',
2058 'gl_test_func': 'glTexParameteri',
2059 'first_element_only': True,
2061 'TexSubImage2D': {
2062 'type': 'Manual',
2063 'immediate': False,
2064 'client_test': False,
2065 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2066 'GLint xoffset, GLint yoffset, '
2067 'GLsizei width, GLsizei height, '
2068 'GLenumTextureFormat format, GLenumPixelType type, '
2069 'const void* pixels, GLboolean internal'
2071 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2072 'Uniform1fv': {
2073 'type': 'PUTn',
2074 'data_type': 'GLfloat',
2075 'count': 1,
2076 'decoder_func': 'DoUniform1fv',
2078 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2079 'Uniform1iv': {
2080 'type': 'PUTn',
2081 'data_type': 'GLint',
2082 'count': 1,
2083 'decoder_func': 'DoUniform1iv',
2084 'unit_test': False,
2086 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2087 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2088 'Uniform2fv': {
2089 'type': 'PUTn',
2090 'data_type': 'GLfloat',
2091 'count': 2,
2092 'decoder_func': 'DoUniform2fv',
2094 'Uniform2iv': {
2095 'type': 'PUTn',
2096 'data_type': 'GLint',
2097 'count': 2,
2098 'decoder_func': 'DoUniform2iv',
2100 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2101 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2102 'Uniform3fv': {
2103 'type': 'PUTn',
2104 'data_type': 'GLfloat',
2105 'count': 3,
2106 'decoder_func': 'DoUniform3fv',
2108 'Uniform3iv': {
2109 'type': 'PUTn',
2110 'data_type': 'GLint',
2111 'count': 3,
2112 'decoder_func': 'DoUniform3iv',
2114 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2115 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2116 'Uniform4fv': {
2117 'type': 'PUTn',
2118 'data_type': 'GLfloat',
2119 'count': 4,
2120 'decoder_func': 'DoUniform4fv',
2122 'Uniform4iv': {
2123 'type': 'PUTn',
2124 'data_type': 'GLint',
2125 'count': 4,
2126 'decoder_func': 'DoUniform4iv',
2128 'UniformMatrix2fv': {
2129 'type': 'PUTn',
2130 'data_type': 'GLfloat',
2131 'count': 4,
2132 'decoder_func': 'DoUniformMatrix2fv',
2134 'UniformMatrix3fv': {
2135 'type': 'PUTn',
2136 'data_type': 'GLfloat',
2137 'count': 9,
2138 'decoder_func': 'DoUniformMatrix3fv',
2140 'UniformMatrix4fv': {
2141 'type': 'PUTn',
2142 'data_type': 'GLfloat',
2143 'count': 16,
2144 'decoder_func': 'DoUniformMatrix4fv',
2146 'UnmapBufferCHROMIUM': {
2147 'gen_cmd': False,
2148 'extension': True,
2149 'chromium': True,
2150 'client_test': False,
2152 'UnmapBufferSubDataCHROMIUM': {
2153 'gen_cmd': False,
2154 'extension': True,
2155 'chromium': True,
2156 'client_test': False,
2157 'pepper_interface': 'ChromiumMapSub',
2159 'UnmapImageCHROMIUM': {
2160 'gen_cmd': False,
2161 'extension': True,
2162 'chromium': True,
2163 'client_test': False,
2165 'UnmapTexSubImage2DCHROMIUM': {
2166 'gen_cmd': False,
2167 'extension': True,
2168 'chromium': True,
2169 'client_test': False,
2170 'pepper_interface': 'ChromiumMapSub',
2172 'UseProgram': {
2173 'decoder_func': 'DoUseProgram',
2174 'impl_func': False,
2175 'unit_test': False,
2177 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2178 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2179 'VertexAttrib1fv': {
2180 'type': 'PUT',
2181 'data_type': 'GLfloat',
2182 'count': 1,
2183 'decoder_func': 'DoVertexAttrib1fv',
2185 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2186 'VertexAttrib2fv': {
2187 'type': 'PUT',
2188 'data_type': 'GLfloat',
2189 'count': 2,
2190 'decoder_func': 'DoVertexAttrib2fv',
2192 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2193 'VertexAttrib3fv': {
2194 'type': 'PUT',
2195 'data_type': 'GLfloat',
2196 'count': 3,
2197 'decoder_func': 'DoVertexAttrib3fv',
2199 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2200 'VertexAttrib4fv': {
2201 'type': 'PUT',
2202 'data_type': 'GLfloat',
2203 'count': 4,
2204 'decoder_func': 'DoVertexAttrib4fv',
2206 'VertexAttribPointer': {
2207 'type': 'Manual',
2208 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2209 'GLenumVertexAttribType type, GLboolean normalized, '
2210 'GLsizei stride, GLuint offset',
2211 'client_test': False,
2213 'Scissor': {
2214 'type': 'StateSet',
2215 'state': 'Scissor',
2217 'Viewport': {
2218 'decoder_func': 'DoViewport',
2220 'ResizeCHROMIUM': {
2221 'type': 'Custom',
2222 'impl_func': False,
2223 'unit_test': False,
2224 'extension': True,
2225 'chromium': True,
2227 'GetRequestableExtensionsCHROMIUM': {
2228 'type': 'Custom',
2229 'impl_func': False,
2230 'immediate': False,
2231 'cmd_args': 'uint32 bucket_id',
2232 'extension': True,
2233 'chromium': True,
2235 'RequestExtensionCHROMIUM': {
2236 'type': 'Custom',
2237 'impl_func': False,
2238 'immediate': False,
2239 'client_test': False,
2240 'cmd_args': 'uint32 bucket_id',
2241 'extension': True,
2242 'chromium': True,
2244 'RateLimitOffscreenContextCHROMIUM': {
2245 'gen_cmd': False,
2246 'extension': True,
2247 'chromium': True,
2248 'client_test': False,
2250 'CreateStreamTextureCHROMIUM': {
2251 'type': 'HandWritten',
2252 'impl_func': False,
2253 'gen_cmd': False,
2254 'immediate': False,
2255 'extension': True,
2256 'chromium': True,
2258 'TexImageIOSurface2DCHROMIUM': {
2259 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2260 'unit_test': False,
2261 'extension': True,
2262 'chromium': True,
2264 'CopyTextureCHROMIUM': {
2265 'decoder_func': 'DoCopyTextureCHROMIUM',
2266 'unit_test': False,
2267 'extension': True,
2268 'chromium': True,
2270 'TexStorage2DEXT': {
2271 'unit_test': False,
2272 'extension': True,
2273 'decoder_func': 'DoTexStorage2DEXT',
2275 'DrawArraysInstancedANGLE': {
2276 'type': 'Manual',
2277 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2278 'GLsizei primcount',
2279 'extension': True,
2280 'unit_test': False,
2281 'pepper_interface': 'InstancedArrays',
2282 'defer_draws': True,
2284 'DrawBuffersEXT': {
2285 'type': 'PUTn',
2286 'decoder_func': 'DoDrawBuffersEXT',
2287 'data_type': 'GLenum',
2288 'count': 1,
2289 'client_test': False,
2290 'unit_test': False,
2291 'extension': True,
2293 'DrawElementsInstancedANGLE': {
2294 'type': 'Manual',
2295 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2296 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2297 'extension': True,
2298 'unit_test': False,
2299 'client_test': False,
2300 'pepper_interface': 'InstancedArrays',
2301 'defer_draws': True,
2303 'VertexAttribDivisorANGLE': {
2304 'type': 'Manual',
2305 'cmd_args': 'GLuint index, GLuint divisor',
2306 'extension': True,
2307 'unit_test': False,
2308 'pepper_interface': 'InstancedArrays',
2310 'GenQueriesEXT': {
2311 'type': 'GENn',
2312 'gl_test_func': 'glGenQueriesARB',
2313 'resource_type': 'Query',
2314 'resource_types': 'Queries',
2315 'unit_test': False,
2316 'pepper_interface': 'Query',
2318 'DeleteQueriesEXT': {
2319 'type': 'DELn',
2320 'gl_test_func': 'glDeleteQueriesARB',
2321 'resource_type': 'Query',
2322 'resource_types': 'Queries',
2323 'unit_test': False,
2324 'pepper_interface': 'Query',
2326 'IsQueryEXT': {
2327 'gen_cmd': False,
2328 'client_test': False,
2329 'pepper_interface': 'Query',
2331 'BeginQueryEXT': {
2332 'type': 'Manual',
2333 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2334 'immediate': False,
2335 'gl_test_func': 'glBeginQuery',
2336 'pepper_interface': 'Query',
2338 'EndQueryEXT': {
2339 'type': 'Manual',
2340 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2341 'gl_test_func': 'glEndnQuery',
2342 'client_test': False,
2343 'pepper_interface': 'Query',
2345 'GetQueryivEXT': {
2346 'gen_cmd': False,
2347 'client_test': False,
2348 'gl_test_func': 'glGetQueryiv',
2349 'pepper_interface': 'Query',
2351 'GetQueryObjectuivEXT': {
2352 'gen_cmd': False,
2353 'client_test': False,
2354 'gl_test_func': 'glGetQueryObjectuiv',
2355 'pepper_interface': 'Query',
2357 'BindUniformLocationCHROMIUM': {
2358 'type': 'GLchar',
2359 'extension': True,
2360 'bucket': True,
2361 'needs_size': True,
2362 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2363 'immediate': False,
2365 'InsertEventMarkerEXT': {
2366 'type': 'GLcharN',
2367 'decoder_func': 'DoInsertEventMarkerEXT',
2368 'expectation': False,
2369 'extension': True,
2371 'PushGroupMarkerEXT': {
2372 'type': 'GLcharN',
2373 'decoder_func': 'DoPushGroupMarkerEXT',
2374 'expectation': False,
2375 'extension': True,
2377 'PopGroupMarkerEXT': {
2378 'decoder_func': 'DoPopGroupMarkerEXT',
2379 'expectation': False,
2380 'extension': True,
2381 'impl_func': False,
2384 'GenVertexArraysOES': {
2385 'type': 'GENn',
2386 'extension': True,
2387 'gl_test_func': 'glGenVertexArraysOES',
2388 'resource_type': 'VertexArray',
2389 'resource_types': 'VertexArrays',
2390 'unit_test': False,
2392 'BindVertexArrayOES': {
2393 'type': 'Bind',
2394 'extension': True,
2395 'gl_test_func': 'glBindVertexArrayOES',
2396 'decoder_func': 'DoBindVertexArrayOES',
2397 'gen_func': 'GenVertexArraysOES',
2398 'unit_test': False,
2399 'client_test': False,
2401 'DeleteVertexArraysOES': {
2402 'type': 'DELn',
2403 'extension': True,
2404 'gl_test_func': 'glDeleteVertexArraysOES',
2405 'resource_type': 'VertexArray',
2406 'resource_types': 'VertexArrays',
2407 'unit_test': False,
2409 'IsVertexArrayOES': {
2410 'type': 'Is',
2411 'extension': True,
2412 'gl_test_func': 'glIsVertexArrayOES',
2413 'decoder_func': 'DoIsVertexArrayOES',
2414 'expectation': False,
2415 'unit_test': False,
2417 'BindTexImage2DCHROMIUM': {
2418 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2419 'unit_test': False,
2420 'extension': True,
2421 'chromium': True,
2423 'ReleaseTexImage2DCHROMIUM': {
2424 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2425 'unit_test': False,
2426 'extension': True,
2427 'chromium': True,
2429 'ShallowFinishCHROMIUM': {
2430 'impl_func': False,
2431 'gen_cmd': False,
2432 'extension': True,
2433 'chromium': True,
2434 'client_test': False,
2436 'ShallowFlushCHROMIUM': {
2437 'impl_func': False,
2438 'gen_cmd': False,
2439 'extension': True,
2440 'chromium': True,
2441 'client_test': False,
2443 'TraceBeginCHROMIUM': {
2444 'type': 'Custom',
2445 'impl_func': False,
2446 'immediate': False,
2447 'client_test': False,
2448 'cmd_args': 'GLuint bucket_id',
2449 'extension': True,
2450 'chromium': True,
2452 'TraceEndCHROMIUM': {
2453 'impl_func': False,
2454 'immediate': False,
2455 'client_test': False,
2456 'decoder_func': 'DoTraceEndCHROMIUM',
2457 'unit_test': False,
2458 'extension': True,
2459 'chromium': True,
2461 'AsyncTexImage2DCHROMIUM': {
2462 'type': 'Manual',
2463 'immediate': False,
2464 'client_test': False,
2465 'extension': True,
2466 'chromium': True,
2468 'AsyncTexSubImage2DCHROMIUM': {
2469 'type': 'Manual',
2470 'immediate': False,
2471 'client_test': False,
2472 'extension': True,
2473 'chromium': True,
2475 'WaitAsyncTexImage2DCHROMIUM': {
2476 'type': 'Manual',
2477 'immediate': False,
2478 'client_test': False,
2479 'extension': True,
2480 'chromium': True,
2482 'DiscardFramebufferEXT': {
2483 'type': 'PUTn',
2484 'count': 1,
2485 'data_type': 'GLenum',
2486 'cmd_args': 'GLenum target, GLsizei count, '
2487 'const GLenum* attachments',
2488 'decoder_func': 'DoDiscardFramebufferEXT',
2489 'unit_test': False,
2490 'client_test': False,
2491 'extension': True,
2493 'LoseContextCHROMIUM': {
2494 'type': 'Manual',
2495 'impl_func': True,
2496 'extension': True,
2497 'chromium': True,
2499 'InsertSyncPointCHROMIUM': {
2500 'type': 'HandWritten',
2501 'impl_func': False,
2502 'extension': True,
2503 'chromium': True,
2505 'WaitSyncPointCHROMIUM': {
2506 'type': 'Custom',
2507 'impl_func': True,
2508 'extension': True,
2509 'chromium': True,
2510 'trace_level': 1,
2512 'DiscardBackbufferCHROMIUM': {
2513 'type': 'Custom',
2514 'impl_func': True,
2515 'extension': True,
2516 'chromium': True,
2521 def Grouper(n, iterable, fillvalue=None):
2522 """Collect data into fixed-length chunks or blocks"""
2523 args = [iter(iterable)] * n
2524 return itertools.izip_longest(fillvalue=fillvalue, *args)
2527 def SplitWords(input_string):
2528 """Transforms a input_string into a list of lower-case components.
2530 Args:
2531 input_string: the input string.
2533 Returns:
2534 a list of lower-case words.
2536 if input_string.find('_') > -1:
2537 # 'some_TEXT_' -> 'some text'
2538 return input_string.replace('_', ' ').strip().lower().split()
2539 else:
2540 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
2541 # mixed case.
2542 # look for capitalization to cut input_strings
2543 # 'SomeText' -> 'Some Text'
2544 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
2545 # 'Vector3' -> 'Vector 3'
2546 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
2547 return input_string.lower().split()
2550 def Lower(words):
2551 """Makes a lower-case identifier from words.
2553 Args:
2554 words: a list of lower-case words.
2556 Returns:
2557 the lower-case identifier.
2559 return '_'.join(words)
2562 def ToUnderscore(input_string):
2563 """converts CamelCase to camel_case."""
2564 words = SplitWords(input_string)
2565 return Lower(words)
2568 class CWriter(object):
2569 """Writes to a file formatting it for Google's style guidelines."""
2571 def __init__(self, filename):
2572 self.filename = filename
2573 self.file_num = 0
2574 self.content = []
2576 def SetFileNum(self, num):
2577 """Used to help write number files and tests."""
2578 self.file_num = num
2580 def Write(self, string):
2581 """Writes a string to a file spliting if it's > 80 characters."""
2582 lines = string.splitlines()
2583 num_lines = len(lines)
2584 for ii in range(0, num_lines):
2585 self.__WriteLine(lines[ii], ii < (num_lines - 1) or string[-1] == '\n')
2587 def __FindSplit(self, string):
2588 """Finds a place to split a string."""
2589 splitter = string.find('=')
2590 if splitter >= 1 and not string[splitter + 1] == '=' and splitter < 80:
2591 return splitter
2592 # parts = string.split('(')
2593 parts = re.split("(?<=[^\"])\((?!\")", string)
2594 fptr = re.compile('\*\w*\)')
2595 if len(parts) > 1:
2596 splitter = len(parts[0])
2597 for ii in range(1, len(parts)):
2598 # Don't split on the dot in "if (.condition)".
2599 if (not parts[ii - 1][-3:] == "if " and
2600 # Don't split "(.)" or "(.*fptr)".
2601 (len(parts[ii]) > 0 and
2602 not parts[ii][0] == ")" and not fptr.match(parts[ii]))
2603 and splitter < 80):
2604 return splitter
2605 splitter += len(parts[ii]) + 1
2606 done = False
2607 end = len(string)
2608 last_splitter = -1
2609 while not done:
2610 splitter = string[0:end].rfind(',')
2611 if splitter < 0 or (splitter > 0 and string[splitter - 1] == '"'):
2612 return last_splitter
2613 elif splitter >= 80:
2614 end = splitter
2615 else:
2616 return splitter
2618 def __WriteLine(self, line, ends_with_eol):
2619 """Given a signle line, writes it to a file, splitting if it's > 80 chars"""
2620 if len(line) >= 80:
2621 i = self.__FindSplit(line)
2622 if i > 0:
2623 line1 = line[0:i + 1]
2624 if line1[-1] == ' ':
2625 line1 = line1[:-1]
2626 lineend = ''
2627 if line1[0] == '#':
2628 lineend = ' \\'
2629 nolint = ''
2630 if len(line1) > 80:
2631 nolint = ' // NOLINT'
2632 self.__AddLine(line1 + nolint + lineend + '\n')
2633 match = re.match("( +)", line1)
2634 indent = ""
2635 if match:
2636 indent = match.group(1)
2637 splitter = line[i]
2638 if not splitter == ',':
2639 indent = " " + indent
2640 self.__WriteLine(indent + line[i + 1:].lstrip(), True)
2641 return
2642 nolint = ''
2643 if len(line) > 80:
2644 nolint = ' // NOLINT'
2645 self.__AddLine(line + nolint)
2646 if ends_with_eol:
2647 self.__AddLine('\n')
2649 def __AddLine(self, line):
2650 self.content.append(line)
2652 def Close(self):
2653 """Close the file."""
2654 content = "".join(self.content)
2655 write_file = True
2656 if os.path.exists(self.filename):
2657 old_file = open(self.filename, "rb");
2658 old_content = old_file.read()
2659 old_file.close();
2660 if content == old_content:
2661 write_file = False
2662 if write_file:
2663 file = open(self.filename, "wb")
2664 file.write(content)
2665 file.close()
2668 class CHeaderWriter(CWriter):
2669 """Writes a C Header file."""
2671 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
2673 def __init__(self, filename, file_comment = None):
2674 CWriter.__init__(self, filename)
2676 base = os.path.abspath(filename)
2677 while os.path.basename(base) != 'src':
2678 new_base = os.path.dirname(base)
2679 assert new_base != base # Prevent infinite loop.
2680 base = new_base
2682 hpath = os.path.relpath(filename, base)
2683 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
2685 self.Write(_LICENSE)
2686 self.Write(_DO_NOT_EDIT_WARNING)
2687 if not file_comment == None:
2688 self.Write(file_comment)
2689 self.Write("#ifndef %s\n" % self.guard)
2690 self.Write("#define %s\n\n" % self.guard)
2692 def Close(self):
2693 self.Write("#endif // %s\n\n" % self.guard)
2694 CWriter.Close(self)
2696 class TypeHandler(object):
2697 """This class emits code for a particular type of function."""
2699 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
2701 def __init__(self):
2702 pass
2704 def InitFunction(self, func):
2705 """Add or adjust anything type specific for this function."""
2706 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
2707 func.AddCmdArg(DataSizeArgument('data_size'))
2709 def AddImmediateFunction(self, generator, func):
2710 """Adds an immediate version of a function."""
2711 # Generate an immediate command if there is only 1 pointer arg.
2712 immediate = func.GetInfo('immediate') # can be True, False or None
2713 if immediate == True or immediate == None:
2714 if func.num_pointer_args == 1 or immediate:
2715 generator.AddFunction(ImmediateFunction(func))
2717 def AddBucketFunction(self, generator, func):
2718 """Adds a bucket version of a function."""
2719 # Generate an immediate command if there is only 1 pointer arg.
2720 bucket = func.GetInfo('bucket') # can be True, False or None
2721 if bucket:
2722 generator.AddFunction(BucketFunction(func))
2724 def WriteStruct(self, func, file):
2725 """Writes a structure that matches the arguments to a function."""
2726 comment = func.GetInfo('cmd_comment')
2727 if not comment == None:
2728 file.Write(comment)
2729 file.Write("struct %s {\n" % func.name)
2730 file.Write(" typedef %s ValueType;\n" % func.name)
2731 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
2732 func.WriteCmdArgFlag(file)
2733 func.WriteCmdFlag(file)
2734 file.Write("\n")
2735 result = func.GetInfo('result')
2736 if not result == None:
2737 if len(result) == 1:
2738 file.Write(" typedef %s Result;\n\n" % result[0])
2739 else:
2740 file.Write(" struct Result {\n")
2741 for line in result:
2742 file.Write(" %s;\n" % line)
2743 file.Write(" };\n\n")
2745 func.WriteCmdComputeSize(file)
2746 func.WriteCmdSetHeader(file)
2747 func.WriteCmdInit(file)
2748 func.WriteCmdSet(file)
2750 file.Write(" gpu::CommandHeader header;\n")
2751 args = func.GetCmdArgs()
2752 for arg in args:
2753 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
2754 file.Write("};\n")
2755 file.Write("\n")
2757 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
2758 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func.name, size))
2759 file.Write(" Sizeof_%s_is_not_%d);\n" % (func.name, size))
2760 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func.name)
2761 file.Write(" OffsetOf_%s_header_not_0);\n" % func.name)
2762 offset = _SIZE_OF_COMMAND_HEADER
2763 for arg in args:
2764 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2765 (func.name, arg.name, offset))
2766 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2767 (func.name, arg.name, offset))
2768 offset += _SIZE_OF_UINT32
2769 if not result == None and len(result) > 1:
2770 offset = 0;
2771 for line in result:
2772 parts = line.split()
2773 name = parts[-1]
2774 check = """
2775 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2776 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2778 file.Write((check.strip() + "\n") % {
2779 'cmd_name': func.name,
2780 'field_name': name,
2781 'offset': offset,
2783 offset += _SIZE_OF_UINT32
2784 file.Write("\n")
2786 def WriteHandlerImplementation(self, func, file):
2787 """Writes the handler implementation for this command."""
2788 file.Write(" %s(%s);\n" %
2789 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2791 def WriteCmdSizeTest(self, func, file):
2792 """Writes the size test for a command."""
2793 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2795 def WriteFormatTest(self, func, file):
2796 """Writes a format test for a command."""
2797 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
2798 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2799 (func.name, func.name))
2800 file.Write(" void* next_cmd = cmd.Set(\n")
2801 file.Write(" &cmd")
2802 args = func.GetCmdArgs()
2803 for value, arg in enumerate(args):
2804 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
2805 file.Write(");\n")
2806 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2807 func.name)
2808 file.Write(" cmd.header.command);\n")
2809 func.type_handler.WriteCmdSizeTest(func, file)
2810 for value, arg in enumerate(args):
2811 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2812 (arg.type, value + 11, arg.name))
2813 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2814 file.Write(" next_cmd, sizeof(cmd));\n")
2815 file.Write("}\n")
2816 file.Write("\n")
2818 def WriteImmediateFormatTest(self, func, file):
2819 """Writes a format test for an immediate version of a command."""
2820 pass
2822 def WriteBucketFormatTest(self, func, file):
2823 """Writes a format test for a bucket version of a command."""
2824 pass
2826 def WriteGetDataSizeCode(self, func, file):
2827 """Writes the code to set data_size used in validation"""
2828 pass
2830 def WriteImmediateCmdSizeTest(self, func, file):
2831 """Writes a size test for an immediate version of a command."""
2832 file.Write(" // TODO(gman): Compute correct size.\n")
2833 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2835 def WriteImmediateHandlerImplementation (self, func, file):
2836 """Writes the handler impl for the immediate version of a command."""
2837 file.Write(" %s(%s);\n" %
2838 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2840 def WriteBucketHandlerImplementation (self, func, file):
2841 """Writes the handler impl for the bucket version of a command."""
2842 file.Write(" %s(%s);\n" %
2843 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2845 def WriteServiceImplementation(self, func, file):
2846 """Writes the service implementation for a command."""
2847 file.Write(
2848 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2849 file.Write(
2850 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2851 func.name)
2852 self.WriteHandlerDeferReadWrite(func, file);
2853 if len(func.GetOriginalArgs()) > 0:
2854 last_arg = func.GetLastOriginalArg()
2855 all_but_last_arg = func.GetOriginalArgs()[:-1]
2856 for arg in all_but_last_arg:
2857 arg.WriteGetCode(file)
2858 self.WriteGetDataSizeCode(func, file)
2859 last_arg.WriteGetCode(file)
2860 func.WriteHandlerValidation(file)
2861 func.WriteHandlerImplementation(file)
2862 file.Write(" return error::kNoError;\n")
2863 file.Write("}\n")
2864 file.Write("\n")
2866 def WriteImmediateServiceImplementation(self, func, file):
2867 """Writes the service implementation for an immediate version of command."""
2868 file.Write(
2869 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2870 file.Write(
2871 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2872 func.name)
2873 self.WriteHandlerDeferReadWrite(func, file);
2874 last_arg = func.GetLastOriginalArg()
2875 all_but_last_arg = func.GetOriginalArgs()[:-1]
2876 for arg in all_but_last_arg:
2877 arg.WriteGetCode(file)
2878 self.WriteGetDataSizeCode(func, file)
2879 last_arg.WriteGetCode(file)
2880 func.WriteHandlerValidation(file)
2881 func.WriteHandlerImplementation(file)
2882 file.Write(" return error::kNoError;\n")
2883 file.Write("}\n")
2884 file.Write("\n")
2886 def WriteBucketServiceImplementation(self, func, file):
2887 """Writes the service implementation for a bucket version of command."""
2888 file.Write(
2889 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2890 file.Write(
2891 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2892 func.name)
2893 self.WriteHandlerDeferReadWrite(func, file);
2894 last_arg = func.GetLastOriginalArg()
2895 all_but_last_arg = func.GetOriginalArgs()[:-1]
2896 for arg in all_but_last_arg:
2897 arg.WriteGetCode(file)
2898 self.WriteGetDataSizeCode(func, file)
2899 last_arg.WriteGetCode(file)
2900 func.WriteHandlerValidation(file)
2901 func.WriteHandlerImplementation(file)
2902 file.Write(" return error::kNoError;\n")
2903 file.Write("}\n")
2904 file.Write("\n")
2906 def WriteHandlerDeferReadWrite(self, func, file):
2907 """Writes the code to handle deferring reads or writes."""
2908 defer_draws = func.GetInfo('defer_draws')
2909 defer_reads = func.GetInfo('defer_reads')
2910 if defer_draws or defer_reads:
2911 file.Write(" error::Error error;\n")
2912 if defer_draws:
2913 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2914 file.Write(" if (error != error::kNoError)\n")
2915 file.Write(" return error;\n")
2916 if defer_reads:
2917 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2918 file.Write(" if (error != error::kNoError)\n")
2919 file.Write(" return error;\n")
2921 def WriteValidUnitTest(self, func, file, test, extra = {}):
2922 """Writes a valid unit test."""
2923 if func.GetInfo('expectation') == False:
2924 test = self._remove_expected_call_re.sub('', test)
2925 name = func.name
2926 arg_strings = []
2927 for count, arg in enumerate(func.GetOriginalArgs()):
2928 arg_strings.append(arg.GetValidArg(func, count, 0))
2929 gl_arg_strings = []
2930 for count, arg in enumerate(func.GetOriginalArgs()):
2931 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
2932 gl_func_name = func.GetGLTestFunctionName()
2933 vars = {
2934 'test_name': 'GLES2DecoderTest%d' % file.file_num,
2935 'name':name,
2936 'gl_func_name': gl_func_name,
2937 'args': ", ".join(arg_strings),
2938 'gl_args': ", ".join(gl_arg_strings),
2940 vars.update(extra)
2941 old_test = ""
2942 while (old_test != test):
2943 old_test = test
2944 test = test % vars
2945 file.Write(test % vars)
2947 def WriteInvalidUnitTest(self, func, file, test, extra = {}):
2948 """Writes a invalid unit test."""
2949 for arg_index, arg in enumerate(func.GetOriginalArgs()):
2950 num_invalid_values = arg.GetNumInvalidValues(func)
2951 for value_index in range(0, num_invalid_values):
2952 arg_strings = []
2953 parse_result = "kNoError"
2954 gl_error = None
2955 for count, arg in enumerate(func.GetOriginalArgs()):
2956 if count == arg_index:
2957 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
2958 count, value_index)
2959 else:
2960 arg_string = arg.GetValidArg(func, count, 0)
2961 arg_strings.append(arg_string)
2962 gl_arg_strings = []
2963 for arg in func.GetOriginalArgs():
2964 gl_arg_strings.append("_")
2965 gl_func_name = func.GetGLTestFunctionName()
2966 gl_error_test = ''
2967 if not gl_error == None:
2968 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2970 vars = {
2971 'test_name': 'GLES2DecoderTest%d' % file.file_num ,
2972 'name': func.name,
2973 'arg_index': arg_index,
2974 'value_index': value_index,
2975 'gl_func_name': gl_func_name,
2976 'args': ", ".join(arg_strings),
2977 'all_but_last_args': ", ".join(arg_strings[:-1]),
2978 'gl_args': ", ".join(gl_arg_strings),
2979 'parse_result': parse_result,
2980 'gl_error_test': gl_error_test,
2982 vars.update(extra)
2983 file.Write(test % vars)
2985 def WriteServiceUnitTest(self, func, file):
2986 """Writes the service unit test for a command."""
2987 valid_test = """
2988 TEST_F(%(test_name)s, %(name)sValidArgs) {
2989 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2990 SpecializedSetup<cmds::%(name)s, 0>(true);
2991 cmds::%(name)s cmd;
2992 cmd.Init(%(args)s);
2993 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2994 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2997 self.WriteValidUnitTest(func, file, valid_test)
2999 invalid_test = """
3000 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3001 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3002 SpecializedSetup<cmds::%(name)s, 0>(false);
3003 cmds::%(name)s cmd;
3004 cmd.Init(%(args)s);
3005 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3008 self.WriteInvalidUnitTest(func, file, invalid_test)
3010 def WriteImmediateServiceUnitTest(self, func, file):
3011 """Writes the service unit test for an immediate command."""
3012 file.Write("// TODO(gman): %s\n" % func.name)
3014 def WriteImmediateValidationCode(self, func, file):
3015 """Writes the validation code for an immediate version of a command."""
3016 pass
3018 def WriteBucketServiceUnitTest(self, func, file):
3019 """Writes the service unit test for a bucket command."""
3020 file.Write("// TODO(gman): %s\n" % func.name)
3022 def WriteBucketValidationCode(self, func, file):
3023 """Writes the validation code for a bucket version of a command."""
3024 file.Write("// TODO(gman): %s\n" % func.name)
3026 def WriteGLES2ImplementationDeclaration(self, func, file):
3027 """Writes the GLES2 Implemention declaration."""
3028 impl_decl = func.GetInfo('impl_decl')
3029 if impl_decl == None or impl_decl == True:
3030 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3031 (func.return_type, func.original_name,
3032 func.MakeTypedOriginalArgString("")))
3033 file.Write("\n")
3035 def WriteGLES2CLibImplementation(self, func, file):
3036 file.Write("%s GLES2%s(%s) {\n" %
3037 (func.return_type, func.name,
3038 func.MakeTypedOriginalArgString("")))
3039 result_string = "return "
3040 if func.return_type == "void":
3041 result_string = ""
3042 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3043 (result_string, func.original_name,
3044 func.MakeOriginalArgString("")))
3045 file.Write("}\n")
3047 def WriteGLES2Header(self, func, file):
3048 """Writes a re-write macro for GLES"""
3049 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
3051 def WriteClientGLCallLog(self, func, file):
3052 """Writes a logging macro for the client side code."""
3053 comma = ""
3054 if len(func.GetOriginalArgs()):
3055 comma = " << "
3056 file.Write(
3057 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3058 (func.original_name, comma, func.MakeLogArgString()))
3060 def WriteClientGLReturnLog(self, func, file):
3061 """Writes the return value logging code."""
3062 if func.return_type != "void":
3063 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3065 def WriteGLES2ImplementationHeader(self, func, file):
3066 """Writes the GLES2 Implemention."""
3067 self.WriteGLES2ImplementationDeclaration(func, file)
3069 def WriteGLES2TraceImplementationHeader(self, func, file):
3070 """Writes the GLES2 Trace Implemention header."""
3071 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3072 (func.return_type, func.original_name,
3073 func.MakeTypedOriginalArgString("")))
3075 def WriteGLES2TraceImplementation(self, func, file):
3076 """Writes the GLES2 Trace Implemention."""
3077 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3078 (func.return_type, func.original_name,
3079 func.MakeTypedOriginalArgString("")))
3080 result_string = "return "
3081 if func.return_type == "void":
3082 result_string = ""
3083 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3084 func.name)
3085 file.Write(" %sgl_->%s(%s);\n" %
3086 (result_string, func.name, func.MakeOriginalArgString("")))
3087 file.Write("}\n")
3088 file.Write("\n")
3090 def WriteGLES2Implementation(self, func, file):
3091 """Writes the GLES2 Implemention."""
3092 impl_func = func.GetInfo('impl_func')
3093 impl_decl = func.GetInfo('impl_decl')
3094 gen_cmd = func.GetInfo('gen_cmd')
3095 if (func.can_auto_generate and
3096 (impl_func == None or impl_func == True) and
3097 (impl_decl == None or impl_decl == True) and
3098 (gen_cmd == None or gen_cmd == True)):
3099 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3100 (func.return_type, func.original_name,
3101 func.MakeTypedOriginalArgString("")))
3102 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3103 self.WriteClientGLCallLog(func, file)
3104 func.WriteDestinationInitalizationValidation(file)
3105 for arg in func.GetOriginalArgs():
3106 arg.WriteClientSideValidationCode(file, func)
3107 file.Write(" helper_->%s(%s);\n" %
3108 (func.name, func.MakeOriginalArgString("")))
3109 file.Write(" CheckGLError();\n")
3110 self.WriteClientGLReturnLog(func, file)
3111 file.Write("}\n")
3112 file.Write("\n")
3114 def WriteGLES2InterfaceHeader(self, func, file):
3115 """Writes the GLES2 Interface."""
3116 file.Write("virtual %s %s(%s) = 0;\n" %
3117 (func.return_type, func.original_name,
3118 func.MakeTypedOriginalArgString("")))
3120 def WriteGLES2InterfaceStub(self, func, file):
3121 """Writes the GLES2 Interface stub declaration."""
3122 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3123 (func.return_type, func.original_name,
3124 func.MakeTypedOriginalArgString("")))
3126 def WriteGLES2InterfaceStubImpl(self, func, file):
3127 """Writes the GLES2 Interface stub declaration."""
3128 args = func.GetOriginalArgs()
3129 arg_string = ", ".join(
3130 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
3131 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3132 (func.return_type, func.original_name, arg_string))
3133 if func.return_type != "void":
3134 file.Write(" return 0;\n")
3135 file.Write("}\n")
3137 def WriteGLES2ImplementationUnitTest(self, func, file):
3138 """Writes the GLES2 Implemention unit test."""
3139 client_test = func.GetInfo('client_test')
3140 if (func.can_auto_generate and
3141 (client_test == None or client_test == True)):
3142 code = """
3143 TEST_F(GLES2ImplementationTest, %(name)s) {
3144 struct Cmds {
3145 cmds::%(name)s cmd;
3147 Cmds expected;
3148 expected.cmd.Init(%(cmd_args)s);
3150 gl_->%(name)s(%(args)s);
3151 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3154 cmd_arg_strings = []
3155 for count, arg in enumerate(func.GetCmdArgs()):
3156 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3157 count += 1
3158 gl_arg_strings = []
3159 for count, arg in enumerate(func.GetOriginalArgs()):
3160 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3161 file.Write(code % {
3162 'name': func.name,
3163 'args': ", ".join(gl_arg_strings),
3164 'cmd_args': ", ".join(cmd_arg_strings),
3166 else:
3167 if client_test != False:
3168 file.Write("// TODO: Implement unit test for %s\n" % func.name)
3170 def WriteDestinationInitalizationValidation(self, func, file):
3171 """Writes the client side destintion initialization validation."""
3172 for arg in func.GetOriginalArgs():
3173 arg.WriteDestinationInitalizationValidation(file, func)
3175 def WriteTraceEvent(self, func, file):
3176 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3177 func.original_name)
3179 def WriteImmediateCmdComputeSize(self, func, file):
3180 """Writes the size computation code for the immediate version of a cmd."""
3181 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3182 file.Write(" return static_cast<uint32>(\n")
3183 file.Write(" sizeof(ValueType) + // NOLINT\n")
3184 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3185 file.Write(" }\n")
3186 file.Write("\n")
3188 def WriteImmediateCmdSetHeader(self, func, file):
3189 """Writes the SetHeader function for the immediate version of a cmd."""
3190 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3191 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3192 file.Write(" }\n")
3193 file.Write("\n")
3195 def WriteImmediateCmdInit(self, func, file):
3196 """Writes the Init function for the immediate version of a command."""
3197 raise NotImplementedError(func.name)
3199 def WriteImmediateCmdSet(self, func, file):
3200 """Writes the Set function for the immediate version of a command."""
3201 raise NotImplementedError(func.name)
3203 def WriteCmdHelper(self, func, file):
3204 """Writes the cmd helper definition for a cmd."""
3205 code = """ void %(name)s(%(typed_args)s) {
3206 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3207 if (c) {
3208 c->Init(%(args)s);
3213 file.Write(code % {
3214 "name": func.name,
3215 "typed_args": func.MakeTypedCmdArgString(""),
3216 "args": func.MakeCmdArgString(""),
3219 def WriteImmediateCmdHelper(self, func, file):
3220 """Writes the cmd helper definition for the immediate version of a cmd."""
3221 code = """ void %(name)s(%(typed_args)s) {
3222 const uint32 s = 0; // TODO(gman): compute correct size
3223 gles2::cmds::%(name)s* c =
3224 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3225 if (c) {
3226 c->Init(%(args)s);
3231 file.Write(code % {
3232 "name": func.name,
3233 "typed_args": func.MakeTypedCmdArgString(""),
3234 "args": func.MakeCmdArgString(""),
3238 class StateSetHandler(TypeHandler):
3239 """Handler for commands that simply set state."""
3241 def __init__(self):
3242 TypeHandler.__init__(self)
3244 def WriteHandlerImplementation(self, func, file):
3245 """Overrriden from TypeHandler."""
3246 state_name = func.GetInfo('state')
3247 state = _STATES[state_name]
3248 states = state['states']
3249 args = func.GetOriginalArgs()
3250 code = []
3251 for ndx,item in enumerate(states):
3252 if 'range_checks' in item:
3253 for range_check in item['range_checks']:
3254 code.append("%s %s" % (args[ndx].name, range_check['check']))
3255 if len(code):
3256 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3257 file.Write(
3258 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3259 ' "%s", "%s out of range");\n' %
3260 (func.name, args[ndx].name))
3261 file.Write(" return error::kNoError;\n")
3262 file.Write(" }\n")
3263 code = []
3264 for ndx,item in enumerate(states):
3265 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3266 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3267 for ndx,item in enumerate(states):
3268 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3269 if 'state_flag' in state:
3270 file.Write(" %s = true;\n" % state['state_flag'])
3271 if not func.GetInfo("no_gl"):
3272 file.Write(" %s(%s);\n" %
3273 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3274 file.Write(" }\n")
3276 def WriteServiceUnitTest(self, func, file):
3277 """Overrriden from TypeHandler."""
3278 TypeHandler.WriteServiceUnitTest(self, func, file)
3279 state_name = func.GetInfo('state')
3280 state = _STATES[state_name]
3281 states = state['states']
3282 for ndx,item in enumerate(states):
3283 if 'range_checks' in item:
3284 for check_ndx, range_check in enumerate(item['range_checks']):
3285 valid_test = """
3286 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3287 SpecializedSetup<cmds::%(name)s, 0>(false);
3288 cmds::%(name)s cmd;
3289 cmd.Init(%(args)s);
3290 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3291 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3294 name = func.name
3295 arg_strings = []
3296 for count, arg in enumerate(func.GetOriginalArgs()):
3297 arg_strings.append(arg.GetValidArg(func, count, 0))
3298 arg_strings[ndx] = range_check['test_value']
3299 vars = {
3300 'test_name': 'GLES2DecoderTest%d' % file.file_num,
3301 'name': name,
3302 'ndx': ndx,
3303 'check_ndx': check_ndx,
3304 'args': ", ".join(arg_strings),
3306 file.Write(valid_test % vars)
3309 class StateSetRGBAlphaHandler(TypeHandler):
3310 """Handler for commands that simply set state that have rgb/alpha."""
3312 def __init__(self):
3313 TypeHandler.__init__(self)
3315 def WriteHandlerImplementation(self, func, file):
3316 """Overrriden from TypeHandler."""
3317 state_name = func.GetInfo('state')
3318 state = _STATES[state_name]
3319 states = state['states']
3320 args = func.GetOriginalArgs()
3321 num_args = len(args)
3322 code = []
3323 for ndx,item in enumerate(states):
3324 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
3325 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3326 for ndx, item in enumerate(states):
3327 file.Write(" state_.%s = %s;\n" %
3328 (item['name'], args[ndx % num_args].name))
3329 if 'state_flag' in state:
3330 file.Write(" %s = true;\n" % state['state_flag'])
3331 if not func.GetInfo("no_gl"):
3332 file.Write(" %s(%s);\n" %
3333 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3334 file.Write(" }\n")
3337 class StateSetFrontBackSeparateHandler(TypeHandler):
3338 """Handler for commands that simply set state that have front/back."""
3340 def __init__(self):
3341 TypeHandler.__init__(self)
3343 def WriteHandlerImplementation(self, func, file):
3344 """Overrriden from TypeHandler."""
3345 state_name = func.GetInfo('state')
3346 state = _STATES[state_name]
3347 states = state['states']
3348 args = func.GetOriginalArgs()
3349 face = args[0].name
3350 num_args = len(args)
3351 file.Write(" bool changed = false;\n")
3352 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3353 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3354 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3355 code = []
3356 for ndx, item in enumerate(group):
3357 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
3358 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
3359 file.Write(" }\n")
3360 file.Write(" if (changed) {\n")
3361 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3362 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3363 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3364 for ndx, item in enumerate(group):
3365 file.Write(" state_.%s = %s;\n" %
3366 (item['name'], args[ndx + 1].name))
3367 file.Write(" }\n")
3368 if 'state_flag' in state:
3369 file.Write(" %s = true;\n" % state['state_flag'])
3370 if not func.GetInfo("no_gl"):
3371 file.Write(" %s(%s);\n" %
3372 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3373 file.Write(" }\n")
3376 class StateSetFrontBackHandler(TypeHandler):
3377 """Handler for commands that simply set state that set both front/back."""
3379 def __init__(self):
3380 TypeHandler.__init__(self)
3382 def WriteHandlerImplementation(self, func, file):
3383 """Overrriden from TypeHandler."""
3384 state_name = func.GetInfo('state')
3385 state = _STATES[state_name]
3386 states = state['states']
3387 args = func.GetOriginalArgs()
3388 num_args = len(args)
3389 code = []
3390 for group_ndx, group in enumerate(Grouper(num_args, states)):
3391 for ndx, item in enumerate(group):
3392 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3393 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3394 for group_ndx, group in enumerate(Grouper(num_args, states)):
3395 for ndx, item in enumerate(group):
3396 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3397 if 'state_flag' in state:
3398 file.Write(" %s = true;\n" % state['state_flag'])
3399 if not func.GetInfo("no_gl"):
3400 file.Write(" %s(%s);\n" %
3401 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3402 file.Write(" }\n")
3405 class StateSetNamedParameter(TypeHandler):
3406 """Handler for commands that set a state chosen with an enum parameter."""
3408 def __init__(self):
3409 TypeHandler.__init__(self)
3411 def WriteHandlerImplementation(self, func, file):
3412 """Overridden from TypeHandler."""
3413 state_name = func.GetInfo('state')
3414 state = _STATES[state_name]
3415 states = state['states']
3416 args = func.GetOriginalArgs()
3417 num_args = len(args)
3418 assert num_args == 2
3419 file.Write(" switch (%s) {\n" % args[0].name)
3420 for state in states:
3421 file.Write(" case %s:\n" % state['enum'])
3422 file.Write(" if (state_.%s != %s) {\n" %
3423 (state['name'], args[1].name))
3424 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
3425 if not func.GetInfo("no_gl"):
3426 file.Write(" %s(%s);\n" %
3427 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3428 file.Write(" }\n")
3429 file.Write(" break;\n")
3430 file.Write(" default:\n")
3431 file.Write(" NOTREACHED();\n")
3432 file.Write(" }\n")
3435 class CustomHandler(TypeHandler):
3436 """Handler for commands that are auto-generated but require minor tweaks."""
3438 def __init__(self):
3439 TypeHandler.__init__(self)
3441 def WriteServiceImplementation(self, func, file):
3442 """Overrriden from TypeHandler."""
3443 pass
3445 def WriteImmediateServiceImplementation(self, func, file):
3446 """Overrriden from TypeHandler."""
3447 pass
3449 def WriteBucketServiceImplementation(self, func, file):
3450 """Overrriden from TypeHandler."""
3451 pass
3453 def WriteServiceUnitTest(self, func, file):
3454 """Overrriden from TypeHandler."""
3455 file.Write("// TODO(gman): %s\n\n" % func.name)
3457 def WriteImmediateServiceUnitTest(self, func, file):
3458 """Overrriden from TypeHandler."""
3459 file.Write("// TODO(gman): %s\n\n" % func.name)
3461 def WriteImmediateCmdGetTotalSize(self, func, file):
3462 """Overrriden from TypeHandler."""
3463 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3465 def WriteImmediateCmdInit(self, func, file):
3466 """Overrriden from TypeHandler."""
3467 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3468 self.WriteImmediateCmdGetTotalSize(func, file)
3469 file.Write(" SetHeader(total_size);\n")
3470 args = func.GetCmdArgs()
3471 for arg in args:
3472 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3473 file.Write(" }\n")
3474 file.Write("\n")
3476 def WriteImmediateCmdSet(self, func, file):
3477 """Overrriden from TypeHandler."""
3478 copy_args = func.MakeCmdArgString("_", False)
3479 file.Write(" void* Set(void* cmd%s) {\n" %
3480 func.MakeTypedCmdArgString("_", True))
3481 self.WriteImmediateCmdGetTotalSize(func, file)
3482 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3483 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3484 "cmd, total_size);\n")
3485 file.Write(" }\n")
3486 file.Write("\n")
3489 class TodoHandler(CustomHandler):
3490 """Handle for commands that are not yet implemented."""
3492 def AddImmediateFunction(self, generator, func):
3493 """Overrriden from TypeHandler."""
3494 pass
3496 def WriteImmediateFormatTest(self, func, file):
3497 """Overrriden from TypeHandler."""
3498 pass
3500 def WriteGLES2ImplementationUnitTest(self, func, file):
3501 """Overrriden from TypeHandler."""
3502 pass
3504 def WriteGLES2Implementation(self, func, file):
3505 """Overrriden from TypeHandler."""
3506 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3507 (func.return_type, func.original_name,
3508 func.MakeTypedOriginalArgString("")))
3509 file.Write(" // TODO: for now this is a no-op\n")
3510 file.Write(
3511 " SetGLError("
3512 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3513 func.name)
3514 if func.return_type != "void":
3515 file.Write(" return 0;\n")
3516 file.Write("}\n")
3517 file.Write("\n")
3519 def WriteServiceImplementation(self, func, file):
3520 """Overrriden from TypeHandler."""
3521 file.Write(
3522 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
3523 file.Write(
3524 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3525 func.name)
3526 file.Write(" // TODO: for now this is a no-op\n")
3527 file.Write(
3528 " LOCAL_SET_GL_ERROR("
3529 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3530 func.name)
3531 file.Write(" return error::kNoError;\n")
3532 file.Write("}\n")
3533 file.Write("\n")
3536 class HandWrittenHandler(CustomHandler):
3537 """Handler for comands where everything must be written by hand."""
3539 def InitFunction(self, func):
3540 """Add or adjust anything type specific for this function."""
3541 CustomHandler.InitFunction(self, func)
3542 func.can_auto_generate = False
3544 def WriteStruct(self, func, file):
3545 """Overrriden from TypeHandler."""
3546 pass
3548 def WriteDocs(self, func, file):
3549 """Overrriden from TypeHandler."""
3550 pass
3552 def WriteServiceUnitTest(self, func, file):
3553 """Overrriden from TypeHandler."""
3554 file.Write("// TODO(gman): %s\n\n" % func.name)
3556 def WriteImmediateServiceUnitTest(self, func, file):
3557 """Overrriden from TypeHandler."""
3558 file.Write("// TODO(gman): %s\n\n" % func.name)
3560 def WriteBucketServiceUnitTest(self, func, file):
3561 """Overrriden from TypeHandler."""
3562 file.Write("// TODO(gman): %s\n\n" % func.name)
3564 def WriteServiceImplementation(self, func, file):
3565 """Overrriden from TypeHandler."""
3566 pass
3568 def WriteImmediateServiceImplementation(self, func, file):
3569 """Overrriden from TypeHandler."""
3570 pass
3572 def WriteBucketServiceImplementation(self, func, file):
3573 """Overrriden from TypeHandler."""
3574 pass
3576 def WriteImmediateCmdHelper(self, func, file):
3577 """Overrriden from TypeHandler."""
3578 pass
3580 def WriteBucketCmdHelper(self, func, file):
3581 """Overrriden from TypeHandler."""
3582 pass
3584 def WriteCmdHelper(self, func, file):
3585 """Overrriden from TypeHandler."""
3586 pass
3588 def WriteFormatTest(self, func, file):
3589 """Overrriden from TypeHandler."""
3590 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3592 def WriteImmediateFormatTest(self, func, file):
3593 """Overrriden from TypeHandler."""
3594 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3596 def WriteBucketFormatTest(self, func, file):
3597 """Overrriden from TypeHandler."""
3598 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3602 class ManualHandler(CustomHandler):
3603 """Handler for commands who's handlers must be written by hand."""
3605 def __init__(self):
3606 CustomHandler.__init__(self)
3608 def InitFunction(self, func):
3609 """Overrriden from TypeHandler."""
3610 if (func.name == 'CompressedTexImage2DBucket'):
3611 func.cmd_args = func.cmd_args[:-1]
3612 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3613 else:
3614 CustomHandler.InitFunction(self, func)
3616 def WriteServiceImplementation(self, func, file):
3617 """Overrriden from TypeHandler."""
3618 pass
3620 def WriteBucketServiceImplementation(self, func, file):
3621 """Overrriden from TypeHandler."""
3622 pass
3624 def WriteServiceUnitTest(self, func, file):
3625 """Overrriden from TypeHandler."""
3626 file.Write("// TODO(gman): %s\n\n" % func.name)
3628 def WriteImmediateServiceUnitTest(self, func, file):
3629 """Overrriden from TypeHandler."""
3630 file.Write("// TODO(gman): %s\n\n" % func.name)
3632 def WriteImmediateServiceImplementation(self, func, file):
3633 """Overrriden from TypeHandler."""
3634 pass
3636 def WriteImmediateFormatTest(self, func, file):
3637 """Overrriden from TypeHandler."""
3638 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3640 def WriteGLES2Implementation(self, func, file):
3641 """Overrriden from TypeHandler."""
3642 if func.GetInfo('impl_func'):
3643 super(ManualHandler, self).WriteGLES2Implementation(func, file)
3645 def WriteGLES2ImplementationHeader(self, func, file):
3646 """Overrriden from TypeHandler."""
3647 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3648 (func.return_type, func.original_name,
3649 func.MakeTypedOriginalArgString("")))
3650 file.Write("\n")
3652 def WriteImmediateCmdGetTotalSize(self, func, file):
3653 """Overrriden from TypeHandler."""
3654 # TODO(gman): Move this data to _FUNCTION_INFO?
3655 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
3658 class DataHandler(TypeHandler):
3659 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3660 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3661 def __init__(self):
3662 TypeHandler.__init__(self)
3664 def InitFunction(self, func):
3665 """Overrriden from TypeHandler."""
3666 if func.name == 'CompressedTexSubImage2DBucket':
3667 func.cmd_args = func.cmd_args[:-1]
3668 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3670 def WriteGetDataSizeCode(self, func, file):
3671 """Overrriden from TypeHandler."""
3672 # TODO(gman): Move this data to _FUNCTION_INFO?
3673 name = func.name
3674 if name.endswith("Immediate"):
3675 name = name[0:-9]
3676 if name == 'BufferData' or name == 'BufferSubData':
3677 file.Write(" uint32 data_size = size;\n")
3678 elif (name == 'CompressedTexImage2D' or
3679 name == 'CompressedTexSubImage2D'):
3680 file.Write(" uint32 data_size = imageSize;\n")
3681 elif (name == 'CompressedTexSubImage2DBucket'):
3682 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3683 file.Write(" uint32 data_size = bucket->size();\n")
3684 file.Write(" GLsizei imageSize = data_size;\n")
3685 elif name == 'TexImage2D' or name == 'TexSubImage2D':
3686 code = """ uint32 data_size;
3687 if (!GLES2Util::ComputeImageDataSize(
3688 width, height, format, type, unpack_alignment_, &data_size)) {
3689 return error::kOutOfBounds;
3692 file.Write(code)
3693 else:
3694 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3696 def WriteImmediateCmdGetTotalSize(self, func, file):
3697 """Overrriden from TypeHandler."""
3698 pass
3700 def WriteImmediateCmdSizeTest(self, func, file):
3701 """Overrriden from TypeHandler."""
3702 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3704 def WriteImmediateCmdInit(self, func, file):
3705 """Overrriden from TypeHandler."""
3706 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3707 self.WriteImmediateCmdGetTotalSize(func, file)
3708 file.Write(" SetHeader(total_size);\n")
3709 args = func.GetCmdArgs()
3710 for arg in args:
3711 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3712 file.Write(" }\n")
3713 file.Write("\n")
3715 def WriteImmediateCmdSet(self, func, file):
3716 """Overrriden from TypeHandler."""
3717 copy_args = func.MakeCmdArgString("_", False)
3718 file.Write(" void* Set(void* cmd%s) {\n" %
3719 func.MakeTypedCmdArgString("_", True))
3720 self.WriteImmediateCmdGetTotalSize(func, file)
3721 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3722 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3723 "cmd, total_size);\n")
3724 file.Write(" }\n")
3725 file.Write("\n")
3727 def WriteImmediateFormatTest(self, func, file):
3728 """Overrriden from TypeHandler."""
3729 # TODO(gman): Remove this exception.
3730 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3731 return
3733 def WriteServiceUnitTest(self, func, file):
3734 """Overrriden from TypeHandler."""
3735 file.Write("// TODO(gman): %s\n\n" % func.name)
3737 def WriteImmediateServiceUnitTest(self, func, file):
3738 """Overrriden from TypeHandler."""
3739 file.Write("// TODO(gman): %s\n\n" % func.name)
3741 def WriteBucketServiceImplementation(self, func, file):
3742 """Overrriden from TypeHandler."""
3743 if not func.name == 'CompressedTexSubImage2DBucket':
3744 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
3747 class BindHandler(TypeHandler):
3748 """Handler for glBind___ type functions."""
3750 def __init__(self):
3751 TypeHandler.__init__(self)
3753 def WriteServiceUnitTest(self, func, file):
3754 """Overrriden from TypeHandler."""
3756 if len(func.GetOriginalArgs()) == 1:
3757 valid_test = """
3758 TEST_F(%(test_name)s, %(name)sValidArgs) {
3759 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3760 SpecializedSetup<cmds::%(name)s, 0>(true);
3761 cmds::%(name)s cmd;
3762 cmd.Init(%(args)s);
3763 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3764 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3767 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3768 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3769 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3770 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3771 SpecializedSetup<cmds::%(name)s, 0>(true);
3772 cmds::%(name)s cmd;
3773 cmd.Init(kNewClientId);
3774 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3775 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3776 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3779 gen_func_names = {
3781 self.WriteValidUnitTest(func, file, valid_test, {
3782 'resource_type': func.GetOriginalArgs()[0].resource_type,
3783 'gl_gen_func_name': func.GetInfo("gen_func"),
3785 else:
3786 valid_test = """
3787 TEST_F(%(test_name)s, %(name)sValidArgs) {
3788 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3789 SpecializedSetup<cmds::%(name)s, 0>(true);
3790 cmds::%(name)s cmd;
3791 cmd.Init(%(args)s);
3792 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3793 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3796 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3797 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3798 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3799 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3800 SpecializedSetup<cmds::%(name)s, 0>(true);
3801 cmds::%(name)s cmd;
3802 cmd.Init(%(first_arg)s, kNewClientId);
3803 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3804 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3805 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3808 gen_func_names = {
3810 self.WriteValidUnitTest(func, file, valid_test, {
3811 'first_arg': func.GetOriginalArgs()[0].GetValidArg(func, 0, 0),
3812 'first_gl_arg': func.GetOriginalArgs()[0].GetValidGLArg(func, 0, 0),
3813 'resource_type': func.GetOriginalArgs()[1].resource_type,
3814 'gl_gen_func_name': func.GetInfo("gen_func"),
3817 invalid_test = """
3818 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3819 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3820 SpecializedSetup<cmds::%(name)s, 0>(false);
3821 cmds::%(name)s cmd;
3822 cmd.Init(%(args)s);
3823 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3826 self.WriteInvalidUnitTest(func, file, invalid_test)
3828 def WriteGLES2Implementation(self, func, file):
3829 """Writes the GLES2 Implemention."""
3831 impl_func = func.GetInfo('impl_func')
3832 impl_decl = func.GetInfo('impl_decl')
3834 if (func.can_auto_generate and
3835 (impl_func == None or impl_func == True) and
3836 (impl_decl == None or impl_decl == True)):
3838 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3839 (func.return_type, func.original_name,
3840 func.MakeTypedOriginalArgString("")))
3841 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3842 func.WriteDestinationInitalizationValidation(file)
3843 self.WriteClientGLCallLog(func, file)
3844 for arg in func.GetOriginalArgs():
3845 arg.WriteClientSideValidationCode(file, func)
3847 code = """ if (Is%(type)sReservedId(%(id)s)) {
3848 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3849 return;
3851 if (Bind%(type)sHelper(%(arg_string)s)) {
3852 helper_->%(name)s(%(arg_string)s);
3854 CheckGLError();
3858 name_arg = None
3859 if len(func.GetOriginalArgs()) == 1:
3860 # Bind functions that have no target (like BindVertexArrayOES)
3861 name_arg = func.GetOriginalArgs()[0]
3862 else:
3863 # Bind functions that have both a target and a name (like BindTexture)
3864 name_arg = func.GetOriginalArgs()[1]
3866 file.Write(code % {
3867 'name': func.name,
3868 'arg_string': func.MakeOriginalArgString(""),
3869 'id': name_arg.name,
3870 'type': name_arg.resource_type,
3871 'lc_type': name_arg.resource_type.lower(),
3874 def WriteGLES2ImplementationUnitTest(self, func, file):
3875 """Overrriden from TypeHandler."""
3876 client_test = func.GetInfo('client_test')
3877 if client_test == False:
3878 return
3879 code = """
3880 TEST_F(GLES2ImplementationTest, %(name)s) {
3881 struct Cmds {
3882 cmds::%(name)s cmd;
3884 Cmds expected;
3885 expected.cmd.Init(%(cmd_args)s);
3887 gl_->%(name)s(%(args)s);
3888 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3889 ClearCommands();
3890 gl_->%(name)s(%(args)s);
3891 EXPECT_TRUE(NoCommandsWritten());
3894 cmd_arg_strings = []
3895 for count, arg in enumerate(func.GetCmdArgs()):
3896 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3897 count += 1
3898 gl_arg_strings = []
3899 for count, arg in enumerate(func.GetOriginalArgs()):
3900 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3901 file.Write(code % {
3902 'name': func.name,
3903 'args': ", ".join(gl_arg_strings),
3904 'cmd_args': ", ".join(cmd_arg_strings),
3908 class GENnHandler(TypeHandler):
3909 """Handler for glGen___ type functions."""
3911 def __init__(self):
3912 TypeHandler.__init__(self)
3914 def InitFunction(self, func):
3915 """Overrriden from TypeHandler."""
3916 pass
3918 def WriteGetDataSizeCode(self, func, file):
3919 """Overrriden from TypeHandler."""
3920 code = """ uint32 data_size;
3921 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3922 return error::kOutOfBounds;
3925 file.Write(code)
3927 def WriteHandlerImplementation (self, func, file):
3928 """Overrriden from TypeHandler."""
3929 file.Write(" if (!%sHelper(n, %s)) {\n"
3930 " return error::kInvalidArguments;\n"
3931 " }\n" %
3932 (func.name, func.GetLastOriginalArg().name))
3934 def WriteImmediateHandlerImplementation(self, func, file):
3935 """Overrriden from TypeHandler."""
3936 file.Write(" if (!%sHelper(n, %s)) {\n"
3937 " return error::kInvalidArguments;\n"
3938 " }\n" %
3939 (func.original_name, func.GetLastOriginalArg().name))
3941 def WriteGLES2Implementation(self, func, file):
3942 """Overrriden from TypeHandler."""
3943 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
3944 for (GLsizei i = 0; i < n; ++i) {
3945 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3947 });""" % func.GetOriginalArgs()[1].name)
3948 args = {
3949 'log_code': log_code,
3950 'return_type': func.return_type,
3951 'name': func.original_name,
3952 'typed_args': func.MakeTypedOriginalArgString(""),
3953 'args': func.MakeOriginalArgString(""),
3954 'resource_types': func.GetInfo('resource_types'),
3955 'count_name': func.GetOriginalArgs()[0].name,
3957 file.Write(
3958 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3959 args)
3960 func.WriteDestinationInitalizationValidation(file)
3961 self.WriteClientGLCallLog(func, file)
3962 for arg in func.GetOriginalArgs():
3963 arg.WriteClientSideValidationCode(file, func)
3964 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3965 GetIdHandler(id_namespaces::k%(resource_types)s)->
3966 MakeIds(this, 0, %(args)s);
3967 %(name)sHelper(%(args)s);
3968 helper_->%(name)sImmediate(%(args)s);
3969 if (share_group_->bind_generates_resource())
3970 helper_->CommandBufferHelper::Flush();
3971 %(log_code)s
3972 CheckGLError();
3976 file.Write(code % args)
3978 def WriteGLES2ImplementationUnitTest(self, func, file):
3979 """Overrriden from TypeHandler."""
3980 code = """
3981 TEST_F(GLES2ImplementationTest, %(name)s) {
3982 GLuint ids[2] = { 0, };
3983 struct Cmds {
3984 cmds::%(name)sImmediate gen;
3985 GLuint data[2];
3987 Cmds expected;
3988 expected.gen.Init(arraysize(ids), &ids[0]);
3989 expected.data[0] = k%(types)sStartId;
3990 expected.data[1] = k%(types)sStartId + 1;
3991 gl_->%(name)s(arraysize(ids), &ids[0]);
3992 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3993 EXPECT_EQ(k%(types)sStartId, ids[0]);
3994 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3997 file.Write(code % {
3998 'name': func.name,
3999 'types': func.GetInfo('resource_types'),
4002 def WriteServiceUnitTest(self, func, file):
4003 """Overrriden from TypeHandler."""
4004 valid_test = """
4005 TEST_F(%(test_name)s, %(name)sValidArgs) {
4006 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4007 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4008 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
4009 SpecializedSetup<cmds::%(name)s, 0>(true);
4010 cmds::%(name)s cmd;
4011 cmd.Init(%(args)s);
4012 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4013 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4014 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4017 self.WriteValidUnitTest(func, file, valid_test, {
4018 'resource_name': func.GetInfo('resource_type'),
4020 invalid_test = """
4021 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4022 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4023 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4024 SpecializedSetup<cmds::%(name)s, 0>(false);
4025 cmds::%(name)s cmd;
4026 cmd.Init(%(args)s);
4027 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4030 self.WriteValidUnitTest(func, file, invalid_test, {
4031 'resource_name': func.GetInfo('resource_type').lower(),
4034 def WriteImmediateServiceUnitTest(self, func, file):
4035 """Overrriden from TypeHandler."""
4036 valid_test = """
4037 TEST_F(%(test_name)s, %(name)sValidArgs) {
4038 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4039 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4040 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4041 GLuint temp = kNewClientId;
4042 SpecializedSetup<cmds::%(name)s, 0>(true);
4043 cmd->Init(1, &temp);
4044 EXPECT_EQ(error::kNoError,
4045 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4046 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4047 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4050 self.WriteValidUnitTest(func, file, valid_test, {
4051 'resource_name': func.GetInfo('resource_type'),
4053 invalid_test = """
4054 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4055 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4056 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4057 SpecializedSetup<cmds::%(name)s, 0>(false);
4058 cmd->Init(1, &client_%(resource_name)s_id_);
4059 EXPECT_EQ(error::kInvalidArguments,
4060 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4063 self.WriteValidUnitTest(func, file, invalid_test, {
4064 'resource_name': func.GetInfo('resource_type').lower(),
4067 def WriteImmediateCmdComputeSize(self, func, file):
4068 """Overrriden from TypeHandler."""
4069 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4070 file.Write(
4071 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4072 file.Write(" }\n")
4073 file.Write("\n")
4074 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4075 file.Write(" return static_cast<uint32>(\n")
4076 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4077 file.Write(" }\n")
4078 file.Write("\n")
4080 def WriteImmediateCmdSetHeader(self, func, file):
4081 """Overrriden from TypeHandler."""
4082 file.Write(" void SetHeader(GLsizei n) {\n")
4083 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4084 file.Write(" }\n")
4085 file.Write("\n")
4087 def WriteImmediateCmdInit(self, func, file):
4088 """Overrriden from TypeHandler."""
4089 last_arg = func.GetLastOriginalArg()
4090 file.Write(" void Init(%s, %s _%s) {\n" %
4091 (func.MakeTypedCmdArgString("_"),
4092 last_arg.type, last_arg.name))
4093 file.Write(" SetHeader(_n);\n")
4094 args = func.GetCmdArgs()
4095 for arg in args:
4096 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4097 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4098 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4099 file.Write(" }\n")
4100 file.Write("\n")
4102 def WriteImmediateCmdSet(self, func, file):
4103 """Overrriden from TypeHandler."""
4104 last_arg = func.GetLastOriginalArg()
4105 copy_args = func.MakeCmdArgString("_", False)
4106 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4107 (func.MakeTypedCmdArgString("_", True),
4108 last_arg.type, last_arg.name))
4109 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4110 (copy_args, last_arg.name))
4111 file.Write(" const uint32 size = ComputeSize(_n);\n")
4112 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4113 "cmd, size);\n")
4114 file.Write(" }\n")
4115 file.Write("\n")
4117 def WriteImmediateCmdHelper(self, func, file):
4118 """Overrriden from TypeHandler."""
4119 code = """ void %(name)s(%(typed_args)s) {
4120 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4121 gles2::cmds::%(name)s* c =
4122 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4123 if (c) {
4124 c->Init(%(args)s);
4129 file.Write(code % {
4130 "name": func.name,
4131 "typed_args": func.MakeTypedOriginalArgString(""),
4132 "args": func.MakeOriginalArgString(""),
4135 def WriteImmediateFormatTest(self, func, file):
4136 """Overrriden from TypeHandler."""
4137 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4138 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4139 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4140 (func.name, func.name))
4141 file.Write(" void* next_cmd = cmd.Set(\n")
4142 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4143 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4144 func.name)
4145 file.Write(" cmd.header.command);\n")
4146 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4147 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4148 file.Write(" cmd.header.size * 4u);\n")
4149 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4150 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4151 file.Write(" next_cmd, sizeof(cmd) +\n")
4152 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4153 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4154 file.Write("}\n")
4155 file.Write("\n")
4158 class CreateHandler(TypeHandler):
4159 """Handler for glCreate___ type functions."""
4161 def __init__(self):
4162 TypeHandler.__init__(self)
4164 def InitFunction(self, func):
4165 """Overrriden from TypeHandler."""
4166 func.AddCmdArg(Argument("client_id", 'uint32'))
4168 def WriteServiceUnitTest(self, func, file):
4169 """Overrriden from TypeHandler."""
4170 valid_test = """
4171 TEST_F(%(test_name)s, %(name)sValidArgs) {
4172 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4173 .WillOnce(Return(kNewServiceId));
4174 SpecializedSetup<cmds::%(name)s, 0>(true);
4175 cmds::%(name)s cmd;
4176 cmd.Init(%(args)s%(comma)skNewClientId);
4177 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4178 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4179 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4182 comma = ""
4183 if len(func.GetOriginalArgs()):
4184 comma =", "
4185 self.WriteValidUnitTest(func, file, valid_test, {
4186 'comma': comma,
4187 'resource_type': func.name[6:],
4189 invalid_test = """
4190 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4191 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4192 SpecializedSetup<cmds::%(name)s, 0>(false);
4193 cmds::%(name)s cmd;
4194 cmd.Init(%(args)s%(comma)skNewClientId);
4195 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4198 self.WriteInvalidUnitTest(func, file, invalid_test, {
4199 'comma': comma,
4202 def WriteHandlerImplementation (self, func, file):
4203 """Overrriden from TypeHandler."""
4204 file.Write(" uint32 client_id = c.client_id;\n")
4205 file.Write(" if (!%sHelper(%s)) {\n" %
4206 (func.name, func.MakeCmdArgString("")))
4207 file.Write(" return error::kInvalidArguments;\n")
4208 file.Write(" }\n")
4210 def WriteGLES2Implementation(self, func, file):
4211 """Overrriden from TypeHandler."""
4212 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4213 (func.return_type, func.original_name,
4214 func.MakeTypedOriginalArgString("")))
4215 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4216 func.WriteDestinationInitalizationValidation(file)
4217 self.WriteClientGLCallLog(func, file)
4218 for arg in func.GetOriginalArgs():
4219 arg.WriteClientSideValidationCode(file, func)
4220 file.Write(" GLuint client_id;\n")
4221 file.Write(
4222 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4223 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4224 file.Write(" helper_->%s(%s);\n" %
4225 (func.name, func.MakeCmdArgString("")))
4226 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4227 file.Write(" CheckGLError();\n")
4228 file.Write(" return client_id;\n")
4229 file.Write("}\n")
4230 file.Write("\n")
4233 class DeleteHandler(TypeHandler):
4234 """Handler for glDelete___ single resource type functions."""
4236 def __init__(self):
4237 TypeHandler.__init__(self)
4239 def WriteServiceImplementation(self, func, file):
4240 """Overrriden from TypeHandler."""
4241 pass
4243 def WriteGLES2Implementation(self, func, file):
4244 """Overrriden from TypeHandler."""
4245 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4246 (func.return_type, func.original_name,
4247 func.MakeTypedOriginalArgString("")))
4248 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4249 func.WriteDestinationInitalizationValidation(file)
4250 self.WriteClientGLCallLog(func, file)
4251 for arg in func.GetOriginalArgs():
4252 arg.WriteClientSideValidationCode(file, func)
4253 file.Write(
4254 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
4255 file.Write(" %sHelper(%s);\n" %
4256 (func.original_name, func.GetOriginalArgs()[-1].name))
4257 file.Write(" CheckGLError();\n")
4258 file.Write("}\n")
4259 file.Write("\n")
4262 class DELnHandler(TypeHandler):
4263 """Handler for glDelete___ type functions."""
4265 def __init__(self):
4266 TypeHandler.__init__(self)
4268 def WriteGetDataSizeCode(self, func, file):
4269 """Overrriden from TypeHandler."""
4270 code = """ uint32 data_size;
4271 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4272 return error::kOutOfBounds;
4275 file.Write(code)
4277 def WriteGLES2ImplementationUnitTest(self, func, file):
4278 """Overrriden from TypeHandler."""
4279 code = """
4280 TEST_F(GLES2ImplementationTest, %(name)s) {
4281 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4282 struct Cmds {
4283 cmds::%(name)sImmediate del;
4284 GLuint data[2];
4286 Cmds expected;
4287 expected.del.Init(arraysize(ids), &ids[0]);
4288 expected.data[0] = k%(types)sStartId;
4289 expected.data[1] = k%(types)sStartId + 1;
4290 gl_->%(name)s(arraysize(ids), &ids[0]);
4291 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4294 file.Write(code % {
4295 'name': func.name,
4296 'types': func.GetInfo('resource_types'),
4299 def WriteServiceUnitTest(self, func, file):
4300 """Overrriden from TypeHandler."""
4301 valid_test = """
4302 TEST_F(%(test_name)s, %(name)sValidArgs) {
4303 EXPECT_CALL(
4304 *gl_,
4305 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4306 .Times(1);
4307 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4308 SpecializedSetup<cmds::%(name)s, 0>(true);
4309 cmds::%(name)s cmd;
4310 cmd.Init(%(args)s);
4311 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4312 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4313 EXPECT_TRUE(
4314 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4317 self.WriteValidUnitTest(func, file, valid_test, {
4318 'resource_name': func.GetInfo('resource_type').lower(),
4319 'upper_resource_name': func.GetInfo('resource_type'),
4321 invalid_test = """
4322 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4323 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4324 SpecializedSetup<cmds::%(name)s, 0>(false);
4325 cmds::%(name)s cmd;
4326 cmd.Init(%(args)s);
4327 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4330 self.WriteValidUnitTest(func, file, invalid_test)
4332 def WriteImmediateServiceUnitTest(self, func, file):
4333 """Overrriden from TypeHandler."""
4334 valid_test = """
4335 TEST_F(%(test_name)s, %(name)sValidArgs) {
4336 EXPECT_CALL(
4337 *gl_,
4338 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4339 .Times(1);
4340 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4341 SpecializedSetup<cmds::%(name)s, 0>(true);
4342 cmd.Init(1, &client_%(resource_name)s_id_);
4343 EXPECT_EQ(error::kNoError,
4344 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4345 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4346 EXPECT_TRUE(
4347 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4350 self.WriteValidUnitTest(func, file, valid_test, {
4351 'resource_name': func.GetInfo('resource_type').lower(),
4352 'upper_resource_name': func.GetInfo('resource_type'),
4354 invalid_test = """
4355 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4356 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4357 SpecializedSetup<cmds::%(name)s, 0>(false);
4358 GLuint temp = kInvalidClientId;
4359 cmd.Init(1, &temp);
4360 EXPECT_EQ(error::kNoError,
4361 ExecuteImmediateCmd(cmd, sizeof(temp)));
4364 self.WriteValidUnitTest(func, file, invalid_test)
4366 def WriteHandlerImplementation (self, func, file):
4367 """Overrriden from TypeHandler."""
4368 file.Write(" %sHelper(n, %s);\n" %
4369 (func.name, func.GetLastOriginalArg().name))
4371 def WriteImmediateHandlerImplementation (self, func, file):
4372 """Overrriden from TypeHandler."""
4373 file.Write(" %sHelper(n, %s);\n" %
4374 (func.original_name, func.GetLastOriginalArg().name))
4376 def WriteGLES2Implementation(self, func, file):
4377 """Overrriden from TypeHandler."""
4378 impl_decl = func.GetInfo('impl_decl')
4379 if impl_decl == None or impl_decl == True:
4380 args = {
4381 'return_type': func.return_type,
4382 'name': func.original_name,
4383 'typed_args': func.MakeTypedOriginalArgString(""),
4384 'args': func.MakeOriginalArgString(""),
4385 'resource_type': func.GetInfo('resource_type').lower(),
4386 'count_name': func.GetOriginalArgs()[0].name,
4388 file.Write(
4389 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4390 args)
4391 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4392 func.WriteDestinationInitalizationValidation(file)
4393 self.WriteClientGLCallLog(func, file)
4394 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4395 for (GLsizei i = 0; i < n; ++i) {
4396 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4399 """ % func.GetOriginalArgs()[1].name)
4400 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4401 for (GLsizei i = 0; i < n; ++i) {
4402 DCHECK(%s[i] != 0);
4405 """ % func.GetOriginalArgs()[1].name)
4406 for arg in func.GetOriginalArgs():
4407 arg.WriteClientSideValidationCode(file, func)
4408 code = """ %(name)sHelper(%(args)s);
4409 CheckGLError();
4413 file.Write(code % args)
4415 def WriteImmediateCmdComputeSize(self, func, file):
4416 """Overrriden from TypeHandler."""
4417 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4418 file.Write(
4419 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4420 file.Write(" }\n")
4421 file.Write("\n")
4422 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4423 file.Write(" return static_cast<uint32>(\n")
4424 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4425 file.Write(" }\n")
4426 file.Write("\n")
4428 def WriteImmediateCmdSetHeader(self, func, file):
4429 """Overrriden from TypeHandler."""
4430 file.Write(" void SetHeader(GLsizei n) {\n")
4431 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4432 file.Write(" }\n")
4433 file.Write("\n")
4435 def WriteImmediateCmdInit(self, func, file):
4436 """Overrriden from TypeHandler."""
4437 last_arg = func.GetLastOriginalArg()
4438 file.Write(" void Init(%s, %s _%s) {\n" %
4439 (func.MakeTypedCmdArgString("_"),
4440 last_arg.type, last_arg.name))
4441 file.Write(" SetHeader(_n);\n")
4442 args = func.GetCmdArgs()
4443 for arg in args:
4444 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4445 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4446 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4447 file.Write(" }\n")
4448 file.Write("\n")
4450 def WriteImmediateCmdSet(self, func, file):
4451 """Overrriden from TypeHandler."""
4452 last_arg = func.GetLastOriginalArg()
4453 copy_args = func.MakeCmdArgString("_", False)
4454 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4455 (func.MakeTypedCmdArgString("_", True),
4456 last_arg.type, last_arg.name))
4457 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4458 (copy_args, last_arg.name))
4459 file.Write(" const uint32 size = ComputeSize(_n);\n")
4460 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4461 "cmd, size);\n")
4462 file.Write(" }\n")
4463 file.Write("\n")
4465 def WriteImmediateCmdHelper(self, func, file):
4466 """Overrriden from TypeHandler."""
4467 code = """ void %(name)s(%(typed_args)s) {
4468 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4469 gles2::cmds::%(name)s* c =
4470 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4471 if (c) {
4472 c->Init(%(args)s);
4477 file.Write(code % {
4478 "name": func.name,
4479 "typed_args": func.MakeTypedOriginalArgString(""),
4480 "args": func.MakeOriginalArgString(""),
4483 def WriteImmediateFormatTest(self, func, file):
4484 """Overrriden from TypeHandler."""
4485 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4486 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4487 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4488 (func.name, func.name))
4489 file.Write(" void* next_cmd = cmd.Set(\n")
4490 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4491 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4492 func.name)
4493 file.Write(" cmd.header.command);\n")
4494 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4495 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4496 file.Write(" cmd.header.size * 4u);\n")
4497 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4498 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4499 file.Write(" next_cmd, sizeof(cmd) +\n")
4500 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4501 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4502 file.Write("}\n")
4503 file.Write("\n")
4506 class GETnHandler(TypeHandler):
4507 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4509 def __init__(self):
4510 TypeHandler.__init__(self)
4512 def AddImmediateFunction(self, generator, func):
4513 """Overrriden from TypeHandler."""
4514 pass
4516 def WriteServiceImplementation(self, func, file):
4517 """Overrriden from TypeHandler."""
4518 file.Write(
4519 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
4520 file.Write(
4521 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4522 func.name)
4523 last_arg = func.GetLastOriginalArg()
4525 all_but_last_args = func.GetOriginalArgs()[:-1]
4526 for arg in all_but_last_args:
4527 arg.WriteGetCode(file)
4529 code = """ typedef cmds::%(func_name)s::Result Result;
4530 GLsizei num_values = 0;
4531 GetNumValuesReturnedForGLGet(pname, &num_values);
4532 Result* result = GetSharedMemoryAs<Result*>(
4533 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4534 %(last_arg_type)s params = result ? result->GetData() : NULL;
4536 file.Write(code % {
4537 'last_arg_type': last_arg.type,
4538 'func_name': func.name,
4540 func.WriteHandlerValidation(file)
4541 code = """ // Check that the client initialized the result.
4542 if (result->size != 0) {
4543 return error::kInvalidArguments;
4546 shadowed = func.GetInfo('shadowed')
4547 if not shadowed:
4548 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
4549 file.Write(code)
4550 func.WriteHandlerImplementation(file)
4551 if shadowed:
4552 code = """ result->SetNumResults(num_values);
4553 return error::kNoError;
4556 else:
4557 code = """ GLenum error = glGetError();
4558 if (error == GL_NO_ERROR) {
4559 result->SetNumResults(num_values);
4560 } else {
4561 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4563 return error::kNoError;
4567 file.Write(code % {'func_name': func.name})
4569 def WriteGLES2Implementation(self, func, file):
4570 """Overrriden from TypeHandler."""
4571 impl_decl = func.GetInfo('impl_decl')
4572 if impl_decl == None or impl_decl == True:
4573 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4574 (func.return_type, func.original_name,
4575 func.MakeTypedOriginalArgString("")))
4576 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4577 func.WriteDestinationInitalizationValidation(file)
4578 self.WriteClientGLCallLog(func, file)
4579 for arg in func.GetOriginalArgs():
4580 arg.WriteClientSideValidationCode(file, func)
4581 all_but_last_args = func.GetOriginalArgs()[:-1]
4582 arg_string = (
4583 ", ".join(["%s" % arg.name for arg in all_but_last_args]))
4584 all_arg_string = (
4585 ", ".join(["%s" % arg.name for arg in func.GetOriginalArgs()]))
4586 self.WriteTraceEvent(func, file)
4587 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4588 return;
4590 typedef cmds::%(func_name)s::Result Result;
4591 Result* result = GetResultAs<Result*>();
4592 if (!result) {
4593 return;
4595 result->SetNumResults(0);
4596 helper_->%(func_name)s(%(arg_string)s,
4597 GetResultShmId(), GetResultShmOffset());
4598 WaitForCmd();
4599 result->CopyResult(params);
4600 GPU_CLIENT_LOG_CODE_BLOCK({
4601 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4602 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4605 CheckGLError();
4608 file.Write(code % {
4609 'func_name': func.name,
4610 'arg_string': arg_string,
4611 'all_arg_string': all_arg_string,
4614 def WriteGLES2ImplementationUnitTest(self, func, file):
4615 """Writes the GLES2 Implemention unit test."""
4616 code = """
4617 TEST_F(GLES2ImplementationTest, %(name)s) {
4618 struct Cmds {
4619 cmds::%(name)s cmd;
4621 typedef cmds::%(name)s::Result Result;
4622 Result::Type result = 0;
4623 Cmds expected;
4624 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4625 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4626 EXPECT_CALL(*command_buffer(), OnFlush())
4627 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4628 .RetiresOnSaturation();
4629 gl_->%(name)s(%(args)s, &result);
4630 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4631 EXPECT_EQ(static_cast<Result::Type>(1), result);
4634 cmd_arg_strings = []
4635 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4636 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4637 cmd_arg_strings[0] = '123'
4638 gl_arg_strings = []
4639 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4640 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4641 gl_arg_strings[0] = '123'
4642 file.Write(code % {
4643 'name': func.name,
4644 'args': ", ".join(gl_arg_strings),
4645 'cmd_args': ", ".join(cmd_arg_strings),
4648 def WriteServiceUnitTest(self, func, file):
4649 """Overrriden from TypeHandler."""
4650 valid_test = """
4651 TEST_F(%(test_name)s, %(name)sValidArgs) {
4652 EXPECT_CALL(*gl_, GetError())
4653 .WillOnce(Return(GL_NO_ERROR))
4654 .WillOnce(Return(GL_NO_ERROR))
4655 .RetiresOnSaturation();
4656 SpecializedSetup<cmds::%(name)s, 0>(true);
4657 typedef cmds::%(name)s::Result Result;
4658 Result* result = static_cast<Result*>(shared_memory_address_);
4659 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4660 result->size = 0;
4661 cmds::%(name)s cmd;
4662 cmd.Init(%(args)s);
4663 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4664 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4665 %(valid_pname)s),
4666 result->GetNumResults());
4667 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4670 gl_arg_strings = []
4671 valid_pname = ''
4672 for count, arg in enumerate(func.GetOriginalArgs()[:-1]):
4673 arg_value = arg.GetValidGLArg(func, count, 0)
4674 gl_arg_strings.append(arg_value)
4675 if arg.name == 'pname':
4676 valid_pname = arg_value
4677 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
4678 gl_arg_strings.append("_")
4679 else:
4680 gl_arg_strings.append("result->GetData()")
4682 self.WriteValidUnitTest(func, file, valid_test, {
4683 'local_gl_args': ", ".join(gl_arg_strings),
4684 'valid_pname': valid_pname,
4687 invalid_test = """
4688 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4689 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4690 SpecializedSetup<cmds::%(name)s, 0>(false);
4691 cmds::%(name)s::Result* result =
4692 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4693 result->size = 0;
4694 cmds::%(name)s cmd;
4695 cmd.Init(%(args)s);
4696 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4697 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4700 self.WriteInvalidUnitTest(func, file, invalid_test)
4703 class PUTHandler(TypeHandler):
4704 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4706 def __init__(self):
4707 TypeHandler.__init__(self)
4709 def WriteServiceUnitTest(self, func, file):
4710 """Writes the service unit test for a command."""
4711 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4712 if func.GetInfo("first_element_only"):
4713 gl_arg_strings = []
4714 for count, arg in enumerate(func.GetOriginalArgs()):
4715 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4716 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
4717 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4718 ", ".join(gl_arg_strings))
4719 valid_test = """
4720 TEST_F(%(test_name)s, %(name)sValidArgs) {
4721 SpecializedSetup<cmds::%(name)s, 0>(true);
4722 cmds::%(name)s cmd;
4723 cmd.Init(%(args)s);
4724 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4725 %(expected_call)s
4726 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4727 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4730 extra = {
4731 'data_type': func.GetInfo('data_type'),
4732 'data_value': func.GetInfo('data_value') or '0',
4733 'expected_call': expected_call,
4735 self.WriteValidUnitTest(func, file, valid_test, extra)
4737 invalid_test = """
4738 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4739 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4740 SpecializedSetup<cmds::%(name)s, 0>(false);
4741 cmds::%(name)s cmd;
4742 cmd.Init(%(args)s);
4743 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4744 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4747 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4749 def WriteImmediateServiceUnitTest(self, func, file):
4750 """Writes the service unit test for a command."""
4751 valid_test = """
4752 TEST_F(%(test_name)s, %(name)sValidArgs) {
4753 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4754 SpecializedSetup<cmds::%(name)s, 0>(true);
4755 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4756 cmd.Init(%(gl_args)s, &temp[0]);
4757 EXPECT_CALL(
4758 *gl_,
4759 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4760 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4761 EXPECT_EQ(error::kNoError,
4762 ExecuteImmediateCmd(cmd, sizeof(temp)));
4763 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4766 gl_arg_strings = []
4767 gl_any_strings = []
4768 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4769 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4770 gl_any_strings.append("_")
4771 extra = {
4772 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
4773 'data_type': func.GetInfo('data_type'),
4774 'data_count': func.GetInfo('count'),
4775 'data_value': func.GetInfo('data_value') or '0',
4776 'gl_args': ", ".join(gl_arg_strings),
4777 'gl_any_args': ", ".join(gl_any_strings),
4779 self.WriteValidUnitTest(func, file, valid_test, extra)
4781 invalid_test = """
4782 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4783 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4784 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4785 SpecializedSetup<cmds::%(name)s, 0>(false);
4786 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4787 cmd.Init(%(all_but_last_args)s, &temp[0]);
4788 EXPECT_EQ(error::%(parse_result)s,
4789 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4792 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4794 def WriteGetDataSizeCode(self, func, file):
4795 """Overrriden from TypeHandler."""
4796 code = """ uint32 data_size;
4797 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4798 return error::kOutOfBounds;
4801 file.Write(code % (func.info.data_type, func.info.count))
4802 if func.is_immediate:
4803 file.Write(" if (data_size > immediate_data_size) {\n")
4804 file.Write(" return error::kOutOfBounds;\n")
4805 file.Write(" }\n")
4807 def WriteGLES2Implementation(self, func, file):
4808 """Overrriden from TypeHandler."""
4809 impl_func = func.GetInfo('impl_func')
4810 if (impl_func != None and impl_func != True):
4811 return;
4812 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4813 (func.return_type, func.original_name,
4814 func.MakeTypedOriginalArgString("")))
4815 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4816 func.WriteDestinationInitalizationValidation(file)
4817 self.WriteClientGLCallLog(func, file)
4818 last_arg_name = func.GetLastOriginalArg().name
4819 values_str = ' << ", " << '.join(
4820 ["%s[%d]" % (last_arg_name, ndx) for ndx in range(0, func.info.count)])
4821 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str)
4822 for arg in func.GetOriginalArgs():
4823 arg.WriteClientSideValidationCode(file, func)
4824 file.Write(" helper_->%sImmediate(%s);\n" %
4825 (func.name, func.MakeOriginalArgString("")))
4826 file.Write(" CheckGLError();\n")
4827 file.Write("}\n")
4828 file.Write("\n")
4830 def WriteGLES2ImplementationUnitTest(self, func, file):
4831 """Writes the GLES2 Implemention unit test."""
4832 client_test = func.GetInfo('client_test')
4833 if (client_test != None and client_test != True):
4834 return;
4835 code = """
4836 TEST_F(GLES2ImplementationTest, %(name)s) {
4837 %(type)s data[%(count)d] = {0};
4838 struct Cmds {
4839 cmds::%(name)sImmediate cmd;
4840 %(type)s data[%(count)d];
4843 for (int jj = 0; jj < %(count)d; ++jj) {
4844 data[jj] = static_cast<%(type)s>(jj);
4846 Cmds expected;
4847 expected.cmd.Init(%(cmd_args)s, &data[0]);
4848 gl_->%(name)s(%(args)s, &data[0]);
4849 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4852 cmd_arg_strings = []
4853 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4854 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4855 gl_arg_strings = []
4856 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4857 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4858 file.Write(code % {
4859 'name': func.name,
4860 'type': func.GetInfo('data_type'),
4861 'count': func.GetInfo('count'),
4862 'args': ", ".join(gl_arg_strings),
4863 'cmd_args': ", ".join(cmd_arg_strings),
4866 def WriteImmediateCmdComputeSize(self, func, file):
4867 """Overrriden from TypeHandler."""
4868 file.Write(" static uint32 ComputeDataSize() {\n")
4869 file.Write(" return static_cast<uint32>(\n")
4870 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4871 (func.info.data_type, func.info.count))
4872 file.Write(" }\n")
4873 file.Write("\n")
4874 file.Write(" static uint32 ComputeSize() {\n")
4875 file.Write(" return static_cast<uint32>(\n")
4876 file.Write(
4877 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4878 file.Write(" }\n")
4879 file.Write("\n")
4881 def WriteImmediateCmdSetHeader(self, func, file):
4882 """Overrriden from TypeHandler."""
4883 file.Write(" void SetHeader() {\n")
4884 file.Write(
4885 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4886 file.Write(" }\n")
4887 file.Write("\n")
4889 def WriteImmediateCmdInit(self, func, file):
4890 """Overrriden from TypeHandler."""
4891 last_arg = func.GetLastOriginalArg()
4892 file.Write(" void Init(%s, %s _%s) {\n" %
4893 (func.MakeTypedCmdArgString("_"),
4894 last_arg.type, last_arg.name))
4895 file.Write(" SetHeader();\n")
4896 args = func.GetCmdArgs()
4897 for arg in args:
4898 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4899 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4900 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
4901 file.Write(" }\n")
4902 file.Write("\n")
4904 def WriteImmediateCmdSet(self, func, file):
4905 """Overrriden from TypeHandler."""
4906 last_arg = func.GetLastOriginalArg()
4907 copy_args = func.MakeCmdArgString("_", False)
4908 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4909 (func.MakeTypedCmdArgString("_", True),
4910 last_arg.type, last_arg.name))
4911 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4912 (copy_args, last_arg.name))
4913 file.Write(" const uint32 size = ComputeSize();\n")
4914 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4915 "cmd, size);\n")
4916 file.Write(" }\n")
4917 file.Write("\n")
4919 def WriteImmediateCmdHelper(self, func, file):
4920 """Overrriden from TypeHandler."""
4921 code = """ void %(name)s(%(typed_args)s) {
4922 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4923 gles2::cmds::%(name)s* c =
4924 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4925 if (c) {
4926 c->Init(%(args)s);
4931 file.Write(code % {
4932 "name": func.name,
4933 "typed_args": func.MakeTypedOriginalArgString(""),
4934 "args": func.MakeOriginalArgString(""),
4937 def WriteImmediateFormatTest(self, func, file):
4938 """Overrriden from TypeHandler."""
4939 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4940 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4941 file.Write(" static %s data[] = {\n" % func.info.data_type)
4942 for v in range(0, func.info.count):
4943 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4944 (func.info.data_type, v))
4945 file.Write(" };\n")
4946 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4947 (func.name, func.name))
4948 file.Write(" void* next_cmd = cmd.Set(\n")
4949 file.Write(" &cmd")
4950 args = func.GetCmdArgs()
4951 for value, arg in enumerate(args):
4952 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4953 file.Write(",\n data);\n")
4954 args = func.GetCmdArgs()
4955 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4956 % func.name)
4957 file.Write(" cmd.header.command);\n")
4958 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4959 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4960 file.Write(" cmd.header.size * 4u);\n")
4961 for value, arg in enumerate(args):
4962 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4963 (arg.type, value + 11, arg.name))
4964 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4965 file.Write(" next_cmd, sizeof(cmd) +\n")
4966 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4967 file.Write(" // TODO(gman): Check that data was inserted;\n")
4968 file.Write("}\n")
4969 file.Write("\n")
4972 class PUTnHandler(TypeHandler):
4973 """Handler for PUTn 'glUniform__v' type functions."""
4975 def __init__(self):
4976 TypeHandler.__init__(self)
4978 def WriteServiceUnitTest(self, func, file):
4979 """Overridden from TypeHandler."""
4980 TypeHandler.WriteServiceUnitTest(self, func, file)
4982 valid_test = """
4983 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4984 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4985 SpecializedSetup<cmds::%(name)s, 0>(true);
4986 cmds::%(name)s cmd;
4987 cmd.Init(%(args)s);
4988 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4989 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4992 gl_arg_strings = []
4993 arg_strings = []
4994 for count, arg in enumerate(func.GetOriginalArgs()):
4995 # hardcoded to match unit tests.
4996 if count == 0:
4997 # the location of the second element of the 2nd uniform.
4998 # defined in GLES2DecoderBase::SetupShaderForUniform
4999 gl_arg_strings.append("3")
5000 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
5001 elif count == 1:
5002 # the number of elements that gl will be called with.
5003 gl_arg_strings.append("3")
5004 # the number of elements requested in the command.
5005 arg_strings.append("5")
5006 else:
5007 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
5008 arg_strings.append(arg.GetValidArg(func, count, 0))
5009 extra = {
5010 'gl_args': ", ".join(gl_arg_strings),
5011 'args': ", ".join(arg_strings),
5013 self.WriteValidUnitTest(func, file, valid_test, extra)
5015 def WriteImmediateServiceUnitTest(self, func, file):
5016 """Overridden from TypeHandler."""
5017 valid_test = """
5018 TEST_F(%(test_name)s, %(name)sValidArgs) {
5019 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5020 EXPECT_CALL(
5021 *gl_,
5022 %(gl_func_name)s(%(gl_args)s,
5023 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
5024 SpecializedSetup<cmds::%(name)s, 0>(true);
5025 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5026 cmd.Init(%(args)s, &temp[0]);
5027 EXPECT_EQ(error::kNoError,
5028 ExecuteImmediateCmd(cmd, sizeof(temp)));
5029 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5032 gl_arg_strings = []
5033 gl_any_strings = []
5034 arg_strings = []
5035 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5036 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
5037 gl_any_strings.append("_")
5038 arg_strings.append(arg.GetValidArg(func, count, 0))
5039 extra = {
5040 'data_type': func.GetInfo('data_type'),
5041 'data_count': func.GetInfo('count'),
5042 'args': ", ".join(arg_strings),
5043 'gl_args': ", ".join(gl_arg_strings),
5044 'gl_any_args': ", ".join(gl_any_strings),
5046 self.WriteValidUnitTest(func, file, valid_test, extra)
5048 invalid_test = """
5049 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5050 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5051 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5052 SpecializedSetup<cmds::%(name)s, 0>(false);
5053 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5054 cmd.Init(%(all_but_last_args)s, &temp[0]);
5055 EXPECT_EQ(error::%(parse_result)s,
5056 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5059 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
5061 def WriteGetDataSizeCode(self, func, file):
5062 """Overrriden from TypeHandler."""
5063 code = """ uint32 data_size;
5064 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5065 return error::kOutOfBounds;
5068 file.Write(code % (func.info.data_type, func.info.count))
5069 if func.is_immediate:
5070 file.Write(" if (data_size > immediate_data_size) {\n")
5071 file.Write(" return error::kOutOfBounds;\n")
5072 file.Write(" }\n")
5074 def WriteGLES2Implementation(self, func, file):
5075 """Overrriden from TypeHandler."""
5076 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5077 (func.return_type, func.original_name,
5078 func.MakeTypedOriginalArgString("")))
5079 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5080 func.WriteDestinationInitalizationValidation(file)
5081 self.WriteClientGLCallLog(func, file)
5082 last_arg_name = func.GetLastOriginalArg().name
5083 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5084 for (GLsizei i = 0; i < count; ++i) {
5085 """)
5086 values_str = ' << ", " << '.join(
5087 ["%s[%d + i * %d]" % (
5088 last_arg_name, ndx, func.info.count) for ndx in range(
5089 0, func.info.count)])
5090 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
5091 file.Write(" }\n });\n")
5092 for arg in func.GetOriginalArgs():
5093 arg.WriteClientSideValidationCode(file, func)
5094 file.Write(" helper_->%sImmediate(%s);\n" %
5095 (func.name, func.MakeOriginalArgString("")))
5096 file.Write(" CheckGLError();\n")
5097 file.Write("}\n")
5098 file.Write("\n")
5100 def WriteGLES2ImplementationUnitTest(self, func, file):
5101 """Writes the GLES2 Implemention unit test."""
5102 code = """
5103 TEST_F(GLES2ImplementationTest, %(name)s) {
5104 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5105 struct Cmds {
5106 cmds::%(name)sImmediate cmd;
5107 %(type)s data[%(count_param)d][%(count)d];
5110 Cmds expected;
5111 for (int ii = 0; ii < %(count_param)d; ++ii) {
5112 for (int jj = 0; jj < %(count)d; ++jj) {
5113 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5116 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5117 gl_->%(name)s(%(args)s, &data[0][0]);
5118 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5121 cmd_arg_strings = []
5122 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
5123 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
5124 gl_arg_strings = []
5125 count_param = 0
5126 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5127 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
5128 if arg.name == "count":
5129 count_param = int(arg.GetValidClientSideArg(func, count, 0))
5130 file.Write(code % {
5131 'name': func.name,
5132 'type': func.GetInfo('data_type'),
5133 'count': func.GetInfo('count'),
5134 'args': ", ".join(gl_arg_strings),
5135 'cmd_args': ", ".join(cmd_arg_strings),
5136 'count_param': count_param,
5139 def WriteImmediateCmdComputeSize(self, func, file):
5140 """Overrriden from TypeHandler."""
5141 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5142 file.Write(" return static_cast<uint32>(\n")
5143 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5144 (func.info.data_type, func.info.count))
5145 file.Write(" }\n")
5146 file.Write("\n")
5147 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5148 file.Write(" return static_cast<uint32>(\n")
5149 file.Write(
5150 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5151 file.Write(" }\n")
5152 file.Write("\n")
5154 def WriteImmediateCmdSetHeader(self, func, file):
5155 """Overrriden from TypeHandler."""
5156 file.Write(" void SetHeader(GLsizei count) {\n")
5157 file.Write(
5158 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5159 file.Write(" }\n")
5160 file.Write("\n")
5162 def WriteImmediateCmdInit(self, func, file):
5163 """Overrriden from TypeHandler."""
5164 last_arg = func.GetLastOriginalArg()
5165 file.Write(" void Init(%s, %s _%s) {\n" %
5166 (func.MakeTypedCmdArgString("_"),
5167 last_arg.type, last_arg.name))
5168 file.Write(" SetHeader(_count);\n")
5169 args = func.GetCmdArgs()
5170 for arg in args:
5171 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5172 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5173 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg.name)
5174 file.Write(" }\n")
5175 file.Write("\n")
5177 def WriteImmediateCmdSet(self, func, file):
5178 """Overrriden from TypeHandler."""
5179 last_arg = func.GetLastOriginalArg()
5180 copy_args = func.MakeCmdArgString("_", False)
5181 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5182 (func.MakeTypedCmdArgString("_", True),
5183 last_arg.type, last_arg.name))
5184 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5185 (copy_args, last_arg.name))
5186 file.Write(" const uint32 size = ComputeSize(_count);\n")
5187 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5188 "cmd, size);\n")
5189 file.Write(" }\n")
5190 file.Write("\n")
5192 def WriteImmediateCmdHelper(self, func, file):
5193 """Overrriden from TypeHandler."""
5194 code = """ void %(name)s(%(typed_args)s) {
5195 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5196 gles2::cmds::%(name)s* c =
5197 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5198 if (c) {
5199 c->Init(%(args)s);
5204 file.Write(code % {
5205 "name": func.name,
5206 "typed_args": func.MakeTypedOriginalArgString(""),
5207 "args": func.MakeOriginalArgString(""),
5210 def WriteImmediateFormatTest(self, func, file):
5211 """Overrriden from TypeHandler."""
5212 args = func.GetCmdArgs()
5213 count_param = 0
5214 for value, arg in enumerate(args):
5215 if arg.name == "count":
5216 count_param = int(arg.GetValidClientSideArg(func, value, 0))
5217 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5218 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5219 file.Write(" static %s data[] = {\n" % func.info.data_type)
5220 for v in range(0, func.info.count * count_param):
5221 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5222 (func.info.data_type, v))
5223 file.Write(" };\n")
5224 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5225 (func.name, func.name))
5226 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
5227 file.Write(" const size_t kExpectedCmdSize =\n")
5228 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5229 (func.info.data_type, func.info.count))
5230 file.Write(" void* next_cmd = cmd.Set(\n")
5231 file.Write(" &cmd")
5232 for value, arg in enumerate(args):
5233 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
5234 file.Write(",\n data);\n")
5235 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5236 func.name)
5237 file.Write(" cmd.header.command);\n")
5238 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5239 for value, arg in enumerate(args):
5240 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5241 (arg.type, value + 1, arg.name))
5242 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5243 file.Write(" next_cmd, sizeof(cmd) +\n")
5244 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5245 file.Write(" // TODO(gman): Check that data was inserted;\n")
5246 file.Write("}\n")
5247 file.Write("\n")
5250 class PUTXnHandler(TypeHandler):
5251 """Handler for glUniform?f functions."""
5252 def __init__(self):
5253 TypeHandler.__init__(self)
5255 def WriteHandlerImplementation(self, func, file):
5256 """Overrriden from TypeHandler."""
5257 code = """ %(type)s temp[%(count)s] = { %(values)s};
5258 Do%(name)sv(%(location)s, 1, &temp[0]);
5260 values = ""
5261 args = func.GetOriginalArgs()
5262 count = int(func.GetInfo('count'))
5263 num_args = len(args)
5264 for ii in range(count):
5265 values += "%s, " % args[len(args) - count + ii].name
5267 file.Write(code % {
5268 'name': func.name,
5269 'count': func.GetInfo('count'),
5270 'type': func.GetInfo('data_type'),
5271 'location': args[0].name,
5272 'args': func.MakeOriginalArgString(""),
5273 'values': values,
5276 def WriteServiceUnitTest(self, func, file):
5277 """Overrriden from TypeHandler."""
5278 valid_test = """
5279 TEST_F(%(test_name)s, %(name)sValidArgs) {
5280 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5281 SpecializedSetup<cmds::%(name)s, 0>(true);
5282 cmds::%(name)s cmd;
5283 cmd.Init(%(args)s);
5284 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5285 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5288 args = func.GetOriginalArgs()
5289 local_args = "%s, 1, _" % args[0].GetValidGLArg(func, 0, 0)
5290 self.WriteValidUnitTest(func, file, valid_test, {
5291 'name': func.name,
5292 'count': func.GetInfo('count'),
5293 'local_args': local_args,
5296 invalid_test = """
5297 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5298 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5299 SpecializedSetup<cmds::%(name)s, 0>(false);
5300 cmds::%(name)s cmd;
5301 cmd.Init(%(args)s);
5302 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5305 self.WriteInvalidUnitTest(func, file, invalid_test, {
5306 'name': func.GetInfo('name'),
5307 'count': func.GetInfo('count'),
5311 class GLcharHandler(CustomHandler):
5312 """Handler for functions that pass a single string ."""
5314 def __init__(self):
5315 CustomHandler.__init__(self)
5317 def WriteImmediateCmdComputeSize(self, func, file):
5318 """Overrriden from TypeHandler."""
5319 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5320 file.Write(" return static_cast<uint32>(\n")
5321 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5322 file.Write(" }\n")
5324 def WriteImmediateCmdSetHeader(self, func, file):
5325 """Overrriden from TypeHandler."""
5326 code = """
5327 void SetHeader(uint32 data_size) {
5328 header.SetCmdBySize<ValueType>(data_size);
5331 file.Write(code)
5333 def WriteImmediateCmdInit(self, func, file):
5334 """Overrriden from TypeHandler."""
5335 last_arg = func.GetLastOriginalArg()
5336 args = func.GetCmdArgs()
5337 set_code = []
5338 for arg in args:
5339 set_code.append(" %s = _%s;" % (arg.name, arg.name))
5340 code = """
5341 void Init(%(typed_args)s, uint32 _data_size) {
5342 SetHeader(_data_size);
5343 %(set_code)s
5344 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5348 file.Write(code % {
5349 "typed_args": func.MakeTypedOriginalArgString("_"),
5350 "set_code": "\n".join(set_code),
5351 "last_arg": last_arg.name
5354 def WriteImmediateCmdSet(self, func, file):
5355 """Overrriden from TypeHandler."""
5356 last_arg = func.GetLastOriginalArg()
5357 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5358 func.MakeTypedOriginalArgString("_", True))
5359 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5360 func.MakeOriginalArgString("_"))
5361 file.Write(" return NextImmediateCmdAddress<ValueType>("
5362 "cmd, _data_size);\n")
5363 file.Write(" }\n")
5364 file.Write("\n")
5366 def WriteImmediateCmdHelper(self, func, file):
5367 """Overrriden from TypeHandler."""
5368 code = """ void %(name)s(%(typed_args)s) {
5369 const uint32 data_size = strlen(name);
5370 gles2::cmds::%(name)s* c =
5371 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5372 if (c) {
5373 c->Init(%(args)s, data_size);
5378 file.Write(code % {
5379 "name": func.name,
5380 "typed_args": func.MakeTypedOriginalArgString(""),
5381 "args": func.MakeOriginalArgString(""),
5385 def WriteImmediateFormatTest(self, func, file):
5386 """Overrriden from TypeHandler."""
5387 init_code = []
5388 check_code = []
5389 all_but_last_arg = func.GetCmdArgs()[:-1]
5390 for value, arg in enumerate(all_but_last_arg):
5391 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
5392 for value, arg in enumerate(all_but_last_arg):
5393 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5394 (arg.type, value + 11, arg.name))
5395 code = """
5396 TEST_F(GLES2FormatTest, %(func_name)s) {
5397 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5398 static const char* const test_str = \"test string\";
5399 void* next_cmd = cmd.Set(
5400 &cmd,
5401 %(init_code)s
5402 test_str,
5403 strlen(test_str));
5404 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5405 cmd.header.command);
5406 EXPECT_EQ(sizeof(cmd) +
5407 RoundSizeToMultipleOfEntries(strlen(test_str)),
5408 cmd.header.size * 4u);
5409 EXPECT_EQ(static_cast<char*>(next_cmd),
5410 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5411 RoundSizeToMultipleOfEntries(strlen(test_str)));
5412 %(check_code)s
5413 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5414 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5415 CheckBytesWritten(
5416 next_cmd,
5417 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5418 sizeof(cmd) + strlen(test_str));
5422 file.Write(code % {
5423 'func_name': func.name,
5424 'init_code': "\n".join(init_code),
5425 'check_code': "\n".join(check_code),
5429 class GLcharNHandler(CustomHandler):
5430 """Handler for functions that pass a single string with an optional len."""
5432 def __init__(self):
5433 CustomHandler.__init__(self)
5435 def InitFunction(self, func):
5436 """Overrriden from TypeHandler."""
5437 func.cmd_args = []
5438 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5440 def AddImmediateFunction(self, generator, func):
5441 """Overrriden from TypeHandler."""
5442 pass
5444 def AddBucketFunction(self, generator, func):
5445 """Overrriden from TypeHandler."""
5446 pass
5448 def WriteServiceImplementation(self, func, file):
5449 """Overrriden from TypeHandler."""
5450 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5451 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5452 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5453 Bucket* bucket = GetBucket(bucket_id);
5454 if (!bucket || bucket->size() == 0) {
5455 return error::kInvalidArguments;
5457 std::string str;
5458 if (!bucket->GetAsString(&str)) {
5459 return error::kInvalidArguments;
5461 %(gl_func_name)s(0, str.c_str());
5462 return error::kNoError;
5465 """ % {
5466 'name': func.name,
5467 'gl_func_name': func.GetGLFunctionName(),
5468 'bucket_id': func.cmd_args[0].name,
5472 class IsHandler(TypeHandler):
5473 """Handler for glIs____ type and glGetError functions."""
5475 def __init__(self):
5476 TypeHandler.__init__(self)
5478 def InitFunction(self, func):
5479 """Overrriden from TypeHandler."""
5480 func.AddCmdArg(Argument("result_shm_id", 'uint32'))
5481 func.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5482 if func.GetInfo('result') == None:
5483 func.AddInfo('result', ['uint32'])
5485 def WriteServiceUnitTest(self, func, file):
5486 """Overrriden from TypeHandler."""
5487 valid_test = """
5488 TEST_F(%(test_name)s, %(name)sValidArgs) {
5489 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5490 SpecializedSetup<cmds::%(name)s, 0>(true);
5491 cmds::%(name)s cmd;
5492 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5493 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5494 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5497 comma = ""
5498 if len(func.GetOriginalArgs()):
5499 comma =", "
5500 self.WriteValidUnitTest(func, file, valid_test, {
5501 'comma': comma,
5504 invalid_test = """
5505 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5506 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5507 SpecializedSetup<cmds::%(name)s, 0>(false);
5508 cmds::%(name)s cmd;
5509 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5510 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5513 self.WriteInvalidUnitTest(func, file, invalid_test, {
5514 'comma': comma,
5517 invalid_test = """
5518 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5519 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5520 SpecializedSetup<cmds::%(name)s, 0>(false);
5521 cmds::%(name)s cmd;
5522 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5523 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5524 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5525 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5528 self.WriteValidUnitTest(func, file, invalid_test, {
5529 'comma': comma,
5532 def WriteServiceImplementation(self, func, file):
5533 """Overrriden from TypeHandler."""
5534 file.Write(
5535 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
5536 file.Write(
5537 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5538 func.name)
5539 args = func.GetOriginalArgs()
5540 for arg in args:
5541 arg.WriteGetCode(file)
5543 code = """ typedef cmds::%(func_name)s::Result Result;
5544 Result* result_dst = GetSharedMemoryAs<Result*>(
5545 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5546 if (!result_dst) {
5547 return error::kOutOfBounds;
5550 file.Write(code % {'func_name': func.name})
5551 func.WriteHandlerValidation(file)
5552 file.Write(" *result_dst = %s(%s);\n" %
5553 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5554 file.Write(" return error::kNoError;\n")
5555 file.Write("}\n")
5556 file.Write("\n")
5558 def WriteGLES2Implementation(self, func, file):
5559 """Overrriden from TypeHandler."""
5560 impl_func = func.GetInfo('impl_func')
5561 if impl_func == None or impl_func == True:
5562 error_value = func.GetInfo("error_value") or "GL_FALSE"
5563 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5564 (func.return_type, func.original_name,
5565 func.MakeTypedOriginalArgString("")))
5566 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5567 self.WriteTraceEvent(func, file)
5568 func.WriteDestinationInitalizationValidation(file)
5569 self.WriteClientGLCallLog(func, file)
5570 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
5571 file.Write(" Result* result = GetResultAs<Result*>();\n")
5572 file.Write(" if (!result) {\n")
5573 file.Write(" return %s;\n" % error_value)
5574 file.Write(" }\n")
5575 file.Write(" *result = 0;\n")
5576 arg_string = func.MakeOriginalArgString("")
5577 comma = ""
5578 if len(arg_string) > 0:
5579 comma = ", "
5580 file.Write(
5581 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5582 (func.name, arg_string, comma))
5583 file.Write(" WaitForCmd();\n")
5584 file.Write(" %s result_value = *result;\n" % func.return_type)
5585 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5586 file.Write(" CheckGLError();\n")
5587 file.Write(" return result_value;\n")
5588 file.Write("}\n")
5589 file.Write("\n")
5591 def WriteGLES2ImplementationUnitTest(self, func, file):
5592 """Overrriden from TypeHandler."""
5593 client_test = func.GetInfo('client_test')
5594 if client_test == None or client_test == True:
5595 code = """
5596 TEST_F(GLES2ImplementationTest, %(name)s) {
5597 struct Cmds {
5598 cmds::%(name)s cmd;
5601 typedef cmds::%(name)s::Result Result;
5602 Cmds expected;
5603 ExpectedMemoryInfo result1 =
5604 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5605 expected.cmd.Init(1, result1.id, result1.offset);
5607 EXPECT_CALL(*command_buffer(), OnFlush())
5608 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5609 .RetiresOnSaturation();
5611 GLboolean result = gl_->%(name)s(1);
5612 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5613 EXPECT_TRUE(result);
5616 file.Write(code % {
5617 'name': func.name,
5621 class STRnHandler(TypeHandler):
5622 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5623 GetTranslatedShaderSourceANGLE."""
5625 def __init__(self):
5626 TypeHandler.__init__(self)
5628 def InitFunction(self, func):
5629 """Overrriden from TypeHandler."""
5630 # remove all but the first cmd args.
5631 cmd_args = func.GetCmdArgs()
5632 func.ClearCmdArgs()
5633 func.AddCmdArg(cmd_args[0])
5634 # add on a bucket id.
5635 func.AddCmdArg(Argument('bucket_id', 'uint32'))
5637 def WriteGLES2Implementation(self, func, file):
5638 """Overrriden from TypeHandler."""
5639 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5640 GPU_CLIENT_SINGLE_THREAD_CHECK();
5642 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5643 << "] gl%(func_name)s" << "("
5644 << %(arg0)s << ", "
5645 << %(arg1)s << ", "
5646 << static_cast<void*>(%(arg2)s) << ", "
5647 << static_cast<void*>(%(arg3)s) << ")");
5648 helper_->SetBucketSize(kResultBucketId, 0);
5649 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5650 std::string str;
5651 GLsizei max_size = 0;
5652 if (GetBucketAsString(kResultBucketId, &str)) {
5653 if (bufsize > 0) {
5654 max_size =
5655 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5656 memcpy(%(dest_name)s, str.c_str(), max_size);
5657 %(dest_name)s[max_size] = '\\0';
5658 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5661 if (%(length_name)s != NULL) {
5662 *%(length_name)s = max_size;
5664 CheckGLError();
5667 args = func.GetOriginalArgs()
5668 str_args = {
5669 'return_type': func.return_type,
5670 'func_name': func.original_name,
5671 'args': func.MakeTypedOriginalArgString(""),
5672 'id_name': args[0].name,
5673 'bufsize_name': args[1].name,
5674 'length_name': args[2].name,
5675 'dest_name': args[3].name,
5676 'arg0': args[0].name,
5677 'arg1': args[1].name,
5678 'arg2': args[2].name,
5679 'arg3': args[3].name,
5681 file.Write(code_1 % str_args)
5682 func.WriteDestinationInitalizationValidation(file)
5683 file.Write(code_2 % str_args)
5685 def WriteServiceUnitTest(self, func, file):
5686 """Overrriden from TypeHandler."""
5687 valid_test = """
5688 TEST_F(%(test_name)s, %(name)sValidArgs) {
5689 const char* kInfo = "hello";
5690 const uint32 kBucketId = 123;
5691 SpecializedSetup<cmds::%(name)s, 0>(true);
5692 %(expect_len_code)s
5693 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5694 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5695 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5696 cmds::%(name)s cmd;
5697 cmd.Init(%(args)s);
5698 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5699 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5700 ASSERT_TRUE(bucket != NULL);
5701 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5702 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5703 bucket->size()));
5704 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5707 args = func.GetOriginalArgs()
5708 id_name = args[0].GetValidGLArg(func, 0, 0)
5709 get_len_func = func.GetInfo('get_len_func')
5710 get_len_enum = func.GetInfo('get_len_enum')
5711 sub = {
5712 'id_name': id_name,
5713 'get_len_func': get_len_func,
5714 'get_len_enum': get_len_enum,
5715 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5716 args[0].GetValidGLArg(func, 0, 0),
5717 'args': '%s, kBucketId' % args[0].GetValidArg(func, 0, 0),
5718 'expect_len_code': '',
5720 if get_len_func and get_len_func[0:2] == 'gl':
5721 sub['expect_len_code'] = (
5722 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5723 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5724 get_len_func[2:], id_name, get_len_enum)
5725 self.WriteValidUnitTest(func, file, valid_test, sub)
5727 invalid_test = """
5728 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5729 const uint32 kBucketId = 123;
5730 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5731 .Times(0);
5732 cmds::%(name)s cmd;
5733 cmd.Init(kInvalidClientId, kBucketId);
5734 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5735 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5738 self.WriteValidUnitTest(func, file, invalid_test)
5740 def WriteServiceImplementation(self, func, file):
5741 """Overrriden from TypeHandler."""
5742 pass
5745 class FunctionInfo(object):
5746 """Holds info about a function."""
5748 def __init__(self, info, type_handler):
5749 for key in info:
5750 setattr(self, key, info[key])
5751 self.type_handler = type_handler
5752 if not 'type' in info:
5753 self.type = ''
5756 class Argument(object):
5757 """A class that represents a function argument."""
5759 cmd_type_map_ = {
5760 'GLenum': 'uint32',
5761 'GLint': 'int32',
5762 'GLintptr': 'int32',
5763 'GLsizei': 'int32',
5764 'GLsizeiptr': 'int32',
5765 'GLfloat': 'float',
5766 'GLclampf': 'float',
5768 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5770 def __init__(self, name, type):
5771 self.name = name
5772 self.optional = type.endswith("Optional*")
5773 if self.optional:
5774 type = type[:-9] + "*"
5775 self.type = type
5777 if type in self.cmd_type_map_:
5778 self.cmd_type = self.cmd_type_map_[type]
5779 else:
5780 self.cmd_type = 'uint32'
5782 def IsPointer(self):
5783 """Returns true if argument is a pointer."""
5784 return False
5786 def AddCmdArgs(self, args):
5787 """Adds command arguments for this argument to the given list."""
5788 return args.append(self)
5790 def AddInitArgs(self, args):
5791 """Adds init arguments for this argument to the given list."""
5792 return args.append(self)
5794 def GetValidArg(self, func, offset, index):
5795 """Gets a valid value for this argument."""
5796 valid_arg = func.GetValidArg(offset)
5797 if valid_arg != None:
5798 return valid_arg
5799 return str(offset + 1)
5801 def GetValidClientSideArg(self, func, offset, index):
5802 """Gets a valid value for this argument."""
5803 return str(offset + 1)
5805 def GetValidClientSideCmdArg(self, func, offset, index):
5806 """Gets a valid value for this argument."""
5807 return str(offset + 1)
5809 def GetValidGLArg(self, func, offset, index):
5810 """Gets a valid GL value for this argument."""
5811 valid_arg = func.GetValidArg(offset)
5812 if valid_arg != None:
5813 return valid_arg
5814 return str(offset + 1)
5816 def GetNumInvalidValues(self, func):
5817 """returns the number of invalid values to be tested."""
5818 return 0
5820 def GetInvalidArg(self, offset, index):
5821 """returns an invalid value and expected parse result by index."""
5822 return ("---ERROR0---", "---ERROR2---", None)
5824 def GetLogArg(self):
5825 """Get argument appropriate for LOG macro."""
5826 if self.type == 'GLboolean':
5827 return 'GLES2Util::GetStringBool(%s)' % self.name
5828 if self.type == 'GLenum':
5829 return 'GLES2Util::GetStringEnum(%s)' % self.name
5830 return self.name
5832 def WriteGetCode(self, file):
5833 """Writes the code to get an argument from a command structure."""
5834 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5835 (self.type, self.name, self.type, self.name))
5837 def WriteValidationCode(self, file, func):
5838 """Writes the validation code for an argument."""
5839 pass
5841 def WriteClientSideValidationCode(self, file, func):
5842 """Writes the validation code for an argument."""
5843 pass
5845 def WriteDestinationInitalizationValidation(self, file, func):
5846 """Writes the client side destintion initialization validation."""
5847 pass
5849 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
5850 """Writes the client side destintion initialization validation if needed."""
5851 parts = self.type.split(" ")
5852 if len(parts) > 1:
5853 return
5854 if parts[0] in self.need_validation_:
5855 file.Write(
5856 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5857 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
5860 def WriteGetAddress(self, file):
5861 """Writes the code to get the address this argument refers to."""
5862 pass
5864 def GetImmediateVersion(self):
5865 """Gets the immediate version of this argument."""
5866 return self
5868 def GetBucketVersion(self):
5869 """Gets the bucket version of this argument."""
5870 return self
5873 class BoolArgument(Argument):
5874 """class for GLboolean"""
5876 def __init__(self, name, type):
5877 Argument.__init__(self, name, 'GLboolean')
5879 def GetValidArg(self, func, offset, index):
5880 """Gets a valid value for this argument."""
5881 return 'true'
5883 def GetValidClientSideArg(self, func, offset, index):
5884 """Gets a valid value for this argument."""
5885 return 'true'
5887 def GetValidClientSideCmdArg(self, func, offset, index):
5888 """Gets a valid value for this argument."""
5889 return 'true'
5891 def GetValidGLArg(self, func, offset, index):
5892 """Gets a valid GL value for this argument."""
5893 return 'true'
5896 class UniformLocationArgument(Argument):
5897 """class for uniform locations."""
5899 def __init__(self, name):
5900 Argument.__init__(self, name, "GLint")
5902 def WriteGetCode(self, file):
5903 """Writes the code to get an argument from a command structure."""
5904 code = """ %s %s = static_cast<%s>(c.%s);
5906 file.Write(code % (self.type, self.name, self.type, self.name))
5908 def GetValidArg(self, func, offset, index):
5909 """Gets a valid value for this argument."""
5910 return "%d" % (offset + 1)
5913 class DataSizeArgument(Argument):
5914 """class for data_size which Bucket commands do not need."""
5916 def __init__(self, name):
5917 Argument.__init__(self, name, "uint32")
5919 def GetBucketVersion(self):
5920 return None
5923 class SizeArgument(Argument):
5924 """class for GLsizei and GLsizeiptr."""
5926 def __init__(self, name, type):
5927 Argument.__init__(self, name, type)
5929 def GetNumInvalidValues(self, func):
5930 """overridden from Argument."""
5931 if func.is_immediate:
5932 return 0
5933 return 1
5935 def GetInvalidArg(self, offset, index):
5936 """overridden from Argument."""
5937 return ("-1", "kNoError", "GL_INVALID_VALUE")
5939 def WriteValidationCode(self, file, func):
5940 """overridden from Argument."""
5941 file.Write(" if (%s < 0) {\n" % self.name)
5942 file.Write(
5943 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5944 (func.original_name, self.name))
5945 file.Write(" return error::kNoError;\n")
5946 file.Write(" }\n")
5948 def WriteClientSideValidationCode(self, file, func):
5949 """overridden from Argument."""
5950 file.Write(" if (%s < 0) {\n" % self.name)
5951 file.Write(
5952 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5953 (func.original_name, self.name))
5954 file.Write(" return;\n")
5955 file.Write(" }\n")
5958 class SizeNotNegativeArgument(SizeArgument):
5959 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5961 def __init__(self, name, type, gl_type):
5962 SizeArgument.__init__(self, name, gl_type)
5964 def GetInvalidArg(self, offset, index):
5965 """overridden from SizeArgument."""
5966 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5968 def WriteValidationCode(self, file, func):
5969 """overridden from SizeArgument."""
5970 pass
5973 class EnumBaseArgument(Argument):
5974 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5976 def __init__(self, name, gl_type, type, gl_error):
5977 Argument.__init__(self, name, gl_type)
5979 self.local_type = type
5980 self.gl_error = gl_error
5981 name = type[len(gl_type):]
5982 self.type_name = name
5983 self.enum_info = _ENUM_LISTS[name]
5985 def WriteValidationCode(self, file, func):
5986 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5987 (ToUnderscore(self.type_name), self.name))
5988 if self.gl_error == "GL_INVALID_ENUM":
5989 file.Write(
5990 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5991 (func.original_name, self.name, self.name))
5992 else:
5993 file.Write(
5994 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5995 (self.gl_error, func.original_name, self.name, self.gl_error))
5996 file.Write(" return error::kNoError;\n")
5997 file.Write(" }\n")
5999 def GetValidArg(self, func, offset, index):
6000 valid_arg = func.GetValidArg(offset)
6001 if valid_arg != None:
6002 return valid_arg
6003 if 'valid' in self.enum_info:
6004 valid = self.enum_info['valid']
6005 num_valid = len(valid)
6006 if index >= num_valid:
6007 index = num_valid - 1
6008 return valid[index]
6009 return str(offset + 1)
6011 def GetValidClientSideArg(self, func, offset, index):
6012 """Gets a valid value for this argument."""
6013 return self.GetValidArg(func, offset, index)
6015 def GetValidClientSideCmdArg(self, func, offset, index):
6016 """Gets a valid value for this argument."""
6017 return self.GetValidArg(func, offset, index)
6019 def GetValidGLArg(self, func, offset, index):
6020 """Gets a valid value for this argument."""
6021 return self.GetValidArg(func, offset, index)
6023 def GetNumInvalidValues(self, func):
6024 """returns the number of invalid values to be tested."""
6025 if 'invalid' in self.enum_info:
6026 invalid = self.enum_info['invalid']
6027 return len(invalid)
6028 return 0
6030 def GetInvalidArg(self, offset, index):
6031 """returns an invalid value by index."""
6032 if 'invalid' in self.enum_info:
6033 invalid = self.enum_info['invalid']
6034 num_invalid = len(invalid)
6035 if index >= num_invalid:
6036 index = num_invalid - 1
6037 return (invalid[index], "kNoError", self.gl_error)
6038 return ("---ERROR1---", "kNoError", self.gl_error)
6041 class EnumArgument(EnumBaseArgument):
6042 """A class that represents a GLenum argument"""
6044 def __init__(self, name, type):
6045 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
6047 def GetLogArg(self):
6048 """Overridden from Argument."""
6049 return ("GLES2Util::GetString%s(%s)" %
6050 (self.type_name, self.name))
6053 class IntArgument(EnumBaseArgument):
6054 """A class for a GLint argument that can only except specific values.
6056 For example glTexImage2D takes a GLint for its internalformat
6057 argument instead of a GLenum.
6060 def __init__(self, name, type):
6061 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
6064 class ValidatedBoolArgument(EnumBaseArgument):
6065 """A class for a GLboolean argument that can only except specific values.
6067 For example glUniformMatrix takes a GLboolean for it's transpose but it
6068 must be false.
6071 def __init__(self, name, type):
6072 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
6074 def GetLogArg(self):
6075 """Overridden from Argument."""
6076 return 'GLES2Util::GetStringBool(%s)' % self.name
6079 class ImmediatePointerArgument(Argument):
6080 """A class that represents an immediate argument to a function.
6082 An immediate argument is one where the data follows the command.
6085 def __init__(self, name, type):
6086 Argument.__init__(self, name, type)
6088 def AddCmdArgs(self, args):
6089 """Overridden from Argument."""
6090 pass
6092 def WriteGetCode(self, file):
6093 """Overridden from Argument."""
6094 file.Write(
6095 " %s %s = GetImmediateDataAs<%s>(\n" %
6096 (self.type, self.name, self.type))
6097 file.Write(" c, data_size, immediate_data_size);\n")
6099 def WriteValidationCode(self, file, func):
6100 """Overridden from Argument."""
6101 file.Write(" if (%s == NULL) {\n" % self.name)
6102 file.Write(" return error::kOutOfBounds;\n")
6103 file.Write(" }\n")
6105 def GetImmediateVersion(self):
6106 """Overridden from Argument."""
6107 return None
6109 def WriteDestinationInitalizationValidation(self, file, func):
6110 """Overridden from Argument."""
6111 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6113 def GetLogArg(self):
6114 """Overridden from Argument."""
6115 return "static_cast<const void*>(%s)" % self.name
6118 class BucketPointerArgument(Argument):
6119 """A class that represents an bucket argument to a function."""
6121 def __init__(self, name, type):
6122 Argument.__init__(self, name, type)
6124 def AddCmdArgs(self, args):
6125 """Overridden from Argument."""
6126 pass
6128 def WriteGetCode(self, file):
6129 """Overridden from Argument."""
6130 file.Write(
6131 " %s %s = bucket->GetData(0, data_size);\n" %
6132 (self.type, self.name))
6134 def WriteValidationCode(self, file, func):
6135 """Overridden from Argument."""
6136 pass
6138 def GetImmediateVersion(self):
6139 """Overridden from Argument."""
6140 return None
6142 def WriteDestinationInitalizationValidation(self, file, func):
6143 """Overridden from Argument."""
6144 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6146 def GetLogArg(self):
6147 """Overridden from Argument."""
6148 return "static_cast<const void*>(%s)" % self.name
6151 class PointerArgument(Argument):
6152 """A class that represents a pointer argument to a function."""
6154 def __init__(self, name, type):
6155 Argument.__init__(self, name, type)
6157 def IsPointer(self):
6158 """Returns true if argument is a pointer."""
6159 return True
6161 def GetValidArg(self, func, offset, index):
6162 """Overridden from Argument."""
6163 return "shared_memory_id_, shared_memory_offset_"
6165 def GetValidGLArg(self, func, offset, index):
6166 """Overridden from Argument."""
6167 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
6169 def GetNumInvalidValues(self, func):
6170 """Overridden from Argument."""
6171 return 2
6173 def GetInvalidArg(self, offset, index):
6174 """Overridden from Argument."""
6175 if index == 0:
6176 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6177 else:
6178 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6179 "kOutOfBounds", None)
6181 def GetLogArg(self):
6182 """Overridden from Argument."""
6183 return "static_cast<const void*>(%s)" % self.name
6185 def AddCmdArgs(self, args):
6186 """Overridden from Argument."""
6187 args.append(Argument("%s_shm_id" % self.name, 'uint32'))
6188 args.append(Argument("%s_shm_offset" % self.name, 'uint32'))
6190 def WriteGetCode(self, file):
6191 """Overridden from Argument."""
6192 file.Write(
6193 " %s %s = GetSharedMemoryAs<%s>(\n" %
6194 (self.type, self.name, self.type))
6195 file.Write(
6196 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6197 (self.name, self.name))
6199 def WriteGetAddress(self, file):
6200 """Overridden from Argument."""
6201 file.Write(
6202 " %s %s = GetSharedMemoryAs<%s>(\n" %
6203 (self.type, self.name, self.type))
6204 file.Write(
6205 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6206 (self.name, self.name, self.name))
6208 def WriteValidationCode(self, file, func):
6209 """Overridden from Argument."""
6210 file.Write(" if (%s == NULL) {\n" % self.name)
6211 file.Write(" return error::kOutOfBounds;\n")
6212 file.Write(" }\n")
6214 def GetImmediateVersion(self):
6215 """Overridden from Argument."""
6216 return ImmediatePointerArgument(self.name, self.type)
6218 def GetBucketVersion(self):
6219 """Overridden from Argument."""
6220 if self.type == "const char*":
6221 return InputStringBucketArgument(self.name, self.type)
6222 return BucketPointerArgument(self.name, self.type)
6224 def WriteDestinationInitalizationValidation(self, file, func):
6225 """Overridden from Argument."""
6226 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6229 class InputStringBucketArgument(Argument):
6230 """An string input argument where the string is passed in a bucket."""
6232 def __init__(self, name, type):
6233 Argument.__init__(self, name + "_bucket_id", "uint32")
6235 def WriteGetCode(self, file):
6236 """Overridden from Argument."""
6237 code = """
6238 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6239 if (!%(name)s_bucket) {
6240 return error::kInvalidArguments;
6242 std::string %(name)s_str;
6243 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6244 return error::kInvalidArguments;
6246 const char* %(name)s = %(name)s_str.c_str();
6248 file.Write(code % {
6249 'name': self.name,
6252 def GetValidArg(self, func, offset, index):
6253 return "kNameBucketId"
6255 def GetValidGLArg(self, func, offset, index):
6256 return "_"
6259 class NonImmediatePointerArgument(PointerArgument):
6260 """A pointer argument that stays a pointer even in an immediate cmd."""
6262 def __init__(self, name, type):
6263 PointerArgument.__init__(self, name, type)
6265 def IsPointer(self):
6266 """Returns true if argument is a pointer."""
6267 return False
6269 def GetImmediateVersion(self):
6270 """Overridden from Argument."""
6271 return self
6274 class ResourceIdArgument(Argument):
6275 """A class that represents a resource id argument to a function."""
6277 def __init__(self, name, type):
6278 match = re.match("(GLid\w+)", type)
6279 self.resource_type = match.group(1)[4:]
6280 type = type.replace(match.group(1), "GLuint")
6281 Argument.__init__(self, name, type)
6283 def WriteGetCode(self, file):
6284 """Overridden from Argument."""
6285 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6287 def GetValidArg(self, func, offset, index):
6288 return "client_%s_id_" % self.resource_type.lower()
6290 def GetValidGLArg(self, func, offset, index):
6291 return "kService%sId" % self.resource_type
6294 class ResourceIdBindArgument(Argument):
6295 """Represents a resource id argument to a bind function."""
6297 def __init__(self, name, type):
6298 match = re.match("(GLidBind\w+)", type)
6299 self.resource_type = match.group(1)[8:]
6300 type = type.replace(match.group(1), "GLuint")
6301 Argument.__init__(self, name, type)
6303 def WriteGetCode(self, file):
6304 """Overridden from Argument."""
6305 code = """ %(type)s %(name)s = c.%(name)s;
6307 file.Write(code % {'type': self.type, 'name': self.name})
6309 def GetValidArg(self, func, offset, index):
6310 return "client_%s_id_" % self.resource_type.lower()
6312 def GetValidGLArg(self, func, offset, index):
6313 return "kService%sId" % self.resource_type
6316 class ResourceIdZeroArgument(Argument):
6317 """Represents a resource id argument to a function that can be zero."""
6319 def __init__(self, name, type):
6320 match = re.match("(GLidZero\w+)", type)
6321 self.resource_type = match.group(1)[8:]
6322 type = type.replace(match.group(1), "GLuint")
6323 Argument.__init__(self, name, type)
6325 def WriteGetCode(self, file):
6326 """Overridden from Argument."""
6327 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6329 def GetValidArg(self, func, offset, index):
6330 return "client_%s_id_" % self.resource_type.lower()
6332 def GetValidGLArg(self, func, offset, index):
6333 return "kService%sId" % self.resource_type
6335 def GetNumInvalidValues(self, func):
6336 """returns the number of invalid values to be tested."""
6337 return 1
6339 def GetInvalidArg(self, offset, index):
6340 """returns an invalid value by index."""
6341 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6344 class Function(object):
6345 """A class that represents a function."""
6347 def __init__(self, original_name, name, info, return_type, original_args,
6348 args_for_cmds, cmd_args, init_args, num_pointer_args):
6349 self.name = name
6350 self.original_name = original_name
6351 self.info = info
6352 self.type_handler = info.type_handler
6353 self.return_type = return_type
6354 self.original_args = original_args
6355 self.num_pointer_args = num_pointer_args
6356 self.can_auto_generate = num_pointer_args == 0 and return_type == "void"
6357 self.cmd_args = cmd_args
6358 self.init_args = init_args
6359 self.InitFunction()
6360 self.args_for_cmds = args_for_cmds
6361 self.is_immediate = False
6363 def IsType(self, type_name):
6364 """Returns true if function is a certain type."""
6365 return self.info.type == type_name
6367 def InitFunction(self):
6368 """Calls the init function for the type handler."""
6369 self.type_handler.InitFunction(self)
6371 def GetInfo(self, name):
6372 """Returns a value from the function info for this function."""
6373 if hasattr(self.info, name):
6374 return getattr(self.info, name)
6375 return None
6377 def GetValidArg(self, index):
6378 """Gets a valid arg from the function info if one exists."""
6379 valid_args = self.GetInfo('valid_args')
6380 if valid_args and str(index) in valid_args:
6381 return valid_args[str(index)]
6382 return None
6384 def AddInfo(self, name, value):
6385 """Adds an info."""
6386 setattr(self.info, name, value)
6388 def IsCoreGLFunction(self):
6389 return (not self.GetInfo('extension') and
6390 not self.GetInfo('pepper_interface'))
6392 def InPepperInterface(self, interface):
6393 ext = self.GetInfo('pepper_interface')
6394 if not interface.GetName():
6395 return self.IsCoreGLFunction()
6396 return ext == interface.GetName()
6398 def InAnyPepperExtension(self):
6399 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
6401 def GetGLFunctionName(self):
6402 """Gets the function to call to execute GL for this command."""
6403 if self.GetInfo('decoder_func'):
6404 return self.GetInfo('decoder_func')
6405 return "gl%s" % self.original_name
6407 def GetGLTestFunctionName(self):
6408 gl_func_name = self.GetInfo('gl_test_func')
6409 if gl_func_name == None:
6410 gl_func_name = self.GetGLFunctionName()
6411 if gl_func_name.startswith("gl"):
6412 gl_func_name = gl_func_name[2:]
6413 else:
6414 gl_func_name = self.original_name
6415 return gl_func_name
6417 def AddCmdArg(self, arg):
6418 """Adds a cmd argument to this function."""
6419 self.cmd_args.append(arg)
6421 def GetCmdArgs(self):
6422 """Gets the command args for this function."""
6423 return self.cmd_args
6425 def ClearCmdArgs(self):
6426 """Clears the command args for this function."""
6427 self.cmd_args = []
6429 def GetInitArgs(self):
6430 """Gets the init args for this function."""
6431 return self.init_args
6433 def GetOriginalArgs(self):
6434 """Gets the original arguments to this function."""
6435 return self.original_args
6437 def GetLastOriginalArg(self):
6438 """Gets the last original argument to this function."""
6439 return self.original_args[len(self.original_args) - 1]
6441 def __MaybePrependComma(self, arg_string, add_comma):
6442 """Adds a comma if arg_string is not empty and add_comma is true."""
6443 comma = ""
6444 if add_comma and len(arg_string):
6445 comma = ", "
6446 return "%s%s" % (comma, arg_string)
6448 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
6449 """Gets a list of arguments as they are in GL."""
6450 args = self.GetOriginalArgs()
6451 arg_string = ", ".join(
6452 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6453 return self.__MaybePrependComma(arg_string, add_comma)
6455 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
6456 """Gets the list of arguments as they are in GL."""
6457 args = self.GetOriginalArgs()
6458 arg_string = separator.join(
6459 ["%s%s" % (prefix, arg.name) for arg in args])
6460 return self.__MaybePrependComma(arg_string, add_comma)
6462 def MakeTypedPepperArgString(self, prefix):
6463 """Gets a list of arguments as they need to be for Pepper."""
6464 if self.GetInfo("pepper_args"):
6465 return self.GetInfo("pepper_args")
6466 else:
6467 return self.MakeTypedOriginalArgString(prefix, False)
6469 def GetPepperName(self):
6470 if self.GetInfo("pepper_name"):
6471 return self.GetInfo("pepper_name")
6472 return self.name
6474 def MakeTypedCmdArgString(self, prefix, add_comma = False):
6475 """Gets a typed list of arguments as they need to be for command buffers."""
6476 args = self.GetCmdArgs()
6477 arg_string = ", ".join(
6478 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6479 return self.__MaybePrependComma(arg_string, add_comma)
6481 def MakeCmdArgString(self, prefix, add_comma = False):
6482 """Gets the list of arguments as they need to be for command buffers."""
6483 args = self.GetCmdArgs()
6484 arg_string = ", ".join(
6485 ["%s%s" % (prefix, arg.name) for arg in args])
6486 return self.__MaybePrependComma(arg_string, add_comma)
6488 def MakeTypedInitString(self, prefix, add_comma = False):
6489 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6490 args = self.GetInitArgs()
6491 arg_string = ", ".join(
6492 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6493 return self.__MaybePrependComma(arg_string, add_comma)
6495 def MakeInitString(self, prefix, add_comma = False):
6496 """Gets the list of arguments as they need to be for cmd Init/Set."""
6497 args = self.GetInitArgs()
6498 arg_string = ", ".join(
6499 ["%s%s" % (prefix, arg.name) for arg in args])
6500 return self.__MaybePrependComma(arg_string, add_comma)
6502 def MakeLogArgString(self):
6503 """Makes a string of the arguments for the LOG macros"""
6504 args = self.GetOriginalArgs()
6505 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
6507 def WriteCommandDescription(self, file):
6508 """Writes a description of the command."""
6509 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
6511 def WriteHandlerValidation(self, file):
6512 """Writes validation code for the function."""
6513 for arg in self.GetOriginalArgs():
6514 arg.WriteValidationCode(file, self)
6515 self.WriteValidationCode(file)
6517 def WriteHandlerImplementation(self, file):
6518 """Writes the handler implementation for this command."""
6519 self.type_handler.WriteHandlerImplementation(self, file)
6521 def WriteValidationCode(self, file):
6522 """Writes the validation code for a command."""
6523 pass
6525 def WriteCmdFlag(self, file):
6526 """Writes the cmd cmd_flags constant."""
6527 flags = []
6528 trace_level = 3 # By default trace only at the highest level
6529 if hasattr(self.info, 'trace_level'):
6530 if (self.info.trace_level < 0) or (self.info.trace_level > 3):
6531 raise KeyError("Unhandled trace_level: %d" % self.info.trace_level)
6532 trace_level = self.info.trace_level
6534 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
6536 if len(flags) > 0:
6537 cmd_flags = ' | '.join(flags)
6538 else:
6539 cmd_flags = 0
6541 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
6544 def WriteCmdArgFlag(self, file):
6545 """Writes the cmd kArgFlags constant."""
6546 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6548 def WriteCmdComputeSize(self, file):
6549 """Writes the ComputeSize function for the command."""
6550 file.Write(" static uint32 ComputeSize() {\n")
6551 file.Write(
6552 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6553 file.Write(" }\n")
6554 file.Write("\n")
6556 def WriteCmdSetHeader(self, file):
6557 """Writes the cmd's SetHeader function."""
6558 file.Write(" void SetHeader() {\n")
6559 file.Write(" header.SetCmd<ValueType>();\n")
6560 file.Write(" }\n")
6561 file.Write("\n")
6563 def WriteCmdInit(self, file):
6564 """Writes the cmd's Init function."""
6565 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
6566 file.Write(" SetHeader();\n")
6567 args = self.GetCmdArgs()
6568 for arg in args:
6569 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6570 file.Write(" }\n")
6571 file.Write("\n")
6573 def WriteCmdSet(self, file):
6574 """Writes the cmd's Set function."""
6575 copy_args = self.MakeCmdArgString("_", False)
6576 file.Write(" void* Set(void* cmd%s) {\n" %
6577 self.MakeTypedCmdArgString("_", True))
6578 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
6579 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6580 file.Write(" }\n")
6581 file.Write("\n")
6583 def WriteStruct(self, file):
6584 self.type_handler.WriteStruct(self, file)
6586 def WriteDocs(self, file):
6587 self.type_handler.WriteDocs(self, file)
6589 def WriteCmdHelper(self, file):
6590 """Writes the cmd's helper."""
6591 self.type_handler.WriteCmdHelper(self, file)
6593 def WriteServiceImplementation(self, file):
6594 """Writes the service implementation for a command."""
6595 self.type_handler.WriteServiceImplementation(self, file)
6597 def WriteServiceUnitTest(self, file):
6598 """Writes the service implementation for a command."""
6599 self.type_handler.WriteServiceUnitTest(self, file)
6601 def WriteGLES2CLibImplementation(self, file):
6602 """Writes the GLES2 C Lib Implemention."""
6603 self.type_handler.WriteGLES2CLibImplementation(self, file)
6605 def WriteGLES2InterfaceHeader(self, file):
6606 """Writes the GLES2 Interface declaration."""
6607 self.type_handler.WriteGLES2InterfaceHeader(self, file)
6609 def WriteGLES2InterfaceStub(self, file):
6610 """Writes the GLES2 Interface Stub declaration."""
6611 self.type_handler.WriteGLES2InterfaceStub(self, file)
6613 def WriteGLES2InterfaceStubImpl(self, file):
6614 """Writes the GLES2 Interface Stub declaration."""
6615 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
6617 def WriteGLES2ImplementationHeader(self, file):
6618 """Writes the GLES2 Implemention declaration."""
6619 self.type_handler.WriteGLES2ImplementationHeader(self, file)
6621 def WriteGLES2Implementation(self, file):
6622 """Writes the GLES2 Implemention definition."""
6623 self.type_handler.WriteGLES2Implementation(self, file)
6625 def WriteGLES2TraceImplementationHeader(self, file):
6626 """Writes the GLES2 Trace Implemention declaration."""
6627 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
6629 def WriteGLES2TraceImplementation(self, file):
6630 """Writes the GLES2 Trace Implemention definition."""
6631 self.type_handler.WriteGLES2TraceImplementation(self, file)
6633 def WriteGLES2Header(self, file):
6634 """Writes the GLES2 Implemention unit test."""
6635 self.type_handler.WriteGLES2Header(self, file)
6637 def WriteGLES2ImplementationUnitTest(self, file):
6638 """Writes the GLES2 Implemention unit test."""
6639 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
6641 def WriteDestinationInitalizationValidation(self, file):
6642 """Writes the client side destintion initialization validation."""
6643 self.type_handler.WriteDestinationInitalizationValidation(self, file)
6645 def WriteFormatTest(self, file):
6646 """Writes the cmd's format test."""
6647 self.type_handler.WriteFormatTest(self, file)
6650 class PepperInterface(object):
6651 """A class that represents a function."""
6653 def __init__(self, info):
6654 self.name = info["name"]
6655 self.dev = info["dev"]
6657 def GetName(self):
6658 return self.name
6660 def GetInterfaceName(self):
6661 upperint = ""
6662 dev = ""
6663 if self.name:
6664 upperint = "_" + self.name.upper()
6665 if self.dev:
6666 dev = "_DEV"
6667 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
6669 def GetInterfaceString(self):
6670 dev = ""
6671 if self.dev:
6672 dev = "(Dev)"
6673 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6675 def GetStructName(self):
6676 dev = ""
6677 if self.dev:
6678 dev = "_Dev"
6679 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6682 class ImmediateFunction(Function):
6683 """A class that represnets an immediate function command."""
6685 def __init__(self, func):
6686 new_args = []
6687 for arg in func.GetOriginalArgs():
6688 new_arg = arg.GetImmediateVersion()
6689 if new_arg:
6690 new_args.append(new_arg)
6692 cmd_args = []
6693 new_args_for_cmds = []
6694 for arg in func.args_for_cmds:
6695 new_arg = arg.GetImmediateVersion()
6696 if new_arg:
6697 new_args_for_cmds.append(new_arg)
6698 new_arg.AddCmdArgs(cmd_args)
6700 new_init_args = []
6701 for arg in new_args_for_cmds:
6702 arg.AddInitArgs(new_init_args)
6704 Function.__init__(
6705 self,
6706 func.original_name,
6707 "%sImmediate" % func.name,
6708 func.info,
6709 func.return_type,
6710 new_args,
6711 new_args_for_cmds,
6712 cmd_args,
6713 new_init_args,
6715 self.is_immediate = True
6717 def WriteCommandDescription(self, file):
6718 """Overridden from Function"""
6719 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6720 self.original_name)
6722 def WriteServiceImplementation(self, file):
6723 """Overridden from Function"""
6724 self.type_handler.WriteImmediateServiceImplementation(self, file)
6726 def WriteHandlerImplementation(self, file):
6727 """Overridden from Function"""
6728 self.type_handler.WriteImmediateHandlerImplementation(self, file)
6730 def WriteServiceUnitTest(self, file):
6731 """Writes the service implementation for a command."""
6732 self.type_handler.WriteImmediateServiceUnitTest(self, file)
6734 def WriteValidationCode(self, file):
6735 """Overridden from Function"""
6736 self.type_handler.WriteImmediateValidationCode(self, file)
6738 def WriteCmdArgFlag(self, file):
6739 """Overridden from Function"""
6740 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6742 def WriteCmdComputeSize(self, file):
6743 """Overridden from Function"""
6744 self.type_handler.WriteImmediateCmdComputeSize(self, file)
6746 def WriteCmdSetHeader(self, file):
6747 """Overridden from Function"""
6748 self.type_handler.WriteImmediateCmdSetHeader(self, file)
6750 def WriteCmdInit(self, file):
6751 """Overridden from Function"""
6752 self.type_handler.WriteImmediateCmdInit(self, file)
6754 def WriteCmdSet(self, file):
6755 """Overridden from Function"""
6756 self.type_handler.WriteImmediateCmdSet(self, file)
6758 def WriteCmdHelper(self, file):
6759 """Overridden from Function"""
6760 self.type_handler.WriteImmediateCmdHelper(self, file)
6762 def WriteFormatTest(self, file):
6763 """Overridden from Function"""
6764 self.type_handler.WriteImmediateFormatTest(self, file)
6767 class BucketFunction(Function):
6768 """A class that represnets a bucket version of a function command."""
6770 def __init__(self, func):
6771 new_args = []
6772 for arg in func.GetOriginalArgs():
6773 new_arg = arg.GetBucketVersion()
6774 if new_arg:
6775 new_args.append(new_arg)
6777 cmd_args = []
6778 new_args_for_cmds = []
6779 for arg in func.args_for_cmds:
6780 new_arg = arg.GetBucketVersion()
6781 if new_arg:
6782 new_args_for_cmds.append(new_arg)
6783 new_arg.AddCmdArgs(cmd_args)
6785 new_init_args = []
6786 for arg in new_args_for_cmds:
6787 arg.AddInitArgs(new_init_args)
6789 Function.__init__(
6790 self,
6791 func.original_name,
6792 "%sBucket" % func.name,
6793 func.info,
6794 func.return_type,
6795 new_args,
6796 new_args_for_cmds,
6797 cmd_args,
6798 new_init_args,
6801 # def InitFunction(self):
6802 # """Overridden from Function"""
6803 # pass
6805 def WriteCommandDescription(self, file):
6806 """Overridden from Function"""
6807 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6808 self.original_name)
6810 def WriteServiceImplementation(self, file):
6811 """Overridden from Function"""
6812 self.type_handler.WriteBucketServiceImplementation(self, file)
6814 def WriteHandlerImplementation(self, file):
6815 """Overridden from Function"""
6816 self.type_handler.WriteBucketHandlerImplementation(self, file)
6818 def WriteServiceUnitTest(self, file):
6819 """Writes the service implementation for a command."""
6820 self.type_handler.WriteBucketServiceUnitTest(self, file)
6823 def CreateArg(arg_string):
6824 """Creates an Argument."""
6825 arg_parts = arg_string.split()
6826 if len(arg_parts) == 1 and arg_parts[0] == 'void':
6827 return None
6828 # Is this a pointer argument?
6829 elif arg_string.find('*') >= 0:
6830 if arg_parts[0] == 'NonImmediate':
6831 return NonImmediatePointerArgument(
6832 arg_parts[-1],
6833 " ".join(arg_parts[1:-1]))
6834 else:
6835 return PointerArgument(
6836 arg_parts[-1],
6837 " ".join(arg_parts[0:-1]))
6838 # Is this a resource argument? Must come after pointer check.
6839 elif arg_parts[0].startswith('GLidBind'):
6840 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6841 elif arg_parts[0].startswith('GLidZero'):
6842 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6843 elif arg_parts[0].startswith('GLid'):
6844 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6845 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
6846 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6847 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
6848 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6849 elif arg_parts[0].startswith('GLboolean'):
6850 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6851 elif arg_parts[0].startswith('GLintUniformLocation'):
6852 return UniformLocationArgument(arg_parts[-1])
6853 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
6854 not arg_parts[0].startswith('GLintptr')):
6855 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6856 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
6857 arg_parts[0].startswith('GLintptrNotNegative')):
6858 return SizeNotNegativeArgument(arg_parts[-1],
6859 " ".join(arg_parts[0:-1]),
6860 arg_parts[0][0:-11])
6861 elif arg_parts[0].startswith('GLsize'):
6862 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6863 else:
6864 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6867 class GLGenerator(object):
6868 """A class to generate GL command buffers."""
6870 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6872 def __init__(self, verbose):
6873 self.original_functions = []
6874 self.functions = []
6875 self.verbose = verbose
6876 self.errors = 0
6877 self._function_info = {}
6878 self._empty_type_handler = TypeHandler()
6879 self._empty_function_info = FunctionInfo({}, self._empty_type_handler)
6880 self.pepper_interfaces = []
6881 self.interface_info = {}
6883 self._type_handlers = {
6884 'Bind': BindHandler(),
6885 'Create': CreateHandler(),
6886 'Custom': CustomHandler(),
6887 'Data': DataHandler(),
6888 'Delete': DeleteHandler(),
6889 'DELn': DELnHandler(),
6890 'GENn': GENnHandler(),
6891 'GETn': GETnHandler(),
6892 'GLchar': GLcharHandler(),
6893 'GLcharN': GLcharNHandler(),
6894 'HandWritten': HandWrittenHandler(),
6895 'Is': IsHandler(),
6896 'Manual': ManualHandler(),
6897 'PUT': PUTHandler(),
6898 'PUTn': PUTnHandler(),
6899 'PUTXn': PUTXnHandler(),
6900 'StateSet': StateSetHandler(),
6901 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6902 'StateSetFrontBack': StateSetFrontBackHandler(),
6903 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6904 'StateSetNamedParameter': StateSetNamedParameter(),
6905 'STRn': STRnHandler(),
6906 'Todo': TodoHandler(),
6909 for func_name in _FUNCTION_INFO:
6910 info = _FUNCTION_INFO[func_name]
6911 type = ''
6912 if 'type' in info:
6913 type = info['type']
6914 self._function_info[func_name] = FunctionInfo(info,
6915 self.GetTypeHandler(type))
6916 for interface in _PEPPER_INTERFACES:
6917 interface = PepperInterface(interface)
6918 self.pepper_interfaces.append(interface)
6919 self.interface_info[interface.GetName()] = interface
6921 def AddFunction(self, func):
6922 """Adds a function."""
6923 self.functions.append(func)
6925 def GetTypeHandler(self, name):
6926 """Gets a type info for the given type."""
6927 if len(name):
6928 if name in self._type_handlers:
6929 return self._type_handlers[name]
6930 else:
6931 raise KeyError("no such type handler: %s" % name)
6932 return self._empty_type_handler
6934 def GetFunctionInfo(self, name):
6935 """Gets a type info for the given function name."""
6936 if name in self._function_info:
6937 return self._function_info[name]
6938 return self._empty_function_info
6940 def Log(self, msg):
6941 """Prints something if verbose is true."""
6942 if self.verbose:
6943 print msg
6945 def Error(self, msg):
6946 """Prints an error."""
6947 print "Error: %s" % msg
6948 self.errors += 1
6950 def WriteLicense(self, file):
6951 """Writes the license."""
6952 file.Write(_LICENSE)
6954 def WriteNamespaceOpen(self, file):
6955 """Writes the code for the namespace."""
6956 file.Write("namespace gpu {\n")
6957 file.Write("namespace gles2 {\n")
6958 file.Write("\n")
6960 def WriteNamespaceClose(self, file):
6961 """Writes the code to close the namespace."""
6962 file.Write("} // namespace gles2\n")
6963 file.Write("} // namespace gpu\n")
6964 file.Write("\n")
6966 def ParseArgs(self, arg_string):
6967 """Parses a function arg string."""
6968 args = []
6969 num_pointer_args = 0
6970 parts = arg_string.split(',')
6971 is_gl_enum = False
6972 for arg_string in parts:
6973 if arg_string.startswith('GLenum '):
6974 is_gl_enum = True
6975 arg = CreateArg(arg_string)
6976 if arg:
6977 args.append(arg)
6978 if arg.IsPointer():
6979 num_pointer_args += 1
6980 return (args, num_pointer_args, is_gl_enum)
6982 def ParseGLH(self, filename):
6983 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6984 f = open("gpu/command_buffer/cmd_buffer_functions.txt", "r")
6985 functions = f.read()
6986 f.close()
6987 for line in functions.splitlines():
6988 match = self._function_re.match(line)
6989 if match:
6990 func_name = match.group(2)[2:]
6991 func_info = self.GetFunctionInfo(func_name)
6992 if func_info.type != 'Noop':
6993 return_type = match.group(1).strip()
6994 arg_string = match.group(3)
6995 (args, num_pointer_args, is_gl_enum) = self.ParseArgs(arg_string)
6996 # comment in to find out which functions use bare enums.
6997 # if is_gl_enum:
6998 # self.Log("%s uses bare GLenum" % func_name)
6999 args_for_cmds = args
7000 if hasattr(func_info, 'cmd_args'):
7001 (args_for_cmds, num_pointer_args, is_gl_enum) = (
7002 self.ParseArgs(getattr(func_info, 'cmd_args')))
7003 cmd_args = []
7004 for arg in args_for_cmds:
7005 arg.AddCmdArgs(cmd_args)
7006 init_args = []
7007 for arg in args_for_cmds:
7008 arg.AddInitArgs(init_args)
7009 return_arg = CreateArg(return_type + " result")
7010 if return_arg:
7011 init_args.append(return_arg)
7012 f = Function(func_name, func_name, func_info, return_type, args,
7013 args_for_cmds, cmd_args, init_args, num_pointer_args)
7014 self.original_functions.append(f)
7015 gen_cmd = f.GetInfo('gen_cmd')
7016 if gen_cmd == True or gen_cmd == None:
7017 self.AddFunction(f)
7018 f.type_handler.AddImmediateFunction(self, f)
7019 f.type_handler.AddBucketFunction(self, f)
7021 self.Log("Auto Generated Functions : %d" %
7022 len([f for f in self.functions if f.can_auto_generate or
7023 (not f.IsType('') and not f.IsType('Custom') and
7024 not f.IsType('Todo'))]))
7026 funcs = [f for f in self.functions if not f.can_auto_generate and
7027 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
7028 self.Log("Non Auto Generated Functions: %d" % len(funcs))
7030 for f in funcs:
7031 self.Log(" %-10s %-20s gl%s" % (f.info.type, f.return_type, f.name))
7033 def WriteCommandIds(self, filename):
7034 """Writes the command buffer format"""
7035 file = CHeaderWriter(filename)
7036 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7037 id = 256
7038 for func in self.functions:
7039 file.Write(" %-60s /* %d */ \\\n" %
7040 ("OP(%s)" % func.name, id))
7041 id += 1
7042 file.Write("\n")
7044 file.Write("enum CommandId {\n")
7045 file.Write(" kStartPoint = cmd::kLastCommonId, "
7046 "// All GLES2 commands start after this.\n")
7047 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7048 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7049 file.Write("#undef GLES2_CMD_OP\n")
7050 file.Write(" kNumCommands\n")
7051 file.Write("};\n")
7052 file.Write("\n")
7053 file.Close()
7055 def WriteFormat(self, filename):
7056 """Writes the command buffer format"""
7057 file = CHeaderWriter(filename)
7058 for func in self.functions:
7059 if True:
7060 #gen_cmd = func.GetInfo('gen_cmd')
7061 #if gen_cmd == True or gen_cmd == None:
7062 func.WriteStruct(file)
7063 file.Write("\n")
7064 file.Close()
7066 def WriteDocs(self, filename):
7067 """Writes the command buffer doc version of the commands"""
7068 file = CWriter(filename)
7069 for func in self.functions:
7070 if True:
7071 #gen_cmd = func.GetInfo('gen_cmd')
7072 #if gen_cmd == True or gen_cmd == None:
7073 func.WriteDocs(file)
7074 file.Write("\n")
7075 file.Close()
7077 def WriteFormatTest(self, filename):
7078 """Writes the command buffer format test."""
7079 file = CHeaderWriter(
7080 filename,
7081 "// This file contains unit tests for gles2 commmands\n"
7082 "// It is included by gles2_cmd_format_test.cc\n"
7083 "\n")
7085 for func in self.functions:
7086 if True:
7087 #gen_cmd = func.GetInfo('gen_cmd')
7088 #if gen_cmd == True or gen_cmd == None:
7089 func.WriteFormatTest(file)
7091 file.Close()
7093 def WriteCmdHelperHeader(self, filename):
7094 """Writes the gles2 command helper."""
7095 file = CHeaderWriter(filename)
7097 for func in self.functions:
7098 if True:
7099 #gen_cmd = func.GetInfo('gen_cmd')
7100 #if gen_cmd == True or gen_cmd == None:
7101 func.WriteCmdHelper(file)
7103 file.Close()
7105 def WriteServiceContextStateHeader(self, filename):
7106 """Writes the service context state header."""
7107 file = CHeaderWriter(
7108 filename,
7109 "// It is included by context_state.h\n")
7110 file.Write("struct EnableFlags {\n")
7111 file.Write(" EnableFlags();\n")
7112 for capability in _CAPABILITY_FLAGS:
7113 file.Write(" bool %s;\n" % capability['name'])
7114 file.Write("};\n\n")
7116 for state_name in sorted(_STATES.keys()):
7117 state = _STATES[state_name]
7118 for item in state['states']:
7119 file.Write("%s %s;\n" % (item['type'], item['name']))
7120 file.Write("\n")
7122 file.Close()
7124 def WriteClientContextStateHeader(self, filename):
7125 """Writes the client context state header."""
7126 file = CHeaderWriter(
7127 filename,
7128 "// It is included by client_context_state.h\n")
7129 file.Write("struct EnableFlags {\n")
7130 file.Write(" EnableFlags();\n")
7131 for capability in _CAPABILITY_FLAGS:
7132 file.Write(" bool %s;\n" % capability['name'])
7133 file.Write("};\n\n")
7135 file.Close()
7137 def WriteContextStateGetters(self, file, class_name):
7138 """Writes the state getters."""
7139 for gl_type in ["GLint", "GLfloat"]:
7140 file.Write("""
7141 bool %s::GetStateAs%s(
7142 GLenum pname, %s* params, GLsizei* num_written) const {
7143 switch (pname) {
7144 """ % (class_name, gl_type, gl_type))
7145 for state_name in sorted(_STATES.keys()):
7146 state = _STATES[state_name]
7147 if 'enum' in state:
7148 file.Write(" case %s:\n" % state['enum'])
7149 file.Write(" *num_written = %d;\n" % len(state['states']))
7150 file.Write(" if (params) {\n")
7151 for ndx,item in enumerate(state['states']):
7152 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7153 (ndx, gl_type, item['name']))
7154 file.Write(" }\n")
7155 file.Write(" return true;\n")
7156 else:
7157 for item in state['states']:
7158 file.Write(" case %s:\n" % item['enum'])
7159 file.Write(" *num_written = 1;\n")
7160 file.Write(" if (params) {\n")
7161 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7162 (gl_type, item['name']))
7163 file.Write(" }\n")
7164 file.Write(" return true;\n")
7165 for capability in _CAPABILITY_FLAGS:
7166 file.Write(" case GL_%s:\n" % capability['name'].upper())
7167 file.Write(" *num_written = 1;\n")
7168 file.Write(" if (params) {\n")
7169 file.Write(
7170 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7171 (gl_type, capability['name']))
7172 file.Write(" }\n")
7173 file.Write(" return true;\n")
7174 file.Write(""" default:
7175 return false;
7178 """)
7180 def WriteServiceContextStateImpl(self, filename):
7181 """Writes the context state service implementation."""
7182 file = CHeaderWriter(
7183 filename,
7184 "// It is included by context_state.cc\n")
7185 code = []
7186 for capability in _CAPABILITY_FLAGS:
7187 code.append("%s(%s)" %
7188 (capability['name'],
7189 ('false', 'true')['default' in capability]))
7190 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7191 ",\n ".join(code))
7192 file.Write("\n")
7194 file.Write("void ContextState::Initialize() {\n")
7195 for state_name in sorted(_STATES.keys()):
7196 state = _STATES[state_name]
7197 for item in state['states']:
7198 file.Write(" %s = %s;\n" % (item['name'], item['default']))
7199 file.Write("}\n")
7201 file.Write("""
7202 void ContextState::InitCapabilities() const {
7203 """)
7204 for capability in _CAPABILITY_FLAGS:
7205 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7206 (capability['name'].upper(), capability['name']))
7207 file.Write("""}
7209 void ContextState::InitState() const {
7210 """)
7212 # We need to sort the keys so the expectations match
7213 for state_name in sorted(_STATES.keys()):
7214 state = _STATES[state_name]
7215 if state['type'] == 'FrontBack':
7216 num_states = len(state['states'])
7217 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7218 args = []
7219 for item in group:
7220 args.append('%s' % item['name'])
7221 file.Write(
7222 " gl%s(%s, %s);\n" %
7223 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7224 elif state['type'] == 'NamedParameter':
7225 for item in state['states']:
7226 if 'extension_flag' in item:
7227 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7228 item['extension_flag'])
7229 file.Write(" gl%s(%s, %s);\n" %
7230 (state['func'], item['enum'], item['name']))
7231 else:
7232 args = []
7233 for item in state['states']:
7234 args.append('%s' % item['name'])
7235 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
7236 file.Write("}\n")
7238 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7239 switch (cap) {
7240 """)
7241 for capability in _CAPABILITY_FLAGS:
7242 file.Write(" case GL_%s:\n" % capability['name'].upper())
7243 file.Write(" return enable_flags.%s;\n" % capability['name'])
7244 file.Write(""" default:
7245 NOTREACHED();
7246 return false;
7249 """)
7251 self.WriteContextStateGetters(file, "ContextState")
7252 file.Close()
7254 def WriteClientContextStateImpl(self, filename):
7255 """Writes the context state client side implementation."""
7256 file = CHeaderWriter(
7257 filename,
7258 "// It is included by client_context_state.cc\n")
7259 code = []
7260 for capability in _CAPABILITY_FLAGS:
7261 code.append("%s(%s)" %
7262 (capability['name'],
7263 ('false', 'true')['default' in capability]))
7264 file.Write(
7265 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7266 ",\n ".join(code))
7267 file.Write("\n")
7269 file.Write("""
7270 bool ClientContextState::SetCapabilityState(
7271 GLenum cap, bool enabled, bool* changed) {
7272 *changed = false;
7273 switch (cap) {
7274 """)
7275 for capability in _CAPABILITY_FLAGS:
7276 file.Write(" case GL_%s:\n" % capability['name'].upper())
7277 file.Write(""" if (enable_flags.%(name)s != enabled) {
7278 *changed = true;
7279 enable_flags.%(name)s = enabled;
7281 return true;
7282 """ % capability)
7283 file.Write(""" default:
7284 return false;
7287 """)
7288 file.Write("""bool ClientContextState::GetEnabled(
7289 GLenum cap, bool* enabled) const {
7290 switch (cap) {
7291 """)
7292 for capability in _CAPABILITY_FLAGS:
7293 file.Write(" case GL_%s:\n" % capability['name'].upper())
7294 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
7295 file.Write(" return true;\n")
7296 file.Write(""" default:
7297 return false;
7300 """)
7301 file.Close()
7303 def WriteServiceImplementation(self, filename):
7304 """Writes the service decorder implementation."""
7305 file = CHeaderWriter(
7306 filename,
7307 "// It is included by gles2_cmd_decoder.cc\n")
7309 for func in self.functions:
7310 if True:
7311 #gen_cmd = func.GetInfo('gen_cmd')
7312 #if gen_cmd == True or gen_cmd == None:
7313 func.WriteServiceImplementation(file)
7315 file.Write("""
7316 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7317 switch (cap) {
7318 """)
7319 for capability in _CAPABILITY_FLAGS:
7320 file.Write(" case GL_%s:\n" % capability['name'].upper())
7321 if 'state_flag' in capability:
7322 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7323 state_.enable_flags.%(name)s = enabled;
7324 %(state_flag)s = true;
7326 return false;
7327 """ % capability)
7328 else:
7329 file.Write(""" state_.enable_flags.%(name)s = enabled;
7330 return true;
7331 """ % capability)
7332 file.Write(""" default:
7333 NOTREACHED();
7334 return false;
7337 """)
7338 file.Close()
7340 def WriteServiceUnitTests(self, filename):
7341 """Writes the service decorder unit tests."""
7342 num_tests = len(self.functions)
7343 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
7344 count = 0
7345 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
7346 count += 1
7347 name = filename % count
7348 file = CHeaderWriter(
7349 name,
7350 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
7351 file.SetFileNum(count)
7352 end = test_num + FUNCTIONS_PER_FILE
7353 if end > num_tests:
7354 end = num_tests
7355 for idx in range(test_num, end):
7356 func = self.functions[idx]
7357 if True:
7358 #gen_cmd = func.GetInfo('gen_cmd')
7359 #if gen_cmd == True or gen_cmd == None:
7360 if func.GetInfo('unit_test') == False:
7361 file.Write("// TODO(gman): %s\n" % func.name)
7362 else:
7363 func.WriteServiceUnitTest(file)
7365 file.Close()
7366 file = CHeaderWriter(
7367 filename % 0,
7368 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7369 file.Write(
7370 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7371 """)
7372 for capability in _CAPABILITY_FLAGS:
7373 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7374 (capability['name'].upper(),
7375 ('false', 'true')['default' in capability]))
7376 file.Write("""}
7378 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7379 """)
7381 # We need to sort the keys so the expectations match
7382 for state_name in sorted(_STATES.keys()):
7383 state = _STATES[state_name]
7384 if state['type'] == 'FrontBack':
7385 num_states = len(state['states'])
7386 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7387 args = []
7388 for item in group:
7389 if 'expected' in item:
7390 args.append(item['expected'])
7391 else:
7392 args.append(item['default'])
7393 file.Write(
7394 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7395 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7396 file.Write(" .Times(1)\n")
7397 file.Write(" .RetiresOnSaturation();\n")
7398 elif state['type'] == 'NamedParameter':
7399 for item in state['states']:
7400 if 'extension_flag' in item:
7401 continue
7402 file.Write(
7403 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7404 (state['func'], item['enum'], item['default']))
7405 file.Write(" .Times(1)\n")
7406 file.Write(" .RetiresOnSaturation();\n")
7407 else:
7408 args = []
7409 for item in state['states']:
7410 if 'expected' in item:
7411 args.append(item['expected'])
7412 else:
7413 args.append(item['default'])
7414 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7415 (state['func'], ", ".join(args)))
7416 file.Write(" .Times(1)\n")
7417 file.Write(" .RetiresOnSaturation();\n")
7418 file.Write("""}
7419 """)
7420 file.Close()
7422 def WriteGLES2Header(self, filename):
7423 """Writes the GLES2 header."""
7424 file = CHeaderWriter(
7425 filename,
7426 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7428 for func in self.original_functions:
7429 func.WriteGLES2Header(file)
7431 file.Write("\n")
7432 file.Close()
7434 def WriteGLES2CLibImplementation(self, filename):
7435 """Writes the GLES2 c lib implementation."""
7436 file = CHeaderWriter(
7437 filename,
7438 "// These functions emulate GLES2 over command buffers.\n")
7440 for func in self.original_functions:
7441 func.WriteGLES2CLibImplementation(file)
7443 file.Write("""
7444 namespace gles2 {
7446 extern const NameToFunc g_gles2_function_table[] = {
7447 """)
7448 for func in self.original_functions:
7449 file.Write(
7450 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7451 (func.name, func.name))
7452 file.Write(""" { NULL, NULL, },
7455 } // namespace gles2
7456 """)
7457 file.Close()
7459 def WriteGLES2InterfaceHeader(self, filename):
7460 """Writes the GLES2 interface header."""
7461 file = CHeaderWriter(
7462 filename,
7463 "// This file is included by gles2_interface.h to declare the\n"
7464 "// GL api functions.\n")
7465 for func in self.original_functions:
7466 func.WriteGLES2InterfaceHeader(file)
7467 file.Close()
7469 def WriteGLES2InterfaceStub(self, filename):
7470 """Writes the GLES2 interface stub header."""
7471 file = CHeaderWriter(
7472 filename,
7473 "// This file is included by gles2_interface_stub.h.\n")
7474 for func in self.original_functions:
7475 func.WriteGLES2InterfaceStub(file)
7476 file.Close()
7478 def WriteGLES2InterfaceStubImpl(self, filename):
7479 """Writes the GLES2 interface header."""
7480 file = CHeaderWriter(
7481 filename,
7482 "// This file is included by gles2_interface_stub.cc.\n")
7483 for func in self.original_functions:
7484 func.WriteGLES2InterfaceStubImpl(file)
7485 file.Close()
7487 def WriteGLES2ImplementationHeader(self, filename):
7488 """Writes the GLES2 Implementation header."""
7489 file = CHeaderWriter(
7490 filename,
7491 "// This file is included by gles2_implementation.h to declare the\n"
7492 "// GL api functions.\n")
7493 for func in self.original_functions:
7494 func.WriteGLES2ImplementationHeader(file)
7495 file.Close()
7497 def WriteGLES2Implementation(self, filename):
7498 """Writes the GLES2 Implementation."""
7499 file = CHeaderWriter(
7500 filename,
7501 "// This file is included by gles2_implementation.cc to define the\n"
7502 "// GL api functions.\n")
7503 for func in self.original_functions:
7504 func.WriteGLES2Implementation(file)
7505 file.Close()
7507 def WriteGLES2TraceImplementationHeader(self, filename):
7508 """Writes the GLES2 Trace Implementation header."""
7509 file = CHeaderWriter(
7510 filename,
7511 "// This file is included by gles2_trace_implementation.h\n")
7512 for func in self.original_functions:
7513 func.WriteGLES2TraceImplementationHeader(file)
7514 file.Close()
7516 def WriteGLES2TraceImplementation(self, filename):
7517 """Writes the GLES2 Trace Implementation."""
7518 file = CHeaderWriter(
7519 filename,
7520 "// This file is included by gles2_trace_implementation.cc\n")
7521 for func in self.original_functions:
7522 func.WriteGLES2TraceImplementation(file)
7523 file.Close()
7525 def WriteGLES2ImplementationUnitTests(self, filename):
7526 """Writes the GLES2 helper header."""
7527 file = CHeaderWriter(
7528 filename,
7529 "// This file is included by gles2_implementation.h to declare the\n"
7530 "// GL api functions.\n")
7531 for func in self.original_functions:
7532 func.WriteGLES2ImplementationUnitTest(file)
7533 file.Close()
7535 def WriteServiceUtilsHeader(self, filename):
7536 """Writes the gles2 auto generated utility header."""
7537 file = CHeaderWriter(filename)
7538 for enum in sorted(_ENUM_LISTS.keys()):
7539 file.Write("ValueValidator<%s> %s;\n" %
7540 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7541 file.Write("\n")
7542 file.Close()
7544 def WriteServiceUtilsImplementation(self, filename):
7545 """Writes the gles2 auto generated utility implementation."""
7546 file = CHeaderWriter(filename)
7547 enums = sorted(_ENUM_LISTS.keys())
7548 for enum in enums:
7549 if len(_ENUM_LISTS[enum]['valid']) > 0:
7550 file.Write("static const %s valid_%s_table[] = {\n" %
7551 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7552 for value in _ENUM_LISTS[enum]['valid']:
7553 file.Write(" %s,\n" % value)
7554 file.Write("};\n")
7555 file.Write("\n")
7556 file.Write("Validators::Validators()\n")
7557 pre = ': '
7558 post = ','
7559 for count, enum in enumerate(enums):
7560 if count + 1 == len(enums):
7561 post = ' {'
7562 if len(_ENUM_LISTS[enum]['valid']) > 0:
7563 code = """ %(pre)s%(name)s(
7564 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7566 else:
7567 code = """ %(pre)s%(name)s()%(post)s
7569 file.Write(code % {
7570 'name': ToUnderscore(enum),
7571 'pre': pre,
7572 'post': post,
7574 pre = ' '
7575 file.Write("}\n\n");
7576 file.Close()
7578 def WriteCommonUtilsHeader(self, filename):
7579 """Writes the gles2 common utility header."""
7580 file = CHeaderWriter(filename)
7581 enums = sorted(_ENUM_LISTS.keys())
7582 for enum in enums:
7583 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7584 file.Write("static std::string GetString%s(uint32 value);\n" % enum)
7585 file.Write("\n")
7586 file.Close()
7588 def WriteCommonUtilsImpl(self, filename):
7589 """Writes the gles2 common utility header."""
7590 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7591 dict = {}
7592 for fname in ['../../third_party/khronos/GLES2/gl2.h',
7593 '../../third_party/khronos/GLES2/gl2ext.h',
7594 '../../gpu/GLES2/gl2chromium.h',
7595 '../../gpu/GLES2/gl2extchromium.h']:
7596 lines = open(fname).readlines()
7597 for line in lines:
7598 m = enum_re.match(line)
7599 if m:
7600 name = m.group(1)
7601 value = m.group(2)
7602 if len(value) <= 10 and not value in dict:
7603 dict[value] = name
7605 file = CHeaderWriter(filename)
7606 file.Write("static const GLES2Util::EnumToString "
7607 "enum_to_string_table[] = {\n")
7608 for value in dict:
7609 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
7610 file.Write("""};
7612 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7613 enum_to_string_table;
7614 const size_t GLES2Util::enum_to_string_table_len_ =
7615 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7617 """)
7619 enums = sorted(_ENUM_LISTS.keys())
7620 for enum in enums:
7621 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7622 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7623 enum)
7624 if len(_ENUM_LISTS[enum]['valid']) > 0:
7625 file.Write(" static const EnumToString string_table[] = {\n")
7626 for value in _ENUM_LISTS[enum]['valid']:
7627 file.Write(' { %s, "%s" },\n' % (value, value))
7628 file.Write(""" };
7629 return GLES2Util::GetQualifiedEnumString(
7630 string_table, arraysize(string_table), value);
7633 """)
7634 else:
7635 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7636 NULL, 0, value);
7639 """)
7640 file.Close()
7642 def WritePepperGLES2Interface(self, filename, dev):
7643 """Writes the Pepper OpenGLES interface definition."""
7644 file = CHeaderWriter(
7645 filename,
7646 "// OpenGL ES interface.\n")
7648 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7649 if dev:
7650 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7651 else:
7652 file.Write("\n#ifndef __gl2_h_\n")
7653 for (k, v) in _GL_TYPES.iteritems():
7654 file.Write("typedef %s %s;\n" % (v, k))
7655 file.Write("#ifdef _WIN64\n")
7656 for (k, v) in _GL_TYPES_64.iteritems():
7657 file.Write("typedef %s %s;\n" % (v, k))
7658 file.Write("#else\n")
7659 for (k, v) in _GL_TYPES_32.iteritems():
7660 file.Write("typedef %s %s;\n" % (v, k))
7661 file.Write("#endif // _WIN64\n")
7662 file.Write("#endif // __gl2_h_\n\n")
7664 for interface in self.pepper_interfaces:
7665 if interface.dev != dev:
7666 continue
7667 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7668 (interface.GetInterfaceName(), interface.GetInterfaceString()))
7669 file.Write("#define %s %s_1_0\n" %
7670 (interface.GetInterfaceName(), interface.GetInterfaceName()))
7672 file.Write("\nstruct %s {\n" % interface.GetStructName())
7673 for func in self.original_functions:
7674 if not func.InPepperInterface(interface):
7675 continue
7677 original_arg = func.MakeTypedPepperArgString("")
7678 context_arg = "PP_Resource context"
7679 if len(original_arg):
7680 arg = context_arg + ", " + original_arg
7681 else:
7682 arg = context_arg
7683 file.Write(" %s (*%s)(%s);\n" %
7684 (func.return_type, func.GetPepperName(), arg))
7685 file.Write("};\n\n")
7688 file.Close()
7690 def WritePepperGLES2Implementation(self, filename):
7691 """Writes the Pepper OpenGLES interface implementation."""
7693 file = CWriter(filename)
7694 file.Write(_LICENSE)
7695 file.Write(_DO_NOT_EDIT_WARNING)
7697 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7698 file.Write("#include \"base/logging.h\"\n")
7699 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7700 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7701 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7703 file.Write("namespace ppapi {\n\n")
7704 file.Write("namespace {\n\n")
7706 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7707 " Enter3D;\n\n")
7709 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
7710 " enter) {\n")
7711 file.Write(" DCHECK(enter);\n")
7712 file.Write(" DCHECK(enter->succeeded());\n")
7713 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
7714 "gles2_impl();\n");
7715 file.Write("}\n\n");
7717 for func in self.original_functions:
7718 if not func.InAnyPepperExtension():
7719 continue
7721 original_arg = func.MakeTypedPepperArgString("")
7722 context_arg = "PP_Resource context_id"
7723 if len(original_arg):
7724 arg = context_arg + ", " + original_arg
7725 else:
7726 arg = context_arg
7727 file.Write("%s %s(%s) {\n" %
7728 (func.return_type, func.GetPepperName(), arg))
7729 file.Write(" Enter3D enter(context_id, true);\n")
7730 file.Write(" if (enter.succeeded()) {\n")
7732 return_str = "" if func.return_type == "void" else "return "
7733 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
7734 (return_str, func.original_name,
7735 func.MakeOriginalArgString("")))
7736 file.Write(" }")
7737 if func.return_type == "void":
7738 file.Write("\n")
7739 else:
7740 file.Write(" else {\n")
7741 error_return = "0"
7742 if func.GetInfo("error_return"):
7743 error_return = func.GetInfo("error_return")
7744 elif func.return_type == "GLboolean":
7745 error_return = "GL_FALSE"
7746 elif "*" in func.return_type:
7747 error_return = "NULL"
7748 file.Write(" return %s;\n" % error_return)
7749 file.Write(" }\n")
7750 file.Write("}\n\n")
7752 file.Write("} // namespace\n")
7754 for interface in self.pepper_interfaces:
7755 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7756 (interface.GetStructName(), interface.GetName()))
7757 file.Write(" static const struct %s "
7758 "ppb_opengles2 = {\n" % interface.GetStructName())
7759 file.Write(" &")
7760 file.Write(",\n &".join(
7761 f.GetPepperName() for f in self.original_functions
7762 if f.InPepperInterface(interface)))
7763 file.Write("\n")
7765 file.Write(" };\n")
7766 file.Write(" return &ppb_opengles2;\n")
7767 file.Write("}\n")
7769 file.Write("} // namespace ppapi\n")
7770 file.Close()
7772 def WriteGLES2ToPPAPIBridge(self, filename):
7773 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7775 file = CWriter(filename)
7776 file.Write(_LICENSE)
7777 file.Write(_DO_NOT_EDIT_WARNING)
7779 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7780 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7781 file.Write("#endif\n")
7782 file.Write("#include <GLES2/gl2.h>\n")
7783 file.Write("#include <GLES2/gl2ext.h>\n")
7784 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7786 for func in self.original_functions:
7787 if not func.InAnyPepperExtension():
7788 continue
7790 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
7792 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7793 (func.return_type, func.GetPepperName(),
7794 func.MakeTypedPepperArgString("")))
7795 return_str = "" if func.return_type == "void" else "return "
7796 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
7797 original_arg = func.MakeOriginalArgString("")
7798 context_arg = "glGetCurrentContextPPAPI()"
7799 if len(original_arg):
7800 arg = context_arg + ", " + original_arg
7801 else:
7802 arg = context_arg
7803 if interface.GetName():
7804 file.Write(" const struct %s* ext = %s;\n" %
7805 (interface.GetStructName(), interface_str))
7806 file.Write(" if (ext)\n")
7807 file.Write(" %sext->%s(%s);\n" %
7808 (return_str, func.GetPepperName(), arg))
7809 if return_str:
7810 file.Write(" %s0;\n" % return_str)
7811 else:
7812 file.Write(" %s%s->%s(%s);\n" %
7813 (return_str, interface_str, func.GetPepperName(), arg))
7814 file.Write("}\n\n")
7815 file.Close()
7817 def WriteMojoGLCallVisitor(self, filename):
7818 """Provides the GL implementation for mojo"""
7819 file = CWriter(filename)
7820 file.Write(_LICENSE)
7821 file.Write(_DO_NOT_EDIT_WARNING)
7823 for func in self.original_functions:
7824 if not func.IsCoreGLFunction():
7825 continue
7826 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
7827 (func.name, func.return_type,
7828 func.MakeTypedOriginalArgString(""),
7829 func.MakeOriginalArgString("")))
7831 file.Close()
7833 def Format(generated_files):
7834 for filename in generated_files:
7835 call(["clang-format", "-i", "-style=chromium", filename])
7837 def main(argv):
7838 """This is the main function."""
7839 parser = OptionParser()
7840 parser.add_option(
7841 "-g", "--generate-implementation-templates", action="store_true",
7842 help="generates files that are generally hand edited..")
7843 parser.add_option(
7844 "--output-dir",
7845 help="base directory for resulting files, under chrome/src. default is "
7846 "empty. Use this if you want the result stored under gen.")
7847 parser.add_option(
7848 "-v", "--verbose", action="store_true",
7849 help="prints more output.")
7851 (options, args) = parser.parse_args(args=argv)
7853 # Add in states and capabilites to GLState
7854 for state_name in sorted(_STATES.keys()):
7855 state = _STATES[state_name]
7856 if 'enum' in state:
7857 _ENUM_LISTS['GLState']['valid'].append(state['enum'])
7858 else:
7859 for item in state['states']:
7860 if 'extension_flag' in item:
7861 continue
7862 _ENUM_LISTS['GLState']['valid'].append(item['enum'])
7863 for capability in _CAPABILITY_FLAGS:
7864 _ENUM_LISTS['GLState']['valid'].append("GL_%s" % capability['name'].upper())
7866 # This script lives under gpu/command_buffer, cd to base directory.
7867 os.chdir(os.path.dirname(__file__) + "/../..")
7869 gen = GLGenerator(options.verbose)
7870 gen.ParseGLH("common/GLES2/gl2.h")
7872 # Support generating files under gen/
7873 if options.output_dir != None:
7874 os.chdir(options.output_dir)
7876 gen.WritePepperGLES2Interface("ppapi/c/ppb_opengles2.h", False)
7877 gen.WritePepperGLES2Interface("ppapi/c/dev/ppb_opengles2ext_dev.h", True)
7878 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
7879 gen.WritePepperGLES2Implementation(
7880 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7881 os.chdir("gpu/command_buffer")
7882 gen.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7883 gen.WriteFormat("common/gles2_cmd_format_autogen.h")
7884 gen.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7885 gen.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7886 gen.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7887 gen.WriteGLES2InterfaceStubImpl(
7888 "client/gles2_interface_stub_impl_autogen.h")
7889 gen.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7890 gen.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7891 gen.WriteGLES2ImplementationUnitTests(
7892 "client/gles2_implementation_unittest_autogen.h")
7893 gen.WriteGLES2TraceImplementationHeader(
7894 "client/gles2_trace_implementation_autogen.h")
7895 gen.WriteGLES2TraceImplementation(
7896 "client/gles2_trace_implementation_impl_autogen.h")
7897 gen.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7898 gen.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7899 gen.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7900 gen.WriteServiceContextStateHeader("service/context_state_autogen.h")
7901 gen.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7902 gen.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7903 gen.WriteClientContextStateImpl(
7904 "client/client_context_state_impl_autogen.h")
7905 gen.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7906 gen.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7907 gen.WriteServiceUtilsImplementation(
7908 "service/gles2_cmd_validation_implementation_autogen.h")
7909 gen.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7910 gen.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7911 gen.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7912 gen.WriteMojoGLCallVisitor(
7913 "../../mojo/public/gles2/gles2_call_visitor_autogen.h")
7915 Format([
7916 "common/gles2_cmd_format_autogen.h",
7917 "common/gles2_cmd_format_test_autogen.h",
7918 "common/gles2_cmd_ids_autogen.h",
7919 "common/gles2_cmd_utils_autogen.h",
7920 "common/gles2_cmd_utils_implementation_autogen.h",
7921 "client/client_context_state_autogen.h",
7922 "client/client_context_state_impl_autogen.h",
7923 "client/gles2_cmd_helper_autogen.h",
7924 "client/gles2_c_lib_autogen.h",
7925 "client/gles2_implementation_autogen.h",
7926 "client/gles2_implementation_impl_autogen.h",
7927 "client/gles2_implementation_unittest_autogen.h",
7928 "client/gles2_interface_autogen.h",
7929 "client/gles2_interface_stub_autogen.h",
7930 "client/gles2_interface_stub_impl_autogen.h",
7931 "client/gles2_trace_implementation_autogen.h",
7932 "client/gles2_trace_implementation_impl_autogen.h",
7933 "service/context_state_autogen.h",
7934 "service/context_state_impl_autogen.h",
7935 "service/gles2_cmd_decoder_autogen.h",
7936 "service/gles2_cmd_decoder_unittest_0_autogen.h",
7937 "service/gles2_cmd_decoder_unittest_1_autogen.h",
7938 "service/gles2_cmd_decoder_unittest_2_autogen.h",
7939 "service/gles2_cmd_decoder_unittest_3_autogen.h",
7940 "service/gles2_cmd_validation_autogen.h",
7941 "service/gles2_cmd_validation_implementation_autogen.h"])
7942 os.chdir("../..")
7943 Format([
7944 "gpu/GLES2/gl2chromium_autogen.h",
7945 "mojo/public/gles2/gles2_call_visitor_autogen.h",
7946 "ppapi/c/dev/ppb_opengles2ext_dev.h",
7947 "ppapi/c/ppb_opengles2.h",
7948 "ppapi/lib/gl/gles2/gles2.c",
7949 "ppapi/shared_impl/ppb_opengles2_shared.cc"])
7951 if gen.errors > 0:
7952 print "%d errors" % gen.errors
7953 return 1
7954 return 0
7957 if __name__ == '__main__':
7958 sys.exit(main(sys.argv[1:]))