gpu: Add CHROMIUM_sync_query extension.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob7105edf4cbba65287f84f4e57e366b2cc43b3ab5
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 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 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
594 # we can add this because we emulate it if the driver does not support it.
595 'GL_VERTEX_ARRAY_BINDING_OES',
596 'GL_VIEWPORT',
598 'invalid': [
599 'GL_FOG_HINT',
602 'GetTexParamTarget': {
603 'type': 'GLenum',
604 'valid': [
605 'GL_TEXTURE_2D',
606 'GL_TEXTURE_CUBE_MAP',
608 'invalid': [
609 'GL_PROXY_TEXTURE_CUBE_MAP',
612 'TextureTarget': {
613 'type': 'GLenum',
614 'valid': [
615 'GL_TEXTURE_2D',
616 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
617 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
618 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
619 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
620 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
621 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
623 'invalid': [
624 'GL_PROXY_TEXTURE_CUBE_MAP',
627 'TextureBindTarget': {
628 'type': 'GLenum',
629 'valid': [
630 'GL_TEXTURE_2D',
631 'GL_TEXTURE_CUBE_MAP',
633 'invalid': [
634 'GL_TEXTURE_1D',
635 'GL_TEXTURE_3D',
638 'ShaderType': {
639 'type': 'GLenum',
640 'valid': [
641 'GL_VERTEX_SHADER',
642 'GL_FRAGMENT_SHADER',
644 'invalid': [
645 'GL_GEOMETRY_SHADER',
648 'FaceType': {
649 'type': 'GLenum',
650 'valid': [
651 'GL_FRONT',
652 'GL_BACK',
653 'GL_FRONT_AND_BACK',
656 'FaceMode': {
657 'type': 'GLenum',
658 'valid': [
659 'GL_CW',
660 'GL_CCW',
663 'CmpFunction': {
664 'type': 'GLenum',
665 'valid': [
666 'GL_NEVER',
667 'GL_LESS',
668 'GL_EQUAL',
669 'GL_LEQUAL',
670 'GL_GREATER',
671 'GL_NOTEQUAL',
672 'GL_GEQUAL',
673 'GL_ALWAYS',
676 'Equation': {
677 'type': 'GLenum',
678 'valid': [
679 'GL_FUNC_ADD',
680 'GL_FUNC_SUBTRACT',
681 'GL_FUNC_REVERSE_SUBTRACT',
683 'invalid': [
684 'GL_MIN',
685 'GL_MAX',
688 'SrcBlendFactor': {
689 'type': 'GLenum',
690 'valid': [
691 'GL_ZERO',
692 'GL_ONE',
693 'GL_SRC_COLOR',
694 'GL_ONE_MINUS_SRC_COLOR',
695 'GL_DST_COLOR',
696 'GL_ONE_MINUS_DST_COLOR',
697 'GL_SRC_ALPHA',
698 'GL_ONE_MINUS_SRC_ALPHA',
699 'GL_DST_ALPHA',
700 'GL_ONE_MINUS_DST_ALPHA',
701 'GL_CONSTANT_COLOR',
702 'GL_ONE_MINUS_CONSTANT_COLOR',
703 'GL_CONSTANT_ALPHA',
704 'GL_ONE_MINUS_CONSTANT_ALPHA',
705 'GL_SRC_ALPHA_SATURATE',
708 'DstBlendFactor': {
709 'type': 'GLenum',
710 'valid': [
711 'GL_ZERO',
712 'GL_ONE',
713 'GL_SRC_COLOR',
714 'GL_ONE_MINUS_SRC_COLOR',
715 'GL_DST_COLOR',
716 'GL_ONE_MINUS_DST_COLOR',
717 'GL_SRC_ALPHA',
718 'GL_ONE_MINUS_SRC_ALPHA',
719 'GL_DST_ALPHA',
720 'GL_ONE_MINUS_DST_ALPHA',
721 'GL_CONSTANT_COLOR',
722 'GL_ONE_MINUS_CONSTANT_COLOR',
723 'GL_CONSTANT_ALPHA',
724 'GL_ONE_MINUS_CONSTANT_ALPHA',
727 'Capability': {
728 'type': 'GLenum',
729 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS],
730 'invalid': [
731 'GL_CLIP_PLANE0',
732 'GL_POINT_SPRITE',
735 'DrawMode': {
736 'type': 'GLenum',
737 'valid': [
738 'GL_POINTS',
739 'GL_LINE_STRIP',
740 'GL_LINE_LOOP',
741 'GL_LINES',
742 'GL_TRIANGLE_STRIP',
743 'GL_TRIANGLE_FAN',
744 'GL_TRIANGLES',
746 'invalid': [
747 'GL_QUADS',
748 'GL_POLYGON',
751 'IndexType': {
752 'type': 'GLenum',
753 'valid': [
754 'GL_UNSIGNED_BYTE',
755 'GL_UNSIGNED_SHORT',
757 'invalid': [
758 'GL_UNSIGNED_INT',
759 'GL_INT',
762 'GetMaxIndexType': {
763 'type': 'GLenum',
764 'valid': [
765 'GL_UNSIGNED_BYTE',
766 'GL_UNSIGNED_SHORT',
767 'GL_UNSIGNED_INT',
769 'invalid': [
770 'GL_INT',
773 'Attachment': {
774 'type': 'GLenum',
775 'valid': [
776 'GL_COLOR_ATTACHMENT0',
777 'GL_DEPTH_ATTACHMENT',
778 'GL_STENCIL_ATTACHMENT',
781 'BackbufferAttachment': {
782 'type': 'GLenum',
783 'valid': [
784 'GL_COLOR_EXT',
785 'GL_DEPTH_EXT',
786 'GL_STENCIL_EXT',
789 'BufferParameter': {
790 'type': 'GLenum',
791 'valid': [
792 'GL_BUFFER_SIZE',
793 'GL_BUFFER_USAGE',
795 'invalid': [
796 'GL_PIXEL_PACK_BUFFER',
799 'FrameBufferParameter': {
800 'type': 'GLenum',
801 'valid': [
802 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
803 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
804 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
805 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
808 'ProgramParameter': {
809 'type': 'GLenum',
810 'valid': [
811 'GL_DELETE_STATUS',
812 'GL_LINK_STATUS',
813 'GL_VALIDATE_STATUS',
814 'GL_INFO_LOG_LENGTH',
815 'GL_ATTACHED_SHADERS',
816 'GL_ACTIVE_ATTRIBUTES',
817 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
818 'GL_ACTIVE_UNIFORMS',
819 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
822 'QueryObjectParameter': {
823 'type': 'GLenum',
824 'valid': [
825 'GL_QUERY_RESULT_EXT',
826 'GL_QUERY_RESULT_AVAILABLE_EXT',
829 'QueryParameter': {
830 'type': 'GLenum',
831 'valid': [
832 'GL_CURRENT_QUERY_EXT',
835 'QueryTarget': {
836 'type': 'GLenum',
837 'valid': [
838 'GL_ANY_SAMPLES_PASSED_EXT',
839 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
840 'GL_COMMANDS_ISSUED_CHROMIUM',
841 'GL_LATENCY_QUERY_CHROMIUM',
842 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
843 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
844 'GL_COMMANDS_COMPLETED_CHROMIUM',
847 'RenderBufferParameter': {
848 'type': 'GLenum',
849 'valid': [
850 'GL_RENDERBUFFER_RED_SIZE',
851 'GL_RENDERBUFFER_GREEN_SIZE',
852 'GL_RENDERBUFFER_BLUE_SIZE',
853 'GL_RENDERBUFFER_ALPHA_SIZE',
854 'GL_RENDERBUFFER_DEPTH_SIZE',
855 'GL_RENDERBUFFER_STENCIL_SIZE',
856 'GL_RENDERBUFFER_WIDTH',
857 'GL_RENDERBUFFER_HEIGHT',
858 'GL_RENDERBUFFER_INTERNAL_FORMAT',
861 'ShaderParameter': {
862 'type': 'GLenum',
863 'valid': [
864 'GL_SHADER_TYPE',
865 'GL_DELETE_STATUS',
866 'GL_COMPILE_STATUS',
867 'GL_INFO_LOG_LENGTH',
868 'GL_SHADER_SOURCE_LENGTH',
869 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
872 'ShaderPrecision': {
873 'type': 'GLenum',
874 'valid': [
875 'GL_LOW_FLOAT',
876 'GL_MEDIUM_FLOAT',
877 'GL_HIGH_FLOAT',
878 'GL_LOW_INT',
879 'GL_MEDIUM_INT',
880 'GL_HIGH_INT',
883 'StringType': {
884 'type': 'GLenum',
885 'valid': [
886 'GL_VENDOR',
887 'GL_RENDERER',
888 'GL_VERSION',
889 'GL_SHADING_LANGUAGE_VERSION',
890 'GL_EXTENSIONS',
893 'TextureParameter': {
894 'type': 'GLenum',
895 'valid': [
896 'GL_TEXTURE_MAG_FILTER',
897 'GL_TEXTURE_MIN_FILTER',
898 'GL_TEXTURE_POOL_CHROMIUM',
899 'GL_TEXTURE_WRAP_S',
900 'GL_TEXTURE_WRAP_T',
902 'invalid': [
903 'GL_GENERATE_MIPMAP',
906 'TexturePool': {
907 'type': 'GLenum',
908 'valid': [
909 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
910 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
913 'TextureWrapMode': {
914 'type': 'GLenum',
915 'valid': [
916 'GL_CLAMP_TO_EDGE',
917 'GL_MIRRORED_REPEAT',
918 'GL_REPEAT',
921 'TextureMinFilterMode': {
922 'type': 'GLenum',
923 'valid': [
924 'GL_NEAREST',
925 'GL_LINEAR',
926 'GL_NEAREST_MIPMAP_NEAREST',
927 'GL_LINEAR_MIPMAP_NEAREST',
928 'GL_NEAREST_MIPMAP_LINEAR',
929 'GL_LINEAR_MIPMAP_LINEAR',
932 'TextureMagFilterMode': {
933 'type': 'GLenum',
934 'valid': [
935 'GL_NEAREST',
936 'GL_LINEAR',
939 'TextureUsage': {
940 'type': 'GLenum',
941 'valid': [
942 'GL_NONE',
943 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
946 'VertexAttribute': {
947 'type': 'GLenum',
948 'valid': [
949 # some enum that the decoder actually passes through to GL needs
950 # to be the first listed here since it's used in unit tests.
951 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
952 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
953 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
954 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
955 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
956 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
957 'GL_CURRENT_VERTEX_ATTRIB',
960 'VertexPointer': {
961 'type': 'GLenum',
962 'valid': [
963 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
966 'HintTarget': {
967 'type': 'GLenum',
968 'valid': [
969 'GL_GENERATE_MIPMAP_HINT',
971 'invalid': [
972 'GL_PERSPECTIVE_CORRECTION_HINT',
975 'HintMode': {
976 'type': 'GLenum',
977 'valid': [
978 'GL_FASTEST',
979 'GL_NICEST',
980 'GL_DONT_CARE',
983 'PixelStore': {
984 'type': 'GLenum',
985 'valid': [
986 'GL_PACK_ALIGNMENT',
987 'GL_UNPACK_ALIGNMENT',
988 'GL_UNPACK_FLIP_Y_CHROMIUM',
989 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
990 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
992 'invalid': [
993 'GL_PACK_SWAP_BYTES',
994 'GL_UNPACK_SWAP_BYTES',
997 'PixelStoreAlignment': {
998 'type': 'GLint',
999 'valid': [
1000 '1',
1001 '2',
1002 '4',
1003 '8',
1005 'invalid': [
1006 '3',
1007 '9',
1010 'ReadPixelFormat': {
1011 'type': 'GLenum',
1012 'valid': [
1013 'GL_ALPHA',
1014 'GL_RGB',
1015 'GL_RGBA',
1018 'PixelType': {
1019 'type': 'GLenum',
1020 'valid': [
1021 'GL_UNSIGNED_BYTE',
1022 'GL_UNSIGNED_SHORT_5_6_5',
1023 'GL_UNSIGNED_SHORT_4_4_4_4',
1024 'GL_UNSIGNED_SHORT_5_5_5_1',
1026 'invalid': [
1027 'GL_SHORT',
1028 'GL_INT',
1031 'ReadPixelType': {
1032 'type': 'GLenum',
1033 'valid': [
1034 'GL_UNSIGNED_BYTE',
1035 'GL_UNSIGNED_SHORT_5_6_5',
1036 'GL_UNSIGNED_SHORT_4_4_4_4',
1037 'GL_UNSIGNED_SHORT_5_5_5_1',
1039 'invalid': [
1040 'GL_SHORT',
1041 'GL_INT',
1044 'RenderBufferFormat': {
1045 'type': 'GLenum',
1046 'valid': [
1047 'GL_RGBA4',
1048 'GL_RGB565',
1049 'GL_RGB5_A1',
1050 'GL_DEPTH_COMPONENT16',
1051 'GL_STENCIL_INDEX8',
1054 'ShaderBinaryFormat': {
1055 'type': 'GLenum',
1056 'valid': [
1059 'StencilOp': {
1060 'type': 'GLenum',
1061 'valid': [
1062 'GL_KEEP',
1063 'GL_ZERO',
1064 'GL_REPLACE',
1065 'GL_INCR',
1066 'GL_INCR_WRAP',
1067 'GL_DECR',
1068 'GL_DECR_WRAP',
1069 'GL_INVERT',
1072 'TextureFormat': {
1073 'type': 'GLenum',
1074 'valid': [
1075 'GL_ALPHA',
1076 'GL_LUMINANCE',
1077 'GL_LUMINANCE_ALPHA',
1078 'GL_RGB',
1079 'GL_RGBA',
1081 'invalid': [
1082 'GL_BGRA',
1083 'GL_BGR',
1086 'TextureInternalFormat': {
1087 'type': 'GLenum',
1088 'valid': [
1089 'GL_ALPHA',
1090 'GL_LUMINANCE',
1091 'GL_LUMINANCE_ALPHA',
1092 'GL_RGB',
1093 'GL_RGBA',
1095 'invalid': [
1096 'GL_BGRA',
1097 'GL_BGR',
1100 'TextureInternalFormatStorage': {
1101 'type': 'GLenum',
1102 'valid': [
1103 'GL_RGB565',
1104 'GL_RGBA4',
1105 'GL_RGB5_A1',
1106 'GL_ALPHA8_EXT',
1107 'GL_LUMINANCE8_EXT',
1108 'GL_LUMINANCE8_ALPHA8_EXT',
1109 'GL_RGB8_OES',
1110 'GL_RGBA8_OES',
1113 'VertexAttribType': {
1114 'type': 'GLenum',
1115 'valid': [
1116 'GL_BYTE',
1117 'GL_UNSIGNED_BYTE',
1118 'GL_SHORT',
1119 'GL_UNSIGNED_SHORT',
1120 # 'GL_FIXED', // This is not available on Desktop GL.
1121 'GL_FLOAT',
1123 'invalid': [
1124 'GL_DOUBLE',
1127 'TextureBorder': {
1128 'type': 'GLint',
1129 'valid': [
1130 '0',
1132 'invalid': [
1133 '1',
1136 'VertexAttribSize': {
1137 'type': 'GLint',
1138 'valid': [
1139 '1',
1140 '2',
1141 '3',
1142 '4',
1144 'invalid': [
1145 '0',
1146 '5',
1149 'ZeroOnly': {
1150 'type': 'GLint',
1151 'valid': [
1152 '0',
1154 'invalid': [
1155 '1',
1158 'FalseOnly': {
1159 'type': 'GLboolean',
1160 'valid': [
1161 'false',
1163 'invalid': [
1164 'true',
1167 'ResetStatus': {
1168 'type': 'GLenum',
1169 'valid': [
1170 'GL_GUILTY_CONTEXT_RESET_ARB',
1171 'GL_INNOCENT_CONTEXT_RESET_ARB',
1172 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1177 # This table specifies the different pepper interfaces that are supported for
1178 # GL commands. 'dev' is true if it's a dev interface.
1179 _PEPPER_INTERFACES = [
1180 {'name': '', 'dev': False},
1181 {'name': 'InstancedArrays', 'dev': False},
1182 {'name': 'FramebufferBlit', 'dev': False},
1183 {'name': 'FramebufferMultisample', 'dev': False},
1184 {'name': 'ChromiumEnableFeature', 'dev': False},
1185 {'name': 'ChromiumMapSub', 'dev': False},
1186 {'name': 'Query', 'dev': False},
1187 {'name': 'DrawBuffers', 'dev': True},
1190 # This table specifies types and other special data for the commands that
1191 # will be generated.
1193 # Must match function names specified in "cmd_buffer_functions.txt".
1195 # cmd_comment: A comment added to the cmd format.
1196 # type: defines which handler will be used to generate code.
1197 # decoder_func: defines which function to call in the decoder to execute the
1198 # corresponding GL command. If not specified the GL command will
1199 # be called directly.
1200 # gl_test_func: GL function that is expected to be called when testing.
1201 # cmd_args: The arguments to use for the command. This overrides generating
1202 # them based on the GL function arguments.
1203 # a NonImmediate type is a type that stays a pointer even in
1204 # and immediate version of acommand.
1205 # gen_cmd: Whether or not this function geneates a command. Default = True.
1206 # immediate: Whether or not to generate an immediate command for the GL
1207 # function. The default is if there is exactly 1 pointer argument
1208 # in the GL function an immediate command is generated.
1209 # bucket: True to generate a bucket version of the command.
1210 # impl_func: Whether or not to generate the GLES2Implementation part of this
1211 # command.
1212 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1213 # for this command.
1214 # needs_size: If true a data_size field is added to the command.
1215 # data_type: The type of data the command uses. For PUTn or PUT types.
1216 # count: The number of units per element. For PUTn or PUT types.
1217 # unit_test: If False no service side unit test will be generated.
1218 # client_test: If False no client side unit test will be generated.
1219 # expectation: If False the unit test will have no expected calls.
1220 # gen_func: Name of function that generates GL resource for corresponding
1221 # bind function.
1222 # states: array of states that get set by this function corresponding to
1223 # the given arguments
1224 # state_flag: name of flag that is set to true when function is called.
1225 # no_gl: no GL function is called.
1226 # valid_args: A dictionary of argument indices to args to use in unit tests
1227 # when they can not be automatically determined.
1228 # pepper_interface: The pepper interface that is used for this extension
1229 # pepper_name: The name of the function as exposed to pepper.
1230 # pepper_args: A string representing the argument list (what would appear in
1231 # C/C++ between the parentheses for the function declaration)
1232 # that the Pepper API expects for this function. Use this only if
1233 # the stable Pepper API differs from the GLES2 argument list.
1234 # invalid_test: False if no invalid test needed.
1235 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1236 # first_element_only: For PUT types, True if only the first element of an
1237 # array is used and we end up calling the single value
1238 # corresponding function. eg. TexParameteriv -> TexParameteri
1240 _FUNCTION_INFO = {
1241 'ActiveTexture': {
1242 'decoder_func': 'DoActiveTexture',
1243 'unit_test': False,
1244 'impl_func': False,
1245 'client_test': False,
1247 'AttachShader': {'decoder_func': 'DoAttachShader'},
1248 'BindAttribLocation': {
1249 'type': 'GLchar',
1250 'bucket': True,
1251 'needs_size': True,
1252 'immediate': False,
1254 'BindBuffer': {
1255 'type': 'Bind',
1256 'decoder_func': 'DoBindBuffer',
1257 'gen_func': 'GenBuffersARB',
1259 'BindFramebuffer': {
1260 'type': 'Bind',
1261 'decoder_func': 'DoBindFramebuffer',
1262 'gl_test_func': 'glBindFramebufferEXT',
1263 'gen_func': 'GenFramebuffersEXT',
1264 'trace_level': 1,
1266 'BindRenderbuffer': {
1267 'type': 'Bind',
1268 'decoder_func': 'DoBindRenderbuffer',
1269 'gl_test_func': 'glBindRenderbufferEXT',
1270 'gen_func': 'GenRenderbuffersEXT',
1272 'BindTexture': {
1273 'type': 'Bind',
1274 'decoder_func': 'DoBindTexture',
1275 'gen_func': 'GenTextures',
1276 # TODO(gman): remove this once client side caching works.
1277 'client_test': False,
1278 'trace_level': 1,
1280 'BlitFramebufferCHROMIUM': {
1281 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1282 'unit_test': False,
1283 'extension': True,
1284 'pepper_interface': 'FramebufferBlit',
1285 'pepper_name': 'BlitFramebufferEXT',
1286 'defer_reads': True,
1287 'defer_draws': True,
1288 'trace_level': 1,
1290 'BufferData': {
1291 'type': 'Manual',
1292 'immediate': False,
1293 'client_test': False,
1295 'BufferSubData': {
1296 'type': 'Data',
1297 'client_test': False,
1298 'decoder_func': 'DoBufferSubData',
1299 'immediate': False,
1301 'CheckFramebufferStatus': {
1302 'type': 'Is',
1303 'decoder_func': 'DoCheckFramebufferStatus',
1304 'gl_test_func': 'glCheckFramebufferStatusEXT',
1305 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1306 'result': ['GLenum'],
1308 'Clear': {
1309 'decoder_func': 'DoClear',
1310 'defer_draws': True,
1311 'trace_level': 1,
1313 'ClearColor': {
1314 'type': 'StateSet',
1315 'state': 'ClearColor',
1317 'ClearDepthf': {
1318 'type': 'StateSet',
1319 'state': 'ClearDepthf',
1320 'decoder_func': 'glClearDepth',
1321 'gl_test_func': 'glClearDepth',
1322 'valid_args': {
1323 '0': '0.5f'
1326 'ColorMask': {
1327 'type': 'StateSet',
1328 'state': 'ColorMask',
1329 'no_gl': True,
1330 'expectation': False,
1332 'ConsumeTextureCHROMIUM': {
1333 'decoder_func': 'DoConsumeTextureCHROMIUM',
1334 'impl_func': False,
1335 'type': 'PUT',
1336 'data_type': 'GLbyte',
1337 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1338 'unit_test': False,
1339 'client_test': False,
1340 'extension': True,
1341 'chromium': True,
1342 'trace_level': 1,
1344 'ClearStencil': {
1345 'type': 'StateSet',
1346 'state': 'ClearStencil',
1348 'EnableFeatureCHROMIUM': {
1349 'type': 'Custom',
1350 'immediate': False,
1351 'decoder_func': 'DoEnableFeatureCHROMIUM',
1352 'expectation': False,
1353 'cmd_args': 'GLuint bucket_id, GLint* result',
1354 'result': ['GLint'],
1355 'extension': True,
1356 'chromium': True,
1357 'pepper_interface': 'ChromiumEnableFeature',
1359 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1360 'CompressedTexImage2D': {
1361 'type': 'Manual',
1362 'immediate': False,
1363 'bucket': True,
1365 'CompressedTexSubImage2D': {
1366 'type': 'Data',
1367 'bucket': True,
1368 'decoder_func': 'DoCompressedTexSubImage2D',
1369 'immediate': False,
1371 'CopyTexImage2D': {
1372 'decoder_func': 'DoCopyTexImage2D',
1373 'unit_test': False,
1374 'defer_reads': True,
1376 'CopyTexSubImage2D': {
1377 'decoder_func': 'DoCopyTexSubImage2D',
1378 'defer_reads': True,
1380 'CreateImageCHROMIUM': {
1381 'type': 'Manual',
1382 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1383 'result': ['GLuint'],
1384 'client_test': False,
1385 'gen_cmd': False,
1386 'expectation': False,
1387 'extension': True,
1388 'chromium': True,
1390 'DestroyImageCHROMIUM': {
1391 'type': 'Manual',
1392 'immediate': False,
1393 'client_test': False,
1394 'gen_cmd': False,
1395 'extension': True,
1396 'chromium': True,
1398 'GetImageParameterivCHROMIUM': {
1399 'type': 'Manual',
1400 'client_test': False,
1401 'gen_cmd': False,
1402 'expectation': False,
1403 'extension': True,
1404 'chromium': True,
1406 'CreateProgram': {
1407 'type': 'Create',
1408 'client_test': False,
1410 'CreateShader': {
1411 'type': 'Create',
1412 'client_test': False,
1414 'BlendColor': {
1415 'type': 'StateSet',
1416 'state': 'BlendColor',
1418 'BlendEquation': {
1419 'type': 'StateSetRGBAlpha',
1420 'state': 'BlendEquation',
1421 'valid_args': {
1422 '0': 'GL_FUNC_SUBTRACT'
1425 'BlendEquationSeparate': {
1426 'type': 'StateSet',
1427 'state': 'BlendEquation',
1428 'valid_args': {
1429 '0': 'GL_FUNC_SUBTRACT'
1432 'BlendFunc': {
1433 'type': 'StateSetRGBAlpha',
1434 'state': 'BlendFunc',
1436 'BlendFuncSeparate': {
1437 'type': 'StateSet',
1438 'state': 'BlendFunc',
1440 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1441 'StencilFunc': {
1442 'type': 'StateSetFrontBack',
1443 'state': 'StencilFunc',
1445 'StencilFuncSeparate': {
1446 'type': 'StateSetFrontBackSeparate',
1447 'state': 'StencilFunc',
1449 'StencilOp': {
1450 'type': 'StateSetFrontBack',
1451 'state': 'StencilOp',
1452 'valid_args': {
1453 '1': 'GL_INCR'
1456 'StencilOpSeparate': {
1457 'type': 'StateSetFrontBackSeparate',
1458 'state': 'StencilOp',
1459 'valid_args': {
1460 '1': 'GL_INCR'
1463 'Hint': {
1464 'type': 'StateSetNamedParameter',
1465 'state': 'Hint',
1467 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1468 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1469 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1470 'LineWidth': {
1471 'type': 'StateSet',
1472 'state': 'LineWidth',
1473 'valid_args': {
1474 '0': '0.5f'
1477 'PolygonOffset': {
1478 'type': 'StateSet',
1479 'state': 'PolygonOffset',
1481 'DeleteBuffers': {
1482 'type': 'DELn',
1483 'gl_test_func': 'glDeleteBuffersARB',
1484 'resource_type': 'Buffer',
1485 'resource_types': 'Buffers',
1487 'DeleteFramebuffers': {
1488 'type': 'DELn',
1489 'gl_test_func': 'glDeleteFramebuffersEXT',
1490 'resource_type': 'Framebuffer',
1491 'resource_types': 'Framebuffers',
1493 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1494 'DeleteRenderbuffers': {
1495 'type': 'DELn',
1496 'gl_test_func': 'glDeleteRenderbuffersEXT',
1497 'resource_type': 'Renderbuffer',
1498 'resource_types': 'Renderbuffers',
1500 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1501 'DeleteSharedIdsCHROMIUM': {
1502 'type': 'Custom',
1503 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1504 'impl_func': False,
1505 'expectation': False,
1506 'immediate': False,
1507 'extension': True,
1508 'chromium': True,
1510 'DeleteTextures': {
1511 'type': 'DELn',
1512 'resource_type': 'Texture',
1513 'resource_types': 'Textures',
1515 'DepthRangef': {
1516 'decoder_func': 'DoDepthRangef',
1517 'gl_test_func': 'glDepthRange',
1519 'DepthMask': {
1520 'type': 'StateSet',
1521 'state': 'DepthMask',
1522 'no_gl': True,
1523 'expectation': False,
1525 'DetachShader': {'decoder_func': 'DoDetachShader'},
1526 'Disable': {
1527 'decoder_func': 'DoDisable',
1528 'impl_func': False,
1529 'client_test': False,
1531 'DisableVertexAttribArray': {
1532 'decoder_func': 'DoDisableVertexAttribArray',
1533 'impl_decl': False,
1535 'DrawArrays': {
1536 'type': 'Manual',
1537 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1538 'defer_draws': True,
1539 'trace_level': 2,
1541 'DrawElements': {
1542 'type': 'Manual',
1543 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1544 'GLenumIndexType type, GLuint index_offset',
1545 'client_test': False,
1546 'defer_draws': True,
1547 'trace_level': 2,
1549 'Enable': {
1550 'decoder_func': 'DoEnable',
1551 'impl_func': False,
1552 'client_test': False,
1554 'EnableVertexAttribArray': {
1555 'decoder_func': 'DoEnableVertexAttribArray',
1556 'impl_decl': False,
1558 'Finish': {
1559 'impl_func': False,
1560 'client_test': False,
1561 'decoder_func': 'DoFinish',
1562 'defer_reads': True,
1564 'Flush': {
1565 'impl_func': False,
1566 'decoder_func': 'DoFlush',
1568 'FramebufferRenderbuffer': {
1569 'decoder_func': 'DoFramebufferRenderbuffer',
1570 'gl_test_func': 'glFramebufferRenderbufferEXT',
1572 'FramebufferTexture2D': {
1573 'decoder_func': 'DoFramebufferTexture2D',
1574 'gl_test_func': 'glFramebufferTexture2DEXT',
1575 'trace_level': 1,
1577 'FramebufferTexture2DMultisampleEXT': {
1578 'decoder_func': 'DoFramebufferTexture2DMultisample',
1579 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1580 'expectation': False,
1581 'unit_test': False,
1582 'extension': True,
1583 'trace_level': 1,
1585 'GenerateMipmap': {
1586 'decoder_func': 'DoGenerateMipmap',
1587 'gl_test_func': 'glGenerateMipmapEXT',
1589 'GenBuffers': {
1590 'type': 'GENn',
1591 'gl_test_func': 'glGenBuffersARB',
1592 'resource_type': 'Buffer',
1593 'resource_types': 'Buffers',
1595 'GenMailboxCHROMIUM': {
1596 'type': 'HandWritten',
1597 'immediate': False,
1598 'impl_func': False,
1599 'extension': True,
1600 'chromium': True,
1602 'GenFramebuffers': {
1603 'type': 'GENn',
1604 'gl_test_func': 'glGenFramebuffersEXT',
1605 'resource_type': 'Framebuffer',
1606 'resource_types': 'Framebuffers',
1608 'GenRenderbuffers': {
1609 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1610 'resource_type': 'Renderbuffer',
1611 'resource_types': 'Renderbuffers',
1613 'GenTextures': {
1614 'type': 'GENn',
1615 'gl_test_func': 'glGenTextures',
1616 'resource_type': 'Texture',
1617 'resource_types': 'Textures',
1619 'GenSharedIdsCHROMIUM': {
1620 'type': 'Custom',
1621 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1622 'impl_func': False,
1623 'expectation': False,
1624 'immediate': False,
1625 'extension': True,
1626 'chromium': True,
1628 'GetActiveAttrib': {
1629 'type': 'Custom',
1630 'immediate': False,
1631 'cmd_args':
1632 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1633 'void* result',
1634 'result': [
1635 'int32 success',
1636 'int32 size',
1637 'uint32 type',
1640 'GetActiveUniform': {
1641 'type': 'Custom',
1642 'immediate': False,
1643 'cmd_args':
1644 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1645 'void* result',
1646 'result': [
1647 'int32 success',
1648 'int32 size',
1649 'uint32 type',
1652 'GetAttachedShaders': {
1653 'type': 'Custom',
1654 'immediate': False,
1655 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1656 'result': ['SizedResult<GLuint>'],
1658 'GetAttribLocation': {
1659 'type': 'HandWritten',
1660 'immediate': False,
1661 'bucket': True,
1662 'needs_size': True,
1663 'cmd_args':
1664 'GLidProgram program, const char* name, NonImmediate GLint* location',
1665 'result': ['GLint'],
1666 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1668 'GetBooleanv': {
1669 'type': 'GETn',
1670 'result': ['SizedResult<GLboolean>'],
1671 'decoder_func': 'DoGetBooleanv',
1672 'gl_test_func': 'glGetBooleanv',
1674 'GetBufferParameteriv': {
1675 'type': 'GETn',
1676 'result': ['SizedResult<GLint>'],
1677 'decoder_func': 'DoGetBufferParameteriv',
1678 'expectation': False,
1679 'shadowed': True,
1681 'GetError': {
1682 'type': 'Is',
1683 'decoder_func': 'GetErrorState()->GetGLError',
1684 'impl_func': False,
1685 'result': ['GLenum'],
1686 'client_test': False,
1688 'GetFloatv': {
1689 'type': 'GETn',
1690 'result': ['SizedResult<GLfloat>'],
1691 'decoder_func': 'DoGetFloatv',
1692 'gl_test_func': 'glGetFloatv',
1694 'GetFramebufferAttachmentParameteriv': {
1695 'type': 'GETn',
1696 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1697 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1698 'result': ['SizedResult<GLint>'],
1700 'GetIntegerv': {
1701 'type': 'GETn',
1702 'result': ['SizedResult<GLint>'],
1703 'decoder_func': 'DoGetIntegerv',
1704 'client_test': False,
1706 'GetMaxValueInBufferCHROMIUM': {
1707 'type': 'Is',
1708 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1709 'result': ['GLuint'],
1710 'unit_test': False,
1711 'client_test': False,
1712 'extension': True,
1713 'chromium': True,
1714 'impl_func': False,
1716 'GetMultipleIntegervCHROMIUM': {
1717 'type': 'Custom',
1718 'immediate': False,
1719 'expectation': False,
1720 'extension': True,
1721 'chromium': True,
1722 'client_test': False,
1724 'GetProgramiv': {
1725 'type': 'GETn',
1726 'decoder_func': 'DoGetProgramiv',
1727 'result': ['SizedResult<GLint>'],
1728 'expectation': False,
1730 'GetProgramInfoCHROMIUM': {
1731 'type': 'Custom',
1732 'immediate': False,
1733 'expectation': False,
1734 'impl_func': False,
1735 'extension': True,
1736 'chromium': True,
1737 'client_test': False,
1738 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1739 'result': [
1740 'uint32 link_status',
1741 'uint32 num_attribs',
1742 'uint32 num_uniforms',
1745 'GetProgramInfoLog': {
1746 'type': 'STRn',
1747 'expectation': False,
1749 'GetRenderbufferParameteriv': {
1750 'type': 'GETn',
1751 'decoder_func': 'DoGetRenderbufferParameteriv',
1752 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1753 'result': ['SizedResult<GLint>'],
1755 'GetShaderiv': {
1756 'type': 'GETn',
1757 'decoder_func': 'DoGetShaderiv',
1758 'result': ['SizedResult<GLint>'],
1760 'GetShaderInfoLog': {
1761 'type': 'STRn',
1762 'get_len_func': 'glGetShaderiv',
1763 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1764 'unit_test': False,
1766 'GetShaderPrecisionFormat': {
1767 'type': 'Custom',
1768 'immediate': False,
1769 'cmd_args':
1770 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1771 'void* result',
1772 'result': [
1773 'int32 success',
1774 'int32 min_range',
1775 'int32 max_range',
1776 'int32 precision',
1779 'GetShaderSource': {
1780 'type': 'STRn',
1781 'get_len_func': 'DoGetShaderiv',
1782 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1783 'unit_test': False,
1784 'client_test': False,
1786 'GetString': {
1787 'type': 'Custom',
1788 'client_test': False,
1789 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1791 'GetTexParameterfv': {
1792 'type': 'GETn',
1793 'decoder_func': 'DoGetTexParameterfv',
1794 'result': ['SizedResult<GLfloat>']
1796 'GetTexParameteriv': {
1797 'type': 'GETn',
1798 'decoder_func': 'DoGetTexParameteriv',
1799 'result': ['SizedResult<GLint>']
1801 'GetTranslatedShaderSourceANGLE': {
1802 'type': 'STRn',
1803 'get_len_func': 'DoGetShaderiv',
1804 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1805 'unit_test': False,
1806 'extension': True,
1808 'GetUniformfv': {
1809 'type': 'Custom',
1810 'immediate': False,
1811 'result': ['SizedResult<GLfloat>'],
1813 'GetUniformiv': {
1814 'type': 'Custom',
1815 'immediate': False,
1816 'result': ['SizedResult<GLint>'],
1818 'GetUniformLocation': {
1819 'type': 'HandWritten',
1820 'immediate': False,
1821 'bucket': True,
1822 'needs_size': True,
1823 'cmd_args':
1824 'GLidProgram program, const char* name, NonImmediate GLint* location',
1825 'result': ['GLint'],
1826 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1828 'GetVertexAttribfv': {
1829 'type': 'GETn',
1830 'result': ['SizedResult<GLfloat>'],
1831 'impl_decl': False,
1832 'decoder_func': 'DoGetVertexAttribfv',
1833 'expectation': False,
1834 'client_test': False,
1836 'GetVertexAttribiv': {
1837 'type': 'GETn',
1838 'result': ['SizedResult<GLint>'],
1839 'impl_decl': False,
1840 'decoder_func': 'DoGetVertexAttribiv',
1841 'expectation': False,
1842 'client_test': False,
1844 'GetVertexAttribPointerv': {
1845 'type': 'Custom',
1846 'immediate': False,
1847 'result': ['SizedResult<GLuint>'],
1848 'client_test': False,
1850 'IsBuffer': {
1851 'type': 'Is',
1852 'decoder_func': 'DoIsBuffer',
1853 'expectation': False,
1855 'IsEnabled': {
1856 'type': 'Is',
1857 'decoder_func': 'DoIsEnabled',
1858 'impl_func': False,
1859 'expectation': False,
1861 'IsFramebuffer': {
1862 'type': 'Is',
1863 'decoder_func': 'DoIsFramebuffer',
1864 'expectation': False,
1866 'IsProgram': {
1867 'type': 'Is',
1868 'decoder_func': 'DoIsProgram',
1869 'expectation': False,
1871 'IsRenderbuffer': {
1872 'type': 'Is',
1873 'decoder_func': 'DoIsRenderbuffer',
1874 'expectation': False,
1876 'IsShader': {
1877 'type': 'Is',
1878 'decoder_func': 'DoIsShader',
1879 'expectation': False,
1881 'IsTexture': {
1882 'type': 'Is',
1883 'decoder_func': 'DoIsTexture',
1884 'expectation': False,
1886 'LinkProgram': {
1887 'decoder_func': 'DoLinkProgram',
1888 'impl_func': False,
1890 'MapBufferCHROMIUM': {
1891 'gen_cmd': False,
1892 'extension': True,
1893 'chromium': True,
1894 'client_test': False,
1896 'MapBufferSubDataCHROMIUM': {
1897 'gen_cmd': False,
1898 'extension': True,
1899 'chromium': True,
1900 'client_test': False,
1901 'pepper_interface': 'ChromiumMapSub',
1903 'MapImageCHROMIUM': {
1904 'gen_cmd': False,
1905 'extension': True,
1906 'chromium': True,
1907 'client_test': False,
1909 'MapTexSubImage2DCHROMIUM': {
1910 'gen_cmd': False,
1911 'extension': True,
1912 'chromium': True,
1913 'client_test': False,
1914 'pepper_interface': 'ChromiumMapSub',
1916 'PixelStorei': {'type': 'Manual'},
1917 'PostSubBufferCHROMIUM': {
1918 'type': 'Custom',
1919 'impl_func': False,
1920 'unit_test': False,
1921 'client_test': False,
1922 'extension': True,
1923 'chromium': True,
1925 'ProduceTextureCHROMIUM': {
1926 'decoder_func': 'DoProduceTextureCHROMIUM',
1927 'impl_func': False,
1928 'type': 'PUT',
1929 'data_type': 'GLbyte',
1930 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1931 'unit_test': False,
1932 'client_test': False,
1933 'extension': True,
1934 'chromium': True,
1935 'trace_level': 1,
1937 'RenderbufferStorage': {
1938 'decoder_func': 'DoRenderbufferStorage',
1939 'gl_test_func': 'glRenderbufferStorageEXT',
1940 'expectation': False,
1942 'RenderbufferStorageMultisampleCHROMIUM': {
1943 'cmd_comment':
1944 '// GL_CHROMIUM_framebuffer_multisample\n',
1945 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
1946 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
1947 'expectation': False,
1948 'unit_test': False,
1949 'extension': True,
1950 'pepper_interface': 'FramebufferMultisample',
1951 'pepper_name': 'RenderbufferStorageMultisampleEXT',
1953 'RenderbufferStorageMultisampleEXT': {
1954 'cmd_comment':
1955 '// GL_EXT_multisampled_render_to_texture\n',
1956 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
1957 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1958 'expectation': False,
1959 'unit_test': False,
1960 'extension': True,
1962 'ReadPixels': {
1963 'cmd_comment':
1964 '// ReadPixels has the result separated from the pixel buffer so that\n'
1965 '// it is easier to specify the result going to some specific place\n'
1966 '// that exactly fits the rectangle of pixels.\n',
1967 'type': 'Custom',
1968 'immediate': False,
1969 'impl_func': False,
1970 'client_test': False,
1971 'cmd_args':
1972 'GLint x, GLint y, GLsizei width, GLsizei height, '
1973 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1974 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1975 'uint32 result_shm_id, uint32 result_shm_offset, '
1976 'GLboolean async',
1977 'result': ['uint32'],
1978 'defer_reads': True,
1980 'RegisterSharedIdsCHROMIUM': {
1981 'type': 'Custom',
1982 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1983 'impl_func': False,
1984 'expectation': False,
1985 'immediate': False,
1986 'extension': True,
1987 'chromium': True,
1989 'ReleaseShaderCompiler': {
1990 'decoder_func': 'DoReleaseShaderCompiler',
1991 'unit_test': False,
1993 'ShaderBinary': {
1994 'type': 'Custom',
1995 'client_test': False,
1997 'ShaderSource': {
1998 'type': 'Manual',
1999 'immediate': False,
2000 'bucket': True,
2001 'needs_size': True,
2002 'client_test': False,
2003 'cmd_args':
2004 'GLuint shader, const char* data',
2005 'pepper_args':
2006 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2008 'StencilMask': {
2009 'type': 'StateSetFrontBack',
2010 'state': 'StencilMask',
2011 'no_gl': True,
2012 'expectation': False,
2014 'StencilMaskSeparate': {
2015 'type': 'StateSetFrontBackSeparate',
2016 'state': 'StencilMask',
2017 'no_gl': True,
2018 'expectation': False,
2020 'SwapBuffers': {
2021 'impl_func': False,
2022 'decoder_func': 'DoSwapBuffers',
2023 'unit_test': False,
2024 'client_test': False,
2025 'extension': True,
2026 'trace_level': 1,
2028 'TexImage2D': {
2029 'type': 'Manual',
2030 'immediate': False,
2031 'client_test': False,
2033 'TexParameterf': {
2034 'decoder_func': 'DoTexParameterf',
2035 'valid_args': {
2036 '2': 'GL_NEAREST'
2039 'TexParameteri': {
2040 'decoder_func': 'DoTexParameteri',
2041 'valid_args': {
2042 '2': 'GL_NEAREST'
2045 'TexParameterfv': {
2046 'type': 'PUT',
2047 'data_type': 'GLfloat',
2048 'data_value': 'GL_NEAREST',
2049 'count': 1,
2050 'decoder_func': 'DoTexParameterfv',
2051 'gl_test_func': 'glTexParameterf',
2052 'first_element_only': True,
2054 'TexParameteriv': {
2055 'type': 'PUT',
2056 'data_type': 'GLint',
2057 'data_value': 'GL_NEAREST',
2058 'count': 1,
2059 'decoder_func': 'DoTexParameteriv',
2060 'gl_test_func': 'glTexParameteri',
2061 'first_element_only': True,
2063 'TexSubImage2D': {
2064 'type': 'Manual',
2065 'immediate': False,
2066 'client_test': False,
2067 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2068 'GLint xoffset, GLint yoffset, '
2069 'GLsizei width, GLsizei height, '
2070 'GLenumTextureFormat format, GLenumPixelType type, '
2071 'const void* pixels, GLboolean internal'
2073 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2074 'Uniform1fv': {
2075 'type': 'PUTn',
2076 'data_type': 'GLfloat',
2077 'count': 1,
2078 'decoder_func': 'DoUniform1fv',
2080 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2081 'Uniform1iv': {
2082 'type': 'PUTn',
2083 'data_type': 'GLint',
2084 'count': 1,
2085 'decoder_func': 'DoUniform1iv',
2086 'unit_test': False,
2088 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2089 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2090 'Uniform2fv': {
2091 'type': 'PUTn',
2092 'data_type': 'GLfloat',
2093 'count': 2,
2094 'decoder_func': 'DoUniform2fv',
2096 'Uniform2iv': {
2097 'type': 'PUTn',
2098 'data_type': 'GLint',
2099 'count': 2,
2100 'decoder_func': 'DoUniform2iv',
2102 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2103 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2104 'Uniform3fv': {
2105 'type': 'PUTn',
2106 'data_type': 'GLfloat',
2107 'count': 3,
2108 'decoder_func': 'DoUniform3fv',
2110 'Uniform3iv': {
2111 'type': 'PUTn',
2112 'data_type': 'GLint',
2113 'count': 3,
2114 'decoder_func': 'DoUniform3iv',
2116 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2117 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2118 'Uniform4fv': {
2119 'type': 'PUTn',
2120 'data_type': 'GLfloat',
2121 'count': 4,
2122 'decoder_func': 'DoUniform4fv',
2124 'Uniform4iv': {
2125 'type': 'PUTn',
2126 'data_type': 'GLint',
2127 'count': 4,
2128 'decoder_func': 'DoUniform4iv',
2130 'UniformMatrix2fv': {
2131 'type': 'PUTn',
2132 'data_type': 'GLfloat',
2133 'count': 4,
2134 'decoder_func': 'DoUniformMatrix2fv',
2136 'UniformMatrix3fv': {
2137 'type': 'PUTn',
2138 'data_type': 'GLfloat',
2139 'count': 9,
2140 'decoder_func': 'DoUniformMatrix3fv',
2142 'UniformMatrix4fv': {
2143 'type': 'PUTn',
2144 'data_type': 'GLfloat',
2145 'count': 16,
2146 'decoder_func': 'DoUniformMatrix4fv',
2148 'UnmapBufferCHROMIUM': {
2149 'gen_cmd': False,
2150 'extension': True,
2151 'chromium': True,
2152 'client_test': False,
2154 'UnmapBufferSubDataCHROMIUM': {
2155 'gen_cmd': False,
2156 'extension': True,
2157 'chromium': True,
2158 'client_test': False,
2159 'pepper_interface': 'ChromiumMapSub',
2161 'UnmapImageCHROMIUM': {
2162 'gen_cmd': False,
2163 'extension': True,
2164 'chromium': True,
2165 'client_test': False,
2167 'UnmapTexSubImage2DCHROMIUM': {
2168 'gen_cmd': False,
2169 'extension': True,
2170 'chromium': True,
2171 'client_test': False,
2172 'pepper_interface': 'ChromiumMapSub',
2174 'UseProgram': {
2175 'type': 'Bind',
2176 'decoder_func': 'DoUseProgram',
2178 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2179 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2180 'VertexAttrib1fv': {
2181 'type': 'PUT',
2182 'data_type': 'GLfloat',
2183 'count': 1,
2184 'decoder_func': 'DoVertexAttrib1fv',
2186 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2187 'VertexAttrib2fv': {
2188 'type': 'PUT',
2189 'data_type': 'GLfloat',
2190 'count': 2,
2191 'decoder_func': 'DoVertexAttrib2fv',
2193 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2194 'VertexAttrib3fv': {
2195 'type': 'PUT',
2196 'data_type': 'GLfloat',
2197 'count': 3,
2198 'decoder_func': 'DoVertexAttrib3fv',
2200 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2201 'VertexAttrib4fv': {
2202 'type': 'PUT',
2203 'data_type': 'GLfloat',
2204 'count': 4,
2205 'decoder_func': 'DoVertexAttrib4fv',
2207 'VertexAttribPointer': {
2208 'type': 'Manual',
2209 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2210 'GLenumVertexAttribType type, GLboolean normalized, '
2211 'GLsizei stride, GLuint offset',
2212 'client_test': False,
2214 'Scissor': {
2215 'type': 'StateSet',
2216 'state': 'Scissor',
2218 'Viewport': {
2219 'decoder_func': 'DoViewport',
2221 'ResizeCHROMIUM': {
2222 'type': 'Custom',
2223 'impl_func': False,
2224 'unit_test': False,
2225 'extension': True,
2226 'chromium': True,
2228 'GetRequestableExtensionsCHROMIUM': {
2229 'type': 'Custom',
2230 'impl_func': False,
2231 'immediate': False,
2232 'cmd_args': 'uint32 bucket_id',
2233 'extension': True,
2234 'chromium': True,
2236 'RequestExtensionCHROMIUM': {
2237 'type': 'Custom',
2238 'impl_func': False,
2239 'immediate': False,
2240 'client_test': False,
2241 'cmd_args': 'uint32 bucket_id',
2242 'extension': True,
2243 'chromium': True,
2245 'RateLimitOffscreenContextCHROMIUM': {
2246 'gen_cmd': False,
2247 'extension': True,
2248 'chromium': True,
2249 'client_test': False,
2251 'CreateStreamTextureCHROMIUM': {
2252 'type': 'HandWritten',
2253 'impl_func': False,
2254 'gen_cmd': False,
2255 'immediate': False,
2256 'extension': True,
2257 'chromium': True,
2259 'TexImageIOSurface2DCHROMIUM': {
2260 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2261 'unit_test': False,
2262 'extension': True,
2263 'chromium': True,
2265 'CopyTextureCHROMIUM': {
2266 'decoder_func': 'DoCopyTextureCHROMIUM',
2267 'unit_test': False,
2268 'extension': True,
2269 'chromium': True,
2271 'TexStorage2DEXT': {
2272 'unit_test': False,
2273 'extension': True,
2274 'decoder_func': 'DoTexStorage2DEXT',
2276 'DrawArraysInstancedANGLE': {
2277 'type': 'Manual',
2278 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2279 'GLsizei primcount',
2280 'extension': True,
2281 'unit_test': False,
2282 'pepper_interface': 'InstancedArrays',
2283 'defer_draws': True,
2285 'DrawBuffersEXT': {
2286 'type': 'PUTn',
2287 'decoder_func': 'DoDrawBuffersEXT',
2288 'data_type': 'GLenum',
2289 'count': 1,
2290 'client_test': False,
2291 'unit_test': False,
2292 'extension': True,
2293 'pepper_interface': 'DrawBuffers',
2295 'DrawElementsInstancedANGLE': {
2296 'type': 'Manual',
2297 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2298 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2299 'extension': True,
2300 'unit_test': False,
2301 'client_test': False,
2302 'pepper_interface': 'InstancedArrays',
2303 'defer_draws': True,
2305 'VertexAttribDivisorANGLE': {
2306 'type': 'Manual',
2307 'cmd_args': 'GLuint index, GLuint divisor',
2308 'extension': True,
2309 'unit_test': False,
2310 'pepper_interface': 'InstancedArrays',
2312 'GenQueriesEXT': {
2313 'type': 'GENn',
2314 'gl_test_func': 'glGenQueriesARB',
2315 'resource_type': 'Query',
2316 'resource_types': 'Queries',
2317 'unit_test': False,
2318 'pepper_interface': 'Query',
2320 'DeleteQueriesEXT': {
2321 'type': 'DELn',
2322 'gl_test_func': 'glDeleteQueriesARB',
2323 'resource_type': 'Query',
2324 'resource_types': 'Queries',
2325 'unit_test': False,
2326 'pepper_interface': 'Query',
2328 'IsQueryEXT': {
2329 'gen_cmd': False,
2330 'client_test': False,
2331 'pepper_interface': 'Query',
2333 'BeginQueryEXT': {
2334 'type': 'Manual',
2335 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2336 'immediate': False,
2337 'gl_test_func': 'glBeginQuery',
2338 'pepper_interface': 'Query',
2340 'EndQueryEXT': {
2341 'type': 'Manual',
2342 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2343 'gl_test_func': 'glEndnQuery',
2344 'client_test': False,
2345 'pepper_interface': 'Query',
2347 'GetQueryivEXT': {
2348 'gen_cmd': False,
2349 'client_test': False,
2350 'gl_test_func': 'glGetQueryiv',
2351 'pepper_interface': 'Query',
2353 'GetQueryObjectuivEXT': {
2354 'gen_cmd': False,
2355 'client_test': False,
2356 'gl_test_func': 'glGetQueryObjectuiv',
2357 'pepper_interface': 'Query',
2359 'BindUniformLocationCHROMIUM': {
2360 'type': 'GLchar',
2361 'extension': True,
2362 'bucket': True,
2363 'needs_size': True,
2364 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2365 'immediate': False,
2367 'InsertEventMarkerEXT': {
2368 'type': 'GLcharN',
2369 'decoder_func': 'DoInsertEventMarkerEXT',
2370 'expectation': False,
2371 'extension': True,
2373 'PushGroupMarkerEXT': {
2374 'type': 'GLcharN',
2375 'decoder_func': 'DoPushGroupMarkerEXT',
2376 'expectation': False,
2377 'extension': True,
2379 'PopGroupMarkerEXT': {
2380 'decoder_func': 'DoPopGroupMarkerEXT',
2381 'expectation': False,
2382 'extension': True,
2383 'impl_func': False,
2386 'GenVertexArraysOES': {
2387 'type': 'GENn',
2388 'extension': True,
2389 'gl_test_func': 'glGenVertexArraysOES',
2390 'resource_type': 'VertexArray',
2391 'resource_types': 'VertexArrays',
2392 'unit_test': False,
2394 'BindVertexArrayOES': {
2395 'type': 'Bind',
2396 'extension': True,
2397 'gl_test_func': 'glBindVertexArrayOES',
2398 'decoder_func': 'DoBindVertexArrayOES',
2399 'gen_func': 'GenVertexArraysOES',
2400 'unit_test': False,
2401 'client_test': False,
2403 'DeleteVertexArraysOES': {
2404 'type': 'DELn',
2405 'extension': True,
2406 'gl_test_func': 'glDeleteVertexArraysOES',
2407 'resource_type': 'VertexArray',
2408 'resource_types': 'VertexArrays',
2409 'unit_test': False,
2411 'IsVertexArrayOES': {
2412 'type': 'Is',
2413 'extension': True,
2414 'gl_test_func': 'glIsVertexArrayOES',
2415 'decoder_func': 'DoIsVertexArrayOES',
2416 'expectation': False,
2417 'unit_test': False,
2419 'BindTexImage2DCHROMIUM': {
2420 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2421 'unit_test': False,
2422 'extension': True,
2423 'chromium': True,
2425 'ReleaseTexImage2DCHROMIUM': {
2426 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2427 'unit_test': False,
2428 'extension': True,
2429 'chromium': True,
2431 'ShallowFinishCHROMIUM': {
2432 'impl_func': False,
2433 'gen_cmd': False,
2434 'extension': True,
2435 'chromium': True,
2436 'client_test': False,
2438 'ShallowFlushCHROMIUM': {
2439 'impl_func': False,
2440 'gen_cmd': False,
2441 'extension': True,
2442 'chromium': True,
2443 'client_test': False,
2445 'TraceBeginCHROMIUM': {
2446 'type': 'Custom',
2447 'impl_func': False,
2448 'immediate': False,
2449 'client_test': False,
2450 'cmd_args': 'GLuint bucket_id',
2451 'extension': True,
2452 'chromium': True,
2454 'TraceEndCHROMIUM': {
2455 'impl_func': False,
2456 'immediate': False,
2457 'client_test': False,
2458 'decoder_func': 'DoTraceEndCHROMIUM',
2459 'unit_test': False,
2460 'extension': True,
2461 'chromium': True,
2463 'AsyncTexImage2DCHROMIUM': {
2464 'type': 'Manual',
2465 'immediate': False,
2466 'client_test': False,
2467 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2468 'GLintTextureInternalFormat internalformat, '
2469 'GLsizei width, GLsizei height, '
2470 'GLintTextureBorder border, '
2471 'GLenumTextureFormat format, GLenumPixelType type, '
2472 'const void* pixels, '
2473 'uint32 async_upload_token, '
2474 'void* sync_data',
2475 'extension': True,
2476 'chromium': True,
2478 'AsyncTexSubImage2DCHROMIUM': {
2479 'type': 'Manual',
2480 'immediate': False,
2481 'client_test': False,
2482 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2483 'GLint xoffset, GLint yoffset, '
2484 'GLsizei width, GLsizei height, '
2485 'GLenumTextureFormat format, GLenumPixelType type, '
2486 'const void* data, '
2487 'uint32 async_upload_token, '
2488 'void* sync_data',
2489 'extension': True,
2490 'chromium': True,
2492 'WaitAsyncTexImage2DCHROMIUM': {
2493 'type': 'Manual',
2494 'immediate': False,
2495 'client_test': False,
2496 'extension': True,
2497 'chromium': True,
2499 'WaitAllAsyncTexImage2DCHROMIUM': {
2500 'type': 'Manual',
2501 'immediate': False,
2502 'client_test': False,
2503 'extension': True,
2504 'chromium': True,
2506 'DiscardFramebufferEXT': {
2507 'type': 'PUTn',
2508 'count': 1,
2509 'data_type': 'GLenum',
2510 'cmd_args': 'GLenum target, GLsizei count, '
2511 'const GLenum* attachments',
2512 'decoder_func': 'DoDiscardFramebufferEXT',
2513 'unit_test': False,
2514 'client_test': False,
2515 'extension': True,
2517 'LoseContextCHROMIUM': {
2518 'type': 'Manual',
2519 'impl_func': True,
2520 'extension': True,
2521 'chromium': True,
2523 'InsertSyncPointCHROMIUM': {
2524 'type': 'HandWritten',
2525 'impl_func': False,
2526 'extension': True,
2527 'chromium': True,
2529 'WaitSyncPointCHROMIUM': {
2530 'type': 'Custom',
2531 'impl_func': True,
2532 'extension': True,
2533 'chromium': True,
2534 'trace_level': 1,
2536 'DiscardBackbufferCHROMIUM': {
2537 'type': 'Custom',
2538 'impl_func': True,
2539 'extension': True,
2540 'chromium': True,
2542 'ScheduleOverlayPlaneCHROMIUM': {
2543 'type': 'Custom',
2544 'impl_func': True,
2545 'unit_test': False,
2546 'client_test': False,
2547 'extension': True,
2548 'chromium': True,
2553 def Grouper(n, iterable, fillvalue=None):
2554 """Collect data into fixed-length chunks or blocks"""
2555 args = [iter(iterable)] * n
2556 return itertools.izip_longest(fillvalue=fillvalue, *args)
2559 def SplitWords(input_string):
2560 """Transforms a input_string into a list of lower-case components.
2562 Args:
2563 input_string: the input string.
2565 Returns:
2566 a list of lower-case words.
2568 if input_string.find('_') > -1:
2569 # 'some_TEXT_' -> 'some text'
2570 return input_string.replace('_', ' ').strip().lower().split()
2571 else:
2572 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
2573 # mixed case.
2574 # look for capitalization to cut input_strings
2575 # 'SomeText' -> 'Some Text'
2576 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
2577 # 'Vector3' -> 'Vector 3'
2578 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
2579 return input_string.lower().split()
2582 def Lower(words):
2583 """Makes a lower-case identifier from words.
2585 Args:
2586 words: a list of lower-case words.
2588 Returns:
2589 the lower-case identifier.
2591 return '_'.join(words)
2594 def ToUnderscore(input_string):
2595 """converts CamelCase to camel_case."""
2596 words = SplitWords(input_string)
2597 return Lower(words)
2600 class CWriter(object):
2601 """Writes to a file formatting it for Google's style guidelines."""
2603 def __init__(self, filename):
2604 self.filename = filename
2605 self.file_num = 0
2606 self.content = []
2608 def SetFileNum(self, num):
2609 """Used to help write number files and tests."""
2610 self.file_num = num
2612 def Write(self, string):
2613 """Writes a string to a file spliting if it's > 80 characters."""
2614 lines = string.splitlines()
2615 num_lines = len(lines)
2616 for ii in range(0, num_lines):
2617 self.content.append(lines[ii])
2618 if ii < (num_lines - 1) or string[-1] == '\n':
2619 self.content.append('\n')
2621 def Close(self):
2622 """Close the file."""
2623 content = "".join(self.content)
2624 write_file = True
2625 if os.path.exists(self.filename):
2626 old_file = open(self.filename, "rb");
2627 old_content = old_file.read()
2628 old_file.close();
2629 if content == old_content:
2630 write_file = False
2631 if write_file:
2632 file = open(self.filename, "wb")
2633 file.write(content)
2634 file.close()
2637 class CHeaderWriter(CWriter):
2638 """Writes a C Header file."""
2640 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
2642 def __init__(self, filename, file_comment = None):
2643 CWriter.__init__(self, filename)
2645 base = os.path.abspath(filename)
2646 while os.path.basename(base) != 'src':
2647 new_base = os.path.dirname(base)
2648 assert new_base != base # Prevent infinite loop.
2649 base = new_base
2651 hpath = os.path.relpath(filename, base)
2652 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
2654 self.Write(_LICENSE)
2655 self.Write(_DO_NOT_EDIT_WARNING)
2656 if not file_comment == None:
2657 self.Write(file_comment)
2658 self.Write("#ifndef %s\n" % self.guard)
2659 self.Write("#define %s\n\n" % self.guard)
2661 def Close(self):
2662 self.Write("#endif // %s\n\n" % self.guard)
2663 CWriter.Close(self)
2665 class TypeHandler(object):
2666 """This class emits code for a particular type of function."""
2668 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
2670 def __init__(self):
2671 pass
2673 def InitFunction(self, func):
2674 """Add or adjust anything type specific for this function."""
2675 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
2676 func.AddCmdArg(DataSizeArgument('data_size'))
2678 def AddImmediateFunction(self, generator, func):
2679 """Adds an immediate version of a function."""
2680 # Generate an immediate command if there is only 1 pointer arg.
2681 immediate = func.GetInfo('immediate') # can be True, False or None
2682 if immediate == True or immediate == None:
2683 if func.num_pointer_args == 1 or immediate:
2684 generator.AddFunction(ImmediateFunction(func))
2686 def AddBucketFunction(self, generator, func):
2687 """Adds a bucket version of a function."""
2688 # Generate an immediate command if there is only 1 pointer arg.
2689 bucket = func.GetInfo('bucket') # can be True, False or None
2690 if bucket:
2691 generator.AddFunction(BucketFunction(func))
2693 def WriteStruct(self, func, file):
2694 """Writes a structure that matches the arguments to a function."""
2695 comment = func.GetInfo('cmd_comment')
2696 if not comment == None:
2697 file.Write(comment)
2698 file.Write("struct %s {\n" % func.name)
2699 file.Write(" typedef %s ValueType;\n" % func.name)
2700 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
2701 func.WriteCmdArgFlag(file)
2702 func.WriteCmdFlag(file)
2703 file.Write("\n")
2704 result = func.GetInfo('result')
2705 if not result == None:
2706 if len(result) == 1:
2707 file.Write(" typedef %s Result;\n\n" % result[0])
2708 else:
2709 file.Write(" struct Result {\n")
2710 for line in result:
2711 file.Write(" %s;\n" % line)
2712 file.Write(" };\n\n")
2714 func.WriteCmdComputeSize(file)
2715 func.WriteCmdSetHeader(file)
2716 func.WriteCmdInit(file)
2717 func.WriteCmdSet(file)
2719 file.Write(" gpu::CommandHeader header;\n")
2720 args = func.GetCmdArgs()
2721 for arg in args:
2722 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
2723 file.Write("};\n")
2724 file.Write("\n")
2726 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
2727 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func.name, size))
2728 file.Write(" Sizeof_%s_is_not_%d);\n" % (func.name, size))
2729 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func.name)
2730 file.Write(" OffsetOf_%s_header_not_0);\n" % func.name)
2731 offset = _SIZE_OF_COMMAND_HEADER
2732 for arg in args:
2733 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2734 (func.name, arg.name, offset))
2735 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2736 (func.name, arg.name, offset))
2737 offset += _SIZE_OF_UINT32
2738 if not result == None and len(result) > 1:
2739 offset = 0;
2740 for line in result:
2741 parts = line.split()
2742 name = parts[-1]
2743 check = """
2744 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2745 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2747 file.Write((check.strip() + "\n") % {
2748 'cmd_name': func.name,
2749 'field_name': name,
2750 'offset': offset,
2752 offset += _SIZE_OF_UINT32
2753 file.Write("\n")
2755 def WriteHandlerImplementation(self, func, file):
2756 """Writes the handler implementation for this command."""
2757 file.Write(" %s(%s);\n" %
2758 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2760 def WriteCmdSizeTest(self, func, file):
2761 """Writes the size test for a command."""
2762 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2764 def WriteFormatTest(self, func, file):
2765 """Writes a format test for a command."""
2766 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
2767 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2768 (func.name, func.name))
2769 file.Write(" void* next_cmd = cmd.Set(\n")
2770 file.Write(" &cmd")
2771 args = func.GetCmdArgs()
2772 for value, arg in enumerate(args):
2773 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
2774 file.Write(");\n")
2775 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2776 func.name)
2777 file.Write(" cmd.header.command);\n")
2778 func.type_handler.WriteCmdSizeTest(func, file)
2779 for value, arg in enumerate(args):
2780 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2781 (arg.type, value + 11, arg.name))
2782 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2783 file.Write(" next_cmd, sizeof(cmd));\n")
2784 file.Write("}\n")
2785 file.Write("\n")
2787 def WriteImmediateFormatTest(self, func, file):
2788 """Writes a format test for an immediate version of a command."""
2789 pass
2791 def WriteBucketFormatTest(self, func, file):
2792 """Writes a format test for a bucket version of a command."""
2793 pass
2795 def WriteGetDataSizeCode(self, func, file):
2796 """Writes the code to set data_size used in validation"""
2797 pass
2799 def WriteImmediateCmdSizeTest(self, func, file):
2800 """Writes a size test for an immediate version of a command."""
2801 file.Write(" // TODO(gman): Compute correct size.\n")
2802 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2804 def WriteImmediateHandlerImplementation (self, func, file):
2805 """Writes the handler impl for the immediate version of a command."""
2806 file.Write(" %s(%s);\n" %
2807 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2809 def WriteBucketHandlerImplementation (self, func, file):
2810 """Writes the handler impl for the bucket version of a command."""
2811 file.Write(" %s(%s);\n" %
2812 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2814 def WriteServiceImplementation(self, func, file):
2815 """Writes the service implementation for a command."""
2816 file.Write(
2817 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2818 file.Write(
2819 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2820 func.name)
2821 self.WriteHandlerDeferReadWrite(func, file);
2822 if len(func.GetOriginalArgs()) > 0:
2823 last_arg = func.GetLastOriginalArg()
2824 all_but_last_arg = func.GetOriginalArgs()[:-1]
2825 for arg in all_but_last_arg:
2826 arg.WriteGetCode(file)
2827 self.WriteGetDataSizeCode(func, file)
2828 last_arg.WriteGetCode(file)
2829 func.WriteHandlerValidation(file)
2830 func.WriteHandlerImplementation(file)
2831 file.Write(" return error::kNoError;\n")
2832 file.Write("}\n")
2833 file.Write("\n")
2835 def WriteImmediateServiceImplementation(self, func, file):
2836 """Writes the service implementation for an immediate version of command."""
2837 file.Write(
2838 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2839 file.Write(
2840 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2841 func.name)
2842 self.WriteHandlerDeferReadWrite(func, file);
2843 last_arg = func.GetLastOriginalArg()
2844 all_but_last_arg = func.GetOriginalArgs()[:-1]
2845 for arg in all_but_last_arg:
2846 arg.WriteGetCode(file)
2847 self.WriteGetDataSizeCode(func, file)
2848 last_arg.WriteGetCode(file)
2849 func.WriteHandlerValidation(file)
2850 func.WriteHandlerImplementation(file)
2851 file.Write(" return error::kNoError;\n")
2852 file.Write("}\n")
2853 file.Write("\n")
2855 def WriteBucketServiceImplementation(self, func, file):
2856 """Writes the service implementation for a bucket version of command."""
2857 file.Write(
2858 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2859 file.Write(
2860 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2861 func.name)
2862 self.WriteHandlerDeferReadWrite(func, file);
2863 last_arg = func.GetLastOriginalArg()
2864 all_but_last_arg = func.GetOriginalArgs()[:-1]
2865 for arg in all_but_last_arg:
2866 arg.WriteGetCode(file)
2867 self.WriteGetDataSizeCode(func, file)
2868 last_arg.WriteGetCode(file)
2869 func.WriteHandlerValidation(file)
2870 func.WriteHandlerImplementation(file)
2871 file.Write(" return error::kNoError;\n")
2872 file.Write("}\n")
2873 file.Write("\n")
2875 def WriteHandlerDeferReadWrite(self, func, file):
2876 """Writes the code to handle deferring reads or writes."""
2877 defer_draws = func.GetInfo('defer_draws')
2878 defer_reads = func.GetInfo('defer_reads')
2879 if defer_draws or defer_reads:
2880 file.Write(" error::Error error;\n")
2881 if defer_draws:
2882 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2883 file.Write(" if (error != error::kNoError)\n")
2884 file.Write(" return error;\n")
2885 if defer_reads:
2886 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2887 file.Write(" if (error != error::kNoError)\n")
2888 file.Write(" return error;\n")
2890 def WriteValidUnitTest(self, func, file, test, extra = {}):
2891 """Writes a valid unit test."""
2892 if func.GetInfo('expectation') == False:
2893 test = self._remove_expected_call_re.sub('', test)
2894 name = func.name
2895 arg_strings = []
2896 for count, arg in enumerate(func.GetOriginalArgs()):
2897 arg_strings.append(arg.GetValidArg(func, count, 0))
2898 gl_arg_strings = []
2899 for count, arg in enumerate(func.GetOriginalArgs()):
2900 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
2901 gl_func_name = func.GetGLTestFunctionName()
2902 vars = {
2903 'test_name': 'GLES2DecoderTest%d' % file.file_num,
2904 'name':name,
2905 'gl_func_name': gl_func_name,
2906 'args': ", ".join(arg_strings),
2907 'gl_args': ", ".join(gl_arg_strings),
2909 vars.update(extra)
2910 old_test = ""
2911 while (old_test != test):
2912 old_test = test
2913 test = test % vars
2914 file.Write(test % vars)
2916 def WriteInvalidUnitTest(self, func, file, test, extra = {}):
2917 """Writes a invalid unit test."""
2918 for arg_index, arg in enumerate(func.GetOriginalArgs()):
2919 num_invalid_values = arg.GetNumInvalidValues(func)
2920 for value_index in range(0, num_invalid_values):
2921 arg_strings = []
2922 parse_result = "kNoError"
2923 gl_error = None
2924 for count, arg in enumerate(func.GetOriginalArgs()):
2925 if count == arg_index:
2926 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
2927 count, value_index)
2928 else:
2929 arg_string = arg.GetValidArg(func, count, 0)
2930 arg_strings.append(arg_string)
2931 gl_arg_strings = []
2932 for arg in func.GetOriginalArgs():
2933 gl_arg_strings.append("_")
2934 gl_func_name = func.GetGLTestFunctionName()
2935 gl_error_test = ''
2936 if not gl_error == None:
2937 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2939 vars = {
2940 'test_name': 'GLES2DecoderTest%d' % file.file_num ,
2941 'name': func.name,
2942 'arg_index': arg_index,
2943 'value_index': value_index,
2944 'gl_func_name': gl_func_name,
2945 'args': ", ".join(arg_strings),
2946 'all_but_last_args': ", ".join(arg_strings[:-1]),
2947 'gl_args': ", ".join(gl_arg_strings),
2948 'parse_result': parse_result,
2949 'gl_error_test': gl_error_test,
2951 vars.update(extra)
2952 file.Write(test % vars)
2954 def WriteServiceUnitTest(self, func, file):
2955 """Writes the service unit test for a command."""
2956 valid_test = """
2957 TEST_F(%(test_name)s, %(name)sValidArgs) {
2958 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2959 SpecializedSetup<cmds::%(name)s, 0>(true);
2960 cmds::%(name)s cmd;
2961 cmd.Init(%(args)s);
2962 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2963 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2966 self.WriteValidUnitTest(func, file, valid_test)
2968 invalid_test = """
2969 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
2970 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
2971 SpecializedSetup<cmds::%(name)s, 0>(false);
2972 cmds::%(name)s cmd;
2973 cmd.Init(%(args)s);
2974 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
2977 self.WriteInvalidUnitTest(func, file, invalid_test)
2979 def WriteImmediateServiceUnitTest(self, func, file):
2980 """Writes the service unit test for an immediate command."""
2981 file.Write("// TODO(gman): %s\n" % func.name)
2983 def WriteImmediateValidationCode(self, func, file):
2984 """Writes the validation code for an immediate version of a command."""
2985 pass
2987 def WriteBucketServiceUnitTest(self, func, file):
2988 """Writes the service unit test for a bucket command."""
2989 file.Write("// TODO(gman): %s\n" % func.name)
2991 def WriteBucketValidationCode(self, func, file):
2992 """Writes the validation code for a bucket version of a command."""
2993 file.Write("// TODO(gman): %s\n" % func.name)
2995 def WriteGLES2ImplementationDeclaration(self, func, file):
2996 """Writes the GLES2 Implemention declaration."""
2997 impl_decl = func.GetInfo('impl_decl')
2998 if impl_decl == None or impl_decl == True:
2999 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3000 (func.return_type, func.original_name,
3001 func.MakeTypedOriginalArgString("")))
3002 file.Write("\n")
3004 def WriteGLES2CLibImplementation(self, func, file):
3005 file.Write("%s GLES2%s(%s) {\n" %
3006 (func.return_type, func.name,
3007 func.MakeTypedOriginalArgString("")))
3008 result_string = "return "
3009 if func.return_type == "void":
3010 result_string = ""
3011 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3012 (result_string, func.original_name,
3013 func.MakeOriginalArgString("")))
3014 file.Write("}\n")
3016 def WriteGLES2Header(self, func, file):
3017 """Writes a re-write macro for GLES"""
3018 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
3020 def WriteClientGLCallLog(self, func, file):
3021 """Writes a logging macro for the client side code."""
3022 comma = ""
3023 if len(func.GetOriginalArgs()):
3024 comma = " << "
3025 file.Write(
3026 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3027 (func.original_name, comma, func.MakeLogArgString()))
3029 def WriteClientGLReturnLog(self, func, file):
3030 """Writes the return value logging code."""
3031 if func.return_type != "void":
3032 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3034 def WriteGLES2ImplementationHeader(self, func, file):
3035 """Writes the GLES2 Implemention."""
3036 self.WriteGLES2ImplementationDeclaration(func, file)
3038 def WriteGLES2TraceImplementationHeader(self, func, file):
3039 """Writes the GLES2 Trace Implemention header."""
3040 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3041 (func.return_type, func.original_name,
3042 func.MakeTypedOriginalArgString("")))
3044 def WriteGLES2TraceImplementation(self, func, file):
3045 """Writes the GLES2 Trace Implemention."""
3046 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3047 (func.return_type, func.original_name,
3048 func.MakeTypedOriginalArgString("")))
3049 result_string = "return "
3050 if func.return_type == "void":
3051 result_string = ""
3052 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3053 func.name)
3054 file.Write(" %sgl_->%s(%s);\n" %
3055 (result_string, func.name, func.MakeOriginalArgString("")))
3056 file.Write("}\n")
3057 file.Write("\n")
3059 def WriteGLES2Implementation(self, func, file):
3060 """Writes the GLES2 Implemention."""
3061 impl_func = func.GetInfo('impl_func')
3062 impl_decl = func.GetInfo('impl_decl')
3063 gen_cmd = func.GetInfo('gen_cmd')
3064 if (func.can_auto_generate and
3065 (impl_func == None or impl_func == True) and
3066 (impl_decl == None or impl_decl == True) and
3067 (gen_cmd == None or gen_cmd == True)):
3068 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3069 (func.return_type, func.original_name,
3070 func.MakeTypedOriginalArgString("")))
3071 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3072 self.WriteClientGLCallLog(func, file)
3073 func.WriteDestinationInitalizationValidation(file)
3074 for arg in func.GetOriginalArgs():
3075 arg.WriteClientSideValidationCode(file, func)
3076 file.Write(" helper_->%s(%s);\n" %
3077 (func.name, func.MakeOriginalArgString("")))
3078 file.Write(" CheckGLError();\n")
3079 self.WriteClientGLReturnLog(func, file)
3080 file.Write("}\n")
3081 file.Write("\n")
3083 def WriteGLES2InterfaceHeader(self, func, file):
3084 """Writes the GLES2 Interface."""
3085 file.Write("virtual %s %s(%s) = 0;\n" %
3086 (func.return_type, func.original_name,
3087 func.MakeTypedOriginalArgString("")))
3089 def WriteGLES2InterfaceStub(self, func, file):
3090 """Writes the GLES2 Interface stub declaration."""
3091 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3092 (func.return_type, func.original_name,
3093 func.MakeTypedOriginalArgString("")))
3095 def WriteGLES2InterfaceStubImpl(self, func, file):
3096 """Writes the GLES2 Interface stub declaration."""
3097 args = func.GetOriginalArgs()
3098 arg_string = ", ".join(
3099 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
3100 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3101 (func.return_type, func.original_name, arg_string))
3102 if func.return_type != "void":
3103 file.Write(" return 0;\n")
3104 file.Write("}\n")
3106 def WriteGLES2ImplementationUnitTest(self, func, file):
3107 """Writes the GLES2 Implemention unit test."""
3108 client_test = func.GetInfo('client_test')
3109 if (func.can_auto_generate and
3110 (client_test == None or client_test == True)):
3111 code = """
3112 TEST_F(GLES2ImplementationTest, %(name)s) {
3113 struct Cmds {
3114 cmds::%(name)s cmd;
3116 Cmds expected;
3117 expected.cmd.Init(%(cmd_args)s);
3119 gl_->%(name)s(%(args)s);
3120 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3123 cmd_arg_strings = []
3124 for count, arg in enumerate(func.GetCmdArgs()):
3125 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3126 count += 1
3127 gl_arg_strings = []
3128 for count, arg in enumerate(func.GetOriginalArgs()):
3129 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3130 file.Write(code % {
3131 'name': func.name,
3132 'args': ", ".join(gl_arg_strings),
3133 'cmd_args': ", ".join(cmd_arg_strings),
3135 else:
3136 if client_test != False:
3137 file.Write("// TODO: Implement unit test for %s\n" % func.name)
3139 def WriteDestinationInitalizationValidation(self, func, file):
3140 """Writes the client side destintion initialization validation."""
3141 for arg in func.GetOriginalArgs():
3142 arg.WriteDestinationInitalizationValidation(file, func)
3144 def WriteTraceEvent(self, func, file):
3145 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3146 func.original_name)
3148 def WriteImmediateCmdComputeSize(self, func, file):
3149 """Writes the size computation code for the immediate version of a cmd."""
3150 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3151 file.Write(" return static_cast<uint32>(\n")
3152 file.Write(" sizeof(ValueType) + // NOLINT\n")
3153 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3154 file.Write(" }\n")
3155 file.Write("\n")
3157 def WriteImmediateCmdSetHeader(self, func, file):
3158 """Writes the SetHeader function for the immediate version of a cmd."""
3159 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3160 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3161 file.Write(" }\n")
3162 file.Write("\n")
3164 def WriteImmediateCmdInit(self, func, file):
3165 """Writes the Init function for the immediate version of a command."""
3166 raise NotImplementedError(func.name)
3168 def WriteImmediateCmdSet(self, func, file):
3169 """Writes the Set function for the immediate version of a command."""
3170 raise NotImplementedError(func.name)
3172 def WriteCmdHelper(self, func, file):
3173 """Writes the cmd helper definition for a cmd."""
3174 code = """ void %(name)s(%(typed_args)s) {
3175 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3176 if (c) {
3177 c->Init(%(args)s);
3182 file.Write(code % {
3183 "name": func.name,
3184 "typed_args": func.MakeTypedCmdArgString(""),
3185 "args": func.MakeCmdArgString(""),
3188 def WriteImmediateCmdHelper(self, func, file):
3189 """Writes the cmd helper definition for the immediate version of a cmd."""
3190 code = """ void %(name)s(%(typed_args)s) {
3191 const uint32 s = 0; // TODO(gman): compute correct size
3192 gles2::cmds::%(name)s* c =
3193 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3194 if (c) {
3195 c->Init(%(args)s);
3200 file.Write(code % {
3201 "name": func.name,
3202 "typed_args": func.MakeTypedCmdArgString(""),
3203 "args": func.MakeCmdArgString(""),
3207 class StateSetHandler(TypeHandler):
3208 """Handler for commands that simply set state."""
3210 def __init__(self):
3211 TypeHandler.__init__(self)
3213 def WriteHandlerImplementation(self, func, file):
3214 """Overrriden from TypeHandler."""
3215 state_name = func.GetInfo('state')
3216 state = _STATES[state_name]
3217 states = state['states']
3218 args = func.GetOriginalArgs()
3219 code = []
3220 for ndx,item in enumerate(states):
3221 if 'range_checks' in item:
3222 for range_check in item['range_checks']:
3223 code.append("%s %s" % (args[ndx].name, range_check['check']))
3224 if len(code):
3225 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3226 file.Write(
3227 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3228 ' "%s", "%s out of range");\n' %
3229 (func.name, args[ndx].name))
3230 file.Write(" return error::kNoError;\n")
3231 file.Write(" }\n")
3232 code = []
3233 for ndx,item in enumerate(states):
3234 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3235 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3236 for ndx,item in enumerate(states):
3237 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3238 if 'state_flag' in state:
3239 file.Write(" %s = true;\n" % state['state_flag'])
3240 if not func.GetInfo("no_gl"):
3241 file.Write(" %s(%s);\n" %
3242 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3243 file.Write(" }\n")
3245 def WriteServiceUnitTest(self, func, file):
3246 """Overrriden from TypeHandler."""
3247 TypeHandler.WriteServiceUnitTest(self, func, file)
3248 state_name = func.GetInfo('state')
3249 state = _STATES[state_name]
3250 states = state['states']
3251 for ndx,item in enumerate(states):
3252 if 'range_checks' in item:
3253 for check_ndx, range_check in enumerate(item['range_checks']):
3254 valid_test = """
3255 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3256 SpecializedSetup<cmds::%(name)s, 0>(false);
3257 cmds::%(name)s cmd;
3258 cmd.Init(%(args)s);
3259 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3260 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3263 name = func.name
3264 arg_strings = []
3265 for count, arg in enumerate(func.GetOriginalArgs()):
3266 arg_strings.append(arg.GetValidArg(func, count, 0))
3267 arg_strings[ndx] = range_check['test_value']
3268 vars = {
3269 'test_name': 'GLES2DecoderTest%d' % file.file_num,
3270 'name': name,
3271 'ndx': ndx,
3272 'check_ndx': check_ndx,
3273 'args': ", ".join(arg_strings),
3275 file.Write(valid_test % vars)
3278 class StateSetRGBAlphaHandler(TypeHandler):
3279 """Handler for commands that simply set state that have rgb/alpha."""
3281 def __init__(self):
3282 TypeHandler.__init__(self)
3284 def WriteHandlerImplementation(self, func, file):
3285 """Overrriden from TypeHandler."""
3286 state_name = func.GetInfo('state')
3287 state = _STATES[state_name]
3288 states = state['states']
3289 args = func.GetOriginalArgs()
3290 num_args = len(args)
3291 code = []
3292 for ndx,item in enumerate(states):
3293 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
3294 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3295 for ndx, item in enumerate(states):
3296 file.Write(" state_.%s = %s;\n" %
3297 (item['name'], args[ndx % num_args].name))
3298 if 'state_flag' in state:
3299 file.Write(" %s = true;\n" % state['state_flag'])
3300 if not func.GetInfo("no_gl"):
3301 file.Write(" %s(%s);\n" %
3302 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3303 file.Write(" }\n")
3306 class StateSetFrontBackSeparateHandler(TypeHandler):
3307 """Handler for commands that simply set state that have front/back."""
3309 def __init__(self):
3310 TypeHandler.__init__(self)
3312 def WriteHandlerImplementation(self, func, file):
3313 """Overrriden from TypeHandler."""
3314 state_name = func.GetInfo('state')
3315 state = _STATES[state_name]
3316 states = state['states']
3317 args = func.GetOriginalArgs()
3318 face = args[0].name
3319 num_args = len(args)
3320 file.Write(" bool changed = false;\n")
3321 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3322 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3323 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3324 code = []
3325 for ndx, item in enumerate(group):
3326 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
3327 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
3328 file.Write(" }\n")
3329 file.Write(" if (changed) {\n")
3330 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3331 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3332 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3333 for ndx, item in enumerate(group):
3334 file.Write(" state_.%s = %s;\n" %
3335 (item['name'], args[ndx + 1].name))
3336 file.Write(" }\n")
3337 if 'state_flag' in state:
3338 file.Write(" %s = true;\n" % state['state_flag'])
3339 if not func.GetInfo("no_gl"):
3340 file.Write(" %s(%s);\n" %
3341 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3342 file.Write(" }\n")
3345 class StateSetFrontBackHandler(TypeHandler):
3346 """Handler for commands that simply set state that set both front/back."""
3348 def __init__(self):
3349 TypeHandler.__init__(self)
3351 def WriteHandlerImplementation(self, func, file):
3352 """Overrriden from TypeHandler."""
3353 state_name = func.GetInfo('state')
3354 state = _STATES[state_name]
3355 states = state['states']
3356 args = func.GetOriginalArgs()
3357 num_args = len(args)
3358 code = []
3359 for group_ndx, group in enumerate(Grouper(num_args, states)):
3360 for ndx, item in enumerate(group):
3361 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3362 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3363 for group_ndx, group in enumerate(Grouper(num_args, states)):
3364 for ndx, item in enumerate(group):
3365 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3366 if 'state_flag' in state:
3367 file.Write(" %s = true;\n" % state['state_flag'])
3368 if not func.GetInfo("no_gl"):
3369 file.Write(" %s(%s);\n" %
3370 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3371 file.Write(" }\n")
3374 class StateSetNamedParameter(TypeHandler):
3375 """Handler for commands that set a state chosen with an enum parameter."""
3377 def __init__(self):
3378 TypeHandler.__init__(self)
3380 def WriteHandlerImplementation(self, func, file):
3381 """Overridden from TypeHandler."""
3382 state_name = func.GetInfo('state')
3383 state = _STATES[state_name]
3384 states = state['states']
3385 args = func.GetOriginalArgs()
3386 num_args = len(args)
3387 assert num_args == 2
3388 file.Write(" switch (%s) {\n" % args[0].name)
3389 for state in states:
3390 file.Write(" case %s:\n" % state['enum'])
3391 file.Write(" if (state_.%s != %s) {\n" %
3392 (state['name'], args[1].name))
3393 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
3394 if not func.GetInfo("no_gl"):
3395 file.Write(" %s(%s);\n" %
3396 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3397 file.Write(" }\n")
3398 file.Write(" break;\n")
3399 file.Write(" default:\n")
3400 file.Write(" NOTREACHED();\n")
3401 file.Write(" }\n")
3404 class CustomHandler(TypeHandler):
3405 """Handler for commands that are auto-generated but require minor tweaks."""
3407 def __init__(self):
3408 TypeHandler.__init__(self)
3410 def WriteServiceImplementation(self, func, file):
3411 """Overrriden from TypeHandler."""
3412 pass
3414 def WriteImmediateServiceImplementation(self, func, file):
3415 """Overrriden from TypeHandler."""
3416 pass
3418 def WriteBucketServiceImplementation(self, func, file):
3419 """Overrriden from TypeHandler."""
3420 pass
3422 def WriteServiceUnitTest(self, func, file):
3423 """Overrriden from TypeHandler."""
3424 file.Write("// TODO(gman): %s\n\n" % func.name)
3426 def WriteImmediateServiceUnitTest(self, func, file):
3427 """Overrriden from TypeHandler."""
3428 file.Write("// TODO(gman): %s\n\n" % func.name)
3430 def WriteImmediateCmdGetTotalSize(self, func, file):
3431 """Overrriden from TypeHandler."""
3432 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3434 def WriteImmediateCmdInit(self, func, file):
3435 """Overrriden from TypeHandler."""
3436 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3437 self.WriteImmediateCmdGetTotalSize(func, file)
3438 file.Write(" SetHeader(total_size);\n")
3439 args = func.GetCmdArgs()
3440 for arg in args:
3441 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3442 file.Write(" }\n")
3443 file.Write("\n")
3445 def WriteImmediateCmdSet(self, func, file):
3446 """Overrriden from TypeHandler."""
3447 copy_args = func.MakeCmdArgString("_", False)
3448 file.Write(" void* Set(void* cmd%s) {\n" %
3449 func.MakeTypedCmdArgString("_", True))
3450 self.WriteImmediateCmdGetTotalSize(func, file)
3451 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3452 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3453 "cmd, total_size);\n")
3454 file.Write(" }\n")
3455 file.Write("\n")
3458 class TodoHandler(CustomHandler):
3459 """Handle for commands that are not yet implemented."""
3461 def AddImmediateFunction(self, generator, func):
3462 """Overrriden from TypeHandler."""
3463 pass
3465 def WriteImmediateFormatTest(self, func, file):
3466 """Overrriden from TypeHandler."""
3467 pass
3469 def WriteGLES2ImplementationUnitTest(self, func, file):
3470 """Overrriden from TypeHandler."""
3471 pass
3473 def WriteGLES2Implementation(self, func, file):
3474 """Overrriden from TypeHandler."""
3475 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3476 (func.return_type, func.original_name,
3477 func.MakeTypedOriginalArgString("")))
3478 file.Write(" // TODO: for now this is a no-op\n")
3479 file.Write(
3480 " SetGLError("
3481 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3482 func.name)
3483 if func.return_type != "void":
3484 file.Write(" return 0;\n")
3485 file.Write("}\n")
3486 file.Write("\n")
3488 def WriteServiceImplementation(self, func, file):
3489 """Overrriden from TypeHandler."""
3490 file.Write(
3491 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
3492 file.Write(
3493 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3494 func.name)
3495 file.Write(" // TODO: for now this is a no-op\n")
3496 file.Write(
3497 " LOCAL_SET_GL_ERROR("
3498 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3499 func.name)
3500 file.Write(" return error::kNoError;\n")
3501 file.Write("}\n")
3502 file.Write("\n")
3505 class HandWrittenHandler(CustomHandler):
3506 """Handler for comands where everything must be written by hand."""
3508 def InitFunction(self, func):
3509 """Add or adjust anything type specific for this function."""
3510 CustomHandler.InitFunction(self, func)
3511 func.can_auto_generate = False
3513 def WriteStruct(self, func, file):
3514 """Overrriden from TypeHandler."""
3515 pass
3517 def WriteDocs(self, func, file):
3518 """Overrriden from TypeHandler."""
3519 pass
3521 def WriteServiceUnitTest(self, func, file):
3522 """Overrriden from TypeHandler."""
3523 file.Write("// TODO(gman): %s\n\n" % func.name)
3525 def WriteImmediateServiceUnitTest(self, func, file):
3526 """Overrriden from TypeHandler."""
3527 file.Write("// TODO(gman): %s\n\n" % func.name)
3529 def WriteBucketServiceUnitTest(self, func, file):
3530 """Overrriden from TypeHandler."""
3531 file.Write("// TODO(gman): %s\n\n" % func.name)
3533 def WriteServiceImplementation(self, func, file):
3534 """Overrriden from TypeHandler."""
3535 pass
3537 def WriteImmediateServiceImplementation(self, func, file):
3538 """Overrriden from TypeHandler."""
3539 pass
3541 def WriteBucketServiceImplementation(self, func, file):
3542 """Overrriden from TypeHandler."""
3543 pass
3545 def WriteImmediateCmdHelper(self, func, file):
3546 """Overrriden from TypeHandler."""
3547 pass
3549 def WriteBucketCmdHelper(self, func, file):
3550 """Overrriden from TypeHandler."""
3551 pass
3553 def WriteCmdHelper(self, func, file):
3554 """Overrriden from TypeHandler."""
3555 pass
3557 def WriteFormatTest(self, func, file):
3558 """Overrriden from TypeHandler."""
3559 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3561 def WriteImmediateFormatTest(self, func, file):
3562 """Overrriden from TypeHandler."""
3563 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3565 def WriteBucketFormatTest(self, func, file):
3566 """Overrriden from TypeHandler."""
3567 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3571 class ManualHandler(CustomHandler):
3572 """Handler for commands who's handlers must be written by hand."""
3574 def __init__(self):
3575 CustomHandler.__init__(self)
3577 def InitFunction(self, func):
3578 """Overrriden from TypeHandler."""
3579 if (func.name == 'CompressedTexImage2DBucket'):
3580 func.cmd_args = func.cmd_args[:-1]
3581 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3582 else:
3583 CustomHandler.InitFunction(self, func)
3585 def WriteServiceImplementation(self, func, file):
3586 """Overrriden from TypeHandler."""
3587 pass
3589 def WriteBucketServiceImplementation(self, func, file):
3590 """Overrriden from TypeHandler."""
3591 pass
3593 def WriteServiceUnitTest(self, func, file):
3594 """Overrriden from TypeHandler."""
3595 file.Write("// TODO(gman): %s\n\n" % func.name)
3597 def WriteImmediateServiceUnitTest(self, func, file):
3598 """Overrriden from TypeHandler."""
3599 file.Write("// TODO(gman): %s\n\n" % func.name)
3601 def WriteImmediateServiceImplementation(self, func, file):
3602 """Overrriden from TypeHandler."""
3603 pass
3605 def WriteImmediateFormatTest(self, func, file):
3606 """Overrriden from TypeHandler."""
3607 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3609 def WriteGLES2Implementation(self, func, file):
3610 """Overrriden from TypeHandler."""
3611 if func.GetInfo('impl_func'):
3612 super(ManualHandler, self).WriteGLES2Implementation(func, file)
3614 def WriteGLES2ImplementationHeader(self, func, file):
3615 """Overrriden from TypeHandler."""
3616 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3617 (func.return_type, func.original_name,
3618 func.MakeTypedOriginalArgString("")))
3619 file.Write("\n")
3621 def WriteImmediateCmdGetTotalSize(self, func, file):
3622 """Overrriden from TypeHandler."""
3623 # TODO(gman): Move this data to _FUNCTION_INFO?
3624 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
3627 class DataHandler(TypeHandler):
3628 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3629 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3630 def __init__(self):
3631 TypeHandler.__init__(self)
3633 def InitFunction(self, func):
3634 """Overrriden from TypeHandler."""
3635 if func.name == 'CompressedTexSubImage2DBucket':
3636 func.cmd_args = func.cmd_args[:-1]
3637 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3639 def WriteGetDataSizeCode(self, func, file):
3640 """Overrriden from TypeHandler."""
3641 # TODO(gman): Move this data to _FUNCTION_INFO?
3642 name = func.name
3643 if name.endswith("Immediate"):
3644 name = name[0:-9]
3645 if name == 'BufferData' or name == 'BufferSubData':
3646 file.Write(" uint32 data_size = size;\n")
3647 elif (name == 'CompressedTexImage2D' or
3648 name == 'CompressedTexSubImage2D'):
3649 file.Write(" uint32 data_size = imageSize;\n")
3650 elif (name == 'CompressedTexSubImage2DBucket'):
3651 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3652 file.Write(" uint32 data_size = bucket->size();\n")
3653 file.Write(" GLsizei imageSize = data_size;\n")
3654 elif name == 'TexImage2D' or name == 'TexSubImage2D':
3655 code = """ uint32 data_size;
3656 if (!GLES2Util::ComputeImageDataSize(
3657 width, height, format, type, unpack_alignment_, &data_size)) {
3658 return error::kOutOfBounds;
3661 file.Write(code)
3662 else:
3663 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3665 def WriteImmediateCmdGetTotalSize(self, func, file):
3666 """Overrriden from TypeHandler."""
3667 pass
3669 def WriteImmediateCmdSizeTest(self, func, file):
3670 """Overrriden from TypeHandler."""
3671 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3673 def WriteImmediateCmdInit(self, func, file):
3674 """Overrriden from TypeHandler."""
3675 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3676 self.WriteImmediateCmdGetTotalSize(func, file)
3677 file.Write(" SetHeader(total_size);\n")
3678 args = func.GetCmdArgs()
3679 for arg in args:
3680 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3681 file.Write(" }\n")
3682 file.Write("\n")
3684 def WriteImmediateCmdSet(self, func, file):
3685 """Overrriden from TypeHandler."""
3686 copy_args = func.MakeCmdArgString("_", False)
3687 file.Write(" void* Set(void* cmd%s) {\n" %
3688 func.MakeTypedCmdArgString("_", True))
3689 self.WriteImmediateCmdGetTotalSize(func, file)
3690 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3691 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3692 "cmd, total_size);\n")
3693 file.Write(" }\n")
3694 file.Write("\n")
3696 def WriteImmediateFormatTest(self, func, file):
3697 """Overrriden from TypeHandler."""
3698 # TODO(gman): Remove this exception.
3699 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3700 return
3702 def WriteServiceUnitTest(self, func, file):
3703 """Overrriden from TypeHandler."""
3704 file.Write("// TODO(gman): %s\n\n" % func.name)
3706 def WriteImmediateServiceUnitTest(self, func, file):
3707 """Overrriden from TypeHandler."""
3708 file.Write("// TODO(gman): %s\n\n" % func.name)
3710 def WriteBucketServiceImplementation(self, func, file):
3711 """Overrriden from TypeHandler."""
3712 if not func.name == 'CompressedTexSubImage2DBucket':
3713 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
3716 class BindHandler(TypeHandler):
3717 """Handler for glBind___ type functions."""
3719 def __init__(self):
3720 TypeHandler.__init__(self)
3722 def WriteServiceUnitTest(self, func, file):
3723 """Overrriden from TypeHandler."""
3725 if len(func.GetOriginalArgs()) == 1:
3726 valid_test = """
3727 TEST_F(%(test_name)s, %(name)sValidArgs) {
3728 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3729 SpecializedSetup<cmds::%(name)s, 0>(true);
3730 cmds::%(name)s cmd;
3731 cmd.Init(%(args)s);
3732 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3733 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3736 if func.GetInfo("gen_func"):
3737 valid_test += """
3738 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3739 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3740 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3741 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3742 SpecializedSetup<cmds::%(name)s, 0>(true);
3743 cmds::%(name)s cmd;
3744 cmd.Init(kNewClientId);
3745 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3746 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3747 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3750 self.WriteValidUnitTest(func, file, valid_test, {
3751 'resource_type': func.GetOriginalArgs()[0].resource_type,
3752 'gl_gen_func_name': func.GetInfo("gen_func"),
3754 else:
3755 valid_test = """
3756 TEST_F(%(test_name)s, %(name)sValidArgs) {
3757 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3758 SpecializedSetup<cmds::%(name)s, 0>(true);
3759 cmds::%(name)s cmd;
3760 cmd.Init(%(args)s);
3761 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3762 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3765 if func.GetInfo("gen_func"):
3766 valid_test += """
3767 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3768 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)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(%(first_arg)s, 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 self.WriteValidUnitTest(func, file, valid_test, {
3780 'first_arg': func.GetOriginalArgs()[0].GetValidArg(func, 0, 0),
3781 'first_gl_arg': func.GetOriginalArgs()[0].GetValidGLArg(func, 0, 0),
3782 'resource_type': func.GetOriginalArgs()[1].resource_type,
3783 'gl_gen_func_name': func.GetInfo("gen_func"),
3786 invalid_test = """
3787 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3788 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3789 SpecializedSetup<cmds::%(name)s, 0>(false);
3790 cmds::%(name)s cmd;
3791 cmd.Init(%(args)s);
3792 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3795 self.WriteInvalidUnitTest(func, file, invalid_test)
3797 def WriteGLES2Implementation(self, func, file):
3798 """Writes the GLES2 Implemention."""
3800 impl_func = func.GetInfo('impl_func')
3801 impl_decl = func.GetInfo('impl_decl')
3803 if (func.can_auto_generate and
3804 (impl_func == None or impl_func == True) and
3805 (impl_decl == None or impl_decl == True)):
3807 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3808 (func.return_type, func.original_name,
3809 func.MakeTypedOriginalArgString("")))
3810 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3811 func.WriteDestinationInitalizationValidation(file)
3812 self.WriteClientGLCallLog(func, file)
3813 for arg in func.GetOriginalArgs():
3814 arg.WriteClientSideValidationCode(file, func)
3816 code = """ if (Is%(type)sReservedId(%(id)s)) {
3817 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3818 return;
3820 if (%(name)sHelper(%(arg_string)s)) {
3821 helper_->%(name)s(%(arg_string)s);
3823 CheckGLError();
3827 name_arg = None
3828 if len(func.GetOriginalArgs()) == 1:
3829 # Bind functions that have no target (like BindVertexArrayOES)
3830 name_arg = func.GetOriginalArgs()[0]
3831 else:
3832 # Bind functions that have both a target and a name (like BindTexture)
3833 name_arg = func.GetOriginalArgs()[1]
3835 file.Write(code % {
3836 'name': func.name,
3837 'arg_string': func.MakeOriginalArgString(""),
3838 'id': name_arg.name,
3839 'type': name_arg.resource_type,
3840 'lc_type': name_arg.resource_type.lower(),
3843 def WriteGLES2ImplementationUnitTest(self, func, file):
3844 """Overrriden from TypeHandler."""
3845 client_test = func.GetInfo('client_test')
3846 if client_test == False:
3847 return
3848 code = """
3849 TEST_F(GLES2ImplementationTest, %(name)s) {
3850 struct Cmds {
3851 cmds::%(name)s cmd;
3853 Cmds expected;
3854 expected.cmd.Init(%(cmd_args)s);
3856 gl_->%(name)s(%(args)s);
3857 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3858 ClearCommands();
3859 gl_->%(name)s(%(args)s);
3860 EXPECT_TRUE(NoCommandsWritten());
3863 cmd_arg_strings = []
3864 for count, arg in enumerate(func.GetCmdArgs()):
3865 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3866 count += 1
3867 gl_arg_strings = []
3868 for count, arg in enumerate(func.GetOriginalArgs()):
3869 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3870 file.Write(code % {
3871 'name': func.name,
3872 'args': ", ".join(gl_arg_strings),
3873 'cmd_args': ", ".join(cmd_arg_strings),
3877 class GENnHandler(TypeHandler):
3878 """Handler for glGen___ type functions."""
3880 def __init__(self):
3881 TypeHandler.__init__(self)
3883 def InitFunction(self, func):
3884 """Overrriden from TypeHandler."""
3885 pass
3887 def WriteGetDataSizeCode(self, func, file):
3888 """Overrriden from TypeHandler."""
3889 code = """ uint32 data_size;
3890 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3891 return error::kOutOfBounds;
3894 file.Write(code)
3896 def WriteHandlerImplementation (self, func, file):
3897 """Overrriden from TypeHandler."""
3898 file.Write(" if (!%sHelper(n, %s)) {\n"
3899 " return error::kInvalidArguments;\n"
3900 " }\n" %
3901 (func.name, func.GetLastOriginalArg().name))
3903 def WriteImmediateHandlerImplementation(self, func, file):
3904 """Overrriden from TypeHandler."""
3905 file.Write(" if (!%sHelper(n, %s)) {\n"
3906 " return error::kInvalidArguments;\n"
3907 " }\n" %
3908 (func.original_name, func.GetLastOriginalArg().name))
3910 def WriteGLES2Implementation(self, func, file):
3911 """Overrriden from TypeHandler."""
3912 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
3913 for (GLsizei i = 0; i < n; ++i) {
3914 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3916 });""" % func.GetOriginalArgs()[1].name)
3917 args = {
3918 'log_code': log_code,
3919 'return_type': func.return_type,
3920 'name': func.original_name,
3921 'typed_args': func.MakeTypedOriginalArgString(""),
3922 'args': func.MakeOriginalArgString(""),
3923 'resource_types': func.GetInfo('resource_types'),
3924 'count_name': func.GetOriginalArgs()[0].name,
3926 file.Write(
3927 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3928 args)
3929 func.WriteDestinationInitalizationValidation(file)
3930 self.WriteClientGLCallLog(func, file)
3931 for arg in func.GetOriginalArgs():
3932 arg.WriteClientSideValidationCode(file, func)
3933 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3934 GetIdHandler(id_namespaces::k%(resource_types)s)->
3935 MakeIds(this, 0, %(args)s);
3936 %(name)sHelper(%(args)s);
3937 helper_->%(name)sImmediate(%(args)s);
3938 if (share_group_->bind_generates_resource())
3939 helper_->CommandBufferHelper::Flush();
3940 %(log_code)s
3941 CheckGLError();
3945 file.Write(code % args)
3947 def WriteGLES2ImplementationUnitTest(self, func, file):
3948 """Overrriden from TypeHandler."""
3949 code = """
3950 TEST_F(GLES2ImplementationTest, %(name)s) {
3951 GLuint ids[2] = { 0, };
3952 struct Cmds {
3953 cmds::%(name)sImmediate gen;
3954 GLuint data[2];
3956 Cmds expected;
3957 expected.gen.Init(arraysize(ids), &ids[0]);
3958 expected.data[0] = k%(types)sStartId;
3959 expected.data[1] = k%(types)sStartId + 1;
3960 gl_->%(name)s(arraysize(ids), &ids[0]);
3961 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3962 EXPECT_EQ(k%(types)sStartId, ids[0]);
3963 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3966 file.Write(code % {
3967 'name': func.name,
3968 'types': func.GetInfo('resource_types'),
3971 def WriteServiceUnitTest(self, func, file):
3972 """Overrriden from TypeHandler."""
3973 valid_test = """
3974 TEST_F(%(test_name)s, %(name)sValidArgs) {
3975 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
3976 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3977 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
3978 SpecializedSetup<cmds::%(name)s, 0>(true);
3979 cmds::%(name)s cmd;
3980 cmd.Init(%(args)s);
3981 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3982 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3983 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
3986 self.WriteValidUnitTest(func, file, valid_test, {
3987 'resource_name': func.GetInfo('resource_type'),
3989 invalid_test = """
3990 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
3991 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
3992 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
3993 SpecializedSetup<cmds::%(name)s, 0>(false);
3994 cmds::%(name)s cmd;
3995 cmd.Init(%(args)s);
3996 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
3999 self.WriteValidUnitTest(func, file, invalid_test, {
4000 'resource_name': func.GetInfo('resource_type').lower(),
4003 def WriteImmediateServiceUnitTest(self, func, file):
4004 """Overrriden from TypeHandler."""
4005 valid_test = """
4006 TEST_F(%(test_name)s, %(name)sValidArgs) {
4007 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4008 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4009 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4010 GLuint temp = kNewClientId;
4011 SpecializedSetup<cmds::%(name)s, 0>(true);
4012 cmd->Init(1, &temp);
4013 EXPECT_EQ(error::kNoError,
4014 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4015 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4016 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4019 self.WriteValidUnitTest(func, file, valid_test, {
4020 'resource_name': func.GetInfo('resource_type'),
4022 invalid_test = """
4023 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4024 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4025 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4026 SpecializedSetup<cmds::%(name)s, 0>(false);
4027 cmd->Init(1, &client_%(resource_name)s_id_);
4028 EXPECT_EQ(error::kInvalidArguments,
4029 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4032 self.WriteValidUnitTest(func, file, invalid_test, {
4033 'resource_name': func.GetInfo('resource_type').lower(),
4036 def WriteImmediateCmdComputeSize(self, func, file):
4037 """Overrriden from TypeHandler."""
4038 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4039 file.Write(
4040 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4041 file.Write(" }\n")
4042 file.Write("\n")
4043 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4044 file.Write(" return static_cast<uint32>(\n")
4045 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4046 file.Write(" }\n")
4047 file.Write("\n")
4049 def WriteImmediateCmdSetHeader(self, func, file):
4050 """Overrriden from TypeHandler."""
4051 file.Write(" void SetHeader(GLsizei n) {\n")
4052 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4053 file.Write(" }\n")
4054 file.Write("\n")
4056 def WriteImmediateCmdInit(self, func, file):
4057 """Overrriden from TypeHandler."""
4058 last_arg = func.GetLastOriginalArg()
4059 file.Write(" void Init(%s, %s _%s) {\n" %
4060 (func.MakeTypedCmdArgString("_"),
4061 last_arg.type, last_arg.name))
4062 file.Write(" SetHeader(_n);\n")
4063 args = func.GetCmdArgs()
4064 for arg in args:
4065 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4066 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4067 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4068 file.Write(" }\n")
4069 file.Write("\n")
4071 def WriteImmediateCmdSet(self, func, file):
4072 """Overrriden from TypeHandler."""
4073 last_arg = func.GetLastOriginalArg()
4074 copy_args = func.MakeCmdArgString("_", False)
4075 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4076 (func.MakeTypedCmdArgString("_", True),
4077 last_arg.type, last_arg.name))
4078 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4079 (copy_args, last_arg.name))
4080 file.Write(" const uint32 size = ComputeSize(_n);\n")
4081 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4082 "cmd, size);\n")
4083 file.Write(" }\n")
4084 file.Write("\n")
4086 def WriteImmediateCmdHelper(self, func, file):
4087 """Overrriden from TypeHandler."""
4088 code = """ void %(name)s(%(typed_args)s) {
4089 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4090 gles2::cmds::%(name)s* c =
4091 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4092 if (c) {
4093 c->Init(%(args)s);
4098 file.Write(code % {
4099 "name": func.name,
4100 "typed_args": func.MakeTypedOriginalArgString(""),
4101 "args": func.MakeOriginalArgString(""),
4104 def WriteImmediateFormatTest(self, func, file):
4105 """Overrriden from TypeHandler."""
4106 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4107 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4108 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4109 (func.name, func.name))
4110 file.Write(" void* next_cmd = cmd.Set(\n")
4111 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4112 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4113 func.name)
4114 file.Write(" cmd.header.command);\n")
4115 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4116 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4117 file.Write(" cmd.header.size * 4u);\n")
4118 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4119 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4120 file.Write(" next_cmd, sizeof(cmd) +\n")
4121 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4122 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4123 file.Write("}\n")
4124 file.Write("\n")
4127 class CreateHandler(TypeHandler):
4128 """Handler for glCreate___ type functions."""
4130 def __init__(self):
4131 TypeHandler.__init__(self)
4133 def InitFunction(self, func):
4134 """Overrriden from TypeHandler."""
4135 func.AddCmdArg(Argument("client_id", 'uint32'))
4137 def WriteServiceUnitTest(self, func, file):
4138 """Overrriden from TypeHandler."""
4139 valid_test = """
4140 TEST_F(%(test_name)s, %(name)sValidArgs) {
4141 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4142 .WillOnce(Return(kNewServiceId));
4143 SpecializedSetup<cmds::%(name)s, 0>(true);
4144 cmds::%(name)s cmd;
4145 cmd.Init(%(args)s%(comma)skNewClientId);
4146 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4147 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4148 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4151 comma = ""
4152 if len(func.GetOriginalArgs()):
4153 comma =", "
4154 self.WriteValidUnitTest(func, file, valid_test, {
4155 'comma': comma,
4156 'resource_type': func.name[6:],
4158 invalid_test = """
4159 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4160 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4161 SpecializedSetup<cmds::%(name)s, 0>(false);
4162 cmds::%(name)s cmd;
4163 cmd.Init(%(args)s%(comma)skNewClientId);
4164 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4167 self.WriteInvalidUnitTest(func, file, invalid_test, {
4168 'comma': comma,
4171 def WriteHandlerImplementation (self, func, file):
4172 """Overrriden from TypeHandler."""
4173 file.Write(" uint32 client_id = c.client_id;\n")
4174 file.Write(" if (!%sHelper(%s)) {\n" %
4175 (func.name, func.MakeCmdArgString("")))
4176 file.Write(" return error::kInvalidArguments;\n")
4177 file.Write(" }\n")
4179 def WriteGLES2Implementation(self, func, file):
4180 """Overrriden from TypeHandler."""
4181 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4182 (func.return_type, func.original_name,
4183 func.MakeTypedOriginalArgString("")))
4184 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4185 func.WriteDestinationInitalizationValidation(file)
4186 self.WriteClientGLCallLog(func, file)
4187 for arg in func.GetOriginalArgs():
4188 arg.WriteClientSideValidationCode(file, func)
4189 file.Write(" GLuint client_id;\n")
4190 file.Write(
4191 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4192 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4193 file.Write(" helper_->%s(%s);\n" %
4194 (func.name, func.MakeCmdArgString("")))
4195 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4196 file.Write(" CheckGLError();\n")
4197 file.Write(" return client_id;\n")
4198 file.Write("}\n")
4199 file.Write("\n")
4202 class DeleteHandler(TypeHandler):
4203 """Handler for glDelete___ single resource type functions."""
4205 def __init__(self):
4206 TypeHandler.__init__(self)
4208 def WriteServiceImplementation(self, func, file):
4209 """Overrriden from TypeHandler."""
4210 pass
4212 def WriteGLES2Implementation(self, func, file):
4213 """Overrriden from TypeHandler."""
4214 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4215 (func.return_type, func.original_name,
4216 func.MakeTypedOriginalArgString("")))
4217 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4218 func.WriteDestinationInitalizationValidation(file)
4219 self.WriteClientGLCallLog(func, file)
4220 for arg in func.GetOriginalArgs():
4221 arg.WriteClientSideValidationCode(file, func)
4222 file.Write(
4223 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
4224 file.Write(" %sHelper(%s);\n" %
4225 (func.original_name, func.GetOriginalArgs()[-1].name))
4226 file.Write(" CheckGLError();\n")
4227 file.Write("}\n")
4228 file.Write("\n")
4231 class DELnHandler(TypeHandler):
4232 """Handler for glDelete___ type functions."""
4234 def __init__(self):
4235 TypeHandler.__init__(self)
4237 def WriteGetDataSizeCode(self, func, file):
4238 """Overrriden from TypeHandler."""
4239 code = """ uint32 data_size;
4240 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4241 return error::kOutOfBounds;
4244 file.Write(code)
4246 def WriteGLES2ImplementationUnitTest(self, func, file):
4247 """Overrriden from TypeHandler."""
4248 code = """
4249 TEST_F(GLES2ImplementationTest, %(name)s) {
4250 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4251 struct Cmds {
4252 cmds::%(name)sImmediate del;
4253 GLuint data[2];
4255 Cmds expected;
4256 expected.del.Init(arraysize(ids), &ids[0]);
4257 expected.data[0] = k%(types)sStartId;
4258 expected.data[1] = k%(types)sStartId + 1;
4259 gl_->%(name)s(arraysize(ids), &ids[0]);
4260 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4263 file.Write(code % {
4264 'name': func.name,
4265 'types': func.GetInfo('resource_types'),
4268 def WriteServiceUnitTest(self, func, file):
4269 """Overrriden from TypeHandler."""
4270 valid_test = """
4271 TEST_F(%(test_name)s, %(name)sValidArgs) {
4272 EXPECT_CALL(
4273 *gl_,
4274 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4275 .Times(1);
4276 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4277 SpecializedSetup<cmds::%(name)s, 0>(true);
4278 cmds::%(name)s cmd;
4279 cmd.Init(%(args)s);
4280 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4281 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4282 EXPECT_TRUE(
4283 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4286 self.WriteValidUnitTest(func, file, valid_test, {
4287 'resource_name': func.GetInfo('resource_type').lower(),
4288 'upper_resource_name': func.GetInfo('resource_type'),
4290 invalid_test = """
4291 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4292 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4293 SpecializedSetup<cmds::%(name)s, 0>(false);
4294 cmds::%(name)s cmd;
4295 cmd.Init(%(args)s);
4296 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4299 self.WriteValidUnitTest(func, file, invalid_test)
4301 def WriteImmediateServiceUnitTest(self, func, file):
4302 """Overrriden from TypeHandler."""
4303 valid_test = """
4304 TEST_F(%(test_name)s, %(name)sValidArgs) {
4305 EXPECT_CALL(
4306 *gl_,
4307 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4308 .Times(1);
4309 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4310 SpecializedSetup<cmds::%(name)s, 0>(true);
4311 cmd.Init(1, &client_%(resource_name)s_id_);
4312 EXPECT_EQ(error::kNoError,
4313 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4314 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4315 EXPECT_TRUE(
4316 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4319 self.WriteValidUnitTest(func, file, valid_test, {
4320 'resource_name': func.GetInfo('resource_type').lower(),
4321 'upper_resource_name': func.GetInfo('resource_type'),
4323 invalid_test = """
4324 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4325 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4326 SpecializedSetup<cmds::%(name)s, 0>(false);
4327 GLuint temp = kInvalidClientId;
4328 cmd.Init(1, &temp);
4329 EXPECT_EQ(error::kNoError,
4330 ExecuteImmediateCmd(cmd, sizeof(temp)));
4333 self.WriteValidUnitTest(func, file, invalid_test)
4335 def WriteHandlerImplementation (self, func, file):
4336 """Overrriden from TypeHandler."""
4337 file.Write(" %sHelper(n, %s);\n" %
4338 (func.name, func.GetLastOriginalArg().name))
4340 def WriteImmediateHandlerImplementation (self, func, file):
4341 """Overrriden from TypeHandler."""
4342 file.Write(" %sHelper(n, %s);\n" %
4343 (func.original_name, func.GetLastOriginalArg().name))
4345 def WriteGLES2Implementation(self, func, file):
4346 """Overrriden from TypeHandler."""
4347 impl_decl = func.GetInfo('impl_decl')
4348 if impl_decl == None or impl_decl == True:
4349 args = {
4350 'return_type': func.return_type,
4351 'name': func.original_name,
4352 'typed_args': func.MakeTypedOriginalArgString(""),
4353 'args': func.MakeOriginalArgString(""),
4354 'resource_type': func.GetInfo('resource_type').lower(),
4355 'count_name': func.GetOriginalArgs()[0].name,
4357 file.Write(
4358 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4359 args)
4360 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4361 func.WriteDestinationInitalizationValidation(file)
4362 self.WriteClientGLCallLog(func, file)
4363 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4364 for (GLsizei i = 0; i < n; ++i) {
4365 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4368 """ % func.GetOriginalArgs()[1].name)
4369 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4370 for (GLsizei i = 0; i < n; ++i) {
4371 DCHECK(%s[i] != 0);
4374 """ % func.GetOriginalArgs()[1].name)
4375 for arg in func.GetOriginalArgs():
4376 arg.WriteClientSideValidationCode(file, func)
4377 code = """ %(name)sHelper(%(args)s);
4378 CheckGLError();
4382 file.Write(code % args)
4384 def WriteImmediateCmdComputeSize(self, func, file):
4385 """Overrriden from TypeHandler."""
4386 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4387 file.Write(
4388 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4389 file.Write(" }\n")
4390 file.Write("\n")
4391 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4392 file.Write(" return static_cast<uint32>(\n")
4393 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4394 file.Write(" }\n")
4395 file.Write("\n")
4397 def WriteImmediateCmdSetHeader(self, func, file):
4398 """Overrriden from TypeHandler."""
4399 file.Write(" void SetHeader(GLsizei n) {\n")
4400 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4401 file.Write(" }\n")
4402 file.Write("\n")
4404 def WriteImmediateCmdInit(self, func, file):
4405 """Overrriden from TypeHandler."""
4406 last_arg = func.GetLastOriginalArg()
4407 file.Write(" void Init(%s, %s _%s) {\n" %
4408 (func.MakeTypedCmdArgString("_"),
4409 last_arg.type, last_arg.name))
4410 file.Write(" SetHeader(_n);\n")
4411 args = func.GetCmdArgs()
4412 for arg in args:
4413 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4414 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4415 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4416 file.Write(" }\n")
4417 file.Write("\n")
4419 def WriteImmediateCmdSet(self, func, file):
4420 """Overrriden from TypeHandler."""
4421 last_arg = func.GetLastOriginalArg()
4422 copy_args = func.MakeCmdArgString("_", False)
4423 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4424 (func.MakeTypedCmdArgString("_", True),
4425 last_arg.type, last_arg.name))
4426 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4427 (copy_args, last_arg.name))
4428 file.Write(" const uint32 size = ComputeSize(_n);\n")
4429 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4430 "cmd, size);\n")
4431 file.Write(" }\n")
4432 file.Write("\n")
4434 def WriteImmediateCmdHelper(self, func, file):
4435 """Overrriden from TypeHandler."""
4436 code = """ void %(name)s(%(typed_args)s) {
4437 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4438 gles2::cmds::%(name)s* c =
4439 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4440 if (c) {
4441 c->Init(%(args)s);
4446 file.Write(code % {
4447 "name": func.name,
4448 "typed_args": func.MakeTypedOriginalArgString(""),
4449 "args": func.MakeOriginalArgString(""),
4452 def WriteImmediateFormatTest(self, func, file):
4453 """Overrriden from TypeHandler."""
4454 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4455 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4456 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4457 (func.name, func.name))
4458 file.Write(" void* next_cmd = cmd.Set(\n")
4459 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4460 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4461 func.name)
4462 file.Write(" cmd.header.command);\n")
4463 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4464 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4465 file.Write(" cmd.header.size * 4u);\n")
4466 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4467 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4468 file.Write(" next_cmd, sizeof(cmd) +\n")
4469 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4470 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4471 file.Write("}\n")
4472 file.Write("\n")
4475 class GETnHandler(TypeHandler):
4476 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4478 def __init__(self):
4479 TypeHandler.__init__(self)
4481 def AddImmediateFunction(self, generator, func):
4482 """Overrriden from TypeHandler."""
4483 pass
4485 def WriteServiceImplementation(self, func, file):
4486 """Overrriden from TypeHandler."""
4487 file.Write(
4488 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
4489 file.Write(
4490 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4491 func.name)
4492 last_arg = func.GetLastOriginalArg()
4494 all_but_last_args = func.GetOriginalArgs()[:-1]
4495 for arg in all_but_last_args:
4496 arg.WriteGetCode(file)
4498 code = """ typedef cmds::%(func_name)s::Result Result;
4499 GLsizei num_values = 0;
4500 GetNumValuesReturnedForGLGet(pname, &num_values);
4501 Result* result = GetSharedMemoryAs<Result*>(
4502 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4503 %(last_arg_type)s params = result ? result->GetData() : NULL;
4505 file.Write(code % {
4506 'last_arg_type': last_arg.type,
4507 'func_name': func.name,
4509 func.WriteHandlerValidation(file)
4510 code = """ // Check that the client initialized the result.
4511 if (result->size != 0) {
4512 return error::kInvalidArguments;
4515 shadowed = func.GetInfo('shadowed')
4516 if not shadowed:
4517 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
4518 file.Write(code)
4519 func.WriteHandlerImplementation(file)
4520 if shadowed:
4521 code = """ result->SetNumResults(num_values);
4522 return error::kNoError;
4525 else:
4526 code = """ GLenum error = glGetError();
4527 if (error == GL_NO_ERROR) {
4528 result->SetNumResults(num_values);
4529 } else {
4530 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4532 return error::kNoError;
4536 file.Write(code % {'func_name': func.name})
4538 def WriteGLES2Implementation(self, func, file):
4539 """Overrriden from TypeHandler."""
4540 impl_decl = func.GetInfo('impl_decl')
4541 if impl_decl == None or impl_decl == True:
4542 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4543 (func.return_type, func.original_name,
4544 func.MakeTypedOriginalArgString("")))
4545 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4546 func.WriteDestinationInitalizationValidation(file)
4547 self.WriteClientGLCallLog(func, file)
4548 for arg in func.GetOriginalArgs():
4549 arg.WriteClientSideValidationCode(file, func)
4550 all_but_last_args = func.GetOriginalArgs()[:-1]
4551 arg_string = (
4552 ", ".join(["%s" % arg.name for arg in all_but_last_args]))
4553 all_arg_string = (
4554 ", ".join(["%s" % arg.name for arg in func.GetOriginalArgs()]))
4555 self.WriteTraceEvent(func, file)
4556 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4557 return;
4559 typedef cmds::%(func_name)s::Result Result;
4560 Result* result = GetResultAs<Result*>();
4561 if (!result) {
4562 return;
4564 result->SetNumResults(0);
4565 helper_->%(func_name)s(%(arg_string)s,
4566 GetResultShmId(), GetResultShmOffset());
4567 WaitForCmd();
4568 result->CopyResult(params);
4569 GPU_CLIENT_LOG_CODE_BLOCK({
4570 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4571 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4574 CheckGLError();
4577 file.Write(code % {
4578 'func_name': func.name,
4579 'arg_string': arg_string,
4580 'all_arg_string': all_arg_string,
4583 def WriteGLES2ImplementationUnitTest(self, func, file):
4584 """Writes the GLES2 Implemention unit test."""
4585 code = """
4586 TEST_F(GLES2ImplementationTest, %(name)s) {
4587 struct Cmds {
4588 cmds::%(name)s cmd;
4590 typedef cmds::%(name)s::Result Result;
4591 Result::Type result = 0;
4592 Cmds expected;
4593 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4594 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4595 EXPECT_CALL(*command_buffer(), OnFlush())
4596 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4597 .RetiresOnSaturation();
4598 gl_->%(name)s(%(args)s, &result);
4599 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4600 EXPECT_EQ(static_cast<Result::Type>(1), result);
4603 cmd_arg_strings = []
4604 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4605 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4606 cmd_arg_strings[0] = '123'
4607 gl_arg_strings = []
4608 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4609 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4610 gl_arg_strings[0] = '123'
4611 file.Write(code % {
4612 'name': func.name,
4613 'args': ", ".join(gl_arg_strings),
4614 'cmd_args': ", ".join(cmd_arg_strings),
4617 def WriteServiceUnitTest(self, func, file):
4618 """Overrriden from TypeHandler."""
4619 valid_test = """
4620 TEST_F(%(test_name)s, %(name)sValidArgs) {
4621 EXPECT_CALL(*gl_, GetError())
4622 .WillOnce(Return(GL_NO_ERROR))
4623 .WillOnce(Return(GL_NO_ERROR))
4624 .RetiresOnSaturation();
4625 SpecializedSetup<cmds::%(name)s, 0>(true);
4626 typedef cmds::%(name)s::Result Result;
4627 Result* result = static_cast<Result*>(shared_memory_address_);
4628 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4629 result->size = 0;
4630 cmds::%(name)s cmd;
4631 cmd.Init(%(args)s);
4632 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4633 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4634 %(valid_pname)s),
4635 result->GetNumResults());
4636 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4639 gl_arg_strings = []
4640 valid_pname = ''
4641 for count, arg in enumerate(func.GetOriginalArgs()[:-1]):
4642 arg_value = arg.GetValidGLArg(func, count, 0)
4643 gl_arg_strings.append(arg_value)
4644 if arg.name == 'pname':
4645 valid_pname = arg_value
4646 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
4647 gl_arg_strings.append("_")
4648 else:
4649 gl_arg_strings.append("result->GetData()")
4651 self.WriteValidUnitTest(func, file, valid_test, {
4652 'local_gl_args': ", ".join(gl_arg_strings),
4653 'valid_pname': valid_pname,
4656 invalid_test = """
4657 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4658 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4659 SpecializedSetup<cmds::%(name)s, 0>(false);
4660 cmds::%(name)s::Result* result =
4661 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4662 result->size = 0;
4663 cmds::%(name)s cmd;
4664 cmd.Init(%(args)s);
4665 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4666 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4669 self.WriteInvalidUnitTest(func, file, invalid_test)
4672 class PUTHandler(TypeHandler):
4673 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4675 def __init__(self):
4676 TypeHandler.__init__(self)
4678 def WriteServiceUnitTest(self, func, file):
4679 """Writes the service unit test for a command."""
4680 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4681 if func.GetInfo("first_element_only"):
4682 gl_arg_strings = []
4683 for count, arg in enumerate(func.GetOriginalArgs()):
4684 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4685 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
4686 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4687 ", ".join(gl_arg_strings))
4688 valid_test = """
4689 TEST_F(%(test_name)s, %(name)sValidArgs) {
4690 SpecializedSetup<cmds::%(name)s, 0>(true);
4691 cmds::%(name)s cmd;
4692 cmd.Init(%(args)s);
4693 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4694 %(expected_call)s
4695 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4696 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4699 extra = {
4700 'data_type': func.GetInfo('data_type'),
4701 'data_value': func.GetInfo('data_value') or '0',
4702 'expected_call': expected_call,
4704 self.WriteValidUnitTest(func, file, valid_test, extra)
4706 invalid_test = """
4707 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4708 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4709 SpecializedSetup<cmds::%(name)s, 0>(false);
4710 cmds::%(name)s cmd;
4711 cmd.Init(%(args)s);
4712 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4713 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4716 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4718 def WriteImmediateServiceUnitTest(self, func, file):
4719 """Writes the service unit test for a command."""
4720 valid_test = """
4721 TEST_F(%(test_name)s, %(name)sValidArgs) {
4722 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4723 SpecializedSetup<cmds::%(name)s, 0>(true);
4724 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4725 cmd.Init(%(gl_args)s, &temp[0]);
4726 EXPECT_CALL(
4727 *gl_,
4728 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4729 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4730 EXPECT_EQ(error::kNoError,
4731 ExecuteImmediateCmd(cmd, sizeof(temp)));
4732 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4735 gl_arg_strings = []
4736 gl_any_strings = []
4737 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4738 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4739 gl_any_strings.append("_")
4740 extra = {
4741 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
4742 'data_type': func.GetInfo('data_type'),
4743 'data_count': func.GetInfo('count'),
4744 'data_value': func.GetInfo('data_value') or '0',
4745 'gl_args': ", ".join(gl_arg_strings),
4746 'gl_any_args': ", ".join(gl_any_strings),
4748 self.WriteValidUnitTest(func, file, valid_test, extra)
4750 invalid_test = """
4751 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4752 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4753 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4754 SpecializedSetup<cmds::%(name)s, 0>(false);
4755 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4756 cmd.Init(%(all_but_last_args)s, &temp[0]);
4757 EXPECT_EQ(error::%(parse_result)s,
4758 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4761 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4763 def WriteGetDataSizeCode(self, func, file):
4764 """Overrriden from TypeHandler."""
4765 code = """ uint32 data_size;
4766 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4767 return error::kOutOfBounds;
4770 file.Write(code % (func.info.data_type, func.info.count))
4771 if func.is_immediate:
4772 file.Write(" if (data_size > immediate_data_size) {\n")
4773 file.Write(" return error::kOutOfBounds;\n")
4774 file.Write(" }\n")
4776 def WriteGLES2Implementation(self, func, file):
4777 """Overrriden from TypeHandler."""
4778 impl_func = func.GetInfo('impl_func')
4779 if (impl_func != None and impl_func != True):
4780 return;
4781 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4782 (func.return_type, func.original_name,
4783 func.MakeTypedOriginalArgString("")))
4784 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4785 func.WriteDestinationInitalizationValidation(file)
4786 self.WriteClientGLCallLog(func, file)
4787 last_arg_name = func.GetLastOriginalArg().name
4788 values_str = ' << ", " << '.join(
4789 ["%s[%d]" % (last_arg_name, ndx) for ndx in range(0, func.info.count)])
4790 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str)
4791 for arg in func.GetOriginalArgs():
4792 arg.WriteClientSideValidationCode(file, func)
4793 file.Write(" helper_->%sImmediate(%s);\n" %
4794 (func.name, func.MakeOriginalArgString("")))
4795 file.Write(" CheckGLError();\n")
4796 file.Write("}\n")
4797 file.Write("\n")
4799 def WriteGLES2ImplementationUnitTest(self, func, file):
4800 """Writes the GLES2 Implemention unit test."""
4801 client_test = func.GetInfo('client_test')
4802 if (client_test != None and client_test != True):
4803 return;
4804 code = """
4805 TEST_F(GLES2ImplementationTest, %(name)s) {
4806 %(type)s data[%(count)d] = {0};
4807 struct Cmds {
4808 cmds::%(name)sImmediate cmd;
4809 %(type)s data[%(count)d];
4812 for (int jj = 0; jj < %(count)d; ++jj) {
4813 data[jj] = static_cast<%(type)s>(jj);
4815 Cmds expected;
4816 expected.cmd.Init(%(cmd_args)s, &data[0]);
4817 gl_->%(name)s(%(args)s, &data[0]);
4818 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4821 cmd_arg_strings = []
4822 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4823 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4824 gl_arg_strings = []
4825 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4826 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4827 file.Write(code % {
4828 'name': func.name,
4829 'type': func.GetInfo('data_type'),
4830 'count': func.GetInfo('count'),
4831 'args': ", ".join(gl_arg_strings),
4832 'cmd_args': ", ".join(cmd_arg_strings),
4835 def WriteImmediateCmdComputeSize(self, func, file):
4836 """Overrriden from TypeHandler."""
4837 file.Write(" static uint32 ComputeDataSize() {\n")
4838 file.Write(" return static_cast<uint32>(\n")
4839 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4840 (func.info.data_type, func.info.count))
4841 file.Write(" }\n")
4842 file.Write("\n")
4843 file.Write(" static uint32 ComputeSize() {\n")
4844 file.Write(" return static_cast<uint32>(\n")
4845 file.Write(
4846 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4847 file.Write(" }\n")
4848 file.Write("\n")
4850 def WriteImmediateCmdSetHeader(self, func, file):
4851 """Overrriden from TypeHandler."""
4852 file.Write(" void SetHeader() {\n")
4853 file.Write(
4854 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4855 file.Write(" }\n")
4856 file.Write("\n")
4858 def WriteImmediateCmdInit(self, func, file):
4859 """Overrriden from TypeHandler."""
4860 last_arg = func.GetLastOriginalArg()
4861 file.Write(" void Init(%s, %s _%s) {\n" %
4862 (func.MakeTypedCmdArgString("_"),
4863 last_arg.type, last_arg.name))
4864 file.Write(" SetHeader();\n")
4865 args = func.GetCmdArgs()
4866 for arg in args:
4867 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4868 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4869 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
4870 file.Write(" }\n")
4871 file.Write("\n")
4873 def WriteImmediateCmdSet(self, func, file):
4874 """Overrriden from TypeHandler."""
4875 last_arg = func.GetLastOriginalArg()
4876 copy_args = func.MakeCmdArgString("_", False)
4877 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4878 (func.MakeTypedCmdArgString("_", True),
4879 last_arg.type, last_arg.name))
4880 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4881 (copy_args, last_arg.name))
4882 file.Write(" const uint32 size = ComputeSize();\n")
4883 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4884 "cmd, size);\n")
4885 file.Write(" }\n")
4886 file.Write("\n")
4888 def WriteImmediateCmdHelper(self, func, file):
4889 """Overrriden from TypeHandler."""
4890 code = """ void %(name)s(%(typed_args)s) {
4891 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4892 gles2::cmds::%(name)s* c =
4893 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4894 if (c) {
4895 c->Init(%(args)s);
4900 file.Write(code % {
4901 "name": func.name,
4902 "typed_args": func.MakeTypedOriginalArgString(""),
4903 "args": func.MakeOriginalArgString(""),
4906 def WriteImmediateFormatTest(self, func, file):
4907 """Overrriden from TypeHandler."""
4908 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4909 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4910 file.Write(" static %s data[] = {\n" % func.info.data_type)
4911 for v in range(0, func.info.count):
4912 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4913 (func.info.data_type, v))
4914 file.Write(" };\n")
4915 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4916 (func.name, func.name))
4917 file.Write(" void* next_cmd = cmd.Set(\n")
4918 file.Write(" &cmd")
4919 args = func.GetCmdArgs()
4920 for value, arg in enumerate(args):
4921 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4922 file.Write(",\n data);\n")
4923 args = func.GetCmdArgs()
4924 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4925 % func.name)
4926 file.Write(" cmd.header.command);\n")
4927 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4928 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4929 file.Write(" cmd.header.size * 4u);\n")
4930 for value, arg in enumerate(args):
4931 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4932 (arg.type, value + 11, arg.name))
4933 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4934 file.Write(" next_cmd, sizeof(cmd) +\n")
4935 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4936 file.Write(" // TODO(gman): Check that data was inserted;\n")
4937 file.Write("}\n")
4938 file.Write("\n")
4941 class PUTnHandler(TypeHandler):
4942 """Handler for PUTn 'glUniform__v' type functions."""
4944 def __init__(self):
4945 TypeHandler.__init__(self)
4947 def WriteServiceUnitTest(self, func, file):
4948 """Overridden from TypeHandler."""
4949 TypeHandler.WriteServiceUnitTest(self, func, file)
4951 valid_test = """
4952 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4953 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4954 SpecializedSetup<cmds::%(name)s, 0>(true);
4955 cmds::%(name)s cmd;
4956 cmd.Init(%(args)s);
4957 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4958 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4961 gl_arg_strings = []
4962 arg_strings = []
4963 for count, arg in enumerate(func.GetOriginalArgs()):
4964 # hardcoded to match unit tests.
4965 if count == 0:
4966 # the location of the second element of the 2nd uniform.
4967 # defined in GLES2DecoderBase::SetupShaderForUniform
4968 gl_arg_strings.append("3")
4969 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
4970 elif count == 1:
4971 # the number of elements that gl will be called with.
4972 gl_arg_strings.append("3")
4973 # the number of elements requested in the command.
4974 arg_strings.append("5")
4975 else:
4976 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4977 arg_strings.append(arg.GetValidArg(func, count, 0))
4978 extra = {
4979 'gl_args': ", ".join(gl_arg_strings),
4980 'args': ", ".join(arg_strings),
4982 self.WriteValidUnitTest(func, file, valid_test, extra)
4984 def WriteImmediateServiceUnitTest(self, func, file):
4985 """Overridden from TypeHandler."""
4986 valid_test = """
4987 TEST_F(%(test_name)s, %(name)sValidArgs) {
4988 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4989 EXPECT_CALL(
4990 *gl_,
4991 %(gl_func_name)s(%(gl_args)s,
4992 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
4993 SpecializedSetup<cmds::%(name)s, 0>(true);
4994 %(data_type)s temp[%(data_count)s * 2] = { 0, };
4995 cmd.Init(%(args)s, &temp[0]);
4996 EXPECT_EQ(error::kNoError,
4997 ExecuteImmediateCmd(cmd, sizeof(temp)));
4998 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5001 gl_arg_strings = []
5002 gl_any_strings = []
5003 arg_strings = []
5004 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5005 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
5006 gl_any_strings.append("_")
5007 arg_strings.append(arg.GetValidArg(func, count, 0))
5008 extra = {
5009 'data_type': func.GetInfo('data_type'),
5010 'data_count': func.GetInfo('count'),
5011 'args': ", ".join(arg_strings),
5012 'gl_args': ", ".join(gl_arg_strings),
5013 'gl_any_args': ", ".join(gl_any_strings),
5015 self.WriteValidUnitTest(func, file, valid_test, extra)
5017 invalid_test = """
5018 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5019 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5020 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5021 SpecializedSetup<cmds::%(name)s, 0>(false);
5022 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5023 cmd.Init(%(all_but_last_args)s, &temp[0]);
5024 EXPECT_EQ(error::%(parse_result)s,
5025 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5028 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
5030 def WriteGetDataSizeCode(self, func, file):
5031 """Overrriden from TypeHandler."""
5032 code = """ uint32 data_size;
5033 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5034 return error::kOutOfBounds;
5037 file.Write(code % (func.info.data_type, func.info.count))
5038 if func.is_immediate:
5039 file.Write(" if (data_size > immediate_data_size) {\n")
5040 file.Write(" return error::kOutOfBounds;\n")
5041 file.Write(" }\n")
5043 def WriteGLES2Implementation(self, func, file):
5044 """Overrriden from TypeHandler."""
5045 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5046 (func.return_type, func.original_name,
5047 func.MakeTypedOriginalArgString("")))
5048 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5049 func.WriteDestinationInitalizationValidation(file)
5050 self.WriteClientGLCallLog(func, file)
5051 last_arg_name = func.GetLastOriginalArg().name
5052 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5053 for (GLsizei i = 0; i < count; ++i) {
5054 """)
5055 values_str = ' << ", " << '.join(
5056 ["%s[%d + i * %d]" % (
5057 last_arg_name, ndx, func.info.count) for ndx in range(
5058 0, func.info.count)])
5059 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
5060 file.Write(" }\n });\n")
5061 for arg in func.GetOriginalArgs():
5062 arg.WriteClientSideValidationCode(file, func)
5063 file.Write(" helper_->%sImmediate(%s);\n" %
5064 (func.name, func.MakeOriginalArgString("")))
5065 file.Write(" CheckGLError();\n")
5066 file.Write("}\n")
5067 file.Write("\n")
5069 def WriteGLES2ImplementationUnitTest(self, func, file):
5070 """Writes the GLES2 Implemention unit test."""
5071 code = """
5072 TEST_F(GLES2ImplementationTest, %(name)s) {
5073 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5074 struct Cmds {
5075 cmds::%(name)sImmediate cmd;
5076 %(type)s data[%(count_param)d][%(count)d];
5079 Cmds expected;
5080 for (int ii = 0; ii < %(count_param)d; ++ii) {
5081 for (int jj = 0; jj < %(count)d; ++jj) {
5082 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5085 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5086 gl_->%(name)s(%(args)s, &data[0][0]);
5087 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5090 cmd_arg_strings = []
5091 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
5092 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
5093 gl_arg_strings = []
5094 count_param = 0
5095 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5096 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
5097 if arg.name == "count":
5098 count_param = int(arg.GetValidClientSideArg(func, count, 0))
5099 file.Write(code % {
5100 'name': func.name,
5101 'type': func.GetInfo('data_type'),
5102 'count': func.GetInfo('count'),
5103 'args': ", ".join(gl_arg_strings),
5104 'cmd_args': ", ".join(cmd_arg_strings),
5105 'count_param': count_param,
5108 def WriteImmediateCmdComputeSize(self, func, file):
5109 """Overrriden from TypeHandler."""
5110 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5111 file.Write(" return static_cast<uint32>(\n")
5112 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5113 (func.info.data_type, func.info.count))
5114 file.Write(" }\n")
5115 file.Write("\n")
5116 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5117 file.Write(" return static_cast<uint32>(\n")
5118 file.Write(
5119 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5120 file.Write(" }\n")
5121 file.Write("\n")
5123 def WriteImmediateCmdSetHeader(self, func, file):
5124 """Overrriden from TypeHandler."""
5125 file.Write(" void SetHeader(GLsizei count) {\n")
5126 file.Write(
5127 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5128 file.Write(" }\n")
5129 file.Write("\n")
5131 def WriteImmediateCmdInit(self, func, file):
5132 """Overrriden from TypeHandler."""
5133 last_arg = func.GetLastOriginalArg()
5134 file.Write(" void Init(%s, %s _%s) {\n" %
5135 (func.MakeTypedCmdArgString("_"),
5136 last_arg.type, last_arg.name))
5137 file.Write(" SetHeader(_count);\n")
5138 args = func.GetCmdArgs()
5139 for arg in args:
5140 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5141 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5142 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg.name)
5143 file.Write(" }\n")
5144 file.Write("\n")
5146 def WriteImmediateCmdSet(self, func, file):
5147 """Overrriden from TypeHandler."""
5148 last_arg = func.GetLastOriginalArg()
5149 copy_args = func.MakeCmdArgString("_", False)
5150 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5151 (func.MakeTypedCmdArgString("_", True),
5152 last_arg.type, last_arg.name))
5153 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5154 (copy_args, last_arg.name))
5155 file.Write(" const uint32 size = ComputeSize(_count);\n")
5156 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5157 "cmd, size);\n")
5158 file.Write(" }\n")
5159 file.Write("\n")
5161 def WriteImmediateCmdHelper(self, func, file):
5162 """Overrriden from TypeHandler."""
5163 code = """ void %(name)s(%(typed_args)s) {
5164 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5165 gles2::cmds::%(name)s* c =
5166 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5167 if (c) {
5168 c->Init(%(args)s);
5173 file.Write(code % {
5174 "name": func.name,
5175 "typed_args": func.MakeTypedOriginalArgString(""),
5176 "args": func.MakeOriginalArgString(""),
5179 def WriteImmediateFormatTest(self, func, file):
5180 """Overrriden from TypeHandler."""
5181 args = func.GetCmdArgs()
5182 count_param = 0
5183 for value, arg in enumerate(args):
5184 if arg.name == "count":
5185 count_param = int(arg.GetValidClientSideArg(func, value, 0))
5186 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5187 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5188 file.Write(" static %s data[] = {\n" % func.info.data_type)
5189 for v in range(0, func.info.count * count_param):
5190 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5191 (func.info.data_type, v))
5192 file.Write(" };\n")
5193 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5194 (func.name, func.name))
5195 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
5196 file.Write(" const size_t kExpectedCmdSize =\n")
5197 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5198 (func.info.data_type, func.info.count))
5199 file.Write(" void* next_cmd = cmd.Set(\n")
5200 file.Write(" &cmd")
5201 for value, arg in enumerate(args):
5202 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
5203 file.Write(",\n data);\n")
5204 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5205 func.name)
5206 file.Write(" cmd.header.command);\n")
5207 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5208 for value, arg in enumerate(args):
5209 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5210 (arg.type, value + 1, arg.name))
5211 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5212 file.Write(" next_cmd, sizeof(cmd) +\n")
5213 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5214 file.Write(" // TODO(gman): Check that data was inserted;\n")
5215 file.Write("}\n")
5216 file.Write("\n")
5219 class PUTXnHandler(TypeHandler):
5220 """Handler for glUniform?f functions."""
5221 def __init__(self):
5222 TypeHandler.__init__(self)
5224 def WriteHandlerImplementation(self, func, file):
5225 """Overrriden from TypeHandler."""
5226 code = """ %(type)s temp[%(count)s] = { %(values)s};
5227 Do%(name)sv(%(location)s, 1, &temp[0]);
5229 values = ""
5230 args = func.GetOriginalArgs()
5231 count = int(func.GetInfo('count'))
5232 num_args = len(args)
5233 for ii in range(count):
5234 values += "%s, " % args[len(args) - count + ii].name
5236 file.Write(code % {
5237 'name': func.name,
5238 'count': func.GetInfo('count'),
5239 'type': func.GetInfo('data_type'),
5240 'location': args[0].name,
5241 'args': func.MakeOriginalArgString(""),
5242 'values': values,
5245 def WriteServiceUnitTest(self, func, file):
5246 """Overrriden from TypeHandler."""
5247 valid_test = """
5248 TEST_F(%(test_name)s, %(name)sValidArgs) {
5249 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5250 SpecializedSetup<cmds::%(name)s, 0>(true);
5251 cmds::%(name)s cmd;
5252 cmd.Init(%(args)s);
5253 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5254 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5257 args = func.GetOriginalArgs()
5258 local_args = "%s, 1, _" % args[0].GetValidGLArg(func, 0, 0)
5259 self.WriteValidUnitTest(func, file, valid_test, {
5260 'name': func.name,
5261 'count': func.GetInfo('count'),
5262 'local_args': local_args,
5265 invalid_test = """
5266 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5267 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5268 SpecializedSetup<cmds::%(name)s, 0>(false);
5269 cmds::%(name)s cmd;
5270 cmd.Init(%(args)s);
5271 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5274 self.WriteInvalidUnitTest(func, file, invalid_test, {
5275 'name': func.GetInfo('name'),
5276 'count': func.GetInfo('count'),
5280 class GLcharHandler(CustomHandler):
5281 """Handler for functions that pass a single string ."""
5283 def __init__(self):
5284 CustomHandler.__init__(self)
5286 def WriteImmediateCmdComputeSize(self, func, file):
5287 """Overrriden from TypeHandler."""
5288 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5289 file.Write(" return static_cast<uint32>(\n")
5290 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5291 file.Write(" }\n")
5293 def WriteImmediateCmdSetHeader(self, func, file):
5294 """Overrriden from TypeHandler."""
5295 code = """
5296 void SetHeader(uint32 data_size) {
5297 header.SetCmdBySize<ValueType>(data_size);
5300 file.Write(code)
5302 def WriteImmediateCmdInit(self, func, file):
5303 """Overrriden from TypeHandler."""
5304 last_arg = func.GetLastOriginalArg()
5305 args = func.GetCmdArgs()
5306 set_code = []
5307 for arg in args:
5308 set_code.append(" %s = _%s;" % (arg.name, arg.name))
5309 code = """
5310 void Init(%(typed_args)s, uint32 _data_size) {
5311 SetHeader(_data_size);
5312 %(set_code)s
5313 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5317 file.Write(code % {
5318 "typed_args": func.MakeTypedOriginalArgString("_"),
5319 "set_code": "\n".join(set_code),
5320 "last_arg": last_arg.name
5323 def WriteImmediateCmdSet(self, func, file):
5324 """Overrriden from TypeHandler."""
5325 last_arg = func.GetLastOriginalArg()
5326 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5327 func.MakeTypedOriginalArgString("_", True))
5328 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5329 func.MakeOriginalArgString("_"))
5330 file.Write(" return NextImmediateCmdAddress<ValueType>("
5331 "cmd, _data_size);\n")
5332 file.Write(" }\n")
5333 file.Write("\n")
5335 def WriteImmediateCmdHelper(self, func, file):
5336 """Overrriden from TypeHandler."""
5337 code = """ void %(name)s(%(typed_args)s) {
5338 const uint32 data_size = strlen(name);
5339 gles2::cmds::%(name)s* c =
5340 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5341 if (c) {
5342 c->Init(%(args)s, data_size);
5347 file.Write(code % {
5348 "name": func.name,
5349 "typed_args": func.MakeTypedOriginalArgString(""),
5350 "args": func.MakeOriginalArgString(""),
5354 def WriteImmediateFormatTest(self, func, file):
5355 """Overrriden from TypeHandler."""
5356 init_code = []
5357 check_code = []
5358 all_but_last_arg = func.GetCmdArgs()[:-1]
5359 for value, arg in enumerate(all_but_last_arg):
5360 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
5361 for value, arg in enumerate(all_but_last_arg):
5362 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5363 (arg.type, value + 11, arg.name))
5364 code = """
5365 TEST_F(GLES2FormatTest, %(func_name)s) {
5366 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5367 static const char* const test_str = \"test string\";
5368 void* next_cmd = cmd.Set(
5369 &cmd,
5370 %(init_code)s
5371 test_str,
5372 strlen(test_str));
5373 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5374 cmd.header.command);
5375 EXPECT_EQ(sizeof(cmd) +
5376 RoundSizeToMultipleOfEntries(strlen(test_str)),
5377 cmd.header.size * 4u);
5378 EXPECT_EQ(static_cast<char*>(next_cmd),
5379 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5380 RoundSizeToMultipleOfEntries(strlen(test_str)));
5381 %(check_code)s
5382 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5383 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5384 CheckBytesWritten(
5385 next_cmd,
5386 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5387 sizeof(cmd) + strlen(test_str));
5391 file.Write(code % {
5392 'func_name': func.name,
5393 'init_code': "\n".join(init_code),
5394 'check_code': "\n".join(check_code),
5398 class GLcharNHandler(CustomHandler):
5399 """Handler for functions that pass a single string with an optional len."""
5401 def __init__(self):
5402 CustomHandler.__init__(self)
5404 def InitFunction(self, func):
5405 """Overrriden from TypeHandler."""
5406 func.cmd_args = []
5407 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5409 def AddImmediateFunction(self, generator, func):
5410 """Overrriden from TypeHandler."""
5411 pass
5413 def AddBucketFunction(self, generator, func):
5414 """Overrriden from TypeHandler."""
5415 pass
5417 def WriteServiceImplementation(self, func, file):
5418 """Overrriden from TypeHandler."""
5419 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5420 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5421 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5422 Bucket* bucket = GetBucket(bucket_id);
5423 if (!bucket || bucket->size() == 0) {
5424 return error::kInvalidArguments;
5426 std::string str;
5427 if (!bucket->GetAsString(&str)) {
5428 return error::kInvalidArguments;
5430 %(gl_func_name)s(0, str.c_str());
5431 return error::kNoError;
5434 """ % {
5435 'name': func.name,
5436 'gl_func_name': func.GetGLFunctionName(),
5437 'bucket_id': func.cmd_args[0].name,
5441 class IsHandler(TypeHandler):
5442 """Handler for glIs____ type and glGetError functions."""
5444 def __init__(self):
5445 TypeHandler.__init__(self)
5447 def InitFunction(self, func):
5448 """Overrriden from TypeHandler."""
5449 func.AddCmdArg(Argument("result_shm_id", 'uint32'))
5450 func.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5451 if func.GetInfo('result') == None:
5452 func.AddInfo('result', ['uint32'])
5454 def WriteServiceUnitTest(self, func, file):
5455 """Overrriden from TypeHandler."""
5456 valid_test = """
5457 TEST_F(%(test_name)s, %(name)sValidArgs) {
5458 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5459 SpecializedSetup<cmds::%(name)s, 0>(true);
5460 cmds::%(name)s cmd;
5461 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5462 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5463 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5466 comma = ""
5467 if len(func.GetOriginalArgs()):
5468 comma =", "
5469 self.WriteValidUnitTest(func, file, valid_test, {
5470 'comma': comma,
5473 invalid_test = """
5474 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5475 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5476 SpecializedSetup<cmds::%(name)s, 0>(false);
5477 cmds::%(name)s cmd;
5478 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5479 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5482 self.WriteInvalidUnitTest(func, file, invalid_test, {
5483 'comma': comma,
5486 invalid_test = """
5487 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5488 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5489 SpecializedSetup<cmds::%(name)s, 0>(false);
5490 cmds::%(name)s cmd;
5491 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5492 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5493 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5494 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5497 self.WriteValidUnitTest(func, file, invalid_test, {
5498 'comma': comma,
5501 def WriteServiceImplementation(self, func, file):
5502 """Overrriden from TypeHandler."""
5503 file.Write(
5504 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
5505 file.Write(
5506 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5507 func.name)
5508 args = func.GetOriginalArgs()
5509 for arg in args:
5510 arg.WriteGetCode(file)
5512 code = """ typedef cmds::%(func_name)s::Result Result;
5513 Result* result_dst = GetSharedMemoryAs<Result*>(
5514 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5515 if (!result_dst) {
5516 return error::kOutOfBounds;
5519 file.Write(code % {'func_name': func.name})
5520 func.WriteHandlerValidation(file)
5521 file.Write(" *result_dst = %s(%s);\n" %
5522 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5523 file.Write(" return error::kNoError;\n")
5524 file.Write("}\n")
5525 file.Write("\n")
5527 def WriteGLES2Implementation(self, func, file):
5528 """Overrriden from TypeHandler."""
5529 impl_func = func.GetInfo('impl_func')
5530 if impl_func == None or impl_func == True:
5531 error_value = func.GetInfo("error_value") or "GL_FALSE"
5532 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5533 (func.return_type, func.original_name,
5534 func.MakeTypedOriginalArgString("")))
5535 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5536 self.WriteTraceEvent(func, file)
5537 func.WriteDestinationInitalizationValidation(file)
5538 self.WriteClientGLCallLog(func, file)
5539 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
5540 file.Write(" Result* result = GetResultAs<Result*>();\n")
5541 file.Write(" if (!result) {\n")
5542 file.Write(" return %s;\n" % error_value)
5543 file.Write(" }\n")
5544 file.Write(" *result = 0;\n")
5545 arg_string = func.MakeOriginalArgString("")
5546 comma = ""
5547 if len(arg_string) > 0:
5548 comma = ", "
5549 file.Write(
5550 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5551 (func.name, arg_string, comma))
5552 file.Write(" WaitForCmd();\n")
5553 file.Write(" %s result_value = *result;\n" % func.return_type)
5554 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5555 file.Write(" CheckGLError();\n")
5556 file.Write(" return result_value;\n")
5557 file.Write("}\n")
5558 file.Write("\n")
5560 def WriteGLES2ImplementationUnitTest(self, func, file):
5561 """Overrriden from TypeHandler."""
5562 client_test = func.GetInfo('client_test')
5563 if client_test == None or client_test == True:
5564 code = """
5565 TEST_F(GLES2ImplementationTest, %(name)s) {
5566 struct Cmds {
5567 cmds::%(name)s cmd;
5570 Cmds expected;
5571 ExpectedMemoryInfo result1 =
5572 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5573 expected.cmd.Init(1, result1.id, result1.offset);
5575 EXPECT_CALL(*command_buffer(), OnFlush())
5576 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5577 .RetiresOnSaturation();
5579 GLboolean result = gl_->%(name)s(1);
5580 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5581 EXPECT_TRUE(result);
5584 file.Write(code % {
5585 'name': func.name,
5589 class STRnHandler(TypeHandler):
5590 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5591 GetTranslatedShaderSourceANGLE."""
5593 def __init__(self):
5594 TypeHandler.__init__(self)
5596 def InitFunction(self, func):
5597 """Overrriden from TypeHandler."""
5598 # remove all but the first cmd args.
5599 cmd_args = func.GetCmdArgs()
5600 func.ClearCmdArgs()
5601 func.AddCmdArg(cmd_args[0])
5602 # add on a bucket id.
5603 func.AddCmdArg(Argument('bucket_id', 'uint32'))
5605 def WriteGLES2Implementation(self, func, file):
5606 """Overrriden from TypeHandler."""
5607 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5608 GPU_CLIENT_SINGLE_THREAD_CHECK();
5610 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5611 << "] gl%(func_name)s" << "("
5612 << %(arg0)s << ", "
5613 << %(arg1)s << ", "
5614 << static_cast<void*>(%(arg2)s) << ", "
5615 << static_cast<void*>(%(arg3)s) << ")");
5616 helper_->SetBucketSize(kResultBucketId, 0);
5617 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5618 std::string str;
5619 GLsizei max_size = 0;
5620 if (GetBucketAsString(kResultBucketId, &str)) {
5621 if (bufsize > 0) {
5622 max_size =
5623 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5624 memcpy(%(dest_name)s, str.c_str(), max_size);
5625 %(dest_name)s[max_size] = '\\0';
5626 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5629 if (%(length_name)s != NULL) {
5630 *%(length_name)s = max_size;
5632 CheckGLError();
5635 args = func.GetOriginalArgs()
5636 str_args = {
5637 'return_type': func.return_type,
5638 'func_name': func.original_name,
5639 'args': func.MakeTypedOriginalArgString(""),
5640 'id_name': args[0].name,
5641 'bufsize_name': args[1].name,
5642 'length_name': args[2].name,
5643 'dest_name': args[3].name,
5644 'arg0': args[0].name,
5645 'arg1': args[1].name,
5646 'arg2': args[2].name,
5647 'arg3': args[3].name,
5649 file.Write(code_1 % str_args)
5650 func.WriteDestinationInitalizationValidation(file)
5651 file.Write(code_2 % str_args)
5653 def WriteServiceUnitTest(self, func, file):
5654 """Overrriden from TypeHandler."""
5655 valid_test = """
5656 TEST_F(%(test_name)s, %(name)sValidArgs) {
5657 const char* kInfo = "hello";
5658 const uint32 kBucketId = 123;
5659 SpecializedSetup<cmds::%(name)s, 0>(true);
5660 %(expect_len_code)s
5661 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5662 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5663 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5664 cmds::%(name)s cmd;
5665 cmd.Init(%(args)s);
5666 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5667 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5668 ASSERT_TRUE(bucket != NULL);
5669 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5670 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5671 bucket->size()));
5672 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5675 args = func.GetOriginalArgs()
5676 id_name = args[0].GetValidGLArg(func, 0, 0)
5677 get_len_func = func.GetInfo('get_len_func')
5678 get_len_enum = func.GetInfo('get_len_enum')
5679 sub = {
5680 'id_name': id_name,
5681 'get_len_func': get_len_func,
5682 'get_len_enum': get_len_enum,
5683 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5684 args[0].GetValidGLArg(func, 0, 0),
5685 'args': '%s, kBucketId' % args[0].GetValidArg(func, 0, 0),
5686 'expect_len_code': '',
5688 if get_len_func and get_len_func[0:2] == 'gl':
5689 sub['expect_len_code'] = (
5690 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5691 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5692 get_len_func[2:], id_name, get_len_enum)
5693 self.WriteValidUnitTest(func, file, valid_test, sub)
5695 invalid_test = """
5696 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5697 const uint32 kBucketId = 123;
5698 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5699 .Times(0);
5700 cmds::%(name)s cmd;
5701 cmd.Init(kInvalidClientId, kBucketId);
5702 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5703 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5706 self.WriteValidUnitTest(func, file, invalid_test)
5708 def WriteServiceImplementation(self, func, file):
5709 """Overrriden from TypeHandler."""
5710 pass
5713 class FunctionInfo(object):
5714 """Holds info about a function."""
5716 def __init__(self, info, type_handler):
5717 for key in info:
5718 setattr(self, key, info[key])
5719 self.type_handler = type_handler
5720 if not 'type' in info:
5721 self.type = ''
5724 class Argument(object):
5725 """A class that represents a function argument."""
5727 cmd_type_map_ = {
5728 'GLenum': 'uint32',
5729 'GLint': 'int32',
5730 'GLintptr': 'int32',
5731 'GLsizei': 'int32',
5732 'GLsizeiptr': 'int32',
5733 'GLfloat': 'float',
5734 'GLclampf': 'float',
5736 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5738 def __init__(self, name, type):
5739 self.name = name
5740 self.optional = type.endswith("Optional*")
5741 if self.optional:
5742 type = type[:-9] + "*"
5743 self.type = type
5745 if type in self.cmd_type_map_:
5746 self.cmd_type = self.cmd_type_map_[type]
5747 else:
5748 self.cmd_type = 'uint32'
5750 def IsPointer(self):
5751 """Returns true if argument is a pointer."""
5752 return False
5754 def AddCmdArgs(self, args):
5755 """Adds command arguments for this argument to the given list."""
5756 return args.append(self)
5758 def AddInitArgs(self, args):
5759 """Adds init arguments for this argument to the given list."""
5760 return args.append(self)
5762 def GetValidArg(self, func, offset, index):
5763 """Gets a valid value for this argument."""
5764 valid_arg = func.GetValidArg(offset)
5765 if valid_arg != None:
5766 return valid_arg
5767 return str(offset + 1)
5769 def GetValidClientSideArg(self, func, offset, index):
5770 """Gets a valid value for this argument."""
5771 return str(offset + 1)
5773 def GetValidClientSideCmdArg(self, func, offset, index):
5774 """Gets a valid value for this argument."""
5775 return str(offset + 1)
5777 def GetValidGLArg(self, func, offset, index):
5778 """Gets a valid GL value for this argument."""
5779 valid_arg = func.GetValidArg(offset)
5780 if valid_arg != None:
5781 return valid_arg
5782 return str(offset + 1)
5784 def GetNumInvalidValues(self, func):
5785 """returns the number of invalid values to be tested."""
5786 return 0
5788 def GetInvalidArg(self, offset, index):
5789 """returns an invalid value and expected parse result by index."""
5790 return ("---ERROR0---", "---ERROR2---", None)
5792 def GetLogArg(self):
5793 """Get argument appropriate for LOG macro."""
5794 if self.type == 'GLboolean':
5795 return 'GLES2Util::GetStringBool(%s)' % self.name
5796 if self.type == 'GLenum':
5797 return 'GLES2Util::GetStringEnum(%s)' % self.name
5798 return self.name
5800 def WriteGetCode(self, file):
5801 """Writes the code to get an argument from a command structure."""
5802 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5803 (self.type, self.name, self.type, self.name))
5805 def WriteValidationCode(self, file, func):
5806 """Writes the validation code for an argument."""
5807 pass
5809 def WriteClientSideValidationCode(self, file, func):
5810 """Writes the validation code for an argument."""
5811 pass
5813 def WriteDestinationInitalizationValidation(self, file, func):
5814 """Writes the client side destintion initialization validation."""
5815 pass
5817 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
5818 """Writes the client side destintion initialization validation if needed."""
5819 parts = self.type.split(" ")
5820 if len(parts) > 1:
5821 return
5822 if parts[0] in self.need_validation_:
5823 file.Write(
5824 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5825 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
5828 def WriteGetAddress(self, file):
5829 """Writes the code to get the address this argument refers to."""
5830 pass
5832 def GetImmediateVersion(self):
5833 """Gets the immediate version of this argument."""
5834 return self
5836 def GetBucketVersion(self):
5837 """Gets the bucket version of this argument."""
5838 return self
5841 class BoolArgument(Argument):
5842 """class for GLboolean"""
5844 def __init__(self, name, type):
5845 Argument.__init__(self, name, 'GLboolean')
5847 def GetValidArg(self, func, offset, index):
5848 """Gets a valid value for this argument."""
5849 return 'true'
5851 def GetValidClientSideArg(self, func, offset, index):
5852 """Gets a valid value for this argument."""
5853 return 'true'
5855 def GetValidClientSideCmdArg(self, func, offset, index):
5856 """Gets a valid value for this argument."""
5857 return 'true'
5859 def GetValidGLArg(self, func, offset, index):
5860 """Gets a valid GL value for this argument."""
5861 return 'true'
5864 class UniformLocationArgument(Argument):
5865 """class for uniform locations."""
5867 def __init__(self, name):
5868 Argument.__init__(self, name, "GLint")
5870 def WriteGetCode(self, file):
5871 """Writes the code to get an argument from a command structure."""
5872 code = """ %s %s = static_cast<%s>(c.%s);
5874 file.Write(code % (self.type, self.name, self.type, self.name))
5876 def GetValidArg(self, func, offset, index):
5877 """Gets a valid value for this argument."""
5878 return "%d" % (offset + 1)
5881 class DataSizeArgument(Argument):
5882 """class for data_size which Bucket commands do not need."""
5884 def __init__(self, name):
5885 Argument.__init__(self, name, "uint32")
5887 def GetBucketVersion(self):
5888 return None
5891 class SizeArgument(Argument):
5892 """class for GLsizei and GLsizeiptr."""
5894 def __init__(self, name, type):
5895 Argument.__init__(self, name, type)
5897 def GetNumInvalidValues(self, func):
5898 """overridden from Argument."""
5899 if func.is_immediate:
5900 return 0
5901 return 1
5903 def GetInvalidArg(self, offset, index):
5904 """overridden from Argument."""
5905 return ("-1", "kNoError", "GL_INVALID_VALUE")
5907 def WriteValidationCode(self, file, func):
5908 """overridden from Argument."""
5909 file.Write(" if (%s < 0) {\n" % self.name)
5910 file.Write(
5911 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5912 (func.original_name, self.name))
5913 file.Write(" return error::kNoError;\n")
5914 file.Write(" }\n")
5916 def WriteClientSideValidationCode(self, file, func):
5917 """overridden from Argument."""
5918 file.Write(" if (%s < 0) {\n" % self.name)
5919 file.Write(
5920 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5921 (func.original_name, self.name))
5922 file.Write(" return;\n")
5923 file.Write(" }\n")
5926 class SizeNotNegativeArgument(SizeArgument):
5927 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5929 def __init__(self, name, type, gl_type):
5930 SizeArgument.__init__(self, name, gl_type)
5932 def GetInvalidArg(self, offset, index):
5933 """overridden from SizeArgument."""
5934 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5936 def WriteValidationCode(self, file, func):
5937 """overridden from SizeArgument."""
5938 pass
5941 class EnumBaseArgument(Argument):
5942 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5944 def __init__(self, name, gl_type, type, gl_error):
5945 Argument.__init__(self, name, gl_type)
5947 self.local_type = type
5948 self.gl_error = gl_error
5949 name = type[len(gl_type):]
5950 self.type_name = name
5951 self.enum_info = _ENUM_LISTS[name]
5953 def WriteValidationCode(self, file, func):
5954 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5955 (ToUnderscore(self.type_name), self.name))
5956 if self.gl_error == "GL_INVALID_ENUM":
5957 file.Write(
5958 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5959 (func.original_name, self.name, self.name))
5960 else:
5961 file.Write(
5962 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5963 (self.gl_error, func.original_name, self.name, self.gl_error))
5964 file.Write(" return error::kNoError;\n")
5965 file.Write(" }\n")
5967 def GetValidArg(self, func, offset, index):
5968 valid_arg = func.GetValidArg(offset)
5969 if valid_arg != None:
5970 return valid_arg
5971 if 'valid' in self.enum_info:
5972 valid = self.enum_info['valid']
5973 num_valid = len(valid)
5974 if index >= num_valid:
5975 index = num_valid - 1
5976 return valid[index]
5977 return str(offset + 1)
5979 def GetValidClientSideArg(self, func, offset, index):
5980 """Gets a valid value for this argument."""
5981 return self.GetValidArg(func, offset, index)
5983 def GetValidClientSideCmdArg(self, func, offset, index):
5984 """Gets a valid value for this argument."""
5985 return self.GetValidArg(func, offset, index)
5987 def GetValidGLArg(self, func, offset, index):
5988 """Gets a valid value for this argument."""
5989 return self.GetValidArg(func, offset, index)
5991 def GetNumInvalidValues(self, func):
5992 """returns the number of invalid values to be tested."""
5993 if 'invalid' in self.enum_info:
5994 invalid = self.enum_info['invalid']
5995 return len(invalid)
5996 return 0
5998 def GetInvalidArg(self, offset, index):
5999 """returns an invalid value by index."""
6000 if 'invalid' in self.enum_info:
6001 invalid = self.enum_info['invalid']
6002 num_invalid = len(invalid)
6003 if index >= num_invalid:
6004 index = num_invalid - 1
6005 return (invalid[index], "kNoError", self.gl_error)
6006 return ("---ERROR1---", "kNoError", self.gl_error)
6009 class EnumArgument(EnumBaseArgument):
6010 """A class that represents a GLenum argument"""
6012 def __init__(self, name, type):
6013 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
6015 def GetLogArg(self):
6016 """Overridden from Argument."""
6017 return ("GLES2Util::GetString%s(%s)" %
6018 (self.type_name, self.name))
6021 class IntArgument(EnumBaseArgument):
6022 """A class for a GLint argument that can only except specific values.
6024 For example glTexImage2D takes a GLint for its internalformat
6025 argument instead of a GLenum.
6028 def __init__(self, name, type):
6029 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
6032 class ValidatedBoolArgument(EnumBaseArgument):
6033 """A class for a GLboolean argument that can only except specific values.
6035 For example glUniformMatrix takes a GLboolean for it's transpose but it
6036 must be false.
6039 def __init__(self, name, type):
6040 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
6042 def GetLogArg(self):
6043 """Overridden from Argument."""
6044 return 'GLES2Util::GetStringBool(%s)' % self.name
6047 class ImmediatePointerArgument(Argument):
6048 """A class that represents an immediate argument to a function.
6050 An immediate argument is one where the data follows the command.
6053 def __init__(self, name, type):
6054 Argument.__init__(self, name, type)
6056 def AddCmdArgs(self, args):
6057 """Overridden from Argument."""
6058 pass
6060 def WriteGetCode(self, file):
6061 """Overridden from Argument."""
6062 file.Write(
6063 " %s %s = GetImmediateDataAs<%s>(\n" %
6064 (self.type, self.name, self.type))
6065 file.Write(" c, data_size, immediate_data_size);\n")
6067 def WriteValidationCode(self, file, func):
6068 """Overridden from Argument."""
6069 file.Write(" if (%s == NULL) {\n" % self.name)
6070 file.Write(" return error::kOutOfBounds;\n")
6071 file.Write(" }\n")
6073 def GetImmediateVersion(self):
6074 """Overridden from Argument."""
6075 return None
6077 def WriteDestinationInitalizationValidation(self, file, func):
6078 """Overridden from Argument."""
6079 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6081 def GetLogArg(self):
6082 """Overridden from Argument."""
6083 return "static_cast<const void*>(%s)" % self.name
6086 class BucketPointerArgument(Argument):
6087 """A class that represents an bucket argument to a function."""
6089 def __init__(self, name, type):
6090 Argument.__init__(self, name, type)
6092 def AddCmdArgs(self, args):
6093 """Overridden from Argument."""
6094 pass
6096 def WriteGetCode(self, file):
6097 """Overridden from Argument."""
6098 file.Write(
6099 " %s %s = bucket->GetData(0, data_size);\n" %
6100 (self.type, self.name))
6102 def WriteValidationCode(self, file, func):
6103 """Overridden from Argument."""
6104 pass
6106 def GetImmediateVersion(self):
6107 """Overridden from Argument."""
6108 return None
6110 def WriteDestinationInitalizationValidation(self, file, func):
6111 """Overridden from Argument."""
6112 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6114 def GetLogArg(self):
6115 """Overridden from Argument."""
6116 return "static_cast<const void*>(%s)" % self.name
6119 class PointerArgument(Argument):
6120 """A class that represents a pointer argument to a function."""
6122 def __init__(self, name, type):
6123 Argument.__init__(self, name, type)
6125 def IsPointer(self):
6126 """Returns true if argument is a pointer."""
6127 return True
6129 def GetValidArg(self, func, offset, index):
6130 """Overridden from Argument."""
6131 return "shared_memory_id_, shared_memory_offset_"
6133 def GetValidGLArg(self, func, offset, index):
6134 """Overridden from Argument."""
6135 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
6137 def GetNumInvalidValues(self, func):
6138 """Overridden from Argument."""
6139 return 2
6141 def GetInvalidArg(self, offset, index):
6142 """Overridden from Argument."""
6143 if index == 0:
6144 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6145 else:
6146 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6147 "kOutOfBounds", None)
6149 def GetLogArg(self):
6150 """Overridden from Argument."""
6151 return "static_cast<const void*>(%s)" % self.name
6153 def AddCmdArgs(self, args):
6154 """Overridden from Argument."""
6155 args.append(Argument("%s_shm_id" % self.name, 'uint32'))
6156 args.append(Argument("%s_shm_offset" % self.name, 'uint32'))
6158 def WriteGetCode(self, file):
6159 """Overridden from Argument."""
6160 file.Write(
6161 " %s %s = GetSharedMemoryAs<%s>(\n" %
6162 (self.type, self.name, self.type))
6163 file.Write(
6164 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6165 (self.name, self.name))
6167 def WriteGetAddress(self, file):
6168 """Overridden from Argument."""
6169 file.Write(
6170 " %s %s = GetSharedMemoryAs<%s>(\n" %
6171 (self.type, self.name, self.type))
6172 file.Write(
6173 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6174 (self.name, self.name, self.name))
6176 def WriteValidationCode(self, file, func):
6177 """Overridden from Argument."""
6178 file.Write(" if (%s == NULL) {\n" % self.name)
6179 file.Write(" return error::kOutOfBounds;\n")
6180 file.Write(" }\n")
6182 def GetImmediateVersion(self):
6183 """Overridden from Argument."""
6184 return ImmediatePointerArgument(self.name, self.type)
6186 def GetBucketVersion(self):
6187 """Overridden from Argument."""
6188 if self.type == "const char*":
6189 return InputStringBucketArgument(self.name, self.type)
6190 return BucketPointerArgument(self.name, self.type)
6192 def WriteDestinationInitalizationValidation(self, file, func):
6193 """Overridden from Argument."""
6194 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6197 class InputStringBucketArgument(Argument):
6198 """An string input argument where the string is passed in a bucket."""
6200 def __init__(self, name, type):
6201 Argument.__init__(self, name + "_bucket_id", "uint32")
6203 def WriteGetCode(self, file):
6204 """Overridden from Argument."""
6205 code = """
6206 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6207 if (!%(name)s_bucket) {
6208 return error::kInvalidArguments;
6210 std::string %(name)s_str;
6211 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6212 return error::kInvalidArguments;
6214 const char* %(name)s = %(name)s_str.c_str();
6216 file.Write(code % {
6217 'name': self.name,
6220 def GetValidArg(self, func, offset, index):
6221 return "kNameBucketId"
6223 def GetValidGLArg(self, func, offset, index):
6224 return "_"
6227 class NonImmediatePointerArgument(PointerArgument):
6228 """A pointer argument that stays a pointer even in an immediate cmd."""
6230 def __init__(self, name, type):
6231 PointerArgument.__init__(self, name, type)
6233 def IsPointer(self):
6234 """Returns true if argument is a pointer."""
6235 return False
6237 def GetImmediateVersion(self):
6238 """Overridden from Argument."""
6239 return self
6242 class ResourceIdArgument(Argument):
6243 """A class that represents a resource id argument to a function."""
6245 def __init__(self, name, type):
6246 match = re.match("(GLid\w+)", type)
6247 self.resource_type = match.group(1)[4:]
6248 type = type.replace(match.group(1), "GLuint")
6249 Argument.__init__(self, name, type)
6251 def WriteGetCode(self, file):
6252 """Overridden from Argument."""
6253 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6255 def GetValidArg(self, func, offset, index):
6256 return "client_%s_id_" % self.resource_type.lower()
6258 def GetValidGLArg(self, func, offset, index):
6259 return "kService%sId" % self.resource_type
6262 class ResourceIdBindArgument(Argument):
6263 """Represents a resource id argument to a bind function."""
6265 def __init__(self, name, type):
6266 match = re.match("(GLidBind\w+)", type)
6267 self.resource_type = match.group(1)[8:]
6268 type = type.replace(match.group(1), "GLuint")
6269 Argument.__init__(self, name, type)
6271 def WriteGetCode(self, file):
6272 """Overridden from Argument."""
6273 code = """ %(type)s %(name)s = c.%(name)s;
6275 file.Write(code % {'type': self.type, 'name': self.name})
6277 def GetValidArg(self, func, offset, index):
6278 return "client_%s_id_" % self.resource_type.lower()
6280 def GetValidGLArg(self, func, offset, index):
6281 return "kService%sId" % self.resource_type
6284 class ResourceIdZeroArgument(Argument):
6285 """Represents a resource id argument to a function that can be zero."""
6287 def __init__(self, name, type):
6288 match = re.match("(GLidZero\w+)", type)
6289 self.resource_type = match.group(1)[8:]
6290 type = type.replace(match.group(1), "GLuint")
6291 Argument.__init__(self, name, type)
6293 def WriteGetCode(self, file):
6294 """Overridden from Argument."""
6295 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6297 def GetValidArg(self, func, offset, index):
6298 return "client_%s_id_" % self.resource_type.lower()
6300 def GetValidGLArg(self, func, offset, index):
6301 return "kService%sId" % self.resource_type
6303 def GetNumInvalidValues(self, func):
6304 """returns the number of invalid values to be tested."""
6305 return 1
6307 def GetInvalidArg(self, offset, index):
6308 """returns an invalid value by index."""
6309 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6312 class Function(object):
6313 """A class that represents a function."""
6315 def __init__(self, original_name, name, info, return_type, original_args,
6316 args_for_cmds, cmd_args, init_args, num_pointer_args):
6317 self.name = name
6318 self.original_name = original_name
6319 self.info = info
6320 self.type_handler = info.type_handler
6321 self.return_type = return_type
6322 self.original_args = original_args
6323 self.num_pointer_args = num_pointer_args
6324 self.can_auto_generate = num_pointer_args == 0 and return_type == "void"
6325 self.cmd_args = cmd_args
6326 self.init_args = init_args
6327 self.InitFunction()
6328 self.args_for_cmds = args_for_cmds
6329 self.is_immediate = False
6331 def IsType(self, type_name):
6332 """Returns true if function is a certain type."""
6333 return self.info.type == type_name
6335 def InitFunction(self):
6336 """Calls the init function for the type handler."""
6337 self.type_handler.InitFunction(self)
6339 def GetInfo(self, name):
6340 """Returns a value from the function info for this function."""
6341 if hasattr(self.info, name):
6342 return getattr(self.info, name)
6343 return None
6345 def GetValidArg(self, index):
6346 """Gets a valid arg from the function info if one exists."""
6347 valid_args = self.GetInfo('valid_args')
6348 if valid_args and str(index) in valid_args:
6349 return valid_args[str(index)]
6350 return None
6352 def AddInfo(self, name, value):
6353 """Adds an info."""
6354 setattr(self.info, name, value)
6356 def IsCoreGLFunction(self):
6357 return (not self.GetInfo('extension') and
6358 not self.GetInfo('pepper_interface'))
6360 def InPepperInterface(self, interface):
6361 ext = self.GetInfo('pepper_interface')
6362 if not interface.GetName():
6363 return self.IsCoreGLFunction()
6364 return ext == interface.GetName()
6366 def InAnyPepperExtension(self):
6367 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
6369 def GetGLFunctionName(self):
6370 """Gets the function to call to execute GL for this command."""
6371 if self.GetInfo('decoder_func'):
6372 return self.GetInfo('decoder_func')
6373 return "gl%s" % self.original_name
6375 def GetGLTestFunctionName(self):
6376 gl_func_name = self.GetInfo('gl_test_func')
6377 if gl_func_name == None:
6378 gl_func_name = self.GetGLFunctionName()
6379 if gl_func_name.startswith("gl"):
6380 gl_func_name = gl_func_name[2:]
6381 else:
6382 gl_func_name = self.original_name
6383 return gl_func_name
6385 def AddCmdArg(self, arg):
6386 """Adds a cmd argument to this function."""
6387 self.cmd_args.append(arg)
6389 def GetCmdArgs(self):
6390 """Gets the command args for this function."""
6391 return self.cmd_args
6393 def ClearCmdArgs(self):
6394 """Clears the command args for this function."""
6395 self.cmd_args = []
6397 def GetInitArgs(self):
6398 """Gets the init args for this function."""
6399 return self.init_args
6401 def GetOriginalArgs(self):
6402 """Gets the original arguments to this function."""
6403 return self.original_args
6405 def GetLastOriginalArg(self):
6406 """Gets the last original argument to this function."""
6407 return self.original_args[len(self.original_args) - 1]
6409 def __MaybePrependComma(self, arg_string, add_comma):
6410 """Adds a comma if arg_string is not empty and add_comma is true."""
6411 comma = ""
6412 if add_comma and len(arg_string):
6413 comma = ", "
6414 return "%s%s" % (comma, arg_string)
6416 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
6417 """Gets a list of arguments as they are in GL."""
6418 args = self.GetOriginalArgs()
6419 arg_string = ", ".join(
6420 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6421 return self.__MaybePrependComma(arg_string, add_comma)
6423 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
6424 """Gets the list of arguments as they are in GL."""
6425 args = self.GetOriginalArgs()
6426 arg_string = separator.join(
6427 ["%s%s" % (prefix, arg.name) for arg in args])
6428 return self.__MaybePrependComma(arg_string, add_comma)
6430 def MakeTypedPepperArgString(self, prefix):
6431 """Gets a list of arguments as they need to be for Pepper."""
6432 if self.GetInfo("pepper_args"):
6433 return self.GetInfo("pepper_args")
6434 else:
6435 return self.MakeTypedOriginalArgString(prefix, False)
6437 def GetPepperName(self):
6438 if self.GetInfo("pepper_name"):
6439 return self.GetInfo("pepper_name")
6440 return self.name
6442 def MakeTypedCmdArgString(self, prefix, add_comma = False):
6443 """Gets a typed list of arguments as they need to be for command buffers."""
6444 args = self.GetCmdArgs()
6445 arg_string = ", ".join(
6446 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6447 return self.__MaybePrependComma(arg_string, add_comma)
6449 def MakeCmdArgString(self, prefix, add_comma = False):
6450 """Gets the list of arguments as they need to be for command buffers."""
6451 args = self.GetCmdArgs()
6452 arg_string = ", ".join(
6453 ["%s%s" % (prefix, arg.name) for arg in args])
6454 return self.__MaybePrependComma(arg_string, add_comma)
6456 def MakeTypedInitString(self, prefix, add_comma = False):
6457 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6458 args = self.GetInitArgs()
6459 arg_string = ", ".join(
6460 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6461 return self.__MaybePrependComma(arg_string, add_comma)
6463 def MakeInitString(self, prefix, add_comma = False):
6464 """Gets the list of arguments as they need to be for cmd Init/Set."""
6465 args = self.GetInitArgs()
6466 arg_string = ", ".join(
6467 ["%s%s" % (prefix, arg.name) for arg in args])
6468 return self.__MaybePrependComma(arg_string, add_comma)
6470 def MakeLogArgString(self):
6471 """Makes a string of the arguments for the LOG macros"""
6472 args = self.GetOriginalArgs()
6473 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
6475 def WriteCommandDescription(self, file):
6476 """Writes a description of the command."""
6477 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
6479 def WriteHandlerValidation(self, file):
6480 """Writes validation code for the function."""
6481 for arg in self.GetOriginalArgs():
6482 arg.WriteValidationCode(file, self)
6483 self.WriteValidationCode(file)
6485 def WriteHandlerImplementation(self, file):
6486 """Writes the handler implementation for this command."""
6487 self.type_handler.WriteHandlerImplementation(self, file)
6489 def WriteValidationCode(self, file):
6490 """Writes the validation code for a command."""
6491 pass
6493 def WriteCmdFlag(self, file):
6494 """Writes the cmd cmd_flags constant."""
6495 flags = []
6496 trace_level = 3 # By default trace only at the highest level
6497 if hasattr(self.info, 'trace_level'):
6498 if (self.info.trace_level < 0) or (self.info.trace_level > 3):
6499 raise KeyError("Unhandled trace_level: %d" % self.info.trace_level)
6500 trace_level = self.info.trace_level
6502 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
6504 if len(flags) > 0:
6505 cmd_flags = ' | '.join(flags)
6506 else:
6507 cmd_flags = 0
6509 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
6512 def WriteCmdArgFlag(self, file):
6513 """Writes the cmd kArgFlags constant."""
6514 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6516 def WriteCmdComputeSize(self, file):
6517 """Writes the ComputeSize function for the command."""
6518 file.Write(" static uint32 ComputeSize() {\n")
6519 file.Write(
6520 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6521 file.Write(" }\n")
6522 file.Write("\n")
6524 def WriteCmdSetHeader(self, file):
6525 """Writes the cmd's SetHeader function."""
6526 file.Write(" void SetHeader() {\n")
6527 file.Write(" header.SetCmd<ValueType>();\n")
6528 file.Write(" }\n")
6529 file.Write("\n")
6531 def WriteCmdInit(self, file):
6532 """Writes the cmd's Init function."""
6533 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
6534 file.Write(" SetHeader();\n")
6535 args = self.GetCmdArgs()
6536 for arg in args:
6537 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6538 file.Write(" }\n")
6539 file.Write("\n")
6541 def WriteCmdSet(self, file):
6542 """Writes the cmd's Set function."""
6543 copy_args = self.MakeCmdArgString("_", False)
6544 file.Write(" void* Set(void* cmd%s) {\n" %
6545 self.MakeTypedCmdArgString("_", True))
6546 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
6547 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6548 file.Write(" }\n")
6549 file.Write("\n")
6551 def WriteStruct(self, file):
6552 self.type_handler.WriteStruct(self, file)
6554 def WriteDocs(self, file):
6555 self.type_handler.WriteDocs(self, file)
6557 def WriteCmdHelper(self, file):
6558 """Writes the cmd's helper."""
6559 self.type_handler.WriteCmdHelper(self, file)
6561 def WriteServiceImplementation(self, file):
6562 """Writes the service implementation for a command."""
6563 self.type_handler.WriteServiceImplementation(self, file)
6565 def WriteServiceUnitTest(self, file):
6566 """Writes the service implementation for a command."""
6567 self.type_handler.WriteServiceUnitTest(self, file)
6569 def WriteGLES2CLibImplementation(self, file):
6570 """Writes the GLES2 C Lib Implemention."""
6571 self.type_handler.WriteGLES2CLibImplementation(self, file)
6573 def WriteGLES2InterfaceHeader(self, file):
6574 """Writes the GLES2 Interface declaration."""
6575 self.type_handler.WriteGLES2InterfaceHeader(self, file)
6577 def WriteGLES2InterfaceStub(self, file):
6578 """Writes the GLES2 Interface Stub declaration."""
6579 self.type_handler.WriteGLES2InterfaceStub(self, file)
6581 def WriteGLES2InterfaceStubImpl(self, file):
6582 """Writes the GLES2 Interface Stub declaration."""
6583 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
6585 def WriteGLES2ImplementationHeader(self, file):
6586 """Writes the GLES2 Implemention declaration."""
6587 self.type_handler.WriteGLES2ImplementationHeader(self, file)
6589 def WriteGLES2Implementation(self, file):
6590 """Writes the GLES2 Implemention definition."""
6591 self.type_handler.WriteGLES2Implementation(self, file)
6593 def WriteGLES2TraceImplementationHeader(self, file):
6594 """Writes the GLES2 Trace Implemention declaration."""
6595 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
6597 def WriteGLES2TraceImplementation(self, file):
6598 """Writes the GLES2 Trace Implemention definition."""
6599 self.type_handler.WriteGLES2TraceImplementation(self, file)
6601 def WriteGLES2Header(self, file):
6602 """Writes the GLES2 Implemention unit test."""
6603 self.type_handler.WriteGLES2Header(self, file)
6605 def WriteGLES2ImplementationUnitTest(self, file):
6606 """Writes the GLES2 Implemention unit test."""
6607 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
6609 def WriteDestinationInitalizationValidation(self, file):
6610 """Writes the client side destintion initialization validation."""
6611 self.type_handler.WriteDestinationInitalizationValidation(self, file)
6613 def WriteFormatTest(self, file):
6614 """Writes the cmd's format test."""
6615 self.type_handler.WriteFormatTest(self, file)
6618 class PepperInterface(object):
6619 """A class that represents a function."""
6621 def __init__(self, info):
6622 self.name = info["name"]
6623 self.dev = info["dev"]
6625 def GetName(self):
6626 return self.name
6628 def GetInterfaceName(self):
6629 upperint = ""
6630 dev = ""
6631 if self.name:
6632 upperint = "_" + self.name.upper()
6633 if self.dev:
6634 dev = "_DEV"
6635 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
6637 def GetInterfaceString(self):
6638 dev = ""
6639 if self.dev:
6640 dev = "(Dev)"
6641 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6643 def GetStructName(self):
6644 dev = ""
6645 if self.dev:
6646 dev = "_Dev"
6647 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6650 class ImmediateFunction(Function):
6651 """A class that represnets an immediate function command."""
6653 def __init__(self, func):
6654 new_args = []
6655 for arg in func.GetOriginalArgs():
6656 new_arg = arg.GetImmediateVersion()
6657 if new_arg:
6658 new_args.append(new_arg)
6660 cmd_args = []
6661 new_args_for_cmds = []
6662 for arg in func.args_for_cmds:
6663 new_arg = arg.GetImmediateVersion()
6664 if new_arg:
6665 new_args_for_cmds.append(new_arg)
6666 new_arg.AddCmdArgs(cmd_args)
6668 new_init_args = []
6669 for arg in new_args_for_cmds:
6670 arg.AddInitArgs(new_init_args)
6672 Function.__init__(
6673 self,
6674 func.original_name,
6675 "%sImmediate" % func.name,
6676 func.info,
6677 func.return_type,
6678 new_args,
6679 new_args_for_cmds,
6680 cmd_args,
6681 new_init_args,
6683 self.is_immediate = True
6685 def WriteCommandDescription(self, file):
6686 """Overridden from Function"""
6687 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6688 self.original_name)
6690 def WriteServiceImplementation(self, file):
6691 """Overridden from Function"""
6692 self.type_handler.WriteImmediateServiceImplementation(self, file)
6694 def WriteHandlerImplementation(self, file):
6695 """Overridden from Function"""
6696 self.type_handler.WriteImmediateHandlerImplementation(self, file)
6698 def WriteServiceUnitTest(self, file):
6699 """Writes the service implementation for a command."""
6700 self.type_handler.WriteImmediateServiceUnitTest(self, file)
6702 def WriteValidationCode(self, file):
6703 """Overridden from Function"""
6704 self.type_handler.WriteImmediateValidationCode(self, file)
6706 def WriteCmdArgFlag(self, file):
6707 """Overridden from Function"""
6708 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6710 def WriteCmdComputeSize(self, file):
6711 """Overridden from Function"""
6712 self.type_handler.WriteImmediateCmdComputeSize(self, file)
6714 def WriteCmdSetHeader(self, file):
6715 """Overridden from Function"""
6716 self.type_handler.WriteImmediateCmdSetHeader(self, file)
6718 def WriteCmdInit(self, file):
6719 """Overridden from Function"""
6720 self.type_handler.WriteImmediateCmdInit(self, file)
6722 def WriteCmdSet(self, file):
6723 """Overridden from Function"""
6724 self.type_handler.WriteImmediateCmdSet(self, file)
6726 def WriteCmdHelper(self, file):
6727 """Overridden from Function"""
6728 self.type_handler.WriteImmediateCmdHelper(self, file)
6730 def WriteFormatTest(self, file):
6731 """Overridden from Function"""
6732 self.type_handler.WriteImmediateFormatTest(self, file)
6735 class BucketFunction(Function):
6736 """A class that represnets a bucket version of a function command."""
6738 def __init__(self, func):
6739 new_args = []
6740 for arg in func.GetOriginalArgs():
6741 new_arg = arg.GetBucketVersion()
6742 if new_arg:
6743 new_args.append(new_arg)
6745 cmd_args = []
6746 new_args_for_cmds = []
6747 for arg in func.args_for_cmds:
6748 new_arg = arg.GetBucketVersion()
6749 if new_arg:
6750 new_args_for_cmds.append(new_arg)
6751 new_arg.AddCmdArgs(cmd_args)
6753 new_init_args = []
6754 for arg in new_args_for_cmds:
6755 arg.AddInitArgs(new_init_args)
6757 Function.__init__(
6758 self,
6759 func.original_name,
6760 "%sBucket" % func.name,
6761 func.info,
6762 func.return_type,
6763 new_args,
6764 new_args_for_cmds,
6765 cmd_args,
6766 new_init_args,
6769 # def InitFunction(self):
6770 # """Overridden from Function"""
6771 # pass
6773 def WriteCommandDescription(self, file):
6774 """Overridden from Function"""
6775 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6776 self.original_name)
6778 def WriteServiceImplementation(self, file):
6779 """Overridden from Function"""
6780 self.type_handler.WriteBucketServiceImplementation(self, file)
6782 def WriteHandlerImplementation(self, file):
6783 """Overridden from Function"""
6784 self.type_handler.WriteBucketHandlerImplementation(self, file)
6786 def WriteServiceUnitTest(self, file):
6787 """Writes the service implementation for a command."""
6788 self.type_handler.WriteBucketServiceUnitTest(self, file)
6791 def CreateArg(arg_string):
6792 """Creates an Argument."""
6793 arg_parts = arg_string.split()
6794 if len(arg_parts) == 1 and arg_parts[0] == 'void':
6795 return None
6796 # Is this a pointer argument?
6797 elif arg_string.find('*') >= 0:
6798 if arg_parts[0] == 'NonImmediate':
6799 return NonImmediatePointerArgument(
6800 arg_parts[-1],
6801 " ".join(arg_parts[1:-1]))
6802 else:
6803 return PointerArgument(
6804 arg_parts[-1],
6805 " ".join(arg_parts[0:-1]))
6806 # Is this a resource argument? Must come after pointer check.
6807 elif arg_parts[0].startswith('GLidBind'):
6808 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6809 elif arg_parts[0].startswith('GLidZero'):
6810 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6811 elif arg_parts[0].startswith('GLid'):
6812 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6813 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
6814 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6815 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
6816 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6817 elif arg_parts[0].startswith('GLboolean'):
6818 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6819 elif arg_parts[0].startswith('GLintUniformLocation'):
6820 return UniformLocationArgument(arg_parts[-1])
6821 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
6822 not arg_parts[0].startswith('GLintptr')):
6823 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6824 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
6825 arg_parts[0].startswith('GLintptrNotNegative')):
6826 return SizeNotNegativeArgument(arg_parts[-1],
6827 " ".join(arg_parts[0:-1]),
6828 arg_parts[0][0:-11])
6829 elif arg_parts[0].startswith('GLsize'):
6830 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6831 else:
6832 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6835 class GLGenerator(object):
6836 """A class to generate GL command buffers."""
6838 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6840 def __init__(self, verbose):
6841 self.original_functions = []
6842 self.functions = []
6843 self.verbose = verbose
6844 self.errors = 0
6845 self._function_info = {}
6846 self._empty_type_handler = TypeHandler()
6847 self._empty_function_info = FunctionInfo({}, self._empty_type_handler)
6848 self.pepper_interfaces = []
6849 self.interface_info = {}
6851 self._type_handlers = {
6852 'Bind': BindHandler(),
6853 'Create': CreateHandler(),
6854 'Custom': CustomHandler(),
6855 'Data': DataHandler(),
6856 'Delete': DeleteHandler(),
6857 'DELn': DELnHandler(),
6858 'GENn': GENnHandler(),
6859 'GETn': GETnHandler(),
6860 'GLchar': GLcharHandler(),
6861 'GLcharN': GLcharNHandler(),
6862 'HandWritten': HandWrittenHandler(),
6863 'Is': IsHandler(),
6864 'Manual': ManualHandler(),
6865 'PUT': PUTHandler(),
6866 'PUTn': PUTnHandler(),
6867 'PUTXn': PUTXnHandler(),
6868 'StateSet': StateSetHandler(),
6869 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6870 'StateSetFrontBack': StateSetFrontBackHandler(),
6871 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6872 'StateSetNamedParameter': StateSetNamedParameter(),
6873 'STRn': STRnHandler(),
6874 'Todo': TodoHandler(),
6877 for func_name in _FUNCTION_INFO:
6878 info = _FUNCTION_INFO[func_name]
6879 type = ''
6880 if 'type' in info:
6881 type = info['type']
6882 self._function_info[func_name] = FunctionInfo(info,
6883 self.GetTypeHandler(type))
6884 for interface in _PEPPER_INTERFACES:
6885 interface = PepperInterface(interface)
6886 self.pepper_interfaces.append(interface)
6887 self.interface_info[interface.GetName()] = interface
6889 def AddFunction(self, func):
6890 """Adds a function."""
6891 self.functions.append(func)
6893 def GetTypeHandler(self, name):
6894 """Gets a type info for the given type."""
6895 if len(name):
6896 if name in self._type_handlers:
6897 return self._type_handlers[name]
6898 else:
6899 raise KeyError("no such type handler: %s" % name)
6900 return self._empty_type_handler
6902 def GetFunctionInfo(self, name):
6903 """Gets a type info for the given function name."""
6904 if name in self._function_info:
6905 return self._function_info[name]
6906 return self._empty_function_info
6908 def Log(self, msg):
6909 """Prints something if verbose is true."""
6910 if self.verbose:
6911 print msg
6913 def Error(self, msg):
6914 """Prints an error."""
6915 print "Error: %s" % msg
6916 self.errors += 1
6918 def WriteLicense(self, file):
6919 """Writes the license."""
6920 file.Write(_LICENSE)
6922 def WriteNamespaceOpen(self, file):
6923 """Writes the code for the namespace."""
6924 file.Write("namespace gpu {\n")
6925 file.Write("namespace gles2 {\n")
6926 file.Write("\n")
6928 def WriteNamespaceClose(self, file):
6929 """Writes the code to close the namespace."""
6930 file.Write("} // namespace gles2\n")
6931 file.Write("} // namespace gpu\n")
6932 file.Write("\n")
6934 def ParseArgs(self, arg_string):
6935 """Parses a function arg string."""
6936 args = []
6937 num_pointer_args = 0
6938 parts = arg_string.split(',')
6939 is_gl_enum = False
6940 for arg_string in parts:
6941 if arg_string.startswith('GLenum '):
6942 is_gl_enum = True
6943 arg = CreateArg(arg_string)
6944 if arg:
6945 args.append(arg)
6946 if arg.IsPointer():
6947 num_pointer_args += 1
6948 return (args, num_pointer_args, is_gl_enum)
6950 def ParseGLH(self, filename):
6951 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6952 f = open(filename, "r")
6953 functions = f.read()
6954 f.close()
6955 for line in functions.splitlines():
6956 match = self._function_re.match(line)
6957 if match:
6958 func_name = match.group(2)[2:]
6959 func_info = self.GetFunctionInfo(func_name)
6960 if func_info.type != 'Noop':
6961 return_type = match.group(1).strip()
6962 arg_string = match.group(3)
6963 (args, num_pointer_args, is_gl_enum) = self.ParseArgs(arg_string)
6964 # comment in to find out which functions use bare enums.
6965 # if is_gl_enum:
6966 # self.Log("%s uses bare GLenum" % func_name)
6967 args_for_cmds = args
6968 if hasattr(func_info, 'cmd_args'):
6969 (args_for_cmds, num_pointer_args, is_gl_enum) = (
6970 self.ParseArgs(getattr(func_info, 'cmd_args')))
6971 cmd_args = []
6972 for arg in args_for_cmds:
6973 arg.AddCmdArgs(cmd_args)
6974 init_args = []
6975 for arg in args_for_cmds:
6976 arg.AddInitArgs(init_args)
6977 return_arg = CreateArg(return_type + " result")
6978 if return_arg:
6979 init_args.append(return_arg)
6980 f = Function(func_name, func_name, func_info, return_type, args,
6981 args_for_cmds, cmd_args, init_args, num_pointer_args)
6982 self.original_functions.append(f)
6983 gen_cmd = f.GetInfo('gen_cmd')
6984 if gen_cmd == True or gen_cmd == None:
6985 self.AddFunction(f)
6986 f.type_handler.AddImmediateFunction(self, f)
6987 f.type_handler.AddBucketFunction(self, f)
6989 self.Log("Auto Generated Functions : %d" %
6990 len([f for f in self.functions if f.can_auto_generate or
6991 (not f.IsType('') and not f.IsType('Custom') and
6992 not f.IsType('Todo'))]))
6994 funcs = [f for f in self.functions if not f.can_auto_generate and
6995 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
6996 self.Log("Non Auto Generated Functions: %d" % len(funcs))
6998 for f in funcs:
6999 self.Log(" %-10s %-20s gl%s" % (f.info.type, f.return_type, f.name))
7001 def WriteCommandIds(self, filename):
7002 """Writes the command buffer format"""
7003 file = CHeaderWriter(filename)
7004 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7005 id = 256
7006 for func in self.functions:
7007 file.Write(" %-60s /* %d */ \\\n" %
7008 ("OP(%s)" % func.name, id))
7009 id += 1
7010 file.Write("\n")
7012 file.Write("enum CommandId {\n")
7013 file.Write(" kStartPoint = cmd::kLastCommonId, "
7014 "// All GLES2 commands start after this.\n")
7015 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7016 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7017 file.Write("#undef GLES2_CMD_OP\n")
7018 file.Write(" kNumCommands\n")
7019 file.Write("};\n")
7020 file.Write("\n")
7021 file.Close()
7023 def WriteFormat(self, filename):
7024 """Writes the command buffer format"""
7025 file = CHeaderWriter(filename)
7026 for func in self.functions:
7027 if True:
7028 #gen_cmd = func.GetInfo('gen_cmd')
7029 #if gen_cmd == True or gen_cmd == None:
7030 func.WriteStruct(file)
7031 file.Write("\n")
7032 file.Close()
7034 def WriteDocs(self, filename):
7035 """Writes the command buffer doc version of the commands"""
7036 file = CWriter(filename)
7037 for func in self.functions:
7038 if True:
7039 #gen_cmd = func.GetInfo('gen_cmd')
7040 #if gen_cmd == True or gen_cmd == None:
7041 func.WriteDocs(file)
7042 file.Write("\n")
7043 file.Close()
7045 def WriteFormatTest(self, filename):
7046 """Writes the command buffer format test."""
7047 file = CHeaderWriter(
7048 filename,
7049 "// This file contains unit tests for gles2 commmands\n"
7050 "// It is included by gles2_cmd_format_test.cc\n"
7051 "\n")
7053 for func in self.functions:
7054 if True:
7055 #gen_cmd = func.GetInfo('gen_cmd')
7056 #if gen_cmd == True or gen_cmd == None:
7057 func.WriteFormatTest(file)
7059 file.Close()
7061 def WriteCmdHelperHeader(self, filename):
7062 """Writes the gles2 command helper."""
7063 file = CHeaderWriter(filename)
7065 for func in self.functions:
7066 if True:
7067 #gen_cmd = func.GetInfo('gen_cmd')
7068 #if gen_cmd == True or gen_cmd == None:
7069 func.WriteCmdHelper(file)
7071 file.Close()
7073 def WriteServiceContextStateHeader(self, filename):
7074 """Writes the service context state header."""
7075 file = CHeaderWriter(
7076 filename,
7077 "// It is included by context_state.h\n")
7078 file.Write("struct EnableFlags {\n")
7079 file.Write(" EnableFlags();\n")
7080 for capability in _CAPABILITY_FLAGS:
7081 file.Write(" bool %s;\n" % capability['name'])
7082 file.Write("};\n\n")
7084 for state_name in sorted(_STATES.keys()):
7085 state = _STATES[state_name]
7086 for item in state['states']:
7087 file.Write("%s %s;\n" % (item['type'], item['name']))
7088 file.Write("\n")
7090 file.Close()
7092 def WriteClientContextStateHeader(self, filename):
7093 """Writes the client context state header."""
7094 file = CHeaderWriter(
7095 filename,
7096 "// It is included by client_context_state.h\n")
7097 file.Write("struct EnableFlags {\n")
7098 file.Write(" EnableFlags();\n")
7099 for capability in _CAPABILITY_FLAGS:
7100 file.Write(" bool %s;\n" % capability['name'])
7101 file.Write("};\n\n")
7103 file.Close()
7105 def WriteContextStateGetters(self, file, class_name):
7106 """Writes the state getters."""
7107 for gl_type in ["GLint", "GLfloat"]:
7108 file.Write("""
7109 bool %s::GetStateAs%s(
7110 GLenum pname, %s* params, GLsizei* num_written) const {
7111 switch (pname) {
7112 """ % (class_name, gl_type, gl_type))
7113 for state_name in sorted(_STATES.keys()):
7114 state = _STATES[state_name]
7115 if 'enum' in state:
7116 file.Write(" case %s:\n" % state['enum'])
7117 file.Write(" *num_written = %d;\n" % len(state['states']))
7118 file.Write(" if (params) {\n")
7119 for ndx,item in enumerate(state['states']):
7120 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7121 (ndx, gl_type, item['name']))
7122 file.Write(" }\n")
7123 file.Write(" return true;\n")
7124 else:
7125 for item in state['states']:
7126 file.Write(" case %s:\n" % item['enum'])
7127 file.Write(" *num_written = 1;\n")
7128 file.Write(" if (params) {\n")
7129 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7130 (gl_type, item['name']))
7131 file.Write(" }\n")
7132 file.Write(" return true;\n")
7133 for capability in _CAPABILITY_FLAGS:
7134 file.Write(" case GL_%s:\n" % capability['name'].upper())
7135 file.Write(" *num_written = 1;\n")
7136 file.Write(" if (params) {\n")
7137 file.Write(
7138 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7139 (gl_type, capability['name']))
7140 file.Write(" }\n")
7141 file.Write(" return true;\n")
7142 file.Write(""" default:
7143 return false;
7146 """)
7148 def WriteServiceContextStateImpl(self, filename):
7149 """Writes the context state service implementation."""
7150 file = CHeaderWriter(
7151 filename,
7152 "// It is included by context_state.cc\n")
7153 code = []
7154 for capability in _CAPABILITY_FLAGS:
7155 code.append("%s(%s)" %
7156 (capability['name'],
7157 ('false', 'true')['default' in capability]))
7158 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7159 ",\n ".join(code))
7160 file.Write("\n")
7162 file.Write("void ContextState::Initialize() {\n")
7163 for state_name in sorted(_STATES.keys()):
7164 state = _STATES[state_name]
7165 for item in state['states']:
7166 file.Write(" %s = %s;\n" % (item['name'], item['default']))
7167 file.Write("}\n")
7169 file.Write("""
7170 void ContextState::InitCapabilities(const ContextState* prev_state) const {
7171 """)
7172 def WriteCapabilities(test_prev):
7173 for capability in _CAPABILITY_FLAGS:
7174 capability_name = capability['name']
7175 if test_prev:
7176 file.Write(" if (prev_state->enable_flags.%s != enable_flags.%s)\n" %
7177 (capability_name, capability_name))
7178 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7179 (capability_name.upper(), capability_name))
7181 file.Write(" if (prev_state) {")
7182 WriteCapabilities(True)
7183 file.Write(" } else {")
7184 WriteCapabilities(False)
7185 file.Write(" }")
7187 file.Write("""}
7189 void ContextState::InitState(const ContextState *prev_state) const {
7190 """)
7192 def WriteStates(test_prev):
7193 # We need to sort the keys so the expectations match
7194 for state_name in sorted(_STATES.keys()):
7195 state = _STATES[state_name]
7196 if state['type'] == 'FrontBack':
7197 num_states = len(state['states'])
7198 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7199 if test_prev:
7200 file.Write(" if (")
7201 args = []
7202 for place, item in enumerate(group):
7203 item_name = item['name']
7204 args.append('%s' % item_name)
7205 if test_prev:
7206 if place > 0:
7207 file.Write(' ||\n')
7208 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
7209 if test_prev:
7210 file.Write(")\n")
7211 file.Write(
7212 " gl%s(%s, %s);\n" %
7213 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7214 elif state['type'] == 'NamedParameter':
7215 for item in state['states']:
7216 if 'extension_flag' in item:
7217 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7218 item['extension_flag'])
7219 if test_prev:
7220 file.Write(" if (prev_state->%s != %s)\n" %
7221 (item['name'], item['name']))
7222 file.Write(" gl%s(%s, %s);\n" %
7223 (state['func'], item['enum'], item['name']))
7224 else:
7225 if test_prev:
7226 file.Write(" if (")
7227 args = []
7228 for place, item in enumerate(state['states']):
7229 item_name = item['name']
7230 args.append('%s' % item_name)
7231 if test_prev:
7232 if place > 0:
7233 file.Write(' ||\n')
7234 file.Write("(%s != prev_state->%s)" %
7235 (item_name, item_name))
7236 if test_prev:
7237 file.Write(" )\n")
7238 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
7240 file.Write(" if (prev_state) {")
7241 WriteStates(True)
7242 file.Write(" } else {")
7243 WriteStates(False)
7244 file.Write(" }")
7246 file.Write("}\n")
7248 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7249 switch (cap) {
7250 """)
7251 for capability in _CAPABILITY_FLAGS:
7252 file.Write(" case GL_%s:\n" % capability['name'].upper())
7253 file.Write(" return enable_flags.%s;\n" % capability['name'])
7254 file.Write(""" default:
7255 NOTREACHED();
7256 return false;
7259 """)
7261 self.WriteContextStateGetters(file, "ContextState")
7262 file.Close()
7264 def WriteClientContextStateImpl(self, filename):
7265 """Writes the context state client side implementation."""
7266 file = CHeaderWriter(
7267 filename,
7268 "// It is included by client_context_state.cc\n")
7269 code = []
7270 for capability in _CAPABILITY_FLAGS:
7271 code.append("%s(%s)" %
7272 (capability['name'],
7273 ('false', 'true')['default' in capability]))
7274 file.Write(
7275 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7276 ",\n ".join(code))
7277 file.Write("\n")
7279 file.Write("""
7280 bool ClientContextState::SetCapabilityState(
7281 GLenum cap, bool enabled, bool* changed) {
7282 *changed = false;
7283 switch (cap) {
7284 """)
7285 for capability in _CAPABILITY_FLAGS:
7286 file.Write(" case GL_%s:\n" % capability['name'].upper())
7287 file.Write(""" if (enable_flags.%(name)s != enabled) {
7288 *changed = true;
7289 enable_flags.%(name)s = enabled;
7291 return true;
7292 """ % capability)
7293 file.Write(""" default:
7294 return false;
7297 """)
7298 file.Write("""bool ClientContextState::GetEnabled(
7299 GLenum cap, bool* enabled) const {
7300 switch (cap) {
7301 """)
7302 for capability in _CAPABILITY_FLAGS:
7303 file.Write(" case GL_%s:\n" % capability['name'].upper())
7304 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
7305 file.Write(" return true;\n")
7306 file.Write(""" default:
7307 return false;
7310 """)
7311 file.Close()
7313 def WriteServiceImplementation(self, filename):
7314 """Writes the service decorder implementation."""
7315 file = CHeaderWriter(
7316 filename,
7317 "// It is included by gles2_cmd_decoder.cc\n")
7319 for func in self.functions:
7320 if True:
7321 #gen_cmd = func.GetInfo('gen_cmd')
7322 #if gen_cmd == True or gen_cmd == None:
7323 func.WriteServiceImplementation(file)
7325 file.Write("""
7326 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7327 switch (cap) {
7328 """)
7329 for capability in _CAPABILITY_FLAGS:
7330 file.Write(" case GL_%s:\n" % capability['name'].upper())
7331 if 'state_flag' in capability:
7332 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7333 state_.enable_flags.%(name)s = enabled;
7334 %(state_flag)s = true;
7336 return false;
7337 """ % capability)
7338 else:
7339 file.Write(""" state_.enable_flags.%(name)s = enabled;
7340 return true;
7341 """ % capability)
7342 file.Write(""" default:
7343 NOTREACHED();
7344 return false;
7347 """)
7348 file.Close()
7350 def WriteServiceUnitTests(self, filename):
7351 """Writes the service decorder unit tests."""
7352 num_tests = len(self.functions)
7353 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
7354 count = 0
7355 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
7356 count += 1
7357 name = filename % count
7358 file = CHeaderWriter(
7359 name,
7360 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
7361 file.SetFileNum(count)
7362 end = test_num + FUNCTIONS_PER_FILE
7363 if end > num_tests:
7364 end = num_tests
7365 for idx in range(test_num, end):
7366 func = self.functions[idx]
7367 if True:
7368 #gen_cmd = func.GetInfo('gen_cmd')
7369 #if gen_cmd == True or gen_cmd == None:
7370 if func.GetInfo('unit_test') == False:
7371 file.Write("// TODO(gman): %s\n" % func.name)
7372 else:
7373 func.WriteServiceUnitTest(file)
7375 file.Close()
7376 file = CHeaderWriter(
7377 filename % 0,
7378 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7379 file.Write(
7380 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7381 """)
7382 for capability in _CAPABILITY_FLAGS:
7383 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7384 (capability['name'].upper(),
7385 ('false', 'true')['default' in capability]))
7386 file.Write("""}
7388 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7389 """)
7391 # We need to sort the keys so the expectations match
7392 for state_name in sorted(_STATES.keys()):
7393 state = _STATES[state_name]
7394 if state['type'] == 'FrontBack':
7395 num_states = len(state['states'])
7396 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7397 args = []
7398 for item in group:
7399 if 'expected' in item:
7400 args.append(item['expected'])
7401 else:
7402 args.append(item['default'])
7403 file.Write(
7404 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7405 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7406 file.Write(" .Times(1)\n")
7407 file.Write(" .RetiresOnSaturation();\n")
7408 elif state['type'] == 'NamedParameter':
7409 for item in state['states']:
7410 if 'extension_flag' in item:
7411 continue
7412 file.Write(
7413 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7414 (state['func'], item['enum'], item['default']))
7415 file.Write(" .Times(1)\n")
7416 file.Write(" .RetiresOnSaturation();\n")
7417 else:
7418 args = []
7419 for item in state['states']:
7420 if 'expected' in item:
7421 args.append(item['expected'])
7422 else:
7423 args.append(item['default'])
7424 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7425 (state['func'], ", ".join(args)))
7426 file.Write(" .Times(1)\n")
7427 file.Write(" .RetiresOnSaturation();\n")
7428 file.Write("""}
7429 """)
7430 file.Close()
7432 def WriteGLES2Header(self, filename):
7433 """Writes the GLES2 header."""
7434 file = CHeaderWriter(
7435 filename,
7436 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7438 for func in self.original_functions:
7439 func.WriteGLES2Header(file)
7441 file.Write("\n")
7442 file.Close()
7444 def WriteGLES2CLibImplementation(self, filename):
7445 """Writes the GLES2 c lib implementation."""
7446 file = CHeaderWriter(
7447 filename,
7448 "// These functions emulate GLES2 over command buffers.\n")
7450 for func in self.original_functions:
7451 func.WriteGLES2CLibImplementation(file)
7453 file.Write("""
7454 namespace gles2 {
7456 extern const NameToFunc g_gles2_function_table[] = {
7457 """)
7458 for func in self.original_functions:
7459 file.Write(
7460 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7461 (func.name, func.name))
7462 file.Write(""" { NULL, NULL, },
7465 } // namespace gles2
7466 """)
7467 file.Close()
7469 def WriteGLES2InterfaceHeader(self, filename):
7470 """Writes the GLES2 interface header."""
7471 file = CHeaderWriter(
7472 filename,
7473 "// This file is included by gles2_interface.h to declare the\n"
7474 "// GL api functions.\n")
7475 for func in self.original_functions:
7476 func.WriteGLES2InterfaceHeader(file)
7477 file.Close()
7479 def WriteGLES2InterfaceStub(self, filename):
7480 """Writes the GLES2 interface stub header."""
7481 file = CHeaderWriter(
7482 filename,
7483 "// This file is included by gles2_interface_stub.h.\n")
7484 for func in self.original_functions:
7485 func.WriteGLES2InterfaceStub(file)
7486 file.Close()
7488 def WriteGLES2InterfaceStubImpl(self, filename):
7489 """Writes the GLES2 interface header."""
7490 file = CHeaderWriter(
7491 filename,
7492 "// This file is included by gles2_interface_stub.cc.\n")
7493 for func in self.original_functions:
7494 func.WriteGLES2InterfaceStubImpl(file)
7495 file.Close()
7497 def WriteGLES2ImplementationHeader(self, filename):
7498 """Writes the GLES2 Implementation header."""
7499 file = CHeaderWriter(
7500 filename,
7501 "// This file is included by gles2_implementation.h to declare the\n"
7502 "// GL api functions.\n")
7503 for func in self.original_functions:
7504 func.WriteGLES2ImplementationHeader(file)
7505 file.Close()
7507 def WriteGLES2Implementation(self, filename):
7508 """Writes the GLES2 Implementation."""
7509 file = CHeaderWriter(
7510 filename,
7511 "// This file is included by gles2_implementation.cc to define the\n"
7512 "// GL api functions.\n")
7513 for func in self.original_functions:
7514 func.WriteGLES2Implementation(file)
7515 file.Close()
7517 def WriteGLES2TraceImplementationHeader(self, filename):
7518 """Writes the GLES2 Trace Implementation header."""
7519 file = CHeaderWriter(
7520 filename,
7521 "// This file is included by gles2_trace_implementation.h\n")
7522 for func in self.original_functions:
7523 func.WriteGLES2TraceImplementationHeader(file)
7524 file.Close()
7526 def WriteGLES2TraceImplementation(self, filename):
7527 """Writes the GLES2 Trace Implementation."""
7528 file = CHeaderWriter(
7529 filename,
7530 "// This file is included by gles2_trace_implementation.cc\n")
7531 for func in self.original_functions:
7532 func.WriteGLES2TraceImplementation(file)
7533 file.Close()
7535 def WriteGLES2ImplementationUnitTests(self, filename):
7536 """Writes the GLES2 helper header."""
7537 file = CHeaderWriter(
7538 filename,
7539 "// This file is included by gles2_implementation.h to declare the\n"
7540 "// GL api functions.\n")
7541 for func in self.original_functions:
7542 func.WriteGLES2ImplementationUnitTest(file)
7543 file.Close()
7545 def WriteServiceUtilsHeader(self, filename):
7546 """Writes the gles2 auto generated utility header."""
7547 file = CHeaderWriter(filename)
7548 for enum in sorted(_ENUM_LISTS.keys()):
7549 file.Write("ValueValidator<%s> %s;\n" %
7550 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7551 file.Write("\n")
7552 file.Close()
7554 def WriteServiceUtilsImplementation(self, filename):
7555 """Writes the gles2 auto generated utility implementation."""
7556 file = CHeaderWriter(filename)
7557 enums = sorted(_ENUM_LISTS.keys())
7558 for enum in enums:
7559 if len(_ENUM_LISTS[enum]['valid']) > 0:
7560 file.Write("static const %s valid_%s_table[] = {\n" %
7561 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7562 for value in _ENUM_LISTS[enum]['valid']:
7563 file.Write(" %s,\n" % value)
7564 file.Write("};\n")
7565 file.Write("\n")
7566 file.Write("Validators::Validators()\n")
7567 pre = ': '
7568 post = ','
7569 for count, enum in enumerate(enums):
7570 if count + 1 == len(enums):
7571 post = ' {'
7572 if len(_ENUM_LISTS[enum]['valid']) > 0:
7573 code = """ %(pre)s%(name)s(
7574 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7576 else:
7577 code = """ %(pre)s%(name)s()%(post)s
7579 file.Write(code % {
7580 'name': ToUnderscore(enum),
7581 'pre': pre,
7582 'post': post,
7584 pre = ' '
7585 file.Write("}\n\n");
7586 file.Close()
7588 def WriteCommonUtilsHeader(self, filename):
7589 """Writes the gles2 common utility header."""
7590 file = CHeaderWriter(filename)
7591 enums = sorted(_ENUM_LISTS.keys())
7592 for enum in enums:
7593 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7594 file.Write("static std::string GetString%s(uint32 value);\n" % enum)
7595 file.Write("\n")
7596 file.Close()
7598 def WriteCommonUtilsImpl(self, filename):
7599 """Writes the gles2 common utility header."""
7600 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7601 dict = {}
7602 for fname in ['../../third_party/khronos/GLES2/gl2.h',
7603 '../../third_party/khronos/GLES2/gl2ext.h',
7604 '../../gpu/GLES2/gl2chromium.h',
7605 '../../gpu/GLES2/gl2extchromium.h']:
7606 lines = open(fname).readlines()
7607 for line in lines:
7608 m = enum_re.match(line)
7609 if m:
7610 name = m.group(1)
7611 value = m.group(2)
7612 if len(value) <= 10 and not value in dict:
7613 dict[value] = name
7615 file = CHeaderWriter(filename)
7616 file.Write("static const GLES2Util::EnumToString "
7617 "enum_to_string_table[] = {\n")
7618 for value in dict:
7619 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
7620 file.Write("""};
7622 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7623 enum_to_string_table;
7624 const size_t GLES2Util::enum_to_string_table_len_ =
7625 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7627 """)
7629 enums = sorted(_ENUM_LISTS.keys())
7630 for enum in enums:
7631 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7632 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7633 enum)
7634 if len(_ENUM_LISTS[enum]['valid']) > 0:
7635 file.Write(" static const EnumToString string_table[] = {\n")
7636 for value in _ENUM_LISTS[enum]['valid']:
7637 file.Write(' { %s, "%s" },\n' % (value, value))
7638 file.Write(""" };
7639 return GLES2Util::GetQualifiedEnumString(
7640 string_table, arraysize(string_table), value);
7643 """)
7644 else:
7645 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7646 NULL, 0, value);
7649 """)
7650 file.Close()
7652 def WritePepperGLES2Interface(self, filename, dev):
7653 """Writes the Pepper OpenGLES interface definition."""
7654 file = CHeaderWriter(
7655 filename,
7656 "// OpenGL ES interface.\n")
7658 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7659 if dev:
7660 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7661 else:
7662 file.Write("\n#ifndef __gl2_h_\n")
7663 for (k, v) in _GL_TYPES.iteritems():
7664 file.Write("typedef %s %s;\n" % (v, k))
7665 file.Write("#ifdef _WIN64\n")
7666 for (k, v) in _GL_TYPES_64.iteritems():
7667 file.Write("typedef %s %s;\n" % (v, k))
7668 file.Write("#else\n")
7669 for (k, v) in _GL_TYPES_32.iteritems():
7670 file.Write("typedef %s %s;\n" % (v, k))
7671 file.Write("#endif // _WIN64\n")
7672 file.Write("#endif // __gl2_h_\n\n")
7674 for interface in self.pepper_interfaces:
7675 if interface.dev != dev:
7676 continue
7677 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7678 (interface.GetInterfaceName(), interface.GetInterfaceString()))
7679 file.Write("#define %s %s_1_0\n" %
7680 (interface.GetInterfaceName(), interface.GetInterfaceName()))
7682 file.Write("\nstruct %s {\n" % interface.GetStructName())
7683 for func in self.original_functions:
7684 if not func.InPepperInterface(interface):
7685 continue
7687 original_arg = func.MakeTypedPepperArgString("")
7688 context_arg = "PP_Resource context"
7689 if len(original_arg):
7690 arg = context_arg + ", " + original_arg
7691 else:
7692 arg = context_arg
7693 file.Write(" %s (*%s)(%s);\n" %
7694 (func.return_type, func.GetPepperName(), arg))
7695 file.Write("};\n\n")
7698 file.Close()
7700 def WritePepperGLES2Implementation(self, filename):
7701 """Writes the Pepper OpenGLES interface implementation."""
7703 file = CWriter(filename)
7704 file.Write(_LICENSE)
7705 file.Write(_DO_NOT_EDIT_WARNING)
7707 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7708 file.Write("#include \"base/logging.h\"\n")
7709 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7710 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7711 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7713 file.Write("namespace ppapi {\n\n")
7714 file.Write("namespace {\n\n")
7716 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7717 " Enter3D;\n\n")
7719 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
7720 " enter) {\n")
7721 file.Write(" DCHECK(enter);\n")
7722 file.Write(" DCHECK(enter->succeeded());\n")
7723 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
7724 "gles2_impl();\n");
7725 file.Write("}\n\n");
7727 for func in self.original_functions:
7728 if not func.InAnyPepperExtension():
7729 continue
7731 original_arg = func.MakeTypedPepperArgString("")
7732 context_arg = "PP_Resource context_id"
7733 if len(original_arg):
7734 arg = context_arg + ", " + original_arg
7735 else:
7736 arg = context_arg
7737 file.Write("%s %s(%s) {\n" %
7738 (func.return_type, func.GetPepperName(), arg))
7739 file.Write(" Enter3D enter(context_id, true);\n")
7740 file.Write(" if (enter.succeeded()) {\n")
7742 return_str = "" if func.return_type == "void" else "return "
7743 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
7744 (return_str, func.original_name,
7745 func.MakeOriginalArgString("")))
7746 file.Write(" }")
7747 if func.return_type == "void":
7748 file.Write("\n")
7749 else:
7750 file.Write(" else {\n")
7751 error_return = "0"
7752 if func.GetInfo("error_return"):
7753 error_return = func.GetInfo("error_return")
7754 elif func.return_type == "GLboolean":
7755 error_return = "GL_FALSE"
7756 elif "*" in func.return_type:
7757 error_return = "NULL"
7758 file.Write(" return %s;\n" % error_return)
7759 file.Write(" }\n")
7760 file.Write("}\n\n")
7762 file.Write("} // namespace\n")
7764 for interface in self.pepper_interfaces:
7765 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7766 (interface.GetStructName(), interface.GetName()))
7767 file.Write(" static const struct %s "
7768 "ppb_opengles2 = {\n" % interface.GetStructName())
7769 file.Write(" &")
7770 file.Write(",\n &".join(
7771 f.GetPepperName() for f in self.original_functions
7772 if f.InPepperInterface(interface)))
7773 file.Write("\n")
7775 file.Write(" };\n")
7776 file.Write(" return &ppb_opengles2;\n")
7777 file.Write("}\n")
7779 file.Write("} // namespace ppapi\n")
7780 file.Close()
7782 def WriteGLES2ToPPAPIBridge(self, filename):
7783 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7785 file = CWriter(filename)
7786 file.Write(_LICENSE)
7787 file.Write(_DO_NOT_EDIT_WARNING)
7789 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7790 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7791 file.Write("#endif\n")
7792 file.Write("#include <GLES2/gl2.h>\n")
7793 file.Write("#include <GLES2/gl2ext.h>\n")
7794 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7796 for func in self.original_functions:
7797 if not func.InAnyPepperExtension():
7798 continue
7800 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
7802 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7803 (func.return_type, func.GetPepperName(),
7804 func.MakeTypedPepperArgString("")))
7805 return_str = "" if func.return_type == "void" else "return "
7806 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
7807 original_arg = func.MakeOriginalArgString("")
7808 context_arg = "glGetCurrentContextPPAPI()"
7809 if len(original_arg):
7810 arg = context_arg + ", " + original_arg
7811 else:
7812 arg = context_arg
7813 if interface.GetName():
7814 file.Write(" const struct %s* ext = %s;\n" %
7815 (interface.GetStructName(), interface_str))
7816 file.Write(" if (ext)\n")
7817 file.Write(" %sext->%s(%s);\n" %
7818 (return_str, func.GetPepperName(), arg))
7819 if return_str:
7820 file.Write(" %s0;\n" % return_str)
7821 else:
7822 file.Write(" %s%s->%s(%s);\n" %
7823 (return_str, interface_str, func.GetPepperName(), arg))
7824 file.Write("}\n\n")
7825 file.Close()
7827 def WriteMojoGLCallVisitor(self, filename):
7828 """Provides the GL implementation for mojo"""
7829 file = CWriter(filename)
7830 file.Write(_LICENSE)
7831 file.Write(_DO_NOT_EDIT_WARNING)
7833 for func in self.original_functions:
7834 if not func.IsCoreGLFunction():
7835 continue
7836 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
7837 (func.name, func.return_type,
7838 func.MakeTypedOriginalArgString(""),
7839 func.MakeOriginalArgString("")))
7841 file.Close()
7843 def Format(generated_files):
7844 for filename in generated_files:
7845 call(["clang-format", "-i", "-style=chromium", filename])
7847 def main(argv):
7848 """This is the main function."""
7849 parser = OptionParser()
7850 parser.add_option(
7851 "--output-dir",
7852 help="base directory for resulting files, under chrome/src. default is "
7853 "empty. Use this if you want the result stored under gen.")
7854 parser.add_option(
7855 "-v", "--verbose", action="store_true",
7856 help="prints more output.")
7858 (options, args) = parser.parse_args(args=argv)
7860 # Add in states and capabilites to GLState
7861 for state_name in sorted(_STATES.keys()):
7862 state = _STATES[state_name]
7863 if 'enum' in state:
7864 _ENUM_LISTS['GLState']['valid'].append(state['enum'])
7865 else:
7866 for item in state['states']:
7867 if 'extension_flag' in item:
7868 continue
7869 _ENUM_LISTS['GLState']['valid'].append(item['enum'])
7870 for capability in _CAPABILITY_FLAGS:
7871 _ENUM_LISTS['GLState']['valid'].append("GL_%s" % capability['name'].upper())
7873 # This script lives under gpu/command_buffer, cd to base directory.
7874 os.chdir(os.path.dirname(__file__) + "/../..")
7876 gen = GLGenerator(options.verbose)
7877 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
7879 # Support generating files under gen/
7880 if options.output_dir != None:
7881 os.chdir(options.output_dir)
7883 gen.WritePepperGLES2Interface("ppapi/c/ppb_opengles2.h", False)
7884 gen.WritePepperGLES2Interface("ppapi/c/dev/ppb_opengles2ext_dev.h", True)
7885 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
7886 gen.WritePepperGLES2Implementation(
7887 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7888 os.chdir("gpu/command_buffer")
7889 gen.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7890 gen.WriteFormat("common/gles2_cmd_format_autogen.h")
7891 gen.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7892 gen.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7893 gen.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7894 gen.WriteGLES2InterfaceStubImpl(
7895 "client/gles2_interface_stub_impl_autogen.h")
7896 gen.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7897 gen.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7898 gen.WriteGLES2ImplementationUnitTests(
7899 "client/gles2_implementation_unittest_autogen.h")
7900 gen.WriteGLES2TraceImplementationHeader(
7901 "client/gles2_trace_implementation_autogen.h")
7902 gen.WriteGLES2TraceImplementation(
7903 "client/gles2_trace_implementation_impl_autogen.h")
7904 gen.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7905 gen.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7906 gen.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7907 gen.WriteServiceContextStateHeader("service/context_state_autogen.h")
7908 gen.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7909 gen.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7910 gen.WriteClientContextStateImpl(
7911 "client/client_context_state_impl_autogen.h")
7912 gen.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7913 gen.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7914 gen.WriteServiceUtilsImplementation(
7915 "service/gles2_cmd_validation_implementation_autogen.h")
7916 gen.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7917 gen.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7918 gen.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7919 gen.WriteMojoGLCallVisitor(
7920 "../../mojo/public/c/gles2/gles2_call_visitor_autogen.h")
7922 Format([
7923 "common/gles2_cmd_format_autogen.h",
7924 "common/gles2_cmd_format_test_autogen.h",
7925 "common/gles2_cmd_ids_autogen.h",
7926 "common/gles2_cmd_utils_autogen.h",
7927 "common/gles2_cmd_utils_implementation_autogen.h",
7928 "client/client_context_state_autogen.h",
7929 "client/client_context_state_impl_autogen.h",
7930 "client/gles2_cmd_helper_autogen.h",
7931 "client/gles2_c_lib_autogen.h",
7932 "client/gles2_implementation_autogen.h",
7933 "client/gles2_implementation_impl_autogen.h",
7934 "client/gles2_implementation_unittest_autogen.h",
7935 "client/gles2_interface_autogen.h",
7936 "client/gles2_interface_stub_autogen.h",
7937 "client/gles2_interface_stub_impl_autogen.h",
7938 "client/gles2_trace_implementation_autogen.h",
7939 "client/gles2_trace_implementation_impl_autogen.h",
7940 "service/context_state_autogen.h",
7941 "service/context_state_impl_autogen.h",
7942 "service/gles2_cmd_decoder_autogen.h",
7943 "service/gles2_cmd_decoder_unittest_0_autogen.h",
7944 "service/gles2_cmd_decoder_unittest_1_autogen.h",
7945 "service/gles2_cmd_decoder_unittest_2_autogen.h",
7946 "service/gles2_cmd_decoder_unittest_3_autogen.h",
7947 "service/gles2_cmd_validation_autogen.h",
7948 "service/gles2_cmd_validation_implementation_autogen.h"])
7949 os.chdir("../..")
7950 Format([
7951 "gpu/GLES2/gl2chromium_autogen.h",
7952 "mojo/public/c/gles2/gles2_call_visitor_autogen.h",
7953 "ppapi/c/dev/ppb_opengles2ext_dev.h",
7954 "ppapi/c/ppb_opengles2.h",
7955 "ppapi/lib/gl/gles2/gles2.c",
7956 "ppapi/shared_impl/ppb_opengles2_shared.cc"])
7958 if gen.errors > 0:
7959 print "%d errors" % gen.errors
7960 return 1
7961 return 0
7964 if __name__ == '__main__':
7965 sys.exit(main(sys.argv[1:]))