Add explicit |forceOnlineSignin| to user pod status
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob8548e1dcf5e4787c32d88c3cc63d8709d7a36ed1
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
15 _SIZE_OF_UINT32 = 4
16 _SIZE_OF_COMMAND_HEADER = 4
17 _FIRST_SPECIFIC_COMMAND_ID = 256
19 _LICENSE = """// Copyright (c) 2012 The Chromium Authors. All rights reserved.
20 // Use of this source code is governed by a BSD-style license that can be
21 // found in the LICENSE file.
23 """
25 _DO_NOT_EDIT_WARNING = """// This file is auto-generated from
26 // gpu/command_buffer/build_gles2_cmd_buffer.py
27 // DO NOT EDIT!
29 """
31 # This string is copied directly out of the gl2.h file from GLES2.0
33 # Edits:
35 # *) Any argument that is a resourceID has been changed to GLid<Type>.
36 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
37 # If it's allowed to not exist it's GLidBind<Type>
39 # *) All GLenums have been changed to GLenumTypeOfEnum
41 _GL_TYPES = {
42 'GLenum': 'unsigned int',
43 'GLboolean': 'unsigned char',
44 'GLbitfield': 'unsigned int',
45 'GLbyte': 'signed char',
46 'GLshort': 'short',
47 'GLint': 'int',
48 'GLsizei': 'int',
49 'GLubyte': 'unsigned char',
50 'GLushort': 'unsigned short',
51 'GLuint': 'unsigned int',
52 'GLfloat': 'float',
53 'GLclampf': 'float',
54 'GLvoid': 'void',
55 'GLfixed': 'int',
56 'GLclampx': 'int'
59 _GL_TYPES_32 = {
60 'GLintptr': 'long int',
61 'GLsizeiptr': 'long int'
64 _GL_TYPES_64 = {
65 'GLintptr': 'long long int',
66 'GLsizeiptr': 'long long int'
69 # Capabilites selected with glEnable
70 _CAPABILITY_FLAGS = [
71 {'name': 'blend'},
72 {'name': 'cull_face'},
73 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
74 {'name': 'dither', 'default': True},
75 {'name': 'polygon_offset_fill'},
76 {'name': 'sample_alpha_to_coverage'},
77 {'name': 'sample_coverage'},
78 {'name': 'scissor_test',
79 'state_flag': 'framebuffer_state_.clear_state_dirty'},
80 {'name': 'stencil_test',
81 'state_flag': 'framebuffer_state_.clear_state_dirty'},
84 _STATES = {
85 'ClearColor': {
86 'type': 'Normal',
87 'func': 'ClearColor',
88 'enum': 'GL_COLOR_CLEAR_VALUE',
89 'states': [
90 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
91 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
92 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
93 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
96 'ClearDepthf': {
97 'type': 'Normal',
98 'func': 'ClearDepth',
99 'enum': 'GL_DEPTH_CLEAR_VALUE',
100 'states': [
101 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
104 'ColorMask': {
105 'type': 'Normal',
106 'func': 'ColorMask',
107 'enum': 'GL_COLOR_WRITEMASK',
108 'states': [
109 {'name': 'color_mask_red', 'type': 'GLboolean', 'default': 'true'},
110 {'name': 'color_mask_green', 'type': 'GLboolean', 'default': 'true'},
111 {'name': 'color_mask_blue', 'type': 'GLboolean', 'default': 'true'},
112 {'name': 'color_mask_alpha', 'type': 'GLboolean', 'default': 'true'},
114 'state_flag': 'framebuffer_state_.clear_state_dirty',
116 'ClearStencil': {
117 'type': 'Normal',
118 'func': 'ClearStencil',
119 'enum': 'GL_STENCIL_CLEAR_VALUE',
120 'states': [
121 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
124 'BlendColor': {
125 'type': 'Normal',
126 'func': 'BlendColor',
127 'enum': 'GL_BLEND_COLOR',
128 'states': [
129 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
130 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
131 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
132 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
135 'BlendEquation': {
136 'type': 'SrcDst',
137 'func': 'BlendEquationSeparate',
138 'states': [
140 'name': 'blend_equation_rgb',
141 'type': 'GLenum',
142 'enum': 'GL_BLEND_EQUATION_RGB',
143 'default': 'GL_FUNC_ADD',
146 'name': 'blend_equation_alpha',
147 'type': 'GLenum',
148 'enum': 'GL_BLEND_EQUATION_ALPHA',
149 'default': 'GL_FUNC_ADD',
153 'BlendFunc': {
154 'type': 'SrcDst',
155 'func': 'BlendFuncSeparate',
156 'states': [
158 'name': 'blend_source_rgb',
159 'type': 'GLenum',
160 'enum': 'GL_BLEND_SRC_RGB',
161 'default': 'GL_ONE',
164 'name': 'blend_dest_rgb',
165 'type': 'GLenum',
166 'enum': 'GL_BLEND_DST_RGB',
167 'default': 'GL_ZERO',
170 'name': 'blend_source_alpha',
171 'type': 'GLenum',
172 'enum': 'GL_BLEND_SRC_ALPHA',
173 'default': 'GL_ONE',
176 'name': 'blend_dest_alpha',
177 'type': 'GLenum',
178 'enum': 'GL_BLEND_DST_ALPHA',
179 'default': 'GL_ZERO',
183 'PolygonOffset': {
184 'type': 'Normal',
185 'func': 'PolygonOffset',
186 'states': [
188 'name': 'polygon_offset_factor',
189 'type': 'GLfloat',
190 'enum': 'GL_POLYGON_OFFSET_FACTOR',
191 'default': '0.0f',
194 'name': 'polygon_offset_units',
195 'type': 'GLfloat',
196 'enum': 'GL_POLYGON_OFFSET_UNITS',
197 'default': '0.0f',
201 'CullFace': {
202 'type': 'Normal',
203 'func': 'CullFace',
204 'enum': 'GL_CULL_FACE_MODE',
205 'states': [
207 'name': 'cull_mode',
208 'type': 'GLenum',
209 'default': 'GL_BACK',
213 'FrontFace': {
214 'type': 'Normal',
215 'func': 'FrontFace',
216 'enum': 'GL_FRONT_FACE',
217 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
219 'DepthFunc': {
220 'type': 'Normal',
221 'func': 'DepthFunc',
222 'enum': 'GL_DEPTH_FUNC',
223 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
225 'DepthRange': {
226 'type': 'Normal',
227 'func': 'DepthRange',
228 'enum': 'GL_DEPTH_RANGE',
229 'states': [
230 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
231 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
234 'SampleCoverage': {
235 'type': 'Normal',
236 'func': 'SampleCoverage',
237 'states': [
239 'name': 'sample_coverage_value',
240 'type': 'GLclampf',
241 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
242 'default': '1.0f',
245 'name': 'sample_coverage_invert',
246 'type': 'GLboolean',
247 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
248 'default': 'false',
252 'StencilMask': {
253 'type': 'FrontBack',
254 'func': 'StencilMaskSeparate',
255 'state_flag': 'framebuffer_state_.clear_state_dirty',
256 'states': [
258 'name': 'stencil_front_writemask',
259 'type': 'GLuint',
260 'enum': 'GL_STENCIL_WRITEMASK',
261 'default': '0xFFFFFFFFU',
264 'name': 'stencil_back_writemask',
265 'type': 'GLuint',
266 'enum': 'GL_STENCIL_BACK_WRITEMASK',
267 'default': '0xFFFFFFFFU',
271 'StencilOp': {
272 'type': 'FrontBack',
273 'func': 'StencilOpSeparate',
274 'states': [
276 'name': 'stencil_front_fail_op',
277 'type': 'GLenum',
278 'enum': 'GL_STENCIL_FAIL',
279 'default': 'GL_KEEP',
282 'name': 'stencil_front_z_fail_op',
283 'type': 'GLenum',
284 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
285 'default': 'GL_KEEP',
288 'name': 'stencil_front_z_pass_op',
289 'type': 'GLenum',
290 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
291 'default': 'GL_KEEP',
294 'name': 'stencil_back_fail_op',
295 'type': 'GLenum',
296 'enum': 'GL_STENCIL_BACK_FAIL',
297 'default': 'GL_KEEP',
300 'name': 'stencil_back_z_fail_op',
301 'type': 'GLenum',
302 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
303 'default': 'GL_KEEP',
306 'name': 'stencil_back_z_pass_op',
307 'type': 'GLenum',
308 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
309 'default': 'GL_KEEP',
313 'StencilFunc': {
314 'type': 'FrontBack',
315 'func': 'StencilFuncSeparate',
316 'states': [
318 'name': 'stencil_front_func',
319 'type': 'GLenum',
320 'enum': 'GL_STENCIL_FUNC',
321 'default': 'GL_ALWAYS',
324 'name': 'stencil_front_ref',
325 'type': 'GLint',
326 'enum': 'GL_STENCIL_REF',
327 'default': '0',
330 'name': 'stencil_front_mask',
331 'type': 'GLuint',
332 'enum': 'GL_STENCIL_VALUE_MASK',
333 'default': '0xFFFFFFFFU',
336 'name': 'stencil_back_func',
337 'type': 'GLenum',
338 'enum': 'GL_STENCIL_BACK_FUNC',
339 'default': 'GL_ALWAYS',
342 'name': 'stencil_back_ref',
343 'type': 'GLint',
344 'enum': 'GL_STENCIL_BACK_REF',
345 'default': '0',
348 'name': 'stencil_back_mask',
349 'type': 'GLuint',
350 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
351 'default': '0xFFFFFFFFU',
355 'Hint': {
356 'type': 'NamedParameter',
357 'func': 'Hint',
358 'states': [
360 'name': 'hint_generate_mipmap',
361 'type': 'GLenum',
362 'enum': 'GL_GENERATE_MIPMAP_HINT',
363 'default': 'GL_DONT_CARE'
366 'name': 'hint_fragment_shader_derivative',
367 'type': 'GLenum',
368 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
369 'default': 'GL_DONT_CARE',
370 'extension_flag': 'oes_standard_derivatives'
374 'PixelStore': {
375 'type': 'NamedParameter',
376 'func': 'PixelStorei',
377 'states': [
379 'name': 'pack_alignment',
380 'type': 'GLint',
381 'enum': 'GL_PACK_ALIGNMENT',
382 'default': '4'
385 'name': 'unpack_alignment',
386 'type': 'GLint',
387 'enum': 'GL_UNPACK_ALIGNMENT',
388 'default': '4'
392 # TODO: Consider implemenenting these states
393 # GL_ACTIVE_TEXTURE
394 'LineWidth': {
395 'type': 'Normal',
396 'func': 'LineWidth',
397 'enum': 'GL_LINE_WIDTH',
398 'states': [
400 'name': 'line_width',
401 'type': 'GLfloat',
402 'default': '1.0f',
403 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
406 'DepthMask': {
407 'type': 'Normal',
408 'func': 'DepthMask',
409 'enum': 'GL_DEPTH_WRITEMASK',
410 'states': [
411 {'name': 'depth_mask', 'type': 'GLboolean', 'default': 'true'},
413 'state_flag': 'framebuffer_state_.clear_state_dirty',
415 'Scissor': {
416 'type': 'Normal',
417 'func': 'Scissor',
418 'enum': 'GL_SCISSOR_BOX',
419 'states': [
420 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
422 'name': 'scissor_x',
423 'type': 'GLint',
424 'default': '0',
425 'expected': 'kViewportX',
428 'name': 'scissor_y',
429 'type': 'GLint',
430 'default': '0',
431 'expected': 'kViewportY',
434 'name': 'scissor_width',
435 'type': 'GLsizei',
436 'default': '1',
437 'expected': 'kViewportWidth',
440 'name': 'scissor_height',
441 'type': 'GLsizei',
442 'default': '1',
443 'expected': 'kViewportHeight',
447 'Viewport': {
448 'type': 'Normal',
449 'func': 'Viewport',
450 'enum': 'GL_VIEWPORT',
451 'states': [
452 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
454 'name': 'viewport_x',
455 'type': 'GLint',
456 'default': '0',
457 'expected': 'kViewportX',
460 'name': 'viewport_y',
461 'type': 'GLint',
462 'default': '0',
463 'expected': 'kViewportY',
466 'name': 'viewport_width',
467 'type': 'GLsizei',
468 'default': '1',
469 'expected': 'kViewportWidth',
472 'name': 'viewport_height',
473 'type': 'GLsizei',
474 'default': '1',
475 'expected': 'kViewportHeight',
481 # This is a list of enum names and their valid values. It is used to map
482 # GLenum arguments to a specific set of valid values.
483 _ENUM_LISTS = {
484 'BlitFilter': {
485 'type': 'GLenum',
486 'valid': [
487 'GL_NEAREST',
488 'GL_LINEAR',
490 'invalid': [
491 'GL_LINEAR_MIPMAP_LINEAR',
494 'FrameBufferTarget': {
495 'type': 'GLenum',
496 'valid': [
497 'GL_FRAMEBUFFER',
499 'invalid': [
500 'GL_DRAW_FRAMEBUFFER' ,
501 'GL_READ_FRAMEBUFFER' ,
504 'RenderBufferTarget': {
505 'type': 'GLenum',
506 'valid': [
507 'GL_RENDERBUFFER',
509 'invalid': [
510 'GL_FRAMEBUFFER',
513 'BufferTarget': {
514 'type': 'GLenum',
515 'valid': [
516 'GL_ARRAY_BUFFER',
517 'GL_ELEMENT_ARRAY_BUFFER',
519 'invalid': [
520 'GL_RENDERBUFFER',
523 'BufferUsage': {
524 'type': 'GLenum',
525 'valid': [
526 'GL_STREAM_DRAW',
527 'GL_STATIC_DRAW',
528 'GL_DYNAMIC_DRAW',
530 'invalid': [
531 'GL_STATIC_READ',
534 'CompressedTextureFormat': {
535 'type': 'GLenum',
536 'valid': [
539 'GLState': {
540 'type': 'GLenum',
541 'valid': [
542 # NOTE: State an Capability entries added later.
543 'GL_ACTIVE_TEXTURE',
544 'GL_ALIASED_LINE_WIDTH_RANGE',
545 'GL_ALIASED_POINT_SIZE_RANGE',
546 'GL_ALPHA_BITS',
547 'GL_ARRAY_BUFFER_BINDING',
548 'GL_BLUE_BITS',
549 'GL_COMPRESSED_TEXTURE_FORMATS',
550 'GL_CURRENT_PROGRAM',
551 'GL_DEPTH_BITS',
552 'GL_DEPTH_RANGE',
553 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
554 'GL_FRAMEBUFFER_BINDING',
555 'GL_GENERATE_MIPMAP_HINT',
556 'GL_GREEN_BITS',
557 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
558 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
559 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
560 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
561 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
562 'GL_MAX_RENDERBUFFER_SIZE',
563 'GL_MAX_TEXTURE_IMAGE_UNITS',
564 'GL_MAX_TEXTURE_SIZE',
565 'GL_MAX_VARYING_VECTORS',
566 'GL_MAX_VERTEX_ATTRIBS',
567 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
568 'GL_MAX_VERTEX_UNIFORM_VECTORS',
569 'GL_MAX_VIEWPORT_DIMS',
570 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
571 'GL_NUM_SHADER_BINARY_FORMATS',
572 'GL_PACK_ALIGNMENT',
573 'GL_RED_BITS',
574 'GL_RENDERBUFFER_BINDING',
575 'GL_SAMPLE_BUFFERS',
576 'GL_SAMPLE_COVERAGE_INVERT',
577 'GL_SAMPLE_COVERAGE_VALUE',
578 'GL_SAMPLES',
579 'GL_SCISSOR_BOX',
580 'GL_SHADER_BINARY_FORMATS',
581 'GL_SHADER_COMPILER',
582 'GL_SUBPIXEL_BITS',
583 'GL_STENCIL_BITS',
584 'GL_TEXTURE_BINDING_2D',
585 'GL_TEXTURE_BINDING_CUBE_MAP',
586 'GL_UNPACK_ALIGNMENT',
587 'GL_UNPACK_FLIP_Y_CHROMIUM',
588 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
589 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
590 # we can add this because we emulate it if the driver does not support it.
591 'GL_VERTEX_ARRAY_BINDING_OES',
592 'GL_VIEWPORT',
594 'invalid': [
595 'GL_FOG_HINT',
598 'GetTexParamTarget': {
599 'type': 'GLenum',
600 'valid': [
601 'GL_TEXTURE_2D',
602 'GL_TEXTURE_CUBE_MAP',
604 'invalid': [
605 'GL_PROXY_TEXTURE_CUBE_MAP',
608 'TextureTarget': {
609 'type': 'GLenum',
610 'valid': [
611 'GL_TEXTURE_2D',
612 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
613 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
614 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
615 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
616 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
617 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
619 'invalid': [
620 'GL_PROXY_TEXTURE_CUBE_MAP',
623 'TextureBindTarget': {
624 'type': 'GLenum',
625 'valid': [
626 'GL_TEXTURE_2D',
627 'GL_TEXTURE_CUBE_MAP',
629 'invalid': [
630 'GL_TEXTURE_1D',
631 'GL_TEXTURE_3D',
634 'ShaderType': {
635 'type': 'GLenum',
636 'valid': [
637 'GL_VERTEX_SHADER',
638 'GL_FRAGMENT_SHADER',
640 'invalid': [
641 'GL_GEOMETRY_SHADER',
644 'FaceType': {
645 'type': 'GLenum',
646 'valid': [
647 'GL_FRONT',
648 'GL_BACK',
649 'GL_FRONT_AND_BACK',
652 'FaceMode': {
653 'type': 'GLenum',
654 'valid': [
655 'GL_CW',
656 'GL_CCW',
659 'CmpFunction': {
660 'type': 'GLenum',
661 'valid': [
662 'GL_NEVER',
663 'GL_LESS',
664 'GL_EQUAL',
665 'GL_LEQUAL',
666 'GL_GREATER',
667 'GL_NOTEQUAL',
668 'GL_GEQUAL',
669 'GL_ALWAYS',
672 'Equation': {
673 'type': 'GLenum',
674 'valid': [
675 'GL_FUNC_ADD',
676 'GL_FUNC_SUBTRACT',
677 'GL_FUNC_REVERSE_SUBTRACT',
679 'invalid': [
680 'GL_MIN',
681 'GL_MAX',
684 'SrcBlendFactor': {
685 'type': 'GLenum',
686 'valid': [
687 'GL_ZERO',
688 'GL_ONE',
689 'GL_SRC_COLOR',
690 'GL_ONE_MINUS_SRC_COLOR',
691 'GL_DST_COLOR',
692 'GL_ONE_MINUS_DST_COLOR',
693 'GL_SRC_ALPHA',
694 'GL_ONE_MINUS_SRC_ALPHA',
695 'GL_DST_ALPHA',
696 'GL_ONE_MINUS_DST_ALPHA',
697 'GL_CONSTANT_COLOR',
698 'GL_ONE_MINUS_CONSTANT_COLOR',
699 'GL_CONSTANT_ALPHA',
700 'GL_ONE_MINUS_CONSTANT_ALPHA',
701 'GL_SRC_ALPHA_SATURATE',
704 'DstBlendFactor': {
705 'type': 'GLenum',
706 'valid': [
707 'GL_ZERO',
708 'GL_ONE',
709 'GL_SRC_COLOR',
710 'GL_ONE_MINUS_SRC_COLOR',
711 'GL_DST_COLOR',
712 'GL_ONE_MINUS_DST_COLOR',
713 'GL_SRC_ALPHA',
714 'GL_ONE_MINUS_SRC_ALPHA',
715 'GL_DST_ALPHA',
716 'GL_ONE_MINUS_DST_ALPHA',
717 'GL_CONSTANT_COLOR',
718 'GL_ONE_MINUS_CONSTANT_COLOR',
719 'GL_CONSTANT_ALPHA',
720 'GL_ONE_MINUS_CONSTANT_ALPHA',
723 'Capability': {
724 'type': 'GLenum',
725 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS],
726 'invalid': [
727 'GL_CLIP_PLANE0',
728 'GL_POINT_SPRITE',
731 'DrawMode': {
732 'type': 'GLenum',
733 'valid': [
734 'GL_POINTS',
735 'GL_LINE_STRIP',
736 'GL_LINE_LOOP',
737 'GL_LINES',
738 'GL_TRIANGLE_STRIP',
739 'GL_TRIANGLE_FAN',
740 'GL_TRIANGLES',
742 'invalid': [
743 'GL_QUADS',
744 'GL_POLYGON',
747 'IndexType': {
748 'type': 'GLenum',
749 'valid': [
750 'GL_UNSIGNED_BYTE',
751 'GL_UNSIGNED_SHORT',
753 'invalid': [
754 'GL_UNSIGNED_INT',
755 'GL_INT',
758 'GetMaxIndexType': {
759 'type': 'GLenum',
760 'valid': [
761 'GL_UNSIGNED_BYTE',
762 'GL_UNSIGNED_SHORT',
763 'GL_UNSIGNED_INT',
765 'invalid': [
766 'GL_INT',
769 'Attachment': {
770 'type': 'GLenum',
771 'valid': [
772 'GL_COLOR_ATTACHMENT0',
773 'GL_DEPTH_ATTACHMENT',
774 'GL_STENCIL_ATTACHMENT',
777 'BackbufferAttachment': {
778 'type': 'GLenum',
779 'valid': [
780 'GL_COLOR_EXT',
781 'GL_DEPTH_EXT',
782 'GL_STENCIL_EXT',
785 'BufferParameter': {
786 'type': 'GLenum',
787 'valid': [
788 'GL_BUFFER_SIZE',
789 'GL_BUFFER_USAGE',
791 'invalid': [
792 'GL_PIXEL_PACK_BUFFER',
795 'FrameBufferParameter': {
796 'type': 'GLenum',
797 'valid': [
798 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
799 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
800 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
801 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
804 'ProgramParameter': {
805 'type': 'GLenum',
806 'valid': [
807 'GL_DELETE_STATUS',
808 'GL_LINK_STATUS',
809 'GL_VALIDATE_STATUS',
810 'GL_INFO_LOG_LENGTH',
811 'GL_ATTACHED_SHADERS',
812 'GL_ACTIVE_ATTRIBUTES',
813 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
814 'GL_ACTIVE_UNIFORMS',
815 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
818 'QueryObjectParameter': {
819 'type': 'GLenum',
820 'valid': [
821 'GL_QUERY_RESULT_EXT',
822 'GL_QUERY_RESULT_AVAILABLE_EXT',
825 'QueryParameter': {
826 'type': 'GLenum',
827 'valid': [
828 'GL_CURRENT_QUERY_EXT',
831 'QueryTarget': {
832 'type': 'GLenum',
833 'valid': [
834 'GL_ANY_SAMPLES_PASSED_EXT',
835 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
836 'GL_COMMANDS_ISSUED_CHROMIUM',
837 'GL_LATENCY_QUERY_CHROMIUM',
838 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
839 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
842 'RenderBufferParameter': {
843 'type': 'GLenum',
844 'valid': [
845 'GL_RENDERBUFFER_RED_SIZE',
846 'GL_RENDERBUFFER_GREEN_SIZE',
847 'GL_RENDERBUFFER_BLUE_SIZE',
848 'GL_RENDERBUFFER_ALPHA_SIZE',
849 'GL_RENDERBUFFER_DEPTH_SIZE',
850 'GL_RENDERBUFFER_STENCIL_SIZE',
851 'GL_RENDERBUFFER_WIDTH',
852 'GL_RENDERBUFFER_HEIGHT',
853 'GL_RENDERBUFFER_INTERNAL_FORMAT',
856 'ShaderParameter': {
857 'type': 'GLenum',
858 'valid': [
859 'GL_SHADER_TYPE',
860 'GL_DELETE_STATUS',
861 'GL_COMPILE_STATUS',
862 'GL_INFO_LOG_LENGTH',
863 'GL_SHADER_SOURCE_LENGTH',
864 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
867 'ShaderPrecision': {
868 'type': 'GLenum',
869 'valid': [
870 'GL_LOW_FLOAT',
871 'GL_MEDIUM_FLOAT',
872 'GL_HIGH_FLOAT',
873 'GL_LOW_INT',
874 'GL_MEDIUM_INT',
875 'GL_HIGH_INT',
878 'StringType': {
879 'type': 'GLenum',
880 'valid': [
881 'GL_VENDOR',
882 'GL_RENDERER',
883 'GL_VERSION',
884 'GL_SHADING_LANGUAGE_VERSION',
885 'GL_EXTENSIONS',
888 'TextureParameter': {
889 'type': 'GLenum',
890 'valid': [
891 'GL_TEXTURE_MAG_FILTER',
892 'GL_TEXTURE_MIN_FILTER',
893 'GL_TEXTURE_POOL_CHROMIUM',
894 'GL_TEXTURE_WRAP_S',
895 'GL_TEXTURE_WRAP_T',
897 'invalid': [
898 'GL_GENERATE_MIPMAP',
901 'TexturePool': {
902 'type': 'GLenum',
903 'valid': [
904 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
905 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
908 'TextureWrapMode': {
909 'type': 'GLenum',
910 'valid': [
911 'GL_CLAMP_TO_EDGE',
912 'GL_MIRRORED_REPEAT',
913 'GL_REPEAT',
916 'TextureMinFilterMode': {
917 'type': 'GLenum',
918 'valid': [
919 'GL_NEAREST',
920 'GL_LINEAR',
921 'GL_NEAREST_MIPMAP_NEAREST',
922 'GL_LINEAR_MIPMAP_NEAREST',
923 'GL_NEAREST_MIPMAP_LINEAR',
924 'GL_LINEAR_MIPMAP_LINEAR',
927 'TextureMagFilterMode': {
928 'type': 'GLenum',
929 'valid': [
930 'GL_NEAREST',
931 'GL_LINEAR',
934 'TextureUsage': {
935 'type': 'GLenum',
936 'valid': [
937 'GL_NONE',
938 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
941 'VertexAttribute': {
942 'type': 'GLenum',
943 'valid': [
944 # some enum that the decoder actually passes through to GL needs
945 # to be the first listed here since it's used in unit tests.
946 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
947 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
948 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
949 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
950 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
951 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
952 'GL_CURRENT_VERTEX_ATTRIB',
955 'VertexPointer': {
956 'type': 'GLenum',
957 'valid': [
958 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
961 'HintTarget': {
962 'type': 'GLenum',
963 'valid': [
964 'GL_GENERATE_MIPMAP_HINT',
966 'invalid': [
967 'GL_PERSPECTIVE_CORRECTION_HINT',
970 'HintMode': {
971 'type': 'GLenum',
972 'valid': [
973 'GL_FASTEST',
974 'GL_NICEST',
975 'GL_DONT_CARE',
978 'PixelStore': {
979 'type': 'GLenum',
980 'valid': [
981 'GL_PACK_ALIGNMENT',
982 'GL_UNPACK_ALIGNMENT',
983 'GL_UNPACK_FLIP_Y_CHROMIUM',
984 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
985 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
987 'invalid': [
988 'GL_PACK_SWAP_BYTES',
989 'GL_UNPACK_SWAP_BYTES',
992 'PixelStoreAlignment': {
993 'type': 'GLint',
994 'valid': [
995 '1',
996 '2',
997 '4',
998 '8',
1000 'invalid': [
1001 '3',
1002 '9',
1005 'ReadPixelFormat': {
1006 'type': 'GLenum',
1007 'valid': [
1008 'GL_ALPHA',
1009 'GL_RGB',
1010 'GL_RGBA',
1013 'PixelType': {
1014 'type': 'GLenum',
1015 'valid': [
1016 'GL_UNSIGNED_BYTE',
1017 'GL_UNSIGNED_SHORT_5_6_5',
1018 'GL_UNSIGNED_SHORT_4_4_4_4',
1019 'GL_UNSIGNED_SHORT_5_5_5_1',
1021 'invalid': [
1022 'GL_SHORT',
1023 'GL_INT',
1026 'ReadPixelType': {
1027 'type': 'GLenum',
1028 'valid': [
1029 'GL_UNSIGNED_BYTE',
1030 'GL_UNSIGNED_SHORT_5_6_5',
1031 'GL_UNSIGNED_SHORT_4_4_4_4',
1032 'GL_UNSIGNED_SHORT_5_5_5_1',
1034 'invalid': [
1035 'GL_SHORT',
1036 'GL_INT',
1039 'RenderBufferFormat': {
1040 'type': 'GLenum',
1041 'valid': [
1042 'GL_RGBA4',
1043 'GL_RGB565',
1044 'GL_RGB5_A1',
1045 'GL_DEPTH_COMPONENT16',
1046 'GL_STENCIL_INDEX8',
1049 'ShaderBinaryFormat': {
1050 'type': 'GLenum',
1051 'valid': [
1054 'StencilOp': {
1055 'type': 'GLenum',
1056 'valid': [
1057 'GL_KEEP',
1058 'GL_ZERO',
1059 'GL_REPLACE',
1060 'GL_INCR',
1061 'GL_INCR_WRAP',
1062 'GL_DECR',
1063 'GL_DECR_WRAP',
1064 'GL_INVERT',
1067 'TextureFormat': {
1068 'type': 'GLenum',
1069 'valid': [
1070 'GL_ALPHA',
1071 'GL_LUMINANCE',
1072 'GL_LUMINANCE_ALPHA',
1073 'GL_RGB',
1074 'GL_RGBA',
1076 'invalid': [
1077 'GL_BGRA',
1078 'GL_BGR',
1081 'TextureInternalFormat': {
1082 'type': 'GLenum',
1083 'valid': [
1084 'GL_ALPHA',
1085 'GL_LUMINANCE',
1086 'GL_LUMINANCE_ALPHA',
1087 'GL_RGB',
1088 'GL_RGBA',
1090 'invalid': [
1091 'GL_BGRA',
1092 'GL_BGR',
1095 'TextureInternalFormatStorage': {
1096 'type': 'GLenum',
1097 'valid': [
1098 'GL_RGB565',
1099 'GL_RGBA4',
1100 'GL_RGB5_A1',
1101 'GL_ALPHA8_EXT',
1102 'GL_LUMINANCE8_EXT',
1103 'GL_LUMINANCE8_ALPHA8_EXT',
1104 'GL_RGB8_OES',
1105 'GL_RGBA8_OES',
1108 'VertexAttribType': {
1109 'type': 'GLenum',
1110 'valid': [
1111 'GL_BYTE',
1112 'GL_UNSIGNED_BYTE',
1113 'GL_SHORT',
1114 'GL_UNSIGNED_SHORT',
1115 # 'GL_FIXED', // This is not available on Desktop GL.
1116 'GL_FLOAT',
1118 'invalid': [
1119 'GL_DOUBLE',
1122 'TextureBorder': {
1123 'type': 'GLint',
1124 'valid': [
1125 '0',
1127 'invalid': [
1128 '1',
1131 'VertexAttribSize': {
1132 'type': 'GLint',
1133 'valid': [
1134 '1',
1135 '2',
1136 '3',
1137 '4',
1139 'invalid': [
1140 '0',
1141 '5',
1144 'ZeroOnly': {
1145 'type': 'GLint',
1146 'valid': [
1147 '0',
1149 'invalid': [
1150 '1',
1153 'FalseOnly': {
1154 'type': 'GLboolean',
1155 'valid': [
1156 'false',
1158 'invalid': [
1159 'true',
1162 'ResetStatus': {
1163 'type': 'GLenum',
1164 'valid': [
1165 'GL_GUILTY_CONTEXT_RESET_ARB',
1166 'GL_INNOCENT_CONTEXT_RESET_ARB',
1167 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1172 # This table specifies the different pepper interfaces that are supported for
1173 # GL commands. 'dev' is true if it's a dev interface.
1174 _PEPPER_INTERFACES = [
1175 {'name': '', 'dev': False},
1176 {'name': 'InstancedArrays', 'dev': False},
1177 {'name': 'FramebufferBlit', 'dev': False},
1178 {'name': 'FramebufferMultisample', 'dev': False},
1179 {'name': 'ChromiumEnableFeature', 'dev': False},
1180 {'name': 'ChromiumMapSub', 'dev': False},
1181 {'name': 'Query', 'dev': False},
1184 # This table specifies types and other special data for the commands that
1185 # will be generated.
1187 # Must match function names specified in "cmd_buffer_functions.txt".
1189 # cmd_comment: A comment added to the cmd format.
1190 # type: defines which handler will be used to generate code.
1191 # decoder_func: defines which function to call in the decoder to execute the
1192 # corresponding GL command. If not specified the GL command will
1193 # be called directly.
1194 # gl_test_func: GL function that is expected to be called when testing.
1195 # cmd_args: The arguments to use for the command. This overrides generating
1196 # them based on the GL function arguments.
1197 # a NonImmediate type is a type that stays a pointer even in
1198 # and immediate version of acommand.
1199 # gen_cmd: Whether or not this function geneates a command. Default = True.
1200 # immediate: Whether or not to generate an immediate command for the GL
1201 # function. The default is if there is exactly 1 pointer argument
1202 # in the GL function an immediate command is generated.
1203 # bucket: True to generate a bucket version of the command.
1204 # impl_func: Whether or not to generate the GLES2Implementation part of this
1205 # command.
1206 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1207 # for this command.
1208 # needs_size: If true a data_size field is added to the command.
1209 # data_type: The type of data the command uses. For PUTn or PUT types.
1210 # count: The number of units per element. For PUTn or PUT types.
1211 # unit_test: If False no service side unit test will be generated.
1212 # client_test: If False no client side unit test will be generated.
1213 # expectation: If False the unit test will have no expected calls.
1214 # gen_func: Name of function that generates GL resource for corresponding
1215 # bind function.
1216 # states: array of states that get set by this function corresponding to
1217 # the given arguments
1218 # state_flag: name of flag that is set to true when function is called.
1219 # no_gl: no GL function is called.
1220 # valid_args: A dictionary of argument indices to args to use in unit tests
1221 # when they can not be automatically determined.
1222 # pepper_interface: The pepper interface that is used for this extension
1223 # pepper_name: The name of the function as exposed to pepper.
1224 # pepper_args: A string representing the argument list (what would appear in
1225 # C/C++ between the parentheses for the function declaration)
1226 # that the Pepper API expects for this function. Use this only if
1227 # the stable Pepper API differs from the GLES2 argument list.
1228 # invalid_test: False if no invalid test needed.
1229 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1230 # first_element_only: For PUT types, True if only the first element of an
1231 # array is used and we end up calling the single value
1232 # corresponding function. eg. TexParameteriv -> TexParameteri
1234 _FUNCTION_INFO = {
1235 'ActiveTexture': {
1236 'decoder_func': 'DoActiveTexture',
1237 'unit_test': False,
1238 'impl_func': False,
1239 'client_test': False,
1241 'AttachShader': {'decoder_func': 'DoAttachShader'},
1242 'BindAttribLocation': {
1243 'type': 'GLchar',
1244 'bucket': True,
1245 'needs_size': True,
1246 'immediate': False,
1248 'BindBuffer': {
1249 'type': 'Bind',
1250 'decoder_func': 'DoBindBuffer',
1251 'gen_func': 'GenBuffersARB',
1253 'BindFramebuffer': {
1254 'type': 'Bind',
1255 'decoder_func': 'DoBindFramebuffer',
1256 'gl_test_func': 'glBindFramebufferEXT',
1257 'gen_func': 'GenFramebuffersEXT',
1258 'trace_level': 1,
1260 'BindRenderbuffer': {
1261 'type': 'Bind',
1262 'decoder_func': 'DoBindRenderbuffer',
1263 'gl_test_func': 'glBindRenderbufferEXT',
1264 'gen_func': 'GenRenderbuffersEXT',
1266 'BindTexture': {
1267 'type': 'Bind',
1268 'decoder_func': 'DoBindTexture',
1269 'gen_func': 'GenTextures',
1270 # TODO(gman): remove this once client side caching works.
1271 'client_test': False,
1272 'trace_level': 1,
1274 'BlitFramebufferCHROMIUM': {
1275 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1276 'unit_test': False,
1277 'extension': True,
1278 'pepper_interface': 'FramebufferBlit',
1279 'pepper_name': 'BlitFramebufferEXT',
1280 'defer_reads': True,
1281 'defer_draws': True,
1282 'trace_level': 1,
1284 'BufferData': {
1285 'type': 'Manual',
1286 'immediate': False,
1287 'client_test': False,
1289 'BufferSubData': {
1290 'type': 'Data',
1291 'client_test': False,
1292 'decoder_func': 'DoBufferSubData',
1293 'immediate': False,
1295 'CheckFramebufferStatus': {
1296 'type': 'Is',
1297 'decoder_func': 'DoCheckFramebufferStatus',
1298 'gl_test_func': 'glCheckFramebufferStatusEXT',
1299 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1300 'result': ['GLenum'],
1302 'Clear': {
1303 'decoder_func': 'DoClear',
1304 'defer_draws': True,
1305 'trace_level': 1,
1307 'ClearColor': {
1308 'type': 'StateSet',
1309 'state': 'ClearColor',
1311 'ClearDepthf': {
1312 'type': 'StateSet',
1313 'state': 'ClearDepthf',
1314 'decoder_func': 'glClearDepth',
1315 'gl_test_func': 'glClearDepth',
1316 'valid_args': {
1317 '0': '0.5f'
1320 'ColorMask': {
1321 'type': 'StateSet',
1322 'state': 'ColorMask',
1323 'no_gl': True,
1324 'expectation': False,
1326 'ConsumeTextureCHROMIUM': {
1327 'decoder_func': 'DoConsumeTextureCHROMIUM',
1328 'type': 'PUT',
1329 'data_type': 'GLbyte',
1330 'count': 64,
1331 'unit_test': False,
1332 'extension': True,
1333 'chromium': True,
1334 'trace_level': 1,
1336 'ClearStencil': {
1337 'type': 'StateSet',
1338 'state': 'ClearStencil',
1340 'EnableFeatureCHROMIUM': {
1341 'type': 'Custom',
1342 'immediate': False,
1343 'decoder_func': 'DoEnableFeatureCHROMIUM',
1344 'expectation': False,
1345 'cmd_args': 'GLuint bucket_id, GLint* result',
1346 'result': ['GLint'],
1347 'extension': True,
1348 'chromium': True,
1349 'pepper_interface': 'ChromiumEnableFeature',
1351 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1352 'CompressedTexImage2D': {
1353 'type': 'Manual',
1354 'immediate': False,
1355 'bucket': True,
1357 'CompressedTexSubImage2D': {
1358 'type': 'Data',
1359 'bucket': True,
1360 'decoder_func': 'DoCompressedTexSubImage2D',
1361 'immediate': False,
1363 'CopyTexImage2D': {
1364 'decoder_func': 'DoCopyTexImage2D',
1365 'unit_test': False,
1366 'defer_reads': True,
1368 'CopyTexSubImage2D': {
1369 'decoder_func': 'DoCopyTexSubImage2D',
1370 'defer_reads': True,
1372 'CreateImageCHROMIUM': {
1373 'type': 'Manual',
1374 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1375 'result': ['GLuint'],
1376 'client_test': False,
1377 'gen_cmd': False,
1378 'expectation': False,
1379 'extension': True,
1380 'chromium': True,
1382 'DestroyImageCHROMIUM': {
1383 'type': 'Manual',
1384 'immediate': False,
1385 'client_test': False,
1386 'gen_cmd': False,
1387 'extension': True,
1388 'chromium': True,
1390 'GetImageParameterivCHROMIUM': {
1391 'type': 'Manual',
1392 'client_test': False,
1393 'gen_cmd': False,
1394 'expectation': False,
1395 'extension': True,
1396 'chromium': True,
1398 'CreateProgram': {
1399 'type': 'Create',
1400 'client_test': False,
1402 'CreateShader': {
1403 'type': 'Create',
1404 'client_test': False,
1406 'BlendColor': {
1407 'type': 'StateSet',
1408 'state': 'BlendColor',
1410 'BlendEquation': {
1411 'type': 'StateSetRGBAlpha',
1412 'state': 'BlendEquation',
1413 'valid_args': {
1414 '0': 'GL_FUNC_SUBTRACT'
1417 'BlendEquationSeparate': {
1418 'type': 'StateSet',
1419 'state': 'BlendEquation',
1420 'valid_args': {
1421 '0': 'GL_FUNC_SUBTRACT'
1424 'BlendFunc': {
1425 'type': 'StateSetRGBAlpha',
1426 'state': 'BlendFunc',
1428 'BlendFuncSeparate': {
1429 'type': 'StateSet',
1430 'state': 'BlendFunc',
1432 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1433 'StencilFunc': {
1434 'type': 'StateSetFrontBack',
1435 'state': 'StencilFunc',
1437 'StencilFuncSeparate': {
1438 'type': 'StateSetFrontBackSeparate',
1439 'state': 'StencilFunc',
1441 'StencilOp': {
1442 'type': 'StateSetFrontBack',
1443 'state': 'StencilOp',
1444 'valid_args': {
1445 '1': 'GL_INCR'
1448 'StencilOpSeparate': {
1449 'type': 'StateSetFrontBackSeparate',
1450 'state': 'StencilOp',
1451 'valid_args': {
1452 '1': 'GL_INCR'
1455 'Hint': {
1456 'type': 'StateSetNamedParameter',
1457 'state': 'Hint',
1459 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1460 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1461 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1462 'LineWidth': {
1463 'type': 'StateSet',
1464 'state': 'LineWidth',
1465 'valid_args': {
1466 '0': '0.5f'
1469 'PolygonOffset': {
1470 'type': 'StateSet',
1471 'state': 'PolygonOffset',
1473 'DeleteBuffers': {
1474 'type': 'DELn',
1475 'gl_test_func': 'glDeleteBuffersARB',
1476 'resource_type': 'Buffer',
1477 'resource_types': 'Buffers',
1479 'DeleteFramebuffers': {
1480 'type': 'DELn',
1481 'gl_test_func': 'glDeleteFramebuffersEXT',
1482 'resource_type': 'Framebuffer',
1483 'resource_types': 'Framebuffers',
1485 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1486 'DeleteRenderbuffers': {
1487 'type': 'DELn',
1488 'gl_test_func': 'glDeleteRenderbuffersEXT',
1489 'resource_type': 'Renderbuffer',
1490 'resource_types': 'Renderbuffers',
1492 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1493 'DeleteSharedIdsCHROMIUM': {
1494 'type': 'Custom',
1495 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1496 'impl_func': False,
1497 'expectation': False,
1498 'immediate': False,
1499 'extension': True,
1500 'chromium': True,
1502 'DeleteTextures': {
1503 'type': 'DELn',
1504 'resource_type': 'Texture',
1505 'resource_types': 'Textures',
1507 'DepthRangef': {
1508 'decoder_func': 'DoDepthRangef',
1509 'gl_test_func': 'glDepthRange',
1511 'DepthMask': {
1512 'type': 'StateSet',
1513 'state': 'DepthMask',
1514 'no_gl': True,
1515 'expectation': False,
1517 'DetachShader': {'decoder_func': 'DoDetachShader'},
1518 'Disable': {
1519 'decoder_func': 'DoDisable',
1520 'impl_func': False,
1521 'client_test': False,
1523 'DisableVertexAttribArray': {
1524 'decoder_func': 'DoDisableVertexAttribArray',
1525 'impl_decl': False,
1527 'DrawArrays': {
1528 'type': 'Manual',
1529 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1530 'defer_draws': True,
1531 'trace_level': 2,
1533 'DrawElements': {
1534 'type': 'Manual',
1535 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1536 'GLenumIndexType type, GLuint index_offset',
1537 'client_test': False,
1538 'defer_draws': True,
1539 'trace_level': 2,
1541 'Enable': {
1542 'decoder_func': 'DoEnable',
1543 'impl_func': False,
1544 'client_test': False,
1546 'EnableVertexAttribArray': {
1547 'decoder_func': 'DoEnableVertexAttribArray',
1548 'impl_decl': False,
1550 'Finish': {
1551 'impl_func': False,
1552 'client_test': False,
1553 'decoder_func': 'DoFinish',
1554 'defer_reads': True,
1556 'Flush': {
1557 'impl_func': False,
1558 'decoder_func': 'DoFlush',
1560 'FramebufferRenderbuffer': {
1561 'decoder_func': 'DoFramebufferRenderbuffer',
1562 'gl_test_func': 'glFramebufferRenderbufferEXT',
1564 'FramebufferTexture2D': {
1565 'decoder_func': 'DoFramebufferTexture2D',
1566 'gl_test_func': 'glFramebufferTexture2DEXT',
1567 'trace_level': 1,
1569 'FramebufferTexture2DMultisampleEXT': {
1570 'decoder_func': 'DoFramebufferTexture2DMultisample',
1571 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1572 'expectation': False,
1573 'unit_test': False,
1574 'extension': True,
1575 'trace_level': 1,
1577 'GenerateMipmap': {
1578 'decoder_func': 'DoGenerateMipmap',
1579 'gl_test_func': 'glGenerateMipmapEXT',
1581 'GenBuffers': {
1582 'type': 'GENn',
1583 'gl_test_func': 'glGenBuffersARB',
1584 'resource_type': 'Buffer',
1585 'resource_types': 'Buffers',
1587 'GenMailboxCHROMIUM': {
1588 'type': 'HandWritten',
1589 'immediate': False,
1590 'impl_func': False,
1591 'extension': True,
1592 'chromium': True,
1594 'GenFramebuffers': {
1595 'type': 'GENn',
1596 'gl_test_func': 'glGenFramebuffersEXT',
1597 'resource_type': 'Framebuffer',
1598 'resource_types': 'Framebuffers',
1600 'GenRenderbuffers': {
1601 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1602 'resource_type': 'Renderbuffer',
1603 'resource_types': 'Renderbuffers',
1605 'GenTextures': {
1606 'type': 'GENn',
1607 'gl_test_func': 'glGenTextures',
1608 'resource_type': 'Texture',
1609 'resource_types': 'Textures',
1611 'GenSharedIdsCHROMIUM': {
1612 'type': 'Custom',
1613 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1614 'impl_func': False,
1615 'expectation': False,
1616 'immediate': False,
1617 'extension': True,
1618 'chromium': True,
1620 'GetActiveAttrib': {
1621 'type': 'Custom',
1622 'immediate': False,
1623 'cmd_args':
1624 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1625 'void* result',
1626 'result': [
1627 'int32 success',
1628 'int32 size',
1629 'uint32 type',
1632 'GetActiveUniform': {
1633 'type': 'Custom',
1634 'immediate': False,
1635 'cmd_args':
1636 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1637 'void* result',
1638 'result': [
1639 'int32 success',
1640 'int32 size',
1641 'uint32 type',
1644 'GetAttachedShaders': {
1645 'type': 'Custom',
1646 'immediate': False,
1647 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1648 'result': ['SizedResult<GLuint>'],
1650 'GetAttribLocation': {
1651 'type': 'HandWritten',
1652 'immediate': False,
1653 'bucket': True,
1654 'needs_size': True,
1655 'cmd_args':
1656 'GLidProgram program, const char* name, NonImmediate GLint* location',
1657 'result': ['GLint'],
1658 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1660 'GetBooleanv': {
1661 'type': 'GETn',
1662 'result': ['SizedResult<GLboolean>'],
1663 'decoder_func': 'DoGetBooleanv',
1664 'gl_test_func': 'glGetBooleanv',
1666 'GetBufferParameteriv': {
1667 'type': 'GETn',
1668 'result': ['SizedResult<GLint>'],
1669 'decoder_func': 'DoGetBufferParameteriv',
1670 'expectation': False,
1671 'shadowed': True,
1673 'GetError': {
1674 'type': 'Is',
1675 'decoder_func': 'GetErrorState()->GetGLError',
1676 'impl_func': False,
1677 'result': ['GLenum'],
1678 'client_test': False,
1680 'GetFloatv': {
1681 'type': 'GETn',
1682 'result': ['SizedResult<GLfloat>'],
1683 'decoder_func': 'DoGetFloatv',
1684 'gl_test_func': 'glGetFloatv',
1686 'GetFramebufferAttachmentParameteriv': {
1687 'type': 'GETn',
1688 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1689 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1690 'result': ['SizedResult<GLint>'],
1692 'GetIntegerv': {
1693 'type': 'GETn',
1694 'result': ['SizedResult<GLint>'],
1695 'decoder_func': 'DoGetIntegerv',
1696 'client_test': False,
1698 'GetMaxValueInBufferCHROMIUM': {
1699 'type': 'Is',
1700 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1701 'result': ['GLuint'],
1702 'unit_test': False,
1703 'client_test': False,
1704 'extension': True,
1705 'chromium': True,
1706 'impl_func': False,
1708 'GetMultipleIntegervCHROMIUM': {
1709 'type': 'Custom',
1710 'immediate': False,
1711 'expectation': False,
1712 'extension': True,
1713 'chromium': True,
1714 'client_test': False,
1716 'GetProgramiv': {
1717 'type': 'GETn',
1718 'decoder_func': 'DoGetProgramiv',
1719 'result': ['SizedResult<GLint>'],
1720 'expectation': False,
1722 'GetProgramInfoCHROMIUM': {
1723 'type': 'Custom',
1724 'immediate': False,
1725 'expectation': False,
1726 'impl_func': False,
1727 'extension': True,
1728 'chromium': True,
1729 'client_test': False,
1730 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1731 'result': [
1732 'uint32 link_status',
1733 'uint32 num_attribs',
1734 'uint32 num_uniforms',
1737 'GetProgramInfoLog': {
1738 'type': 'STRn',
1739 'expectation': False,
1741 'GetRenderbufferParameteriv': {
1742 'type': 'GETn',
1743 'decoder_func': 'DoGetRenderbufferParameteriv',
1744 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1745 'result': ['SizedResult<GLint>'],
1747 'GetShaderiv': {
1748 'type': 'GETn',
1749 'decoder_func': 'DoGetShaderiv',
1750 'result': ['SizedResult<GLint>'],
1752 'GetShaderInfoLog': {
1753 'type': 'STRn',
1754 'get_len_func': 'glGetShaderiv',
1755 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1756 'unit_test': False,
1758 'GetShaderPrecisionFormat': {
1759 'type': 'Custom',
1760 'immediate': False,
1761 'cmd_args':
1762 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1763 'void* result',
1764 'result': [
1765 'int32 success',
1766 'int32 min_range',
1767 'int32 max_range',
1768 'int32 precision',
1771 'GetShaderSource': {
1772 'type': 'STRn',
1773 'get_len_func': 'DoGetShaderiv',
1774 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1775 'unit_test': False,
1776 'client_test': False,
1778 'GetString': {
1779 'type': 'Custom',
1780 'client_test': False,
1781 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1783 'GetTexParameterfv': {'type': 'GETn', 'result': ['SizedResult<GLfloat>']},
1784 'GetTexParameteriv': {'type': 'GETn', 'result': ['SizedResult<GLint>']},
1785 'GetTranslatedShaderSourceANGLE': {
1786 'type': 'STRn',
1787 'get_len_func': 'DoGetShaderiv',
1788 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1789 'unit_test': False,
1790 'extension': True,
1792 'GetUniformfv': {
1793 'type': 'Custom',
1794 'immediate': False,
1795 'result': ['SizedResult<GLfloat>'],
1797 'GetUniformiv': {
1798 'type': 'Custom',
1799 'immediate': False,
1800 'result': ['SizedResult<GLint>'],
1802 'GetUniformLocation': {
1803 'type': 'HandWritten',
1804 'immediate': False,
1805 'bucket': True,
1806 'needs_size': True,
1807 'cmd_args':
1808 'GLidProgram program, const char* name, NonImmediate GLint* location',
1809 'result': ['GLint'],
1810 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1812 'GetVertexAttribfv': {
1813 'type': 'GETn',
1814 'result': ['SizedResult<GLfloat>'],
1815 'impl_decl': False,
1816 'decoder_func': 'DoGetVertexAttribfv',
1817 'expectation': False,
1818 'client_test': False,
1820 'GetVertexAttribiv': {
1821 'type': 'GETn',
1822 'result': ['SizedResult<GLint>'],
1823 'impl_decl': False,
1824 'decoder_func': 'DoGetVertexAttribiv',
1825 'expectation': False,
1826 'client_test': False,
1828 'GetVertexAttribPointerv': {
1829 'type': 'Custom',
1830 'immediate': False,
1831 'result': ['SizedResult<GLuint>'],
1832 'client_test': False,
1834 'IsBuffer': {
1835 'type': 'Is',
1836 'decoder_func': 'DoIsBuffer',
1837 'expectation': False,
1839 'IsEnabled': {
1840 'type': 'Is',
1841 'decoder_func': 'DoIsEnabled',
1842 'impl_func': False,
1843 'expectation': False,
1845 'IsFramebuffer': {
1846 'type': 'Is',
1847 'decoder_func': 'DoIsFramebuffer',
1848 'expectation': False,
1850 'IsProgram': {
1851 'type': 'Is',
1852 'decoder_func': 'DoIsProgram',
1853 'expectation': False,
1855 'IsRenderbuffer': {
1856 'type': 'Is',
1857 'decoder_func': 'DoIsRenderbuffer',
1858 'expectation': False,
1860 'IsShader': {
1861 'type': 'Is',
1862 'decoder_func': 'DoIsShader',
1863 'expectation': False,
1865 'IsTexture': {
1866 'type': 'Is',
1867 'decoder_func': 'DoIsTexture',
1868 'expectation': False,
1870 'LinkProgram': {
1871 'decoder_func': 'DoLinkProgram',
1872 'impl_func': False,
1874 'MapBufferCHROMIUM': {
1875 'gen_cmd': False,
1876 'extension': True,
1877 'chromium': True,
1878 'client_test': False,
1880 'MapBufferSubDataCHROMIUM': {
1881 'gen_cmd': False,
1882 'extension': True,
1883 'chromium': True,
1884 'client_test': False,
1885 'pepper_interface': 'ChromiumMapSub',
1887 'MapImageCHROMIUM': {
1888 'gen_cmd': False,
1889 'extension': True,
1890 'chromium': True,
1891 'client_test': False,
1893 'MapTexSubImage2DCHROMIUM': {
1894 'gen_cmd': False,
1895 'extension': True,
1896 'chromium': True,
1897 'client_test': False,
1898 'pepper_interface': 'ChromiumMapSub',
1900 'PixelStorei': {'type': 'Manual'},
1901 'PostSubBufferCHROMIUM': {
1902 'type': 'Custom',
1903 'impl_func': False,
1904 'unit_test': False,
1905 'client_test': False,
1906 'extension': True,
1907 'chromium': True,
1909 'ProduceTextureCHROMIUM': {
1910 'decoder_func': 'DoProduceTextureCHROMIUM',
1911 'type': 'PUT',
1912 'data_type': 'GLbyte',
1913 'count': 64,
1914 'unit_test': False,
1915 'extension': True,
1916 'chromium': True,
1917 'trace_level': 1,
1919 'RenderbufferStorage': {
1920 'decoder_func': 'DoRenderbufferStorage',
1921 'gl_test_func': 'glRenderbufferStorageEXT',
1922 'expectation': False,
1924 'RenderbufferStorageMultisampleCHROMIUM': {
1925 'cmd_comment':
1926 '// GL_CHROMIUM_framebuffer_multisample\n',
1927 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
1928 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
1929 'expectation': False,
1930 'unit_test': False,
1931 'extension': True,
1932 'pepper_interface': 'FramebufferMultisample',
1933 'pepper_name': 'RenderbufferStorageMultisampleEXT',
1935 'RenderbufferStorageMultisampleEXT': {
1936 'cmd_comment':
1937 '// GL_EXT_multisampled_render_to_texture\n',
1938 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
1939 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1940 'expectation': False,
1941 'unit_test': False,
1942 'extension': True,
1944 'ReadPixels': {
1945 'cmd_comment':
1946 '// ReadPixels has the result separated from the pixel buffer so that\n'
1947 '// it is easier to specify the result going to some specific place\n'
1948 '// that exactly fits the rectangle of pixels.\n',
1949 'type': 'Custom',
1950 'immediate': False,
1951 'impl_func': False,
1952 'client_test': False,
1953 'cmd_args':
1954 'GLint x, GLint y, GLsizei width, GLsizei height, '
1955 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1956 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1957 'uint32 result_shm_id, uint32 result_shm_offset, '
1958 'GLboolean async',
1959 'result': ['uint32'],
1960 'defer_reads': True,
1962 'RegisterSharedIdsCHROMIUM': {
1963 'type': 'Custom',
1964 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1965 'impl_func': False,
1966 'expectation': False,
1967 'immediate': False,
1968 'extension': True,
1969 'chromium': True,
1971 'ReleaseShaderCompiler': {
1972 'decoder_func': 'DoReleaseShaderCompiler',
1973 'unit_test': False,
1975 'ShaderBinary': {
1976 'type': 'Custom',
1977 'client_test': False,
1979 'ShaderSource': {
1980 'type': 'Manual',
1981 'immediate': False,
1982 'bucket': True,
1983 'needs_size': True,
1984 'client_test': False,
1985 'cmd_args':
1986 'GLuint shader, const char* data',
1987 'pepper_args':
1988 'GLuint shader, GLsizei count, const char** str, const GLint* length',
1990 'StencilMask': {
1991 'type': 'StateSetFrontBack',
1992 'state': 'StencilMask',
1993 'no_gl': True,
1994 'expectation': False,
1996 'StencilMaskSeparate': {
1997 'type': 'StateSetFrontBackSeparate',
1998 'state': 'StencilMask',
1999 'no_gl': True,
2000 'expectation': False,
2002 'SwapBuffers': {
2003 'impl_func': False,
2004 'decoder_func': 'DoSwapBuffers',
2005 'unit_test': False,
2006 'client_test': False,
2007 'extension': True,
2008 'trace_level': 1,
2010 'TexImage2D': {
2011 'type': 'Manual',
2012 'immediate': False,
2013 'client_test': False,
2015 'TexParameterf': {
2016 'decoder_func': 'DoTexParameterf',
2017 'gl_test_func': 'glTexParameteri',
2018 'valid_args': {
2019 '2': 'GL_NEAREST'
2022 'TexParameteri': {
2023 'decoder_func': 'DoTexParameteri',
2024 'valid_args': {
2025 '2': 'GL_NEAREST'
2028 'TexParameterfv': {
2029 'type': 'PUT',
2030 'data_type': 'GLfloat',
2031 'data_value': 'GL_NEAREST',
2032 'count': 1,
2033 'decoder_func': 'DoTexParameterfv',
2034 'gl_test_func': 'glTexParameteri',
2035 'first_element_only': True,
2037 'TexParameteriv': {
2038 'type': 'PUT',
2039 'data_type': 'GLint',
2040 'data_value': 'GL_NEAREST',
2041 'count': 1,
2042 'decoder_func': 'DoTexParameteriv',
2043 'gl_test_func': 'glTexParameteri',
2044 'first_element_only': True,
2046 'TexSubImage2D': {
2047 'type': 'Manual',
2048 'immediate': False,
2049 'client_test': False,
2050 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2051 'GLint xoffset, GLint yoffset, '
2052 'GLsizei width, GLsizei height, '
2053 'GLenumTextureFormat format, GLenumPixelType type, '
2054 'const void* pixels, GLboolean internal'
2056 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2057 'Uniform1fv': {
2058 'type': 'PUTn',
2059 'data_type': 'GLfloat',
2060 'count': 1,
2061 'decoder_func': 'DoUniform1fv',
2063 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2064 'Uniform1iv': {
2065 'type': 'PUTn',
2066 'data_type': 'GLint',
2067 'count': 1,
2068 'decoder_func': 'DoUniform1iv',
2069 'unit_test': False,
2071 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2072 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2073 'Uniform2fv': {
2074 'type': 'PUTn',
2075 'data_type': 'GLfloat',
2076 'count': 2,
2077 'decoder_func': 'DoUniform2fv',
2079 'Uniform2iv': {
2080 'type': 'PUTn',
2081 'data_type': 'GLint',
2082 'count': 2,
2083 'decoder_func': 'DoUniform2iv',
2085 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2086 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2087 'Uniform3fv': {
2088 'type': 'PUTn',
2089 'data_type': 'GLfloat',
2090 'count': 3,
2091 'decoder_func': 'DoUniform3fv',
2093 'Uniform3iv': {
2094 'type': 'PUTn',
2095 'data_type': 'GLint',
2096 'count': 3,
2097 'decoder_func': 'DoUniform3iv',
2099 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2100 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2101 'Uniform4fv': {
2102 'type': 'PUTn',
2103 'data_type': 'GLfloat',
2104 'count': 4,
2105 'decoder_func': 'DoUniform4fv',
2107 'Uniform4iv': {
2108 'type': 'PUTn',
2109 'data_type': 'GLint',
2110 'count': 4,
2111 'decoder_func': 'DoUniform4iv',
2113 'UniformMatrix2fv': {
2114 'type': 'PUTn',
2115 'data_type': 'GLfloat',
2116 'count': 4,
2117 'decoder_func': 'DoUniformMatrix2fv',
2119 'UniformMatrix3fv': {
2120 'type': 'PUTn',
2121 'data_type': 'GLfloat',
2122 'count': 9,
2123 'decoder_func': 'DoUniformMatrix3fv',
2125 'UniformMatrix4fv': {
2126 'type': 'PUTn',
2127 'data_type': 'GLfloat',
2128 'count': 16,
2129 'decoder_func': 'DoUniformMatrix4fv',
2131 'UnmapBufferCHROMIUM': {
2132 'gen_cmd': False,
2133 'extension': True,
2134 'chromium': True,
2135 'client_test': False,
2137 'UnmapBufferSubDataCHROMIUM': {
2138 'gen_cmd': False,
2139 'extension': True,
2140 'chromium': True,
2141 'client_test': False,
2142 'pepper_interface': 'ChromiumMapSub',
2144 'UnmapImageCHROMIUM': {
2145 'gen_cmd': False,
2146 'extension': True,
2147 'chromium': True,
2148 'client_test': False,
2150 'UnmapTexSubImage2DCHROMIUM': {
2151 'gen_cmd': False,
2152 'extension': True,
2153 'chromium': True,
2154 'client_test': False,
2155 'pepper_interface': 'ChromiumMapSub',
2157 'UseProgram': {
2158 'decoder_func': 'DoUseProgram',
2159 'impl_func': False,
2160 'unit_test': False,
2162 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2163 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2164 'VertexAttrib1fv': {
2165 'type': 'PUT',
2166 'data_type': 'GLfloat',
2167 'count': 1,
2168 'decoder_func': 'DoVertexAttrib1fv',
2170 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2171 'VertexAttrib2fv': {
2172 'type': 'PUT',
2173 'data_type': 'GLfloat',
2174 'count': 2,
2175 'decoder_func': 'DoVertexAttrib2fv',
2177 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2178 'VertexAttrib3fv': {
2179 'type': 'PUT',
2180 'data_type': 'GLfloat',
2181 'count': 3,
2182 'decoder_func': 'DoVertexAttrib3fv',
2184 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2185 'VertexAttrib4fv': {
2186 'type': 'PUT',
2187 'data_type': 'GLfloat',
2188 'count': 4,
2189 'decoder_func': 'DoVertexAttrib4fv',
2191 'VertexAttribPointer': {
2192 'type': 'Manual',
2193 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2194 'GLenumVertexAttribType type, GLboolean normalized, '
2195 'GLsizei stride, GLuint offset',
2196 'client_test': False,
2198 'Scissor': {
2199 'type': 'StateSet',
2200 'state': 'Scissor',
2202 'Viewport': {
2203 'decoder_func': 'DoViewport',
2205 'ResizeCHROMIUM': {
2206 'type': 'Custom',
2207 'impl_func': False,
2208 'unit_test': False,
2209 'extension': True,
2210 'chromium': True,
2212 'GetRequestableExtensionsCHROMIUM': {
2213 'type': 'Custom',
2214 'impl_func': False,
2215 'immediate': False,
2216 'cmd_args': 'uint32 bucket_id',
2217 'extension': True,
2218 'chromium': True,
2220 'RequestExtensionCHROMIUM': {
2221 'type': 'Custom',
2222 'impl_func': False,
2223 'immediate': False,
2224 'client_test': False,
2225 'cmd_args': 'uint32 bucket_id',
2226 'extension': True,
2227 'chromium': True,
2229 'RateLimitOffscreenContextCHROMIUM': {
2230 'gen_cmd': False,
2231 'extension': True,
2232 'chromium': True,
2233 'client_test': False,
2235 'CreateStreamTextureCHROMIUM': {
2236 'type': 'Custom',
2237 'cmd_args': 'GLuint client_id, void* result',
2238 'result': ['GLuint'],
2239 'immediate': False,
2240 'impl_func': False,
2241 'expectation': False,
2242 'extension': True,
2243 'chromium': True,
2244 'client_test': False,
2246 'DestroyStreamTextureCHROMIUM': {
2247 'type': 'Custom',
2248 'impl_func': False,
2249 'expectation': False,
2250 'extension': True,
2251 'chromium': True,
2253 'TexImageIOSurface2DCHROMIUM': {
2254 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2255 'unit_test': False,
2256 'extension': True,
2257 'chromium': True,
2259 'CopyTextureCHROMIUM': {
2260 'decoder_func': 'DoCopyTextureCHROMIUM',
2261 'unit_test': False,
2262 'extension': True,
2263 'chromium': True,
2265 'TexStorage2DEXT': {
2266 'unit_test': False,
2267 'extension': True,
2268 'decoder_func': 'DoTexStorage2DEXT',
2270 'DrawArraysInstancedANGLE': {
2271 'type': 'Manual',
2272 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2273 'GLsizei primcount',
2274 'extension': True,
2275 'unit_test': False,
2276 'pepper_interface': 'InstancedArrays',
2277 'defer_draws': True,
2279 'DrawBuffersEXT': {
2280 'type': 'PUTn',
2281 'decoder_func': 'DoDrawBuffersEXT',
2282 'data_type': 'GLenum',
2283 'count': 1,
2284 'client_test': False,
2285 'unit_test': False,
2286 'extension': True,
2288 'DrawElementsInstancedANGLE': {
2289 'type': 'Manual',
2290 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2291 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2292 'extension': True,
2293 'unit_test': False,
2294 'client_test': False,
2295 'pepper_interface': 'InstancedArrays',
2296 'defer_draws': True,
2298 'VertexAttribDivisorANGLE': {
2299 'type': 'Manual',
2300 'cmd_args': 'GLuint index, GLuint divisor',
2301 'extension': True,
2302 'unit_test': False,
2303 'pepper_interface': 'InstancedArrays',
2305 'GenQueriesEXT': {
2306 'type': 'GENn',
2307 'gl_test_func': 'glGenQueriesARB',
2308 'resource_type': 'Query',
2309 'resource_types': 'Queries',
2310 'unit_test': False,
2311 'pepper_interface': 'Query',
2313 'DeleteQueriesEXT': {
2314 'type': 'DELn',
2315 'gl_test_func': 'glDeleteQueriesARB',
2316 'resource_type': 'Query',
2317 'resource_types': 'Queries',
2318 'unit_test': False,
2319 'pepper_interface': 'Query',
2321 'IsQueryEXT': {
2322 'gen_cmd': False,
2323 'client_test': False,
2324 'pepper_interface': 'Query',
2326 'BeginQueryEXT': {
2327 'type': 'Manual',
2328 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2329 'immediate': False,
2330 'gl_test_func': 'glBeginQuery',
2331 'pepper_interface': 'Query',
2333 'EndQueryEXT': {
2334 'type': 'Manual',
2335 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2336 'gl_test_func': 'glEndnQuery',
2337 'client_test': False,
2338 'pepper_interface': 'Query',
2340 'GetQueryivEXT': {
2341 'gen_cmd': False,
2342 'client_test': False,
2343 'gl_test_func': 'glGetQueryiv',
2344 'pepper_interface': 'Query',
2346 'GetQueryObjectuivEXT': {
2347 'gen_cmd': False,
2348 'client_test': False,
2349 'gl_test_func': 'glGetQueryObjectuiv',
2350 'pepper_interface': 'Query',
2352 'BindUniformLocationCHROMIUM': {
2353 'type': 'GLchar',
2354 'extension': True,
2355 'bucket': True,
2356 'needs_size': True,
2357 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2358 'immediate': False,
2360 'InsertEventMarkerEXT': {
2361 'type': 'GLcharN',
2362 'decoder_func': 'DoInsertEventMarkerEXT',
2363 'expectation': False,
2364 'extension': True,
2366 'PushGroupMarkerEXT': {
2367 'type': 'GLcharN',
2368 'decoder_func': 'DoPushGroupMarkerEXT',
2369 'expectation': False,
2370 'extension': True,
2372 'PopGroupMarkerEXT': {
2373 'decoder_func': 'DoPopGroupMarkerEXT',
2374 'expectation': False,
2375 'extension': True,
2376 'impl_func': False,
2379 'GenVertexArraysOES': {
2380 'type': 'GENn',
2381 'extension': True,
2382 'gl_test_func': 'glGenVertexArraysOES',
2383 'resource_type': 'VertexArray',
2384 'resource_types': 'VertexArrays',
2385 'unit_test': False,
2387 'BindVertexArrayOES': {
2388 'type': 'Bind',
2389 'extension': True,
2390 'gl_test_func': 'glBindVertexArrayOES',
2391 'decoder_func': 'DoBindVertexArrayOES',
2392 'gen_func': 'GenVertexArraysOES',
2393 'unit_test': False,
2394 'client_test': False,
2396 'DeleteVertexArraysOES': {
2397 'type': 'DELn',
2398 'extension': True,
2399 'gl_test_func': 'glDeleteVertexArraysOES',
2400 'resource_type': 'VertexArray',
2401 'resource_types': 'VertexArrays',
2402 'unit_test': False,
2404 'IsVertexArrayOES': {
2405 'type': 'Is',
2406 'extension': True,
2407 'gl_test_func': 'glIsVertexArrayOES',
2408 'decoder_func': 'DoIsVertexArrayOES',
2409 'expectation': False,
2410 'unit_test': False,
2412 'BindTexImage2DCHROMIUM': {
2413 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2414 'unit_test': False,
2415 'extension': True,
2416 'chromium': True,
2418 'ReleaseTexImage2DCHROMIUM': {
2419 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2420 'unit_test': False,
2421 'extension': True,
2422 'chromium': True,
2424 'ShallowFinishCHROMIUM': {
2425 'impl_func': False,
2426 'gen_cmd': False,
2427 'extension': True,
2428 'chromium': True,
2429 'client_test': False,
2431 'ShallowFlushCHROMIUM': {
2432 'impl_func': False,
2433 'gen_cmd': False,
2434 'extension': True,
2435 'chromium': True,
2436 'client_test': False,
2438 'TraceBeginCHROMIUM': {
2439 'type': 'Custom',
2440 'impl_func': False,
2441 'immediate': False,
2442 'client_test': False,
2443 'cmd_args': 'GLuint bucket_id',
2444 'extension': True,
2445 'chromium': True,
2447 'TraceEndCHROMIUM': {
2448 'impl_func': False,
2449 'immediate': False,
2450 'client_test': False,
2451 'decoder_func': 'DoTraceEndCHROMIUM',
2452 'unit_test': False,
2453 'extension': True,
2454 'chromium': True,
2456 'AsyncTexImage2DCHROMIUM': {
2457 'type': 'Manual',
2458 'immediate': False,
2459 'client_test': False,
2460 'extension': True,
2461 'chromium': True,
2463 'AsyncTexSubImage2DCHROMIUM': {
2464 'type': 'Manual',
2465 'immediate': False,
2466 'client_test': False,
2467 'extension': True,
2468 'chromium': True,
2470 'WaitAsyncTexImage2DCHROMIUM': {
2471 'type': 'Manual',
2472 'immediate': False,
2473 'client_test': False,
2474 'extension': True,
2475 'chromium': True,
2477 'DiscardFramebufferEXT': {
2478 'type': 'PUTn',
2479 'count': 1,
2480 'data_type': 'GLenum',
2481 'cmd_args': 'GLenum target, GLsizei count, '
2482 'const GLenum* attachments',
2483 'decoder_func': 'DoDiscardFramebufferEXT',
2484 'unit_test': False,
2485 'client_test': False,
2486 'extension': True,
2488 'LoseContextCHROMIUM': {
2489 'type': 'Manual',
2490 'impl_func': True,
2491 'extension': True,
2492 'chromium': True,
2494 'InsertSyncPointCHROMIUM': {
2495 'type': 'HandWritten',
2496 'impl_func': False,
2497 'extension': True,
2498 'chromium': True,
2500 'WaitSyncPointCHROMIUM': {
2501 'type': 'Custom',
2502 'impl_func': True,
2503 'extension': True,
2504 'chromium': True,
2505 'trace_level': 1,
2507 'DiscardBackbufferCHROMIUM': {
2508 'type': 'Custom',
2509 'impl_func': True,
2510 'extension': True,
2511 'chromium': True,
2516 def Grouper(n, iterable, fillvalue=None):
2517 """Collect data into fixed-length chunks or blocks"""
2518 args = [iter(iterable)] * n
2519 return itertools.izip_longest(fillvalue=fillvalue, *args)
2522 def SplitWords(input_string):
2523 """Transforms a input_string into a list of lower-case components.
2525 Args:
2526 input_string: the input string.
2528 Returns:
2529 a list of lower-case words.
2531 if input_string.find('_') > -1:
2532 # 'some_TEXT_' -> 'some text'
2533 return input_string.replace('_', ' ').strip().lower().split()
2534 else:
2535 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
2536 # mixed case.
2537 # look for capitalization to cut input_strings
2538 # 'SomeText' -> 'Some Text'
2539 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
2540 # 'Vector3' -> 'Vector 3'
2541 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
2542 return input_string.lower().split()
2545 def Lower(words):
2546 """Makes a lower-case identifier from words.
2548 Args:
2549 words: a list of lower-case words.
2551 Returns:
2552 the lower-case identifier.
2554 return '_'.join(words)
2557 def ToUnderscore(input_string):
2558 """converts CamelCase to camel_case."""
2559 words = SplitWords(input_string)
2560 return Lower(words)
2563 class CWriter(object):
2564 """Writes to a file formatting it for Google's style guidelines."""
2566 def __init__(self, filename):
2567 self.filename = filename
2568 self.file_num = 0
2569 self.content = []
2571 def SetFileNum(self, num):
2572 """Used to help write number files and tests."""
2573 self.file_num = num
2575 def Write(self, string):
2576 """Writes a string to a file spliting if it's > 80 characters."""
2577 lines = string.splitlines()
2578 num_lines = len(lines)
2579 for ii in range(0, num_lines):
2580 self.__WriteLine(lines[ii], ii < (num_lines - 1) or string[-1] == '\n')
2582 def __FindSplit(self, string):
2583 """Finds a place to split a string."""
2584 splitter = string.find('=')
2585 if splitter >= 1 and not string[splitter + 1] == '=' and splitter < 80:
2586 return splitter
2587 # parts = string.split('(')
2588 parts = re.split("(?<=[^\"])\((?!\")", string)
2589 fptr = re.compile('\*\w*\)')
2590 if len(parts) > 1:
2591 splitter = len(parts[0])
2592 for ii in range(1, len(parts)):
2593 # Don't split on the dot in "if (.condition)".
2594 if (not parts[ii - 1][-3:] == "if " and
2595 # Don't split "(.)" or "(.*fptr)".
2596 (len(parts[ii]) > 0 and
2597 not parts[ii][0] == ")" and not fptr.match(parts[ii]))
2598 and splitter < 80):
2599 return splitter
2600 splitter += len(parts[ii]) + 1
2601 done = False
2602 end = len(string)
2603 last_splitter = -1
2604 while not done:
2605 splitter = string[0:end].rfind(',')
2606 if splitter < 0 or (splitter > 0 and string[splitter - 1] == '"'):
2607 return last_splitter
2608 elif splitter >= 80:
2609 end = splitter
2610 else:
2611 return splitter
2613 def __WriteLine(self, line, ends_with_eol):
2614 """Given a signle line, writes it to a file, splitting if it's > 80 chars"""
2615 if len(line) >= 80:
2616 i = self.__FindSplit(line)
2617 if i > 0:
2618 line1 = line[0:i + 1]
2619 if line1[-1] == ' ':
2620 line1 = line1[:-1]
2621 lineend = ''
2622 if line1[0] == '#':
2623 lineend = ' \\'
2624 nolint = ''
2625 if len(line1) > 80:
2626 nolint = ' // NOLINT'
2627 self.__AddLine(line1 + nolint + lineend + '\n')
2628 match = re.match("( +)", line1)
2629 indent = ""
2630 if match:
2631 indent = match.group(1)
2632 splitter = line[i]
2633 if not splitter == ',':
2634 indent = " " + indent
2635 self.__WriteLine(indent + line[i + 1:].lstrip(), True)
2636 return
2637 nolint = ''
2638 if len(line) > 80:
2639 nolint = ' // NOLINT'
2640 self.__AddLine(line + nolint)
2641 if ends_with_eol:
2642 self.__AddLine('\n')
2644 def __AddLine(self, line):
2645 self.content.append(line)
2647 def Close(self):
2648 """Close the file."""
2649 content = "".join(self.content)
2650 write_file = True
2651 if os.path.exists(self.filename):
2652 old_file = open(self.filename, "rb");
2653 old_content = old_file.read()
2654 old_file.close();
2655 if content == old_content:
2656 write_file = False
2657 if write_file:
2658 file = open(self.filename, "wb")
2659 file.write(content)
2660 file.close()
2663 class CHeaderWriter(CWriter):
2664 """Writes a C Header file."""
2666 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
2668 def __init__(self, filename, file_comment = None):
2669 CWriter.__init__(self, filename)
2671 base = os.path.abspath(filename)
2672 while os.path.basename(base) != 'src':
2673 new_base = os.path.dirname(base)
2674 assert new_base != base # Prevent infinite loop.
2675 base = new_base
2677 hpath = os.path.relpath(filename, base)
2678 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
2680 self.Write(_LICENSE)
2681 self.Write(_DO_NOT_EDIT_WARNING)
2682 if not file_comment == None:
2683 self.Write(file_comment)
2684 self.Write("#ifndef %s\n" % self.guard)
2685 self.Write("#define %s\n\n" % self.guard)
2687 def Close(self):
2688 self.Write("#endif // %s\n\n" % self.guard)
2689 CWriter.Close(self)
2691 class TypeHandler(object):
2692 """This class emits code for a particular type of function."""
2694 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
2696 def __init__(self):
2697 pass
2699 def InitFunction(self, func):
2700 """Add or adjust anything type specific for this function."""
2701 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
2702 func.AddCmdArg(DataSizeArgument('data_size'))
2704 def AddImmediateFunction(self, generator, func):
2705 """Adds an immediate version of a function."""
2706 # Generate an immediate command if there is only 1 pointer arg.
2707 immediate = func.GetInfo('immediate') # can be True, False or None
2708 if immediate == True or immediate == None:
2709 if func.num_pointer_args == 1 or immediate:
2710 generator.AddFunction(ImmediateFunction(func))
2712 def AddBucketFunction(self, generator, func):
2713 """Adds a bucket version of a function."""
2714 # Generate an immediate command if there is only 1 pointer arg.
2715 bucket = func.GetInfo('bucket') # can be True, False or None
2716 if bucket:
2717 generator.AddFunction(BucketFunction(func))
2719 def WriteStruct(self, func, file):
2720 """Writes a structure that matches the arguments to a function."""
2721 comment = func.GetInfo('cmd_comment')
2722 if not comment == None:
2723 file.Write(comment)
2724 file.Write("struct %s {\n" % func.name)
2725 file.Write(" typedef %s ValueType;\n" % func.name)
2726 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
2727 func.WriteCmdArgFlag(file)
2728 func.WriteCmdFlag(file)
2729 file.Write("\n")
2730 result = func.GetInfo('result')
2731 if not result == None:
2732 if len(result) == 1:
2733 file.Write(" typedef %s Result;\n\n" % result[0])
2734 else:
2735 file.Write(" struct Result {\n")
2736 for line in result:
2737 file.Write(" %s;\n" % line)
2738 file.Write(" };\n\n")
2740 func.WriteCmdComputeSize(file)
2741 func.WriteCmdSetHeader(file)
2742 func.WriteCmdInit(file)
2743 func.WriteCmdSet(file)
2745 file.Write(" gpu::CommandHeader header;\n")
2746 args = func.GetCmdArgs()
2747 for arg in args:
2748 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
2749 file.Write("};\n")
2750 file.Write("\n")
2752 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
2753 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func.name, size))
2754 file.Write(" Sizeof_%s_is_not_%d);\n" % (func.name, size))
2755 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func.name)
2756 file.Write(" OffsetOf_%s_header_not_0);\n" % func.name)
2757 offset = _SIZE_OF_COMMAND_HEADER
2758 for arg in args:
2759 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2760 (func.name, arg.name, offset))
2761 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2762 (func.name, arg.name, offset))
2763 offset += _SIZE_OF_UINT32
2764 if not result == None and len(result) > 1:
2765 offset = 0;
2766 for line in result:
2767 parts = line.split()
2768 name = parts[-1]
2769 check = """
2770 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2771 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2773 file.Write((check.strip() + "\n") % {
2774 'cmd_name': func.name,
2775 'field_name': name,
2776 'offset': offset,
2778 offset += _SIZE_OF_UINT32
2779 file.Write("\n")
2781 def WriteHandlerImplementation(self, func, file):
2782 """Writes the handler implementation for this command."""
2783 file.Write(" %s(%s);\n" %
2784 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2786 def WriteCmdSizeTest(self, func, file):
2787 """Writes the size test for a command."""
2788 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2790 def WriteFormatTest(self, func, file):
2791 """Writes a format test for a command."""
2792 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
2793 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2794 (func.name, func.name))
2795 file.Write(" void* next_cmd = cmd.Set(\n")
2796 file.Write(" &cmd")
2797 args = func.GetCmdArgs()
2798 for value, arg in enumerate(args):
2799 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
2800 file.Write(");\n")
2801 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2802 func.name)
2803 file.Write(" cmd.header.command);\n")
2804 func.type_handler.WriteCmdSizeTest(func, file)
2805 for value, arg in enumerate(args):
2806 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2807 (arg.type, value + 11, arg.name))
2808 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2809 file.Write(" next_cmd, sizeof(cmd));\n")
2810 file.Write("}\n")
2811 file.Write("\n")
2813 def WriteImmediateFormatTest(self, func, file):
2814 """Writes a format test for an immediate version of a command."""
2815 pass
2817 def WriteBucketFormatTest(self, func, file):
2818 """Writes a format test for a bucket version of a command."""
2819 pass
2821 def WriteGetDataSizeCode(self, func, file):
2822 """Writes the code to set data_size used in validation"""
2823 pass
2825 def WriteImmediateCmdSizeTest(self, func, file):
2826 """Writes a size test for an immediate version of a command."""
2827 file.Write(" // TODO(gman): Compute correct size.\n")
2828 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2830 def WriteImmediateHandlerImplementation (self, func, file):
2831 """Writes the handler impl for the immediate version of a command."""
2832 file.Write(" %s(%s);\n" %
2833 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2835 def WriteBucketHandlerImplementation (self, func, file):
2836 """Writes the handler impl for the bucket version of a command."""
2837 file.Write(" %s(%s);\n" %
2838 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2840 def WriteServiceImplementation(self, func, file):
2841 """Writes the service implementation for a command."""
2842 file.Write(
2843 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2844 file.Write(
2845 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2846 func.name)
2847 self.WriteHandlerDeferReadWrite(func, file);
2848 if len(func.GetOriginalArgs()) > 0:
2849 last_arg = func.GetLastOriginalArg()
2850 all_but_last_arg = func.GetOriginalArgs()[:-1]
2851 for arg in all_but_last_arg:
2852 arg.WriteGetCode(file)
2853 self.WriteGetDataSizeCode(func, file)
2854 last_arg.WriteGetCode(file)
2855 func.WriteHandlerValidation(file)
2856 func.WriteHandlerImplementation(file)
2857 file.Write(" return error::kNoError;\n")
2858 file.Write("}\n")
2859 file.Write("\n")
2861 def WriteImmediateServiceImplementation(self, func, file):
2862 """Writes the service implementation for an immediate version of command."""
2863 file.Write(
2864 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2865 file.Write(
2866 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2867 func.name)
2868 self.WriteHandlerDeferReadWrite(func, file);
2869 last_arg = func.GetLastOriginalArg()
2870 all_but_last_arg = func.GetOriginalArgs()[:-1]
2871 for arg in all_but_last_arg:
2872 arg.WriteGetCode(file)
2873 self.WriteGetDataSizeCode(func, file)
2874 last_arg.WriteGetCode(file)
2875 func.WriteHandlerValidation(file)
2876 func.WriteHandlerImplementation(file)
2877 file.Write(" return error::kNoError;\n")
2878 file.Write("}\n")
2879 file.Write("\n")
2881 def WriteBucketServiceImplementation(self, func, file):
2882 """Writes the service implementation for a bucket version of command."""
2883 file.Write(
2884 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2885 file.Write(
2886 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2887 func.name)
2888 self.WriteHandlerDeferReadWrite(func, file);
2889 last_arg = func.GetLastOriginalArg()
2890 all_but_last_arg = func.GetOriginalArgs()[:-1]
2891 for arg in all_but_last_arg:
2892 arg.WriteGetCode(file)
2893 self.WriteGetDataSizeCode(func, file)
2894 last_arg.WriteGetCode(file)
2895 func.WriteHandlerValidation(file)
2896 func.WriteHandlerImplementation(file)
2897 file.Write(" return error::kNoError;\n")
2898 file.Write("}\n")
2899 file.Write("\n")
2901 def WriteHandlerDeferReadWrite(self, func, file):
2902 """Writes the code to handle deferring reads or writes."""
2903 defer_draws = func.GetInfo('defer_draws')
2904 defer_reads = func.GetInfo('defer_reads')
2905 if defer_draws or defer_reads:
2906 file.Write(" error::Error error;\n")
2907 if defer_draws:
2908 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2909 file.Write(" if (error != error::kNoError)\n")
2910 file.Write(" return error;\n")
2911 if defer_reads:
2912 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2913 file.Write(" if (error != error::kNoError)\n")
2914 file.Write(" return error;\n")
2916 def WriteValidUnitTest(self, func, file, test, extra = {}):
2917 """Writes a valid unit test."""
2918 if func.GetInfo('expectation') == False:
2919 test = self._remove_expected_call_re.sub('', test)
2920 name = func.name
2921 arg_strings = []
2922 for count, arg in enumerate(func.GetOriginalArgs()):
2923 arg_strings.append(arg.GetValidArg(func, count, 0))
2924 gl_arg_strings = []
2925 for count, arg in enumerate(func.GetOriginalArgs()):
2926 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
2927 gl_func_name = func.GetGLTestFunctionName()
2928 vars = {
2929 'test_name': 'GLES2DecoderTest%d' % file.file_num,
2930 'name':name,
2931 'gl_func_name': gl_func_name,
2932 'args': ", ".join(arg_strings),
2933 'gl_args': ", ".join(gl_arg_strings),
2935 vars.update(extra)
2936 old_test = ""
2937 while (old_test != test):
2938 old_test = test
2939 test = test % vars
2940 file.Write(test % vars)
2942 def WriteInvalidUnitTest(self, func, file, test, extra = {}):
2943 """Writes a invalid unit test."""
2944 for arg_index, arg in enumerate(func.GetOriginalArgs()):
2945 num_invalid_values = arg.GetNumInvalidValues(func)
2946 for value_index in range(0, num_invalid_values):
2947 arg_strings = []
2948 parse_result = "kNoError"
2949 gl_error = None
2950 for count, arg in enumerate(func.GetOriginalArgs()):
2951 if count == arg_index:
2952 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
2953 count, value_index)
2954 else:
2955 arg_string = arg.GetValidArg(func, count, 0)
2956 arg_strings.append(arg_string)
2957 gl_arg_strings = []
2958 for arg in func.GetOriginalArgs():
2959 gl_arg_strings.append("_")
2960 gl_func_name = func.GetGLTestFunctionName()
2961 gl_error_test = ''
2962 if not gl_error == None:
2963 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2965 vars = {
2966 'test_name': 'GLES2DecoderTest%d' % file.file_num ,
2967 'name': func.name,
2968 'arg_index': arg_index,
2969 'value_index': value_index,
2970 'gl_func_name': gl_func_name,
2971 'args': ", ".join(arg_strings),
2972 'all_but_last_args': ", ".join(arg_strings[:-1]),
2973 'gl_args': ", ".join(gl_arg_strings),
2974 'parse_result': parse_result,
2975 'gl_error_test': gl_error_test,
2977 vars.update(extra)
2978 file.Write(test % vars)
2980 def WriteServiceUnitTest(self, func, file):
2981 """Writes the service unit test for a command."""
2982 valid_test = """
2983 TEST_F(%(test_name)s, %(name)sValidArgs) {
2984 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2985 SpecializedSetup<cmds::%(name)s, 0>(true);
2986 cmds::%(name)s cmd;
2987 cmd.Init(%(args)s);
2988 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2989 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2992 self.WriteValidUnitTest(func, file, valid_test)
2994 invalid_test = """
2995 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
2996 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
2997 SpecializedSetup<cmds::%(name)s, 0>(false);
2998 cmds::%(name)s cmd;
2999 cmd.Init(%(args)s);
3000 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3003 self.WriteInvalidUnitTest(func, file, invalid_test)
3005 def WriteImmediateServiceUnitTest(self, func, file):
3006 """Writes the service unit test for an immediate command."""
3007 file.Write("// TODO(gman): %s\n" % func.name)
3009 def WriteImmediateValidationCode(self, func, file):
3010 """Writes the validation code for an immediate version of a command."""
3011 pass
3013 def WriteBucketServiceUnitTest(self, func, file):
3014 """Writes the service unit test for a bucket command."""
3015 file.Write("// TODO(gman): %s\n" % func.name)
3017 def WriteBucketValidationCode(self, func, file):
3018 """Writes the validation code for a bucket version of a command."""
3019 file.Write("// TODO(gman): %s\n" % func.name)
3021 def WriteGLES2ImplementationDeclaration(self, func, file):
3022 """Writes the GLES2 Implemention declaration."""
3023 impl_decl = func.GetInfo('impl_decl')
3024 if impl_decl == None or impl_decl == True:
3025 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3026 (func.return_type, func.original_name,
3027 func.MakeTypedOriginalArgString("")))
3028 file.Write("\n")
3030 def WriteGLES2CLibImplementation(self, func, file):
3031 file.Write("%s GLES2%s(%s) {\n" %
3032 (func.return_type, func.name,
3033 func.MakeTypedOriginalArgString("")))
3034 result_string = "return "
3035 if func.return_type == "void":
3036 result_string = ""
3037 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3038 (result_string, func.original_name,
3039 func.MakeOriginalArgString("")))
3040 file.Write("}\n")
3042 def WriteGLES2Header(self, func, file):
3043 """Writes a re-write macro for GLES"""
3044 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
3046 def WriteClientGLCallLog(self, func, file):
3047 """Writes a logging macro for the client side code."""
3048 comma = ""
3049 if len(func.GetOriginalArgs()):
3050 comma = " << "
3051 file.Write(
3052 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3053 (func.original_name, comma, func.MakeLogArgString()))
3055 def WriteClientGLReturnLog(self, func, file):
3056 """Writes the return value logging code."""
3057 if func.return_type != "void":
3058 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3060 def WriteGLES2ImplementationHeader(self, func, file):
3061 """Writes the GLES2 Implemention."""
3062 self.WriteGLES2ImplementationDeclaration(func, file)
3064 def WriteGLES2TraceImplementationHeader(self, func, file):
3065 """Writes the GLES2 Trace Implemention header."""
3066 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3067 (func.return_type, func.original_name,
3068 func.MakeTypedOriginalArgString("")))
3070 def WriteGLES2TraceImplementation(self, func, file):
3071 """Writes the GLES2 Trace Implemention."""
3072 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3073 (func.return_type, func.original_name,
3074 func.MakeTypedOriginalArgString("")))
3075 result_string = "return "
3076 if func.return_type == "void":
3077 result_string = ""
3078 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3079 func.name)
3080 file.Write(" %sgl_->%s(%s);\n" %
3081 (result_string, func.name, func.MakeOriginalArgString("")))
3082 file.Write("}\n")
3083 file.Write("\n")
3085 def WriteGLES2Implementation(self, func, file):
3086 """Writes the GLES2 Implemention."""
3087 impl_func = func.GetInfo('impl_func')
3088 impl_decl = func.GetInfo('impl_decl')
3089 gen_cmd = func.GetInfo('gen_cmd')
3090 if (func.can_auto_generate and
3091 (impl_func == None or impl_func == True) and
3092 (impl_decl == None or impl_decl == True) and
3093 (gen_cmd == None or gen_cmd == True)):
3094 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3095 (func.return_type, func.original_name,
3096 func.MakeTypedOriginalArgString("")))
3097 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3098 self.WriteClientGLCallLog(func, file)
3099 func.WriteDestinationInitalizationValidation(file)
3100 for arg in func.GetOriginalArgs():
3101 arg.WriteClientSideValidationCode(file, func)
3102 file.Write(" helper_->%s(%s);\n" %
3103 (func.name, func.MakeOriginalArgString("")))
3104 file.Write(" CheckGLError();\n")
3105 self.WriteClientGLReturnLog(func, file)
3106 file.Write("}\n")
3107 file.Write("\n")
3109 def WriteGLES2InterfaceHeader(self, func, file):
3110 """Writes the GLES2 Interface."""
3111 file.Write("virtual %s %s(%s) = 0;\n" %
3112 (func.return_type, func.original_name,
3113 func.MakeTypedOriginalArgString("")))
3115 def WriteGLES2InterfaceStub(self, func, file):
3116 """Writes the GLES2 Interface stub declaration."""
3117 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3118 (func.return_type, func.original_name,
3119 func.MakeTypedOriginalArgString("")))
3121 def WriteGLES2InterfaceStubImpl(self, func, file):
3122 """Writes the GLES2 Interface stub declaration."""
3123 args = func.GetOriginalArgs()
3124 arg_string = ", ".join(
3125 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
3126 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3127 (func.return_type, func.original_name, arg_string))
3128 if func.return_type != "void":
3129 file.Write(" return 0;\n")
3130 file.Write("}\n")
3132 def WriteGLES2ImplementationUnitTest(self, func, file):
3133 """Writes the GLES2 Implemention unit test."""
3134 client_test = func.GetInfo('client_test')
3135 if (func.can_auto_generate and
3136 (client_test == None or client_test == True)):
3137 code = """
3138 TEST_F(GLES2ImplementationTest, %(name)s) {
3139 struct Cmds {
3140 cmds::%(name)s cmd;
3142 Cmds expected;
3143 expected.cmd.Init(%(cmd_args)s);
3145 gl_->%(name)s(%(args)s);
3146 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3149 cmd_arg_strings = []
3150 for count, arg in enumerate(func.GetCmdArgs()):
3151 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3152 count += 1
3153 gl_arg_strings = []
3154 for count, arg in enumerate(func.GetOriginalArgs()):
3155 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3156 file.Write(code % {
3157 'name': func.name,
3158 'args': ", ".join(gl_arg_strings),
3159 'cmd_args': ", ".join(cmd_arg_strings),
3161 else:
3162 if client_test != False:
3163 file.Write("// TODO: Implement unit test for %s\n" % func.name)
3165 def WriteDestinationInitalizationValidation(self, func, file):
3166 """Writes the client side destintion initialization validation."""
3167 for arg in func.GetOriginalArgs():
3168 arg.WriteDestinationInitalizationValidation(file, func)
3170 def WriteTraceEvent(self, func, file):
3171 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3172 func.original_name)
3174 def WriteImmediateCmdComputeSize(self, func, file):
3175 """Writes the size computation code for the immediate version of a cmd."""
3176 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3177 file.Write(" return static_cast<uint32>(\n")
3178 file.Write(" sizeof(ValueType) + // NOLINT\n")
3179 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3180 file.Write(" }\n")
3181 file.Write("\n")
3183 def WriteImmediateCmdSetHeader(self, func, file):
3184 """Writes the SetHeader function for the immediate version of a cmd."""
3185 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3186 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3187 file.Write(" }\n")
3188 file.Write("\n")
3190 def WriteImmediateCmdInit(self, func, file):
3191 """Writes the Init function for the immediate version of a command."""
3192 raise NotImplementedError(func.name)
3194 def WriteImmediateCmdSet(self, func, file):
3195 """Writes the Set function for the immediate version of a command."""
3196 raise NotImplementedError(func.name)
3198 def WriteCmdHelper(self, func, file):
3199 """Writes the cmd helper definition for a cmd."""
3200 code = """ void %(name)s(%(typed_args)s) {
3201 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3202 if (c) {
3203 c->Init(%(args)s);
3208 file.Write(code % {
3209 "name": func.name,
3210 "typed_args": func.MakeTypedCmdArgString(""),
3211 "args": func.MakeCmdArgString(""),
3214 def WriteImmediateCmdHelper(self, func, file):
3215 """Writes the cmd helper definition for the immediate version of a cmd."""
3216 code = """ void %(name)s(%(typed_args)s) {
3217 const uint32 s = 0; // TODO(gman): compute correct size
3218 gles2::cmds::%(name)s* c =
3219 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3220 if (c) {
3221 c->Init(%(args)s);
3226 file.Write(code % {
3227 "name": func.name,
3228 "typed_args": func.MakeTypedCmdArgString(""),
3229 "args": func.MakeCmdArgString(""),
3233 class StateSetHandler(TypeHandler):
3234 """Handler for commands that simply set state."""
3236 def __init__(self):
3237 TypeHandler.__init__(self)
3239 def WriteHandlerImplementation(self, func, file):
3240 """Overrriden from TypeHandler."""
3241 state_name = func.GetInfo('state')
3242 state = _STATES[state_name]
3243 states = state['states']
3244 args = func.GetOriginalArgs()
3245 code = []
3246 for ndx,item in enumerate(states):
3247 if 'range_checks' in item:
3248 for range_check in item['range_checks']:
3249 code.append("%s %s" % (args[ndx].name, range_check['check']))
3250 if len(code):
3251 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3252 file.Write(
3253 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3254 ' "%s", "%s out of range");\n' %
3255 (func.name, args[ndx].name))
3256 file.Write(" return error::kNoError;\n")
3257 file.Write(" }\n")
3258 code = []
3259 for ndx,item in enumerate(states):
3260 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3261 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3262 for ndx,item in enumerate(states):
3263 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3264 if 'state_flag' in state:
3265 file.Write(" %s = true;\n" % state['state_flag'])
3266 if not func.GetInfo("no_gl"):
3267 file.Write(" %s(%s);\n" %
3268 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3269 file.Write(" }\n")
3271 def WriteServiceUnitTest(self, func, file):
3272 """Overrriden from TypeHandler."""
3273 TypeHandler.WriteServiceUnitTest(self, func, file)
3274 state_name = func.GetInfo('state')
3275 state = _STATES[state_name]
3276 states = state['states']
3277 for ndx,item in enumerate(states):
3278 if 'range_checks' in item:
3279 for check_ndx, range_check in enumerate(item['range_checks']):
3280 valid_test = """
3281 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3282 SpecializedSetup<cmds::%(name)s, 0>(false);
3283 cmds::%(name)s cmd;
3284 cmd.Init(%(args)s);
3285 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3286 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3289 name = func.name
3290 arg_strings = []
3291 for count, arg in enumerate(func.GetOriginalArgs()):
3292 arg_strings.append(arg.GetValidArg(func, count, 0))
3293 arg_strings[ndx] = range_check['test_value']
3294 vars = {
3295 'test_name': 'GLES2DecoderTest%d' % file.file_num,
3296 'name': name,
3297 'ndx': ndx,
3298 'check_ndx': check_ndx,
3299 'args': ", ".join(arg_strings),
3301 file.Write(valid_test % vars)
3304 class StateSetRGBAlphaHandler(TypeHandler):
3305 """Handler for commands that simply set state that have rgb/alpha."""
3307 def __init__(self):
3308 TypeHandler.__init__(self)
3310 def WriteHandlerImplementation(self, func, file):
3311 """Overrriden from TypeHandler."""
3312 state_name = func.GetInfo('state')
3313 state = _STATES[state_name]
3314 states = state['states']
3315 args = func.GetOriginalArgs()
3316 num_args = len(args)
3317 code = []
3318 for ndx,item in enumerate(states):
3319 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
3320 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3321 for ndx, item in enumerate(states):
3322 file.Write(" state_.%s = %s;\n" %
3323 (item['name'], args[ndx % num_args].name))
3324 if 'state_flag' in state:
3325 file.Write(" %s = true;\n" % state['state_flag'])
3326 if not func.GetInfo("no_gl"):
3327 file.Write(" %s(%s);\n" %
3328 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3329 file.Write(" }\n")
3332 class StateSetFrontBackSeparateHandler(TypeHandler):
3333 """Handler for commands that simply set state that have front/back."""
3335 def __init__(self):
3336 TypeHandler.__init__(self)
3338 def WriteHandlerImplementation(self, func, file):
3339 """Overrriden from TypeHandler."""
3340 state_name = func.GetInfo('state')
3341 state = _STATES[state_name]
3342 states = state['states']
3343 args = func.GetOriginalArgs()
3344 face = args[0].name
3345 num_args = len(args)
3346 file.Write(" bool changed = false;\n")
3347 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3348 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3349 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3350 code = []
3351 for ndx, item in enumerate(group):
3352 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
3353 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
3354 file.Write(" }\n")
3355 file.Write(" if (changed) {\n")
3356 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3357 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3358 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3359 for ndx, item in enumerate(group):
3360 file.Write(" state_.%s = %s;\n" %
3361 (item['name'], args[ndx + 1].name))
3362 file.Write(" }\n")
3363 if 'state_flag' in state:
3364 file.Write(" %s = true;\n" % state['state_flag'])
3365 if not func.GetInfo("no_gl"):
3366 file.Write(" %s(%s);\n" %
3367 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3368 file.Write(" }\n")
3371 class StateSetFrontBackHandler(TypeHandler):
3372 """Handler for commands that simply set state that set both front/back."""
3374 def __init__(self):
3375 TypeHandler.__init__(self)
3377 def WriteHandlerImplementation(self, func, file):
3378 """Overrriden from TypeHandler."""
3379 state_name = func.GetInfo('state')
3380 state = _STATES[state_name]
3381 states = state['states']
3382 args = func.GetOriginalArgs()
3383 num_args = len(args)
3384 code = []
3385 for group_ndx, group in enumerate(Grouper(num_args, states)):
3386 for ndx, item in enumerate(group):
3387 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3388 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3389 for group_ndx, group in enumerate(Grouper(num_args, states)):
3390 for ndx, item in enumerate(group):
3391 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3392 if 'state_flag' in state:
3393 file.Write(" %s = true;\n" % state['state_flag'])
3394 if not func.GetInfo("no_gl"):
3395 file.Write(" %s(%s);\n" %
3396 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3397 file.Write(" }\n")
3400 class StateSetNamedParameter(TypeHandler):
3401 """Handler for commands that set a state chosen with an enum parameter."""
3403 def __init__(self):
3404 TypeHandler.__init__(self)
3406 def WriteHandlerImplementation(self, func, file):
3407 """Overridden from TypeHandler."""
3408 state_name = func.GetInfo('state')
3409 state = _STATES[state_name]
3410 states = state['states']
3411 args = func.GetOriginalArgs()
3412 num_args = len(args)
3413 assert num_args == 2
3414 file.Write(" switch (%s) {\n" % args[0].name)
3415 for state in states:
3416 file.Write(" case %s:\n" % state['enum'])
3417 file.Write(" if (state_.%s != %s) {\n" %
3418 (state['name'], args[1].name))
3419 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
3420 if not func.GetInfo("no_gl"):
3421 file.Write(" %s(%s);\n" %
3422 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3423 file.Write(" }\n")
3424 file.Write(" break;\n")
3425 file.Write(" default:\n")
3426 file.Write(" NOTREACHED();\n")
3427 file.Write(" }\n")
3430 class CustomHandler(TypeHandler):
3431 """Handler for commands that are auto-generated but require minor tweaks."""
3433 def __init__(self):
3434 TypeHandler.__init__(self)
3436 def WriteServiceImplementation(self, func, file):
3437 """Overrriden from TypeHandler."""
3438 pass
3440 def WriteImmediateServiceImplementation(self, func, file):
3441 """Overrriden from TypeHandler."""
3442 pass
3444 def WriteBucketServiceImplementation(self, func, file):
3445 """Overrriden from TypeHandler."""
3446 pass
3448 def WriteServiceUnitTest(self, func, file):
3449 """Overrriden from TypeHandler."""
3450 file.Write("// TODO(gman): %s\n\n" % func.name)
3452 def WriteImmediateServiceUnitTest(self, func, file):
3453 """Overrriden from TypeHandler."""
3454 file.Write("// TODO(gman): %s\n\n" % func.name)
3456 def WriteImmediateCmdGetTotalSize(self, func, file):
3457 """Overrriden from TypeHandler."""
3458 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3460 def WriteImmediateCmdInit(self, func, file):
3461 """Overrriden from TypeHandler."""
3462 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3463 self.WriteImmediateCmdGetTotalSize(func, file)
3464 file.Write(" SetHeader(total_size);\n")
3465 args = func.GetCmdArgs()
3466 for arg in args:
3467 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3468 file.Write(" }\n")
3469 file.Write("\n")
3471 def WriteImmediateCmdSet(self, func, file):
3472 """Overrriden from TypeHandler."""
3473 copy_args = func.MakeCmdArgString("_", False)
3474 file.Write(" void* Set(void* cmd%s) {\n" %
3475 func.MakeTypedCmdArgString("_", True))
3476 self.WriteImmediateCmdGetTotalSize(func, file)
3477 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3478 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3479 "cmd, total_size);\n")
3480 file.Write(" }\n")
3481 file.Write("\n")
3484 class TodoHandler(CustomHandler):
3485 """Handle for commands that are not yet implemented."""
3487 def AddImmediateFunction(self, generator, func):
3488 """Overrriden from TypeHandler."""
3489 pass
3491 def WriteImmediateFormatTest(self, func, file):
3492 """Overrriden from TypeHandler."""
3493 pass
3495 def WriteGLES2ImplementationUnitTest(self, func, file):
3496 """Overrriden from TypeHandler."""
3497 pass
3499 def WriteGLES2Implementation(self, func, file):
3500 """Overrriden from TypeHandler."""
3501 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3502 (func.return_type, func.original_name,
3503 func.MakeTypedOriginalArgString("")))
3504 file.Write(" // TODO: for now this is a no-op\n")
3505 file.Write(
3506 " SetGLError("
3507 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3508 func.name)
3509 if func.return_type != "void":
3510 file.Write(" return 0;\n")
3511 file.Write("}\n")
3512 file.Write("\n")
3514 def WriteServiceImplementation(self, func, file):
3515 """Overrriden from TypeHandler."""
3516 file.Write(
3517 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
3518 file.Write(
3519 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3520 func.name)
3521 file.Write(" // TODO: for now this is a no-op\n")
3522 file.Write(
3523 " LOCAL_SET_GL_ERROR("
3524 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3525 func.name)
3526 file.Write(" return error::kNoError;\n")
3527 file.Write("}\n")
3528 file.Write("\n")
3531 class HandWrittenHandler(CustomHandler):
3532 """Handler for comands where everything must be written by hand."""
3534 def InitFunction(self, func):
3535 """Add or adjust anything type specific for this function."""
3536 CustomHandler.InitFunction(self, func)
3537 func.can_auto_generate = False
3539 def WriteStruct(self, func, file):
3540 """Overrriden from TypeHandler."""
3541 pass
3543 def WriteDocs(self, func, file):
3544 """Overrriden from TypeHandler."""
3545 pass
3547 def WriteServiceUnitTest(self, func, file):
3548 """Overrriden from TypeHandler."""
3549 file.Write("// TODO(gman): %s\n\n" % func.name)
3551 def WriteImmediateServiceUnitTest(self, func, file):
3552 """Overrriden from TypeHandler."""
3553 file.Write("// TODO(gman): %s\n\n" % func.name)
3555 def WriteBucketServiceUnitTest(self, func, file):
3556 """Overrriden from TypeHandler."""
3557 file.Write("// TODO(gman): %s\n\n" % func.name)
3559 def WriteServiceImplementation(self, func, file):
3560 """Overrriden from TypeHandler."""
3561 pass
3563 def WriteImmediateServiceImplementation(self, func, file):
3564 """Overrriden from TypeHandler."""
3565 pass
3567 def WriteBucketServiceImplementation(self, func, file):
3568 """Overrriden from TypeHandler."""
3569 pass
3571 def WriteImmediateCmdHelper(self, func, file):
3572 """Overrriden from TypeHandler."""
3573 pass
3575 def WriteBucketCmdHelper(self, func, file):
3576 """Overrriden from TypeHandler."""
3577 pass
3579 def WriteCmdHelper(self, func, file):
3580 """Overrriden from TypeHandler."""
3581 pass
3583 def WriteFormatTest(self, func, file):
3584 """Overrriden from TypeHandler."""
3585 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3587 def WriteImmediateFormatTest(self, func, file):
3588 """Overrriden from TypeHandler."""
3589 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3591 def WriteBucketFormatTest(self, func, file):
3592 """Overrriden from TypeHandler."""
3593 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3597 class ManualHandler(CustomHandler):
3598 """Handler for commands who's handlers must be written by hand."""
3600 def __init__(self):
3601 CustomHandler.__init__(self)
3603 def InitFunction(self, func):
3604 """Overrriden from TypeHandler."""
3605 if (func.name == 'CompressedTexImage2DBucket'):
3606 func.cmd_args = func.cmd_args[:-1]
3607 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3608 else:
3609 CustomHandler.InitFunction(self, func)
3611 def WriteServiceImplementation(self, func, file):
3612 """Overrriden from TypeHandler."""
3613 pass
3615 def WriteBucketServiceImplementation(self, func, file):
3616 """Overrriden from TypeHandler."""
3617 pass
3619 def WriteServiceUnitTest(self, func, file):
3620 """Overrriden from TypeHandler."""
3621 file.Write("// TODO(gman): %s\n\n" % func.name)
3623 def WriteImmediateServiceUnitTest(self, func, file):
3624 """Overrriden from TypeHandler."""
3625 file.Write("// TODO(gman): %s\n\n" % func.name)
3627 def WriteImmediateServiceImplementation(self, func, file):
3628 """Overrriden from TypeHandler."""
3629 pass
3631 def WriteImmediateFormatTest(self, func, file):
3632 """Overrriden from TypeHandler."""
3633 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3635 def WriteGLES2Implementation(self, func, file):
3636 """Overrriden from TypeHandler."""
3637 if func.GetInfo('impl_func'):
3638 super(ManualHandler, self).WriteGLES2Implementation(func, file)
3640 def WriteGLES2ImplementationHeader(self, func, file):
3641 """Overrriden from TypeHandler."""
3642 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3643 (func.return_type, func.original_name,
3644 func.MakeTypedOriginalArgString("")))
3645 file.Write("\n")
3647 def WriteImmediateCmdGetTotalSize(self, func, file):
3648 """Overrriden from TypeHandler."""
3649 # TODO(gman): Move this data to _FUNCTION_INFO?
3650 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
3653 class DataHandler(TypeHandler):
3654 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3655 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3656 def __init__(self):
3657 TypeHandler.__init__(self)
3659 def InitFunction(self, func):
3660 """Overrriden from TypeHandler."""
3661 if func.name == 'CompressedTexSubImage2DBucket':
3662 func.cmd_args = func.cmd_args[:-1]
3663 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3665 def WriteGetDataSizeCode(self, func, file):
3666 """Overrriden from TypeHandler."""
3667 # TODO(gman): Move this data to _FUNCTION_INFO?
3668 name = func.name
3669 if name.endswith("Immediate"):
3670 name = name[0:-9]
3671 if name == 'BufferData' or name == 'BufferSubData':
3672 file.Write(" uint32 data_size = size;\n")
3673 elif (name == 'CompressedTexImage2D' or
3674 name == 'CompressedTexSubImage2D'):
3675 file.Write(" uint32 data_size = imageSize;\n")
3676 elif (name == 'CompressedTexSubImage2DBucket'):
3677 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3678 file.Write(" uint32 data_size = bucket->size();\n")
3679 file.Write(" GLsizei imageSize = data_size;\n")
3680 elif name == 'TexImage2D' or name == 'TexSubImage2D':
3681 code = """ uint32 data_size;
3682 if (!GLES2Util::ComputeImageDataSize(
3683 width, height, format, type, unpack_alignment_, &data_size)) {
3684 return error::kOutOfBounds;
3687 file.Write(code)
3688 else:
3689 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3691 def WriteImmediateCmdGetTotalSize(self, func, file):
3692 """Overrriden from TypeHandler."""
3693 pass
3695 def WriteImmediateCmdSizeTest(self, func, file):
3696 """Overrriden from TypeHandler."""
3697 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3699 def WriteImmediateCmdInit(self, func, file):
3700 """Overrriden from TypeHandler."""
3701 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3702 self.WriteImmediateCmdGetTotalSize(func, file)
3703 file.Write(" SetHeader(total_size);\n")
3704 args = func.GetCmdArgs()
3705 for arg in args:
3706 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3707 file.Write(" }\n")
3708 file.Write("\n")
3710 def WriteImmediateCmdSet(self, func, file):
3711 """Overrriden from TypeHandler."""
3712 copy_args = func.MakeCmdArgString("_", False)
3713 file.Write(" void* Set(void* cmd%s) {\n" %
3714 func.MakeTypedCmdArgString("_", True))
3715 self.WriteImmediateCmdGetTotalSize(func, file)
3716 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3717 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3718 "cmd, total_size);\n")
3719 file.Write(" }\n")
3720 file.Write("\n")
3722 def WriteImmediateFormatTest(self, func, file):
3723 """Overrriden from TypeHandler."""
3724 # TODO(gman): Remove this exception.
3725 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3726 return
3728 def WriteServiceUnitTest(self, func, file):
3729 """Overrriden from TypeHandler."""
3730 file.Write("// TODO(gman): %s\n\n" % func.name)
3732 def WriteImmediateServiceUnitTest(self, func, file):
3733 """Overrriden from TypeHandler."""
3734 file.Write("// TODO(gman): %s\n\n" % func.name)
3736 def WriteBucketServiceImplementation(self, func, file):
3737 """Overrriden from TypeHandler."""
3738 if not func.name == 'CompressedTexSubImage2DBucket':
3739 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
3742 class BindHandler(TypeHandler):
3743 """Handler for glBind___ type functions."""
3745 def __init__(self):
3746 TypeHandler.__init__(self)
3748 def WriteServiceUnitTest(self, func, file):
3749 """Overrriden from TypeHandler."""
3751 if len(func.GetOriginalArgs()) == 1:
3752 valid_test = """
3753 TEST_F(%(test_name)s, %(name)sValidArgs) {
3754 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3755 SpecializedSetup<cmds::%(name)s, 0>(true);
3756 cmds::%(name)s cmd;
3757 cmd.Init(%(args)s);
3758 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3759 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3762 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3763 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3764 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3765 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3766 SpecializedSetup<cmds::%(name)s, 0>(true);
3767 cmds::%(name)s cmd;
3768 cmd.Init(kNewClientId);
3769 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3770 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3771 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3774 gen_func_names = {
3776 self.WriteValidUnitTest(func, file, valid_test, {
3777 'resource_type': func.GetOriginalArgs()[0].resource_type,
3778 'gl_gen_func_name': func.GetInfo("gen_func"),
3780 else:
3781 valid_test = """
3782 TEST_F(%(test_name)s, %(name)sValidArgs) {
3783 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3784 SpecializedSetup<cmds::%(name)s, 0>(true);
3785 cmds::%(name)s cmd;
3786 cmd.Init(%(args)s);
3787 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3788 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3791 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3792 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3793 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3794 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3795 SpecializedSetup<cmds::%(name)s, 0>(true);
3796 cmds::%(name)s cmd;
3797 cmd.Init(%(first_arg)s, kNewClientId);
3798 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3799 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3800 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3803 gen_func_names = {
3805 self.WriteValidUnitTest(func, file, valid_test, {
3806 'first_arg': func.GetOriginalArgs()[0].GetValidArg(func, 0, 0),
3807 'first_gl_arg': func.GetOriginalArgs()[0].GetValidGLArg(func, 0, 0),
3808 'resource_type': func.GetOriginalArgs()[1].resource_type,
3809 'gl_gen_func_name': func.GetInfo("gen_func"),
3812 invalid_test = """
3813 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3814 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3815 SpecializedSetup<cmds::%(name)s, 0>(false);
3816 cmds::%(name)s cmd;
3817 cmd.Init(%(args)s);
3818 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3821 self.WriteInvalidUnitTest(func, file, invalid_test)
3823 def WriteGLES2Implementation(self, func, file):
3824 """Writes the GLES2 Implemention."""
3826 impl_func = func.GetInfo('impl_func')
3827 impl_decl = func.GetInfo('impl_decl')
3829 if (func.can_auto_generate and
3830 (impl_func == None or impl_func == True) and
3831 (impl_decl == None or impl_decl == True)):
3833 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3834 (func.return_type, func.original_name,
3835 func.MakeTypedOriginalArgString("")))
3836 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3837 func.WriteDestinationInitalizationValidation(file)
3838 self.WriteClientGLCallLog(func, file)
3839 for arg in func.GetOriginalArgs():
3840 arg.WriteClientSideValidationCode(file, func)
3842 code = """ if (Is%(type)sReservedId(%(id)s)) {
3843 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3844 return;
3846 if (Bind%(type)sHelper(%(arg_string)s)) {
3847 helper_->%(name)s(%(arg_string)s);
3849 CheckGLError();
3853 name_arg = None
3854 if len(func.GetOriginalArgs()) == 1:
3855 # Bind functions that have no target (like BindVertexArrayOES)
3856 name_arg = func.GetOriginalArgs()[0]
3857 else:
3858 # Bind functions that have both a target and a name (like BindTexture)
3859 name_arg = func.GetOriginalArgs()[1]
3861 file.Write(code % {
3862 'name': func.name,
3863 'arg_string': func.MakeOriginalArgString(""),
3864 'id': name_arg.name,
3865 'type': name_arg.resource_type,
3866 'lc_type': name_arg.resource_type.lower(),
3869 def WriteGLES2ImplementationUnitTest(self, func, file):
3870 """Overrriden from TypeHandler."""
3871 client_test = func.GetInfo('client_test')
3872 if client_test == False:
3873 return
3874 code = """
3875 TEST_F(GLES2ImplementationTest, %(name)s) {
3876 struct Cmds {
3877 cmds::%(name)s cmd;
3879 Cmds expected;
3880 expected.cmd.Init(%(cmd_args)s);
3882 gl_->%(name)s(%(args)s);
3883 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3884 ClearCommands();
3885 gl_->%(name)s(%(args)s);
3886 EXPECT_TRUE(NoCommandsWritten());
3889 cmd_arg_strings = []
3890 for count, arg in enumerate(func.GetCmdArgs()):
3891 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3892 count += 1
3893 gl_arg_strings = []
3894 for count, arg in enumerate(func.GetOriginalArgs()):
3895 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3896 file.Write(code % {
3897 'name': func.name,
3898 'args': ", ".join(gl_arg_strings),
3899 'cmd_args': ", ".join(cmd_arg_strings),
3903 class GENnHandler(TypeHandler):
3904 """Handler for glGen___ type functions."""
3906 def __init__(self):
3907 TypeHandler.__init__(self)
3909 def InitFunction(self, func):
3910 """Overrriden from TypeHandler."""
3911 pass
3913 def WriteGetDataSizeCode(self, func, file):
3914 """Overrriden from TypeHandler."""
3915 code = """ uint32 data_size;
3916 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3917 return error::kOutOfBounds;
3920 file.Write(code)
3922 def WriteHandlerImplementation (self, func, file):
3923 """Overrriden from TypeHandler."""
3924 file.Write(" if (!%sHelper(n, %s)) {\n"
3925 " return error::kInvalidArguments;\n"
3926 " }\n" %
3927 (func.name, func.GetLastOriginalArg().name))
3929 def WriteImmediateHandlerImplementation(self, func, file):
3930 """Overrriden from TypeHandler."""
3931 file.Write(" if (!%sHelper(n, %s)) {\n"
3932 " return error::kInvalidArguments;\n"
3933 " }\n" %
3934 (func.original_name, func.GetLastOriginalArg().name))
3936 def WriteGLES2Implementation(self, func, file):
3937 """Overrriden from TypeHandler."""
3938 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
3939 for (GLsizei i = 0; i < n; ++i) {
3940 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3942 });""" % func.GetOriginalArgs()[1].name)
3943 args = {
3944 'log_code': log_code,
3945 'return_type': func.return_type,
3946 'name': func.original_name,
3947 'typed_args': func.MakeTypedOriginalArgString(""),
3948 'args': func.MakeOriginalArgString(""),
3949 'resource_types': func.GetInfo('resource_types'),
3950 'count_name': func.GetOriginalArgs()[0].name,
3952 file.Write(
3953 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3954 args)
3955 func.WriteDestinationInitalizationValidation(file)
3956 self.WriteClientGLCallLog(func, file)
3957 for arg in func.GetOriginalArgs():
3958 arg.WriteClientSideValidationCode(file, func)
3959 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3960 GetIdHandler(id_namespaces::k%(resource_types)s)->
3961 MakeIds(this, 0, %(args)s);
3962 %(name)sHelper(%(args)s);
3963 helper_->%(name)sImmediate(%(args)s);
3964 helper_->CommandBufferHelper::Flush();
3965 %(log_code)s
3966 CheckGLError();
3970 file.Write(code % args)
3972 def WriteGLES2ImplementationUnitTest(self, func, file):
3973 """Overrriden from TypeHandler."""
3974 code = """
3975 TEST_F(GLES2ImplementationTest, %(name)s) {
3976 GLuint ids[2] = { 0, };
3977 struct Cmds {
3978 cmds::%(name)sImmediate gen;
3979 GLuint data[2];
3981 Cmds expected;
3982 expected.gen.Init(arraysize(ids), &ids[0]);
3983 expected.data[0] = k%(types)sStartId;
3984 expected.data[1] = k%(types)sStartId + 1;
3985 gl_->%(name)s(arraysize(ids), &ids[0]);
3986 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3987 EXPECT_EQ(k%(types)sStartId, ids[0]);
3988 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3991 file.Write(code % {
3992 'name': func.name,
3993 'types': func.GetInfo('resource_types'),
3996 def WriteServiceUnitTest(self, func, file):
3997 """Overrriden from TypeHandler."""
3998 valid_test = """
3999 TEST_F(%(test_name)s, %(name)sValidArgs) {
4000 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4001 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4002 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
4003 SpecializedSetup<cmds::%(name)s, 0>(true);
4004 cmds::%(name)s cmd;
4005 cmd.Init(%(args)s);
4006 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4007 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4008 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4011 self.WriteValidUnitTest(func, file, valid_test, {
4012 'resource_name': func.GetInfo('resource_type'),
4014 invalid_test = """
4015 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4016 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4017 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4018 SpecializedSetup<cmds::%(name)s, 0>(false);
4019 cmds::%(name)s cmd;
4020 cmd.Init(%(args)s);
4021 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4024 self.WriteValidUnitTest(func, file, invalid_test, {
4025 'resource_name': func.GetInfo('resource_type').lower(),
4028 def WriteImmediateServiceUnitTest(self, func, file):
4029 """Overrriden from TypeHandler."""
4030 valid_test = """
4031 TEST_F(%(test_name)s, %(name)sValidArgs) {
4032 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4033 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4034 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4035 GLuint temp = kNewClientId;
4036 SpecializedSetup<cmds::%(name)s, 0>(true);
4037 cmd->Init(1, &temp);
4038 EXPECT_EQ(error::kNoError,
4039 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4040 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4041 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4044 self.WriteValidUnitTest(func, file, valid_test, {
4045 'resource_name': func.GetInfo('resource_type'),
4047 invalid_test = """
4048 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4049 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4050 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4051 SpecializedSetup<cmds::%(name)s, 0>(false);
4052 cmd->Init(1, &client_%(resource_name)s_id_);
4053 EXPECT_EQ(error::kInvalidArguments,
4054 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4057 self.WriteValidUnitTest(func, file, invalid_test, {
4058 'resource_name': func.GetInfo('resource_type').lower(),
4061 def WriteImmediateCmdComputeSize(self, func, file):
4062 """Overrriden from TypeHandler."""
4063 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4064 file.Write(
4065 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4066 file.Write(" }\n")
4067 file.Write("\n")
4068 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4069 file.Write(" return static_cast<uint32>(\n")
4070 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4071 file.Write(" }\n")
4072 file.Write("\n")
4074 def WriteImmediateCmdSetHeader(self, func, file):
4075 """Overrriden from TypeHandler."""
4076 file.Write(" void SetHeader(GLsizei n) {\n")
4077 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4078 file.Write(" }\n")
4079 file.Write("\n")
4081 def WriteImmediateCmdInit(self, func, file):
4082 """Overrriden from TypeHandler."""
4083 last_arg = func.GetLastOriginalArg()
4084 file.Write(" void Init(%s, %s _%s) {\n" %
4085 (func.MakeTypedCmdArgString("_"),
4086 last_arg.type, last_arg.name))
4087 file.Write(" SetHeader(_n);\n")
4088 args = func.GetCmdArgs()
4089 for arg in args:
4090 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4091 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4092 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4093 file.Write(" }\n")
4094 file.Write("\n")
4096 def WriteImmediateCmdSet(self, func, file):
4097 """Overrriden from TypeHandler."""
4098 last_arg = func.GetLastOriginalArg()
4099 copy_args = func.MakeCmdArgString("_", False)
4100 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4101 (func.MakeTypedCmdArgString("_", True),
4102 last_arg.type, last_arg.name))
4103 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4104 (copy_args, last_arg.name))
4105 file.Write(" const uint32 size = ComputeSize(_n);\n")
4106 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4107 "cmd, size);\n")
4108 file.Write(" }\n")
4109 file.Write("\n")
4111 def WriteImmediateCmdHelper(self, func, file):
4112 """Overrriden from TypeHandler."""
4113 code = """ void %(name)s(%(typed_args)s) {
4114 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4115 gles2::cmds::%(name)s* c =
4116 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4117 if (c) {
4118 c->Init(%(args)s);
4123 file.Write(code % {
4124 "name": func.name,
4125 "typed_args": func.MakeTypedOriginalArgString(""),
4126 "args": func.MakeOriginalArgString(""),
4129 def WriteImmediateFormatTest(self, func, file):
4130 """Overrriden from TypeHandler."""
4131 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4132 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4133 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4134 (func.name, func.name))
4135 file.Write(" void* next_cmd = cmd.Set(\n")
4136 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4137 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4138 func.name)
4139 file.Write(" cmd.header.command);\n")
4140 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4141 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4142 file.Write(" cmd.header.size * 4u);\n")
4143 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4144 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4145 file.Write(" next_cmd, sizeof(cmd) +\n")
4146 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4147 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4148 file.Write("}\n")
4149 file.Write("\n")
4152 class CreateHandler(TypeHandler):
4153 """Handler for glCreate___ type functions."""
4155 def __init__(self):
4156 TypeHandler.__init__(self)
4158 def InitFunction(self, func):
4159 """Overrriden from TypeHandler."""
4160 func.AddCmdArg(Argument("client_id", 'uint32'))
4162 def WriteServiceUnitTest(self, func, file):
4163 """Overrriden from TypeHandler."""
4164 valid_test = """
4165 TEST_F(%(test_name)s, %(name)sValidArgs) {
4166 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4167 .WillOnce(Return(kNewServiceId));
4168 SpecializedSetup<cmds::%(name)s, 0>(true);
4169 cmds::%(name)s cmd;
4170 cmd.Init(%(args)s%(comma)skNewClientId);
4171 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4172 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4173 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4176 comma = ""
4177 if len(func.GetOriginalArgs()):
4178 comma =", "
4179 self.WriteValidUnitTest(func, file, valid_test, {
4180 'comma': comma,
4181 'resource_type': func.name[6:],
4183 invalid_test = """
4184 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4185 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4186 SpecializedSetup<cmds::%(name)s, 0>(false);
4187 cmds::%(name)s cmd;
4188 cmd.Init(%(args)s%(comma)skNewClientId);
4189 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4192 self.WriteInvalidUnitTest(func, file, invalid_test, {
4193 'comma': comma,
4196 def WriteHandlerImplementation (self, func, file):
4197 """Overrriden from TypeHandler."""
4198 file.Write(" uint32 client_id = c.client_id;\n")
4199 file.Write(" if (!%sHelper(%s)) {\n" %
4200 (func.name, func.MakeCmdArgString("")))
4201 file.Write(" return error::kInvalidArguments;\n")
4202 file.Write(" }\n")
4204 def WriteGLES2Implementation(self, func, file):
4205 """Overrriden from TypeHandler."""
4206 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4207 (func.return_type, func.original_name,
4208 func.MakeTypedOriginalArgString("")))
4209 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4210 func.WriteDestinationInitalizationValidation(file)
4211 self.WriteClientGLCallLog(func, file)
4212 for arg in func.GetOriginalArgs():
4213 arg.WriteClientSideValidationCode(file, func)
4214 file.Write(" GLuint client_id;\n")
4215 file.Write(
4216 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4217 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4218 file.Write(" helper_->%s(%s);\n" %
4219 (func.name, func.MakeCmdArgString("")))
4220 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4221 file.Write(" CheckGLError();\n")
4222 file.Write(" return client_id;\n")
4223 file.Write("}\n")
4224 file.Write("\n")
4227 class DeleteHandler(TypeHandler):
4228 """Handler for glDelete___ single resource type functions."""
4230 def __init__(self):
4231 TypeHandler.__init__(self)
4233 def WriteServiceImplementation(self, func, file):
4234 """Overrriden from TypeHandler."""
4235 pass
4237 def WriteGLES2Implementation(self, func, file):
4238 """Overrriden from TypeHandler."""
4239 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4240 (func.return_type, func.original_name,
4241 func.MakeTypedOriginalArgString("")))
4242 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4243 func.WriteDestinationInitalizationValidation(file)
4244 self.WriteClientGLCallLog(func, file)
4245 for arg in func.GetOriginalArgs():
4246 arg.WriteClientSideValidationCode(file, func)
4247 file.Write(
4248 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
4249 file.Write(" %sHelper(%s);\n" %
4250 (func.original_name, func.GetOriginalArgs()[-1].name))
4251 file.Write(" CheckGLError();\n")
4252 file.Write("}\n")
4253 file.Write("\n")
4256 class DELnHandler(TypeHandler):
4257 """Handler for glDelete___ type functions."""
4259 def __init__(self):
4260 TypeHandler.__init__(self)
4262 def WriteGetDataSizeCode(self, func, file):
4263 """Overrriden from TypeHandler."""
4264 code = """ uint32 data_size;
4265 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4266 return error::kOutOfBounds;
4269 file.Write(code)
4271 def WriteGLES2ImplementationUnitTest(self, func, file):
4272 """Overrriden from TypeHandler."""
4273 code = """
4274 TEST_F(GLES2ImplementationTest, %(name)s) {
4275 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4276 struct Cmds {
4277 cmds::%(name)sImmediate del;
4278 GLuint data[2];
4280 Cmds expected;
4281 expected.del.Init(arraysize(ids), &ids[0]);
4282 expected.data[0] = k%(types)sStartId;
4283 expected.data[1] = k%(types)sStartId + 1;
4284 gl_->%(name)s(arraysize(ids), &ids[0]);
4285 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4288 file.Write(code % {
4289 'name': func.name,
4290 'types': func.GetInfo('resource_types'),
4293 def WriteServiceUnitTest(self, func, file):
4294 """Overrriden from TypeHandler."""
4295 valid_test = """
4296 TEST_F(%(test_name)s, %(name)sValidArgs) {
4297 EXPECT_CALL(
4298 *gl_,
4299 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4300 .Times(1);
4301 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4302 SpecializedSetup<cmds::%(name)s, 0>(true);
4303 cmds::%(name)s cmd;
4304 cmd.Init(%(args)s);
4305 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4306 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4307 EXPECT_TRUE(
4308 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4311 self.WriteValidUnitTest(func, file, valid_test, {
4312 'resource_name': func.GetInfo('resource_type').lower(),
4313 'upper_resource_name': func.GetInfo('resource_type'),
4315 invalid_test = """
4316 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4317 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4318 SpecializedSetup<cmds::%(name)s, 0>(false);
4319 cmds::%(name)s cmd;
4320 cmd.Init(%(args)s);
4321 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4324 self.WriteValidUnitTest(func, file, invalid_test)
4326 def WriteImmediateServiceUnitTest(self, func, file):
4327 """Overrriden from TypeHandler."""
4328 valid_test = """
4329 TEST_F(%(test_name)s, %(name)sValidArgs) {
4330 EXPECT_CALL(
4331 *gl_,
4332 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4333 .Times(1);
4334 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4335 SpecializedSetup<cmds::%(name)s, 0>(true);
4336 cmd.Init(1, &client_%(resource_name)s_id_);
4337 EXPECT_EQ(error::kNoError,
4338 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4339 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4340 EXPECT_TRUE(
4341 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4344 self.WriteValidUnitTest(func, file, valid_test, {
4345 'resource_name': func.GetInfo('resource_type').lower(),
4346 'upper_resource_name': func.GetInfo('resource_type'),
4348 invalid_test = """
4349 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4350 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4351 SpecializedSetup<cmds::%(name)s, 0>(false);
4352 GLuint temp = kInvalidClientId;
4353 cmd.Init(1, &temp);
4354 EXPECT_EQ(error::kNoError,
4355 ExecuteImmediateCmd(cmd, sizeof(temp)));
4358 self.WriteValidUnitTest(func, file, invalid_test)
4360 def WriteHandlerImplementation (self, func, file):
4361 """Overrriden from TypeHandler."""
4362 file.Write(" %sHelper(n, %s);\n" %
4363 (func.name, func.GetLastOriginalArg().name))
4365 def WriteImmediateHandlerImplementation (self, func, file):
4366 """Overrriden from TypeHandler."""
4367 file.Write(" %sHelper(n, %s);\n" %
4368 (func.original_name, func.GetLastOriginalArg().name))
4370 def WriteGLES2Implementation(self, func, file):
4371 """Overrriden from TypeHandler."""
4372 impl_decl = func.GetInfo('impl_decl')
4373 if impl_decl == None or impl_decl == True:
4374 args = {
4375 'return_type': func.return_type,
4376 'name': func.original_name,
4377 'typed_args': func.MakeTypedOriginalArgString(""),
4378 'args': func.MakeOriginalArgString(""),
4379 'resource_type': func.GetInfo('resource_type').lower(),
4380 'count_name': func.GetOriginalArgs()[0].name,
4382 file.Write(
4383 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4384 args)
4385 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4386 func.WriteDestinationInitalizationValidation(file)
4387 self.WriteClientGLCallLog(func, file)
4388 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4389 for (GLsizei i = 0; i < n; ++i) {
4390 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4393 """ % func.GetOriginalArgs()[1].name)
4394 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4395 for (GLsizei i = 0; i < n; ++i) {
4396 DCHECK(%s[i] != 0);
4399 """ % func.GetOriginalArgs()[1].name)
4400 for arg in func.GetOriginalArgs():
4401 arg.WriteClientSideValidationCode(file, func)
4402 code = """ %(name)sHelper(%(args)s);
4403 CheckGLError();
4407 file.Write(code % args)
4409 def WriteImmediateCmdComputeSize(self, func, file):
4410 """Overrriden from TypeHandler."""
4411 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4412 file.Write(
4413 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4414 file.Write(" }\n")
4415 file.Write("\n")
4416 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4417 file.Write(" return static_cast<uint32>(\n")
4418 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4419 file.Write(" }\n")
4420 file.Write("\n")
4422 def WriteImmediateCmdSetHeader(self, func, file):
4423 """Overrriden from TypeHandler."""
4424 file.Write(" void SetHeader(GLsizei n) {\n")
4425 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4426 file.Write(" }\n")
4427 file.Write("\n")
4429 def WriteImmediateCmdInit(self, func, file):
4430 """Overrriden from TypeHandler."""
4431 last_arg = func.GetLastOriginalArg()
4432 file.Write(" void Init(%s, %s _%s) {\n" %
4433 (func.MakeTypedCmdArgString("_"),
4434 last_arg.type, last_arg.name))
4435 file.Write(" SetHeader(_n);\n")
4436 args = func.GetCmdArgs()
4437 for arg in args:
4438 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4439 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4440 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4441 file.Write(" }\n")
4442 file.Write("\n")
4444 def WriteImmediateCmdSet(self, func, file):
4445 """Overrriden from TypeHandler."""
4446 last_arg = func.GetLastOriginalArg()
4447 copy_args = func.MakeCmdArgString("_", False)
4448 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4449 (func.MakeTypedCmdArgString("_", True),
4450 last_arg.type, last_arg.name))
4451 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4452 (copy_args, last_arg.name))
4453 file.Write(" const uint32 size = ComputeSize(_n);\n")
4454 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4455 "cmd, size);\n")
4456 file.Write(" }\n")
4457 file.Write("\n")
4459 def WriteImmediateCmdHelper(self, func, file):
4460 """Overrriden from TypeHandler."""
4461 code = """ void %(name)s(%(typed_args)s) {
4462 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4463 gles2::cmds::%(name)s* c =
4464 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4465 if (c) {
4466 c->Init(%(args)s);
4471 file.Write(code % {
4472 "name": func.name,
4473 "typed_args": func.MakeTypedOriginalArgString(""),
4474 "args": func.MakeOriginalArgString(""),
4477 def WriteImmediateFormatTest(self, func, file):
4478 """Overrriden from TypeHandler."""
4479 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4480 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4481 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4482 (func.name, func.name))
4483 file.Write(" void* next_cmd = cmd.Set(\n")
4484 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4485 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4486 func.name)
4487 file.Write(" cmd.header.command);\n")
4488 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4489 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4490 file.Write(" cmd.header.size * 4u);\n")
4491 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4492 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4493 file.Write(" next_cmd, sizeof(cmd) +\n")
4494 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4495 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4496 file.Write("}\n")
4497 file.Write("\n")
4500 class GETnHandler(TypeHandler):
4501 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4503 def __init__(self):
4504 TypeHandler.__init__(self)
4506 def AddImmediateFunction(self, generator, func):
4507 """Overrriden from TypeHandler."""
4508 pass
4510 def WriteServiceImplementation(self, func, file):
4511 """Overrriden from TypeHandler."""
4512 file.Write(
4513 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
4514 file.Write(
4515 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4516 func.name)
4517 last_arg = func.GetLastOriginalArg()
4519 all_but_last_args = func.GetOriginalArgs()[:-1]
4520 for arg in all_but_last_args:
4521 arg.WriteGetCode(file)
4523 code = """ typedef cmds::%(func_name)s::Result Result;
4524 GLsizei num_values = 0;
4525 GetNumValuesReturnedForGLGet(pname, &num_values);
4526 Result* result = GetSharedMemoryAs<Result*>(
4527 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4528 %(last_arg_type)s params = result ? result->GetData() : NULL;
4530 file.Write(code % {
4531 'last_arg_type': last_arg.type,
4532 'func_name': func.name,
4534 func.WriteHandlerValidation(file)
4535 code = """ // Check that the client initialized the result.
4536 if (result->size != 0) {
4537 return error::kInvalidArguments;
4540 shadowed = func.GetInfo('shadowed')
4541 if not shadowed:
4542 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
4543 file.Write(code)
4544 func.WriteHandlerImplementation(file)
4545 if shadowed:
4546 code = """ result->SetNumResults(num_values);
4547 return error::kNoError;
4550 else:
4551 code = """ GLenum error = glGetError();
4552 if (error == GL_NO_ERROR) {
4553 result->SetNumResults(num_values);
4554 } else {
4555 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4557 return error::kNoError;
4561 file.Write(code % {'func_name': func.name})
4563 def WriteGLES2Implementation(self, func, file):
4564 """Overrriden from TypeHandler."""
4565 impl_decl = func.GetInfo('impl_decl')
4566 if impl_decl == None or impl_decl == True:
4567 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4568 (func.return_type, func.original_name,
4569 func.MakeTypedOriginalArgString("")))
4570 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4571 func.WriteDestinationInitalizationValidation(file)
4572 self.WriteClientGLCallLog(func, file)
4573 for arg in func.GetOriginalArgs():
4574 arg.WriteClientSideValidationCode(file, func)
4575 all_but_last_args = func.GetOriginalArgs()[:-1]
4576 arg_string = (
4577 ", ".join(["%s" % arg.name for arg in all_but_last_args]))
4578 all_arg_string = (
4579 ", ".join(["%s" % arg.name for arg in func.GetOriginalArgs()]))
4580 self.WriteTraceEvent(func, file)
4581 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4582 return;
4584 typedef cmds::%(func_name)s::Result Result;
4585 Result* result = GetResultAs<Result*>();
4586 if (!result) {
4587 return;
4589 result->SetNumResults(0);
4590 helper_->%(func_name)s(%(arg_string)s,
4591 GetResultShmId(), GetResultShmOffset());
4592 WaitForCmd();
4593 result->CopyResult(params);
4594 GPU_CLIENT_LOG_CODE_BLOCK({
4595 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4596 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4599 CheckGLError();
4602 file.Write(code % {
4603 'func_name': func.name,
4604 'arg_string': arg_string,
4605 'all_arg_string': all_arg_string,
4608 def WriteGLES2ImplementationUnitTest(self, func, file):
4609 """Writes the GLES2 Implemention unit test."""
4610 code = """
4611 TEST_F(GLES2ImplementationTest, %(name)s) {
4612 struct Cmds {
4613 cmds::%(name)s cmd;
4615 typedef cmds::%(name)s::Result Result;
4616 Result::Type result = 0;
4617 Cmds expected;
4618 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4619 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4620 EXPECT_CALL(*command_buffer(), OnFlush())
4621 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4622 .RetiresOnSaturation();
4623 gl_->%(name)s(%(args)s, &result);
4624 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4625 EXPECT_EQ(static_cast<Result::Type>(1), result);
4628 cmd_arg_strings = []
4629 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4630 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4631 cmd_arg_strings[0] = '123'
4632 gl_arg_strings = []
4633 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4634 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4635 gl_arg_strings[0] = '123'
4636 file.Write(code % {
4637 'name': func.name,
4638 'args': ", ".join(gl_arg_strings),
4639 'cmd_args': ", ".join(cmd_arg_strings),
4642 def WriteServiceUnitTest(self, func, file):
4643 """Overrriden from TypeHandler."""
4644 valid_test = """
4645 TEST_F(%(test_name)s, %(name)sValidArgs) {
4646 EXPECT_CALL(*gl_, GetError())
4647 .WillOnce(Return(GL_NO_ERROR))
4648 .WillOnce(Return(GL_NO_ERROR))
4649 .RetiresOnSaturation();
4650 SpecializedSetup<cmds::%(name)s, 0>(true);
4651 typedef cmds::%(name)s::Result Result;
4652 Result* result = static_cast<Result*>(shared_memory_address_);
4653 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4654 result->size = 0;
4655 cmds::%(name)s cmd;
4656 cmd.Init(%(args)s);
4657 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4658 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4659 %(valid_pname)s),
4660 result->GetNumResults());
4661 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4664 gl_arg_strings = []
4665 valid_pname = ''
4666 for count, arg in enumerate(func.GetOriginalArgs()[:-1]):
4667 arg_value = arg.GetValidGLArg(func, count, 0)
4668 gl_arg_strings.append(arg_value)
4669 if arg.name == 'pname':
4670 valid_pname = arg_value
4671 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
4672 gl_arg_strings.append("_")
4673 else:
4674 gl_arg_strings.append("result->GetData()")
4676 self.WriteValidUnitTest(func, file, valid_test, {
4677 'local_gl_args': ", ".join(gl_arg_strings),
4678 'valid_pname': valid_pname,
4681 invalid_test = """
4682 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4683 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4684 SpecializedSetup<cmds::%(name)s, 0>(false);
4685 cmds::%(name)s::Result* result =
4686 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4687 result->size = 0;
4688 cmds::%(name)s cmd;
4689 cmd.Init(%(args)s);
4690 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4691 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4694 self.WriteInvalidUnitTest(func, file, invalid_test)
4697 class PUTHandler(TypeHandler):
4698 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4700 def __init__(self):
4701 TypeHandler.__init__(self)
4703 def WriteServiceUnitTest(self, func, file):
4704 """Writes the service unit test for a command."""
4705 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4706 if func.GetInfo("first_element_only"):
4707 gl_arg_strings = []
4708 for count, arg in enumerate(func.GetOriginalArgs()):
4709 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4710 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
4711 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4712 ", ".join(gl_arg_strings))
4713 valid_test = """
4714 TEST_F(%(test_name)s, %(name)sValidArgs) {
4715 SpecializedSetup<cmds::%(name)s, 0>(true);
4716 cmds::%(name)s cmd;
4717 cmd.Init(%(args)s);
4718 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4719 %(expected_call)s
4720 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4721 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4724 extra = {
4725 'data_type': func.GetInfo('data_type'),
4726 'data_value': func.GetInfo('data_value') or '0',
4727 'expected_call': expected_call,
4729 self.WriteValidUnitTest(func, file, valid_test, extra)
4731 invalid_test = """
4732 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4733 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4734 SpecializedSetup<cmds::%(name)s, 0>(false);
4735 cmds::%(name)s cmd;
4736 cmd.Init(%(args)s);
4737 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4738 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4741 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4743 def WriteImmediateServiceUnitTest(self, func, file):
4744 """Writes the service unit test for a command."""
4745 valid_test = """
4746 TEST_F(%(test_name)s, %(name)sValidArgs) {
4747 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4748 SpecializedSetup<cmds::%(name)s, 0>(true);
4749 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4750 cmd.Init(%(gl_args)s, &temp[0]);
4751 EXPECT_CALL(
4752 *gl_,
4753 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4754 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4755 EXPECT_EQ(error::kNoError,
4756 ExecuteImmediateCmd(cmd, sizeof(temp)));
4757 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4760 gl_arg_strings = []
4761 gl_any_strings = []
4762 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4763 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4764 gl_any_strings.append("_")
4765 extra = {
4766 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
4767 'data_type': func.GetInfo('data_type'),
4768 'data_count': func.GetInfo('count'),
4769 'data_value': func.GetInfo('data_value') or '0',
4770 'gl_args': ", ".join(gl_arg_strings),
4771 'gl_any_args': ", ".join(gl_any_strings),
4773 self.WriteValidUnitTest(func, file, valid_test, extra)
4775 invalid_test = """
4776 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4777 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4778 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4779 SpecializedSetup<cmds::%(name)s, 0>(false);
4780 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4781 cmd.Init(%(all_but_last_args)s, &temp[0]);
4782 EXPECT_EQ(error::%(parse_result)s,
4783 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4786 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4788 def WriteGetDataSizeCode(self, func, file):
4789 """Overrriden from TypeHandler."""
4790 code = """ uint32 data_size;
4791 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4792 return error::kOutOfBounds;
4795 file.Write(code % (func.info.data_type, func.info.count))
4796 if func.is_immediate:
4797 file.Write(" if (data_size > immediate_data_size) {\n")
4798 file.Write(" return error::kOutOfBounds;\n")
4799 file.Write(" }\n")
4801 def WriteGLES2Implementation(self, func, file):
4802 """Overrriden from TypeHandler."""
4803 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4804 (func.return_type, func.original_name,
4805 func.MakeTypedOriginalArgString("")))
4806 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4807 func.WriteDestinationInitalizationValidation(file)
4808 self.WriteClientGLCallLog(func, file)
4809 last_arg_name = func.GetLastOriginalArg().name
4810 values_str = ' << ", " << '.join(
4811 ["%s[%d]" % (last_arg_name, ndx) for ndx in range(0, func.info.count)])
4812 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str)
4813 for arg in func.GetOriginalArgs():
4814 arg.WriteClientSideValidationCode(file, func)
4815 file.Write(" helper_->%sImmediate(%s);\n" %
4816 (func.name, func.MakeOriginalArgString("")))
4817 file.Write(" CheckGLError();\n")
4818 file.Write("}\n")
4819 file.Write("\n")
4821 def WriteGLES2ImplementationUnitTest(self, func, file):
4822 """Writes the GLES2 Implemention unit test."""
4823 code = """
4824 TEST_F(GLES2ImplementationTest, %(name)s) {
4825 %(type)s data[%(count)d] = {0};
4826 struct Cmds {
4827 cmds::%(name)sImmediate cmd;
4828 %(type)s data[%(count)d];
4831 for (int jj = 0; jj < %(count)d; ++jj) {
4832 data[jj] = static_cast<%(type)s>(jj);
4834 Cmds expected;
4835 expected.cmd.Init(%(cmd_args)s, &data[0]);
4836 gl_->%(name)s(%(args)s, &data[0]);
4837 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4840 cmd_arg_strings = []
4841 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4842 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4843 gl_arg_strings = []
4844 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4845 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4846 file.Write(code % {
4847 'name': func.name,
4848 'type': func.GetInfo('data_type'),
4849 'count': func.GetInfo('count'),
4850 'args': ", ".join(gl_arg_strings),
4851 'cmd_args': ", ".join(cmd_arg_strings),
4854 def WriteImmediateCmdComputeSize(self, func, file):
4855 """Overrriden from TypeHandler."""
4856 file.Write(" static uint32 ComputeDataSize() {\n")
4857 file.Write(" return static_cast<uint32>(\n")
4858 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4859 (func.info.data_type, func.info.count))
4860 file.Write(" }\n")
4861 file.Write("\n")
4862 file.Write(" static uint32 ComputeSize() {\n")
4863 file.Write(" return static_cast<uint32>(\n")
4864 file.Write(
4865 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4866 file.Write(" }\n")
4867 file.Write("\n")
4869 def WriteImmediateCmdSetHeader(self, func, file):
4870 """Overrriden from TypeHandler."""
4871 file.Write(" void SetHeader() {\n")
4872 file.Write(
4873 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4874 file.Write(" }\n")
4875 file.Write("\n")
4877 def WriteImmediateCmdInit(self, func, file):
4878 """Overrriden from TypeHandler."""
4879 last_arg = func.GetLastOriginalArg()
4880 file.Write(" void Init(%s, %s _%s) {\n" %
4881 (func.MakeTypedCmdArgString("_"),
4882 last_arg.type, last_arg.name))
4883 file.Write(" SetHeader();\n")
4884 args = func.GetCmdArgs()
4885 for arg in args:
4886 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4887 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4888 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
4889 file.Write(" }\n")
4890 file.Write("\n")
4892 def WriteImmediateCmdSet(self, func, file):
4893 """Overrriden from TypeHandler."""
4894 last_arg = func.GetLastOriginalArg()
4895 copy_args = func.MakeCmdArgString("_", False)
4896 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4897 (func.MakeTypedCmdArgString("_", True),
4898 last_arg.type, last_arg.name))
4899 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4900 (copy_args, last_arg.name))
4901 file.Write(" const uint32 size = ComputeSize();\n")
4902 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4903 "cmd, size);\n")
4904 file.Write(" }\n")
4905 file.Write("\n")
4907 def WriteImmediateCmdHelper(self, func, file):
4908 """Overrriden from TypeHandler."""
4909 code = """ void %(name)s(%(typed_args)s) {
4910 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4911 gles2::cmds::%(name)s* c =
4912 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4913 if (c) {
4914 c->Init(%(args)s);
4919 file.Write(code % {
4920 "name": func.name,
4921 "typed_args": func.MakeTypedOriginalArgString(""),
4922 "args": func.MakeOriginalArgString(""),
4925 def WriteImmediateFormatTest(self, func, file):
4926 """Overrriden from TypeHandler."""
4927 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4928 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4929 file.Write(" static %s data[] = {\n" % func.info.data_type)
4930 for v in range(0, func.info.count):
4931 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4932 (func.info.data_type, v))
4933 file.Write(" };\n")
4934 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4935 (func.name, func.name))
4936 file.Write(" void* next_cmd = cmd.Set(\n")
4937 file.Write(" &cmd")
4938 args = func.GetCmdArgs()
4939 for value, arg in enumerate(args):
4940 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4941 file.Write(",\n data);\n")
4942 args = func.GetCmdArgs()
4943 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4944 % func.name)
4945 file.Write(" cmd.header.command);\n")
4946 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4947 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4948 file.Write(" cmd.header.size * 4u);\n")
4949 for value, arg in enumerate(args):
4950 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4951 (arg.type, value + 11, arg.name))
4952 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4953 file.Write(" next_cmd, sizeof(cmd) +\n")
4954 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4955 file.Write(" // TODO(gman): Check that data was inserted;\n")
4956 file.Write("}\n")
4957 file.Write("\n")
4960 class PUTnHandler(TypeHandler):
4961 """Handler for PUTn 'glUniform__v' type functions."""
4963 def __init__(self):
4964 TypeHandler.__init__(self)
4966 def WriteServiceUnitTest(self, func, file):
4967 """Overridden from TypeHandler."""
4968 TypeHandler.WriteServiceUnitTest(self, func, file)
4970 valid_test = """
4971 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4972 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4973 SpecializedSetup<cmds::%(name)s, 0>(true);
4974 cmds::%(name)s cmd;
4975 cmd.Init(%(args)s);
4976 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4977 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4980 gl_arg_strings = []
4981 arg_strings = []
4982 for count, arg in enumerate(func.GetOriginalArgs()):
4983 # hardcoded to match unit tests.
4984 if count == 0:
4985 # the location of the second element of the 2nd uniform.
4986 # defined in GLES2DecoderBase::SetupShaderForUniform
4987 gl_arg_strings.append("3")
4988 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
4989 elif count == 1:
4990 # the number of elements that gl will be called with.
4991 gl_arg_strings.append("3")
4992 # the number of elements requested in the command.
4993 arg_strings.append("5")
4994 else:
4995 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4996 arg_strings.append(arg.GetValidArg(func, count, 0))
4997 extra = {
4998 'gl_args': ", ".join(gl_arg_strings),
4999 'args': ", ".join(arg_strings),
5001 self.WriteValidUnitTest(func, file, valid_test, extra)
5003 def WriteImmediateServiceUnitTest(self, func, file):
5004 """Overridden from TypeHandler."""
5005 valid_test = """
5006 TEST_F(%(test_name)s, %(name)sValidArgs) {
5007 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5008 EXPECT_CALL(
5009 *gl_,
5010 %(gl_func_name)s(%(gl_args)s,
5011 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
5012 SpecializedSetup<cmds::%(name)s, 0>(true);
5013 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5014 cmd.Init(%(args)s, &temp[0]);
5015 EXPECT_EQ(error::kNoError,
5016 ExecuteImmediateCmd(cmd, sizeof(temp)));
5017 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5020 gl_arg_strings = []
5021 gl_any_strings = []
5022 arg_strings = []
5023 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5024 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
5025 gl_any_strings.append("_")
5026 arg_strings.append(arg.GetValidArg(func, count, 0))
5027 extra = {
5028 'data_type': func.GetInfo('data_type'),
5029 'data_count': func.GetInfo('count'),
5030 'args': ", ".join(arg_strings),
5031 'gl_args': ", ".join(gl_arg_strings),
5032 'gl_any_args': ", ".join(gl_any_strings),
5034 self.WriteValidUnitTest(func, file, valid_test, extra)
5036 invalid_test = """
5037 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5038 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5039 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5040 SpecializedSetup<cmds::%(name)s, 0>(false);
5041 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5042 cmd.Init(%(all_but_last_args)s, &temp[0]);
5043 EXPECT_EQ(error::%(parse_result)s,
5044 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5047 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
5049 def WriteGetDataSizeCode(self, func, file):
5050 """Overrriden from TypeHandler."""
5051 code = """ uint32 data_size;
5052 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5053 return error::kOutOfBounds;
5056 file.Write(code % (func.info.data_type, func.info.count))
5057 if func.is_immediate:
5058 file.Write(" if (data_size > immediate_data_size) {\n")
5059 file.Write(" return error::kOutOfBounds;\n")
5060 file.Write(" }\n")
5062 def WriteGLES2Implementation(self, func, file):
5063 """Overrriden from TypeHandler."""
5064 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5065 (func.return_type, func.original_name,
5066 func.MakeTypedOriginalArgString("")))
5067 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5068 func.WriteDestinationInitalizationValidation(file)
5069 self.WriteClientGLCallLog(func, file)
5070 last_arg_name = func.GetLastOriginalArg().name
5071 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5072 for (GLsizei i = 0; i < count; ++i) {
5073 """)
5074 values_str = ' << ", " << '.join(
5075 ["%s[%d + i * %d]" % (
5076 last_arg_name, ndx, func.info.count) for ndx in range(
5077 0, func.info.count)])
5078 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
5079 file.Write(" }\n });\n")
5080 for arg in func.GetOriginalArgs():
5081 arg.WriteClientSideValidationCode(file, func)
5082 file.Write(" helper_->%sImmediate(%s);\n" %
5083 (func.name, func.MakeOriginalArgString("")))
5084 file.Write(" CheckGLError();\n")
5085 file.Write("}\n")
5086 file.Write("\n")
5088 def WriteGLES2ImplementationUnitTest(self, func, file):
5089 """Writes the GLES2 Implemention unit test."""
5090 code = """
5091 TEST_F(GLES2ImplementationTest, %(name)s) {
5092 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5093 struct Cmds {
5094 cmds::%(name)sImmediate cmd;
5095 %(type)s data[%(count_param)d][%(count)d];
5098 Cmds expected;
5099 for (int ii = 0; ii < %(count_param)d; ++ii) {
5100 for (int jj = 0; jj < %(count)d; ++jj) {
5101 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5104 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5105 gl_->%(name)s(%(args)s, &data[0][0]);
5106 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5109 cmd_arg_strings = []
5110 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
5111 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
5112 gl_arg_strings = []
5113 count_param = 0
5114 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5115 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
5116 if arg.name == "count":
5117 count_param = int(arg.GetValidClientSideArg(func, count, 0))
5118 file.Write(code % {
5119 'name': func.name,
5120 'type': func.GetInfo('data_type'),
5121 'count': func.GetInfo('count'),
5122 'args': ", ".join(gl_arg_strings),
5123 'cmd_args': ", ".join(cmd_arg_strings),
5124 'count_param': count_param,
5127 def WriteImmediateCmdComputeSize(self, func, file):
5128 """Overrriden from TypeHandler."""
5129 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5130 file.Write(" return static_cast<uint32>(\n")
5131 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5132 (func.info.data_type, func.info.count))
5133 file.Write(" }\n")
5134 file.Write("\n")
5135 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5136 file.Write(" return static_cast<uint32>(\n")
5137 file.Write(
5138 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5139 file.Write(" }\n")
5140 file.Write("\n")
5142 def WriteImmediateCmdSetHeader(self, func, file):
5143 """Overrriden from TypeHandler."""
5144 file.Write(" void SetHeader(GLsizei count) {\n")
5145 file.Write(
5146 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5147 file.Write(" }\n")
5148 file.Write("\n")
5150 def WriteImmediateCmdInit(self, func, file):
5151 """Overrriden from TypeHandler."""
5152 last_arg = func.GetLastOriginalArg()
5153 file.Write(" void Init(%s, %s _%s) {\n" %
5154 (func.MakeTypedCmdArgString("_"),
5155 last_arg.type, last_arg.name))
5156 file.Write(" SetHeader(_count);\n")
5157 args = func.GetCmdArgs()
5158 for arg in args:
5159 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5160 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5161 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg.name)
5162 file.Write(" }\n")
5163 file.Write("\n")
5165 def WriteImmediateCmdSet(self, func, file):
5166 """Overrriden from TypeHandler."""
5167 last_arg = func.GetLastOriginalArg()
5168 copy_args = func.MakeCmdArgString("_", False)
5169 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5170 (func.MakeTypedCmdArgString("_", True),
5171 last_arg.type, last_arg.name))
5172 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5173 (copy_args, last_arg.name))
5174 file.Write(" const uint32 size = ComputeSize(_count);\n")
5175 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5176 "cmd, size);\n")
5177 file.Write(" }\n")
5178 file.Write("\n")
5180 def WriteImmediateCmdHelper(self, func, file):
5181 """Overrriden from TypeHandler."""
5182 code = """ void %(name)s(%(typed_args)s) {
5183 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5184 gles2::cmds::%(name)s* c =
5185 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5186 if (c) {
5187 c->Init(%(args)s);
5192 file.Write(code % {
5193 "name": func.name,
5194 "typed_args": func.MakeTypedOriginalArgString(""),
5195 "args": func.MakeOriginalArgString(""),
5198 def WriteImmediateFormatTest(self, func, file):
5199 """Overrriden from TypeHandler."""
5200 args = func.GetCmdArgs()
5201 count_param = 0
5202 for value, arg in enumerate(args):
5203 if arg.name == "count":
5204 count_param = int(arg.GetValidClientSideArg(func, value, 0))
5205 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5206 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5207 file.Write(" static %s data[] = {\n" % func.info.data_type)
5208 for v in range(0, func.info.count * count_param):
5209 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5210 (func.info.data_type, v))
5211 file.Write(" };\n")
5212 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5213 (func.name, func.name))
5214 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
5215 file.Write(" const size_t kExpectedCmdSize =\n")
5216 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5217 (func.info.data_type, func.info.count))
5218 file.Write(" void* next_cmd = cmd.Set(\n")
5219 file.Write(" &cmd")
5220 for value, arg in enumerate(args):
5221 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
5222 file.Write(",\n data);\n")
5223 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5224 func.name)
5225 file.Write(" cmd.header.command);\n")
5226 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5227 for value, arg in enumerate(args):
5228 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5229 (arg.type, value + 1, arg.name))
5230 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5231 file.Write(" next_cmd, sizeof(cmd) +\n")
5232 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5233 file.Write(" // TODO(gman): Check that data was inserted;\n")
5234 file.Write("}\n")
5235 file.Write("\n")
5238 class PUTXnHandler(TypeHandler):
5239 """Handler for glUniform?f functions."""
5240 def __init__(self):
5241 TypeHandler.__init__(self)
5243 def WriteHandlerImplementation(self, func, file):
5244 """Overrriden from TypeHandler."""
5245 code = """ %(type)s temp[%(count)s] = { %(values)s};
5246 Do%(name)sv(%(location)s, 1, &temp[0]);
5248 values = ""
5249 args = func.GetOriginalArgs()
5250 count = int(func.GetInfo('count'))
5251 num_args = len(args)
5252 for ii in range(count):
5253 values += "%s, " % args[len(args) - count + ii].name
5255 file.Write(code % {
5256 'name': func.name,
5257 'count': func.GetInfo('count'),
5258 'type': func.GetInfo('data_type'),
5259 'location': args[0].name,
5260 'args': func.MakeOriginalArgString(""),
5261 'values': values,
5264 def WriteServiceUnitTest(self, func, file):
5265 """Overrriden from TypeHandler."""
5266 valid_test = """
5267 TEST_F(%(test_name)s, %(name)sValidArgs) {
5268 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5269 SpecializedSetup<cmds::%(name)s, 0>(true);
5270 cmds::%(name)s cmd;
5271 cmd.Init(%(args)s);
5272 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5273 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5276 args = func.GetOriginalArgs()
5277 local_args = "%s, 1, _" % args[0].GetValidGLArg(func, 0, 0)
5278 self.WriteValidUnitTest(func, file, valid_test, {
5279 'name': func.name,
5280 'count': func.GetInfo('count'),
5281 'local_args': local_args,
5284 invalid_test = """
5285 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5286 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5287 SpecializedSetup<cmds::%(name)s, 0>(false);
5288 cmds::%(name)s cmd;
5289 cmd.Init(%(args)s);
5290 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5293 self.WriteInvalidUnitTest(func, file, invalid_test, {
5294 'name': func.GetInfo('name'),
5295 'count': func.GetInfo('count'),
5299 class GLcharHandler(CustomHandler):
5300 """Handler for functions that pass a single string ."""
5302 def __init__(self):
5303 CustomHandler.__init__(self)
5305 def WriteImmediateCmdComputeSize(self, func, file):
5306 """Overrriden from TypeHandler."""
5307 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5308 file.Write(" return static_cast<uint32>(\n")
5309 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5310 file.Write(" }\n")
5312 def WriteImmediateCmdSetHeader(self, func, file):
5313 """Overrriden from TypeHandler."""
5314 code = """
5315 void SetHeader(uint32 data_size) {
5316 header.SetCmdBySize<ValueType>(data_size);
5319 file.Write(code)
5321 def WriteImmediateCmdInit(self, func, file):
5322 """Overrriden from TypeHandler."""
5323 last_arg = func.GetLastOriginalArg()
5324 args = func.GetCmdArgs()
5325 set_code = []
5326 for arg in args:
5327 set_code.append(" %s = _%s;" % (arg.name, arg.name))
5328 code = """
5329 void Init(%(typed_args)s, uint32 _data_size) {
5330 SetHeader(_data_size);
5331 %(set_code)s
5332 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5336 file.Write(code % {
5337 "typed_args": func.MakeTypedOriginalArgString("_"),
5338 "set_code": "\n".join(set_code),
5339 "last_arg": last_arg.name
5342 def WriteImmediateCmdSet(self, func, file):
5343 """Overrriden from TypeHandler."""
5344 last_arg = func.GetLastOriginalArg()
5345 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5346 func.MakeTypedOriginalArgString("_", True))
5347 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5348 func.MakeOriginalArgString("_"))
5349 file.Write(" return NextImmediateCmdAddress<ValueType>("
5350 "cmd, _data_size);\n")
5351 file.Write(" }\n")
5352 file.Write("\n")
5354 def WriteImmediateCmdHelper(self, func, file):
5355 """Overrriden from TypeHandler."""
5356 code = """ void %(name)s(%(typed_args)s) {
5357 const uint32 data_size = strlen(name);
5358 gles2::cmds::%(name)s* c =
5359 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5360 if (c) {
5361 c->Init(%(args)s, data_size);
5366 file.Write(code % {
5367 "name": func.name,
5368 "typed_args": func.MakeTypedOriginalArgString(""),
5369 "args": func.MakeOriginalArgString(""),
5373 def WriteImmediateFormatTest(self, func, file):
5374 """Overrriden from TypeHandler."""
5375 init_code = []
5376 check_code = []
5377 all_but_last_arg = func.GetCmdArgs()[:-1]
5378 for value, arg in enumerate(all_but_last_arg):
5379 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
5380 for value, arg in enumerate(all_but_last_arg):
5381 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5382 (arg.type, value + 11, arg.name))
5383 code = """
5384 TEST_F(GLES2FormatTest, %(func_name)s) {
5385 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5386 static const char* const test_str = \"test string\";
5387 void* next_cmd = cmd.Set(
5388 &cmd,
5389 %(init_code)s
5390 test_str,
5391 strlen(test_str));
5392 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5393 cmd.header.command);
5394 EXPECT_EQ(sizeof(cmd) +
5395 RoundSizeToMultipleOfEntries(strlen(test_str)),
5396 cmd.header.size * 4u);
5397 EXPECT_EQ(static_cast<char*>(next_cmd),
5398 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5399 RoundSizeToMultipleOfEntries(strlen(test_str)));
5400 %(check_code)s
5401 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5402 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5403 CheckBytesWritten(
5404 next_cmd,
5405 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5406 sizeof(cmd) + strlen(test_str));
5410 file.Write(code % {
5411 'func_name': func.name,
5412 'init_code': "\n".join(init_code),
5413 'check_code': "\n".join(check_code),
5417 class GLcharNHandler(CustomHandler):
5418 """Handler for functions that pass a single string with an optional len."""
5420 def __init__(self):
5421 CustomHandler.__init__(self)
5423 def InitFunction(self, func):
5424 """Overrriden from TypeHandler."""
5425 func.cmd_args = []
5426 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5428 def AddImmediateFunction(self, generator, func):
5429 """Overrriden from TypeHandler."""
5430 pass
5432 def AddBucketFunction(self, generator, func):
5433 """Overrriden from TypeHandler."""
5434 pass
5436 def WriteServiceImplementation(self, func, file):
5437 """Overrriden from TypeHandler."""
5438 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5439 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5440 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5441 Bucket* bucket = GetBucket(bucket_id);
5442 if (!bucket || bucket->size() == 0) {
5443 return error::kInvalidArguments;
5445 std::string str;
5446 if (!bucket->GetAsString(&str)) {
5447 return error::kInvalidArguments;
5449 %(gl_func_name)s(0, str.c_str());
5450 return error::kNoError;
5453 """ % {
5454 'name': func.name,
5455 'gl_func_name': func.GetGLFunctionName(),
5456 'bucket_id': func.cmd_args[0].name,
5460 class IsHandler(TypeHandler):
5461 """Handler for glIs____ type and glGetError functions."""
5463 def __init__(self):
5464 TypeHandler.__init__(self)
5466 def InitFunction(self, func):
5467 """Overrriden from TypeHandler."""
5468 func.AddCmdArg(Argument("result_shm_id", 'uint32'))
5469 func.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5470 if func.GetInfo('result') == None:
5471 func.AddInfo('result', ['uint32'])
5473 def WriteServiceUnitTest(self, func, file):
5474 """Overrriden from TypeHandler."""
5475 valid_test = """
5476 TEST_F(%(test_name)s, %(name)sValidArgs) {
5477 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5478 SpecializedSetup<cmds::%(name)s, 0>(true);
5479 cmds::%(name)s cmd;
5480 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5481 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5482 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5485 comma = ""
5486 if len(func.GetOriginalArgs()):
5487 comma =", "
5488 self.WriteValidUnitTest(func, file, valid_test, {
5489 'comma': comma,
5492 invalid_test = """
5493 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5494 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5495 SpecializedSetup<cmds::%(name)s, 0>(false);
5496 cmds::%(name)s cmd;
5497 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5498 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5501 self.WriteInvalidUnitTest(func, file, invalid_test, {
5502 'comma': comma,
5505 invalid_test = """
5506 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5507 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5508 SpecializedSetup<cmds::%(name)s, 0>(false);
5509 cmds::%(name)s cmd;
5510 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5511 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5512 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5513 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5516 self.WriteValidUnitTest(func, file, invalid_test, {
5517 'comma': comma,
5520 def WriteServiceImplementation(self, func, file):
5521 """Overrriden from TypeHandler."""
5522 file.Write(
5523 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
5524 file.Write(
5525 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5526 func.name)
5527 args = func.GetOriginalArgs()
5528 for arg in args:
5529 arg.WriteGetCode(file)
5531 code = """ typedef cmds::%(func_name)s::Result Result;
5532 Result* result_dst = GetSharedMemoryAs<Result*>(
5533 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5534 if (!result_dst) {
5535 return error::kOutOfBounds;
5538 file.Write(code % {'func_name': func.name})
5539 func.WriteHandlerValidation(file)
5540 file.Write(" *result_dst = %s(%s);\n" %
5541 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5542 file.Write(" return error::kNoError;\n")
5543 file.Write("}\n")
5544 file.Write("\n")
5546 def WriteGLES2Implementation(self, func, file):
5547 """Overrriden from TypeHandler."""
5548 impl_func = func.GetInfo('impl_func')
5549 if impl_func == None or impl_func == True:
5550 error_value = func.GetInfo("error_value") or "GL_FALSE"
5551 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5552 (func.return_type, func.original_name,
5553 func.MakeTypedOriginalArgString("")))
5554 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5555 self.WriteTraceEvent(func, file)
5556 func.WriteDestinationInitalizationValidation(file)
5557 self.WriteClientGLCallLog(func, file)
5558 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
5559 file.Write(" Result* result = GetResultAs<Result*>();\n")
5560 file.Write(" if (!result) {\n")
5561 file.Write(" return %s;\n" % error_value)
5562 file.Write(" }\n")
5563 file.Write(" *result = 0;\n")
5564 arg_string = func.MakeOriginalArgString("")
5565 comma = ""
5566 if len(arg_string) > 0:
5567 comma = ", "
5568 file.Write(
5569 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5570 (func.name, arg_string, comma))
5571 file.Write(" WaitForCmd();\n")
5572 file.Write(" %s result_value = *result;\n" % func.return_type)
5573 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5574 file.Write(" CheckGLError();\n")
5575 file.Write(" return result_value;\n")
5576 file.Write("}\n")
5577 file.Write("\n")
5579 def WriteGLES2ImplementationUnitTest(self, func, file):
5580 """Overrriden from TypeHandler."""
5581 client_test = func.GetInfo('client_test')
5582 if client_test == None or client_test == True:
5583 code = """
5584 TEST_F(GLES2ImplementationTest, %(name)s) {
5585 struct Cmds {
5586 cmds::%(name)s cmd;
5589 typedef cmds::%(name)s::Result Result;
5590 Cmds expected;
5591 ExpectedMemoryInfo result1 =
5592 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5593 expected.cmd.Init(1, result1.id, result1.offset);
5595 EXPECT_CALL(*command_buffer(), OnFlush())
5596 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5597 .RetiresOnSaturation();
5599 GLboolean result = gl_->%(name)s(1);
5600 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5601 EXPECT_TRUE(result);
5604 file.Write(code % {
5605 'name': func.name,
5609 class STRnHandler(TypeHandler):
5610 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5611 GetTranslatedShaderSourceANGLE."""
5613 def __init__(self):
5614 TypeHandler.__init__(self)
5616 def InitFunction(self, func):
5617 """Overrriden from TypeHandler."""
5618 # remove all but the first cmd args.
5619 cmd_args = func.GetCmdArgs()
5620 func.ClearCmdArgs()
5621 func.AddCmdArg(cmd_args[0])
5622 # add on a bucket id.
5623 func.AddCmdArg(Argument('bucket_id', 'uint32'))
5625 def WriteGLES2Implementation(self, func, file):
5626 """Overrriden from TypeHandler."""
5627 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5628 GPU_CLIENT_SINGLE_THREAD_CHECK();
5630 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5631 << "] gl%(func_name)s" << "("
5632 << %(arg0)s << ", "
5633 << %(arg1)s << ", "
5634 << static_cast<void*>(%(arg2)s) << ", "
5635 << static_cast<void*>(%(arg3)s) << ")");
5636 helper_->SetBucketSize(kResultBucketId, 0);
5637 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5638 std::string str;
5639 GLsizei max_size = 0;
5640 if (GetBucketAsString(kResultBucketId, &str)) {
5641 if (bufsize > 0) {
5642 max_size =
5643 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5644 memcpy(%(dest_name)s, str.c_str(), max_size);
5645 %(dest_name)s[max_size] = '\\0';
5646 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5649 if (%(length_name)s != NULL) {
5650 *%(length_name)s = max_size;
5652 CheckGLError();
5655 args = func.GetOriginalArgs()
5656 str_args = {
5657 'return_type': func.return_type,
5658 'func_name': func.original_name,
5659 'args': func.MakeTypedOriginalArgString(""),
5660 'id_name': args[0].name,
5661 'bufsize_name': args[1].name,
5662 'length_name': args[2].name,
5663 'dest_name': args[3].name,
5664 'arg0': args[0].name,
5665 'arg1': args[1].name,
5666 'arg2': args[2].name,
5667 'arg3': args[3].name,
5669 file.Write(code_1 % str_args)
5670 func.WriteDestinationInitalizationValidation(file)
5671 file.Write(code_2 % str_args)
5673 def WriteServiceUnitTest(self, func, file):
5674 """Overrriden from TypeHandler."""
5675 valid_test = """
5676 TEST_F(%(test_name)s, %(name)sValidArgs) {
5677 const char* kInfo = "hello";
5678 const uint32 kBucketId = 123;
5679 SpecializedSetup<cmds::%(name)s, 0>(true);
5680 %(expect_len_code)s
5681 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5682 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5683 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5684 cmds::%(name)s cmd;
5685 cmd.Init(%(args)s);
5686 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5687 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5688 ASSERT_TRUE(bucket != NULL);
5689 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5690 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5691 bucket->size()));
5692 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5695 args = func.GetOriginalArgs()
5696 id_name = args[0].GetValidGLArg(func, 0, 0)
5697 get_len_func = func.GetInfo('get_len_func')
5698 get_len_enum = func.GetInfo('get_len_enum')
5699 sub = {
5700 'id_name': id_name,
5701 'get_len_func': get_len_func,
5702 'get_len_enum': get_len_enum,
5703 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5704 args[0].GetValidGLArg(func, 0, 0),
5705 'args': '%s, kBucketId' % args[0].GetValidArg(func, 0, 0),
5706 'expect_len_code': '',
5708 if get_len_func and get_len_func[0:2] == 'gl':
5709 sub['expect_len_code'] = (
5710 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5711 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5712 get_len_func[2:], id_name, get_len_enum)
5713 self.WriteValidUnitTest(func, file, valid_test, sub)
5715 invalid_test = """
5716 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5717 const uint32 kBucketId = 123;
5718 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5719 .Times(0);
5720 cmds::%(name)s cmd;
5721 cmd.Init(kInvalidClientId, kBucketId);
5722 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5723 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5726 self.WriteValidUnitTest(func, file, invalid_test)
5728 def WriteServiceImplementation(self, func, file):
5729 """Overrriden from TypeHandler."""
5730 pass
5733 class FunctionInfo(object):
5734 """Holds info about a function."""
5736 def __init__(self, info, type_handler):
5737 for key in info:
5738 setattr(self, key, info[key])
5739 self.type_handler = type_handler
5740 if not 'type' in info:
5741 self.type = ''
5744 class Argument(object):
5745 """A class that represents a function argument."""
5747 cmd_type_map_ = {
5748 'GLenum': 'uint32',
5749 'GLint': 'int32',
5750 'GLintptr': 'int32',
5751 'GLsizei': 'int32',
5752 'GLsizeiptr': 'int32',
5753 'GLfloat': 'float',
5754 'GLclampf': 'float',
5756 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5758 def __init__(self, name, type):
5759 self.name = name
5760 self.optional = type.endswith("Optional*")
5761 if self.optional:
5762 type = type[:-9] + "*"
5763 self.type = type
5765 if type in self.cmd_type_map_:
5766 self.cmd_type = self.cmd_type_map_[type]
5767 else:
5768 self.cmd_type = 'uint32'
5770 def IsPointer(self):
5771 """Returns true if argument is a pointer."""
5772 return False
5774 def AddCmdArgs(self, args):
5775 """Adds command arguments for this argument to the given list."""
5776 return args.append(self)
5778 def AddInitArgs(self, args):
5779 """Adds init arguments for this argument to the given list."""
5780 return args.append(self)
5782 def GetValidArg(self, func, offset, index):
5783 """Gets a valid value for this argument."""
5784 valid_arg = func.GetValidArg(offset)
5785 if valid_arg != None:
5786 return valid_arg
5787 return str(offset + 1)
5789 def GetValidClientSideArg(self, func, offset, index):
5790 """Gets a valid value for this argument."""
5791 return str(offset + 1)
5793 def GetValidClientSideCmdArg(self, func, offset, index):
5794 """Gets a valid value for this argument."""
5795 return str(offset + 1)
5797 def GetValidGLArg(self, func, offset, index):
5798 """Gets a valid GL value for this argument."""
5799 valid_arg = func.GetValidArg(offset)
5800 if valid_arg != None:
5801 return valid_arg
5802 return str(offset + 1)
5804 def GetNumInvalidValues(self, func):
5805 """returns the number of invalid values to be tested."""
5806 return 0
5808 def GetInvalidArg(self, offset, index):
5809 """returns an invalid value and expected parse result by index."""
5810 return ("---ERROR0---", "---ERROR2---", None)
5812 def GetLogArg(self):
5813 """Get argument appropriate for LOG macro."""
5814 if self.type == 'GLboolean':
5815 return 'GLES2Util::GetStringBool(%s)' % self.name
5816 if self.type == 'GLenum':
5817 return 'GLES2Util::GetStringEnum(%s)' % self.name
5818 return self.name
5820 def WriteGetCode(self, file):
5821 """Writes the code to get an argument from a command structure."""
5822 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5823 (self.type, self.name, self.type, self.name))
5825 def WriteValidationCode(self, file, func):
5826 """Writes the validation code for an argument."""
5827 pass
5829 def WriteClientSideValidationCode(self, file, func):
5830 """Writes the validation code for an argument."""
5831 pass
5833 def WriteDestinationInitalizationValidation(self, file, func):
5834 """Writes the client side destintion initialization validation."""
5835 pass
5837 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
5838 """Writes the client side destintion initialization validation if needed."""
5839 parts = self.type.split(" ")
5840 if len(parts) > 1:
5841 return
5842 if parts[0] in self.need_validation_:
5843 file.Write(
5844 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5845 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
5848 def WriteGetAddress(self, file):
5849 """Writes the code to get the address this argument refers to."""
5850 pass
5852 def GetImmediateVersion(self):
5853 """Gets the immediate version of this argument."""
5854 return self
5856 def GetBucketVersion(self):
5857 """Gets the bucket version of this argument."""
5858 return self
5861 class BoolArgument(Argument):
5862 """class for GLboolean"""
5864 def __init__(self, name, type):
5865 Argument.__init__(self, name, 'GLboolean')
5867 def GetValidArg(self, func, offset, index):
5868 """Gets a valid value for this argument."""
5869 return 'true'
5871 def GetValidClientSideArg(self, func, offset, index):
5872 """Gets a valid value for this argument."""
5873 return 'true'
5875 def GetValidClientSideCmdArg(self, func, offset, index):
5876 """Gets a valid value for this argument."""
5877 return 'true'
5879 def GetValidGLArg(self, func, offset, index):
5880 """Gets a valid GL value for this argument."""
5881 return 'true'
5884 class UniformLocationArgument(Argument):
5885 """class for uniform locations."""
5887 def __init__(self, name):
5888 Argument.__init__(self, name, "GLint")
5890 def WriteGetCode(self, file):
5891 """Writes the code to get an argument from a command structure."""
5892 code = """ %s %s = static_cast<%s>(c.%s);
5894 file.Write(code % (self.type, self.name, self.type, self.name))
5896 def GetValidArg(self, func, offset, index):
5897 """Gets a valid value for this argument."""
5898 return "%d" % (offset + 1)
5901 class DataSizeArgument(Argument):
5902 """class for data_size which Bucket commands do not need."""
5904 def __init__(self, name):
5905 Argument.__init__(self, name, "uint32")
5907 def GetBucketVersion(self):
5908 return None
5911 class SizeArgument(Argument):
5912 """class for GLsizei and GLsizeiptr."""
5914 def __init__(self, name, type):
5915 Argument.__init__(self, name, type)
5917 def GetNumInvalidValues(self, func):
5918 """overridden from Argument."""
5919 if func.is_immediate:
5920 return 0
5921 return 1
5923 def GetInvalidArg(self, offset, index):
5924 """overridden from Argument."""
5925 return ("-1", "kNoError", "GL_INVALID_VALUE")
5927 def WriteValidationCode(self, file, func):
5928 """overridden from Argument."""
5929 file.Write(" if (%s < 0) {\n" % self.name)
5930 file.Write(
5931 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5932 (func.original_name, self.name))
5933 file.Write(" return error::kNoError;\n")
5934 file.Write(" }\n")
5936 def WriteClientSideValidationCode(self, file, func):
5937 """overridden from Argument."""
5938 file.Write(" if (%s < 0) {\n" % self.name)
5939 file.Write(
5940 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5941 (func.original_name, self.name))
5942 file.Write(" return;\n")
5943 file.Write(" }\n")
5946 class SizeNotNegativeArgument(SizeArgument):
5947 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5949 def __init__(self, name, type, gl_type):
5950 SizeArgument.__init__(self, name, gl_type)
5952 def GetInvalidArg(self, offset, index):
5953 """overridden from SizeArgument."""
5954 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5956 def WriteValidationCode(self, file, func):
5957 """overridden from SizeArgument."""
5958 pass
5961 class EnumBaseArgument(Argument):
5962 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5964 def __init__(self, name, gl_type, type, gl_error):
5965 Argument.__init__(self, name, gl_type)
5967 self.local_type = type
5968 self.gl_error = gl_error
5969 name = type[len(gl_type):]
5970 self.type_name = name
5971 self.enum_info = _ENUM_LISTS[name]
5973 def WriteValidationCode(self, file, func):
5974 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5975 (ToUnderscore(self.type_name), self.name))
5976 if self.gl_error == "GL_INVALID_ENUM":
5977 file.Write(
5978 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5979 (func.original_name, self.name, self.name))
5980 else:
5981 file.Write(
5982 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5983 (self.gl_error, func.original_name, self.name, self.gl_error))
5984 file.Write(" return error::kNoError;\n")
5985 file.Write(" }\n")
5987 def GetValidArg(self, func, offset, index):
5988 valid_arg = func.GetValidArg(offset)
5989 if valid_arg != None:
5990 return valid_arg
5991 if 'valid' in self.enum_info:
5992 valid = self.enum_info['valid']
5993 num_valid = len(valid)
5994 if index >= num_valid:
5995 index = num_valid - 1
5996 return valid[index]
5997 return str(offset + 1)
5999 def GetValidClientSideArg(self, func, offset, index):
6000 """Gets a valid value for this argument."""
6001 return self.GetValidArg(func, offset, index)
6003 def GetValidClientSideCmdArg(self, func, offset, index):
6004 """Gets a valid value for this argument."""
6005 return self.GetValidArg(func, offset, index)
6007 def GetValidGLArg(self, func, offset, index):
6008 """Gets a valid value for this argument."""
6009 return self.GetValidArg(func, offset, index)
6011 def GetNumInvalidValues(self, func):
6012 """returns the number of invalid values to be tested."""
6013 if 'invalid' in self.enum_info:
6014 invalid = self.enum_info['invalid']
6015 return len(invalid)
6016 return 0
6018 def GetInvalidArg(self, offset, index):
6019 """returns an invalid value by index."""
6020 if 'invalid' in self.enum_info:
6021 invalid = self.enum_info['invalid']
6022 num_invalid = len(invalid)
6023 if index >= num_invalid:
6024 index = num_invalid - 1
6025 return (invalid[index], "kNoError", self.gl_error)
6026 return ("---ERROR1---", "kNoError", self.gl_error)
6029 class EnumArgument(EnumBaseArgument):
6030 """A class that represents a GLenum argument"""
6032 def __init__(self, name, type):
6033 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
6035 def GetLogArg(self):
6036 """Overridden from Argument."""
6037 return ("GLES2Util::GetString%s(%s)" %
6038 (self.type_name, self.name))
6041 class IntArgument(EnumBaseArgument):
6042 """A class for a GLint argument that can only except specific values.
6044 For example glTexImage2D takes a GLint for its internalformat
6045 argument instead of a GLenum.
6048 def __init__(self, name, type):
6049 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
6052 class ValidatedBoolArgument(EnumBaseArgument):
6053 """A class for a GLboolean argument that can only except specific values.
6055 For example glUniformMatrix takes a GLboolean for it's transpose but it
6056 must be false.
6059 def __init__(self, name, type):
6060 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
6062 def GetLogArg(self):
6063 """Overridden from Argument."""
6064 return 'GLES2Util::GetStringBool(%s)' % self.name
6067 class ImmediatePointerArgument(Argument):
6068 """A class that represents an immediate argument to a function.
6070 An immediate argument is one where the data follows the command.
6073 def __init__(self, name, type):
6074 Argument.__init__(self, name, type)
6076 def AddCmdArgs(self, args):
6077 """Overridden from Argument."""
6078 pass
6080 def WriteGetCode(self, file):
6081 """Overridden from Argument."""
6082 file.Write(
6083 " %s %s = GetImmediateDataAs<%s>(\n" %
6084 (self.type, self.name, self.type))
6085 file.Write(" c, data_size, immediate_data_size);\n")
6087 def WriteValidationCode(self, file, func):
6088 """Overridden from Argument."""
6089 file.Write(" if (%s == NULL) {\n" % self.name)
6090 file.Write(" return error::kOutOfBounds;\n")
6091 file.Write(" }\n")
6093 def GetImmediateVersion(self):
6094 """Overridden from Argument."""
6095 return None
6097 def WriteDestinationInitalizationValidation(self, file, func):
6098 """Overridden from Argument."""
6099 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6101 def GetLogArg(self):
6102 """Overridden from Argument."""
6103 return "static_cast<const void*>(%s)" % self.name
6106 class BucketPointerArgument(Argument):
6107 """A class that represents an bucket argument to a function."""
6109 def __init__(self, name, type):
6110 Argument.__init__(self, name, type)
6112 def AddCmdArgs(self, args):
6113 """Overridden from Argument."""
6114 pass
6116 def WriteGetCode(self, file):
6117 """Overridden from Argument."""
6118 file.Write(
6119 " %s %s = bucket->GetData(0, data_size);\n" %
6120 (self.type, self.name))
6122 def WriteValidationCode(self, file, func):
6123 """Overridden from Argument."""
6124 pass
6126 def GetImmediateVersion(self):
6127 """Overridden from Argument."""
6128 return None
6130 def WriteDestinationInitalizationValidation(self, file, func):
6131 """Overridden from Argument."""
6132 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6134 def GetLogArg(self):
6135 """Overridden from Argument."""
6136 return "static_cast<const void*>(%s)" % self.name
6139 class PointerArgument(Argument):
6140 """A class that represents a pointer argument to a function."""
6142 def __init__(self, name, type):
6143 Argument.__init__(self, name, type)
6145 def IsPointer(self):
6146 """Returns true if argument is a pointer."""
6147 return True
6149 def GetValidArg(self, func, offset, index):
6150 """Overridden from Argument."""
6151 return "shared_memory_id_, shared_memory_offset_"
6153 def GetValidGLArg(self, func, offset, index):
6154 """Overridden from Argument."""
6155 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
6157 def GetNumInvalidValues(self, func):
6158 """Overridden from Argument."""
6159 return 2
6161 def GetInvalidArg(self, offset, index):
6162 """Overridden from Argument."""
6163 if index == 0:
6164 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6165 else:
6166 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6167 "kOutOfBounds", None)
6169 def GetLogArg(self):
6170 """Overridden from Argument."""
6171 return "static_cast<const void*>(%s)" % self.name
6173 def AddCmdArgs(self, args):
6174 """Overridden from Argument."""
6175 args.append(Argument("%s_shm_id" % self.name, 'uint32'))
6176 args.append(Argument("%s_shm_offset" % self.name, 'uint32'))
6178 def WriteGetCode(self, file):
6179 """Overridden from Argument."""
6180 file.Write(
6181 " %s %s = GetSharedMemoryAs<%s>(\n" %
6182 (self.type, self.name, self.type))
6183 file.Write(
6184 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6185 (self.name, self.name))
6187 def WriteGetAddress(self, file):
6188 """Overridden from Argument."""
6189 file.Write(
6190 " %s %s = GetSharedMemoryAs<%s>(\n" %
6191 (self.type, self.name, self.type))
6192 file.Write(
6193 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6194 (self.name, self.name, self.name))
6196 def WriteValidationCode(self, file, func):
6197 """Overridden from Argument."""
6198 file.Write(" if (%s == NULL) {\n" % self.name)
6199 file.Write(" return error::kOutOfBounds;\n")
6200 file.Write(" }\n")
6202 def GetImmediateVersion(self):
6203 """Overridden from Argument."""
6204 return ImmediatePointerArgument(self.name, self.type)
6206 def GetBucketVersion(self):
6207 """Overridden from Argument."""
6208 if self.type == "const char*":
6209 return InputStringBucketArgument(self.name, self.type)
6210 return BucketPointerArgument(self.name, self.type)
6212 def WriteDestinationInitalizationValidation(self, file, func):
6213 """Overridden from Argument."""
6214 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6217 class InputStringBucketArgument(Argument):
6218 """An string input argument where the string is passed in a bucket."""
6220 def __init__(self, name, type):
6221 Argument.__init__(self, name + "_bucket_id", "uint32")
6223 def WriteGetCode(self, file):
6224 """Overridden from Argument."""
6225 code = """
6226 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6227 if (!%(name)s_bucket) {
6228 return error::kInvalidArguments;
6230 std::string %(name)s_str;
6231 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6232 return error::kInvalidArguments;
6234 const char* %(name)s = %(name)s_str.c_str();
6236 file.Write(code % {
6237 'name': self.name,
6240 def GetValidArg(self, func, offset, index):
6241 return "kNameBucketId"
6243 def GetValidGLArg(self, func, offset, index):
6244 return "_"
6247 class NonImmediatePointerArgument(PointerArgument):
6248 """A pointer argument that stays a pointer even in an immediate cmd."""
6250 def __init__(self, name, type):
6251 PointerArgument.__init__(self, name, type)
6253 def IsPointer(self):
6254 """Returns true if argument is a pointer."""
6255 return False
6257 def GetImmediateVersion(self):
6258 """Overridden from Argument."""
6259 return self
6262 class ResourceIdArgument(Argument):
6263 """A class that represents a resource id argument to a function."""
6265 def __init__(self, name, type):
6266 match = re.match("(GLid\w+)", type)
6267 self.resource_type = match.group(1)[4:]
6268 type = type.replace(match.group(1), "GLuint")
6269 Argument.__init__(self, name, type)
6271 def WriteGetCode(self, file):
6272 """Overridden from Argument."""
6273 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6275 def GetValidArg(self, func, offset, index):
6276 return "client_%s_id_" % self.resource_type.lower()
6278 def GetValidGLArg(self, func, offset, index):
6279 return "kService%sId" % self.resource_type
6282 class ResourceIdBindArgument(Argument):
6283 """Represents a resource id argument to a bind function."""
6285 def __init__(self, name, type):
6286 match = re.match("(GLidBind\w+)", type)
6287 self.resource_type = match.group(1)[8:]
6288 type = type.replace(match.group(1), "GLuint")
6289 Argument.__init__(self, name, type)
6291 def WriteGetCode(self, file):
6292 """Overridden from Argument."""
6293 code = """ %(type)s %(name)s = c.%(name)s;
6295 file.Write(code % {'type': self.type, '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
6304 class ResourceIdZeroArgument(Argument):
6305 """Represents a resource id argument to a function that can be zero."""
6307 def __init__(self, name, type):
6308 match = re.match("(GLidZero\w+)", type)
6309 self.resource_type = match.group(1)[8:]
6310 type = type.replace(match.group(1), "GLuint")
6311 Argument.__init__(self, name, type)
6313 def WriteGetCode(self, file):
6314 """Overridden from Argument."""
6315 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6317 def GetValidArg(self, func, offset, index):
6318 return "client_%s_id_" % self.resource_type.lower()
6320 def GetValidGLArg(self, func, offset, index):
6321 return "kService%sId" % self.resource_type
6323 def GetNumInvalidValues(self, func):
6324 """returns the number of invalid values to be tested."""
6325 return 1
6327 def GetInvalidArg(self, offset, index):
6328 """returns an invalid value by index."""
6329 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6332 class Function(object):
6333 """A class that represents a function."""
6335 def __init__(self, original_name, name, info, return_type, original_args,
6336 args_for_cmds, cmd_args, init_args, num_pointer_args):
6337 self.name = name
6338 self.original_name = original_name
6339 self.info = info
6340 self.type_handler = info.type_handler
6341 self.return_type = return_type
6342 self.original_args = original_args
6343 self.num_pointer_args = num_pointer_args
6344 self.can_auto_generate = num_pointer_args == 0 and return_type == "void"
6345 self.cmd_args = cmd_args
6346 self.init_args = init_args
6347 self.InitFunction()
6348 self.args_for_cmds = args_for_cmds
6349 self.is_immediate = False
6351 def IsType(self, type_name):
6352 """Returns true if function is a certain type."""
6353 return self.info.type == type_name
6355 def InitFunction(self):
6356 """Calls the init function for the type handler."""
6357 self.type_handler.InitFunction(self)
6359 def GetInfo(self, name):
6360 """Returns a value from the function info for this function."""
6361 if hasattr(self.info, name):
6362 return getattr(self.info, name)
6363 return None
6365 def GetValidArg(self, index):
6366 """Gets a valid arg from the function info if one exists."""
6367 valid_args = self.GetInfo('valid_args')
6368 if valid_args and str(index) in valid_args:
6369 return valid_args[str(index)]
6370 return None
6372 def AddInfo(self, name, value):
6373 """Adds an info."""
6374 setattr(self.info, name, value)
6376 def IsCoreGLFunction(self):
6377 return (not self.GetInfo('extension') and
6378 not self.GetInfo('pepper_interface'))
6380 def InPepperInterface(self, interface):
6381 ext = self.GetInfo('pepper_interface')
6382 if not interface.GetName():
6383 return self.IsCoreGLFunction()
6384 return ext == interface.GetName()
6386 def InAnyPepperExtension(self):
6387 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
6389 def GetGLFunctionName(self):
6390 """Gets the function to call to execute GL for this command."""
6391 if self.GetInfo('decoder_func'):
6392 return self.GetInfo('decoder_func')
6393 return "gl%s" % self.original_name
6395 def GetGLTestFunctionName(self):
6396 gl_func_name = self.GetInfo('gl_test_func')
6397 if gl_func_name == None:
6398 gl_func_name = self.GetGLFunctionName()
6399 if gl_func_name.startswith("gl"):
6400 gl_func_name = gl_func_name[2:]
6401 else:
6402 gl_func_name = self.original_name
6403 return gl_func_name
6405 def AddCmdArg(self, arg):
6406 """Adds a cmd argument to this function."""
6407 self.cmd_args.append(arg)
6409 def GetCmdArgs(self):
6410 """Gets the command args for this function."""
6411 return self.cmd_args
6413 def ClearCmdArgs(self):
6414 """Clears the command args for this function."""
6415 self.cmd_args = []
6417 def GetInitArgs(self):
6418 """Gets the init args for this function."""
6419 return self.init_args
6421 def GetOriginalArgs(self):
6422 """Gets the original arguments to this function."""
6423 return self.original_args
6425 def GetLastOriginalArg(self):
6426 """Gets the last original argument to this function."""
6427 return self.original_args[len(self.original_args) - 1]
6429 def __MaybePrependComma(self, arg_string, add_comma):
6430 """Adds a comma if arg_string is not empty and add_comma is true."""
6431 comma = ""
6432 if add_comma and len(arg_string):
6433 comma = ", "
6434 return "%s%s" % (comma, arg_string)
6436 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
6437 """Gets a list of arguments as they are in GL."""
6438 args = self.GetOriginalArgs()
6439 arg_string = ", ".join(
6440 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6441 return self.__MaybePrependComma(arg_string, add_comma)
6443 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
6444 """Gets the list of arguments as they are in GL."""
6445 args = self.GetOriginalArgs()
6446 arg_string = separator.join(
6447 ["%s%s" % (prefix, arg.name) for arg in args])
6448 return self.__MaybePrependComma(arg_string, add_comma)
6450 def MakeTypedPepperArgString(self, prefix):
6451 """Gets a list of arguments as they need to be for Pepper."""
6452 if self.GetInfo("pepper_args"):
6453 return self.GetInfo("pepper_args")
6454 else:
6455 return self.MakeTypedOriginalArgString(prefix, False)
6457 def GetPepperName(self):
6458 if self.GetInfo("pepper_name"):
6459 return self.GetInfo("pepper_name")
6460 return self.name
6462 def MakeTypedCmdArgString(self, prefix, add_comma = False):
6463 """Gets a typed list of arguments as they need to be for command buffers."""
6464 args = self.GetCmdArgs()
6465 arg_string = ", ".join(
6466 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6467 return self.__MaybePrependComma(arg_string, add_comma)
6469 def MakeCmdArgString(self, prefix, add_comma = False):
6470 """Gets the list of arguments as they need to be for command buffers."""
6471 args = self.GetCmdArgs()
6472 arg_string = ", ".join(
6473 ["%s%s" % (prefix, arg.name) for arg in args])
6474 return self.__MaybePrependComma(arg_string, add_comma)
6476 def MakeTypedInitString(self, prefix, add_comma = False):
6477 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6478 args = self.GetInitArgs()
6479 arg_string = ", ".join(
6480 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6481 return self.__MaybePrependComma(arg_string, add_comma)
6483 def MakeInitString(self, prefix, add_comma = False):
6484 """Gets the list of arguments as they need to be for cmd Init/Set."""
6485 args = self.GetInitArgs()
6486 arg_string = ", ".join(
6487 ["%s%s" % (prefix, arg.name) for arg in args])
6488 return self.__MaybePrependComma(arg_string, add_comma)
6490 def MakeLogArgString(self):
6491 """Makes a string of the arguments for the LOG macros"""
6492 args = self.GetOriginalArgs()
6493 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
6495 def WriteCommandDescription(self, file):
6496 """Writes a description of the command."""
6497 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
6499 def WriteHandlerValidation(self, file):
6500 """Writes validation code for the function."""
6501 for arg in self.GetOriginalArgs():
6502 arg.WriteValidationCode(file, self)
6503 self.WriteValidationCode(file)
6505 def WriteHandlerImplementation(self, file):
6506 """Writes the handler implementation for this command."""
6507 self.type_handler.WriteHandlerImplementation(self, file)
6509 def WriteValidationCode(self, file):
6510 """Writes the validation code for a command."""
6511 pass
6513 def WriteCmdFlag(self, file):
6514 """Writes the cmd cmd_flags constant."""
6515 flags = []
6516 trace_level = 3 # By default trace only at the highest level
6517 if hasattr(self.info, 'trace_level'):
6518 if (self.info.trace_level < 0) or (self.info.trace_level > 3):
6519 raise KeyError("Unhandled trace_level: %d" % self.info.trace_level)
6520 trace_level = self.info.trace_level
6522 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
6524 if len(flags) > 0:
6525 cmd_flags = ' | '.join(flags)
6526 else:
6527 cmd_flags = 0
6529 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
6532 def WriteCmdArgFlag(self, file):
6533 """Writes the cmd kArgFlags constant."""
6534 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6536 def WriteCmdComputeSize(self, file):
6537 """Writes the ComputeSize function for the command."""
6538 file.Write(" static uint32 ComputeSize() {\n")
6539 file.Write(
6540 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6541 file.Write(" }\n")
6542 file.Write("\n")
6544 def WriteCmdSetHeader(self, file):
6545 """Writes the cmd's SetHeader function."""
6546 file.Write(" void SetHeader() {\n")
6547 file.Write(" header.SetCmd<ValueType>();\n")
6548 file.Write(" }\n")
6549 file.Write("\n")
6551 def WriteCmdInit(self, file):
6552 """Writes the cmd's Init function."""
6553 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
6554 file.Write(" SetHeader();\n")
6555 args = self.GetCmdArgs()
6556 for arg in args:
6557 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6558 file.Write(" }\n")
6559 file.Write("\n")
6561 def WriteCmdSet(self, file):
6562 """Writes the cmd's Set function."""
6563 copy_args = self.MakeCmdArgString("_", False)
6564 file.Write(" void* Set(void* cmd%s) {\n" %
6565 self.MakeTypedCmdArgString("_", True))
6566 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
6567 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6568 file.Write(" }\n")
6569 file.Write("\n")
6571 def WriteStruct(self, file):
6572 self.type_handler.WriteStruct(self, file)
6574 def WriteDocs(self, file):
6575 self.type_handler.WriteDocs(self, file)
6577 def WriteCmdHelper(self, file):
6578 """Writes the cmd's helper."""
6579 self.type_handler.WriteCmdHelper(self, file)
6581 def WriteServiceImplementation(self, file):
6582 """Writes the service implementation for a command."""
6583 self.type_handler.WriteServiceImplementation(self, file)
6585 def WriteServiceUnitTest(self, file):
6586 """Writes the service implementation for a command."""
6587 self.type_handler.WriteServiceUnitTest(self, file)
6589 def WriteGLES2CLibImplementation(self, file):
6590 """Writes the GLES2 C Lib Implemention."""
6591 self.type_handler.WriteGLES2CLibImplementation(self, file)
6593 def WriteGLES2InterfaceHeader(self, file):
6594 """Writes the GLES2 Interface declaration."""
6595 self.type_handler.WriteGLES2InterfaceHeader(self, file)
6597 def WriteGLES2InterfaceStub(self, file):
6598 """Writes the GLES2 Interface Stub declaration."""
6599 self.type_handler.WriteGLES2InterfaceStub(self, file)
6601 def WriteGLES2InterfaceStubImpl(self, file):
6602 """Writes the GLES2 Interface Stub declaration."""
6603 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
6605 def WriteGLES2ImplementationHeader(self, file):
6606 """Writes the GLES2 Implemention declaration."""
6607 self.type_handler.WriteGLES2ImplementationHeader(self, file)
6609 def WriteGLES2Implementation(self, file):
6610 """Writes the GLES2 Implemention definition."""
6611 self.type_handler.WriteGLES2Implementation(self, file)
6613 def WriteGLES2TraceImplementationHeader(self, file):
6614 """Writes the GLES2 Trace Implemention declaration."""
6615 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
6617 def WriteGLES2TraceImplementation(self, file):
6618 """Writes the GLES2 Trace Implemention definition."""
6619 self.type_handler.WriteGLES2TraceImplementation(self, file)
6621 def WriteGLES2Header(self, file):
6622 """Writes the GLES2 Implemention unit test."""
6623 self.type_handler.WriteGLES2Header(self, file)
6625 def WriteGLES2ImplementationUnitTest(self, file):
6626 """Writes the GLES2 Implemention unit test."""
6627 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
6629 def WriteDestinationInitalizationValidation(self, file):
6630 """Writes the client side destintion initialization validation."""
6631 self.type_handler.WriteDestinationInitalizationValidation(self, file)
6633 def WriteFormatTest(self, file):
6634 """Writes the cmd's format test."""
6635 self.type_handler.WriteFormatTest(self, file)
6638 class PepperInterface(object):
6639 """A class that represents a function."""
6641 def __init__(self, info):
6642 self.name = info["name"]
6643 self.dev = info["dev"]
6645 def GetName(self):
6646 return self.name
6648 def GetInterfaceName(self):
6649 upperint = ""
6650 dev = ""
6651 if self.name:
6652 upperint = "_" + self.name.upper()
6653 if self.dev:
6654 dev = "_DEV"
6655 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
6657 def GetInterfaceString(self):
6658 dev = ""
6659 if self.dev:
6660 dev = "(Dev)"
6661 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6663 def GetStructName(self):
6664 dev = ""
6665 if self.dev:
6666 dev = "_Dev"
6667 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6670 class ImmediateFunction(Function):
6671 """A class that represnets an immediate function command."""
6673 def __init__(self, func):
6674 new_args = []
6675 for arg in func.GetOriginalArgs():
6676 new_arg = arg.GetImmediateVersion()
6677 if new_arg:
6678 new_args.append(new_arg)
6680 cmd_args = []
6681 new_args_for_cmds = []
6682 for arg in func.args_for_cmds:
6683 new_arg = arg.GetImmediateVersion()
6684 if new_arg:
6685 new_args_for_cmds.append(new_arg)
6686 new_arg.AddCmdArgs(cmd_args)
6688 new_init_args = []
6689 for arg in new_args_for_cmds:
6690 arg.AddInitArgs(new_init_args)
6692 Function.__init__(
6693 self,
6694 func.original_name,
6695 "%sImmediate" % func.name,
6696 func.info,
6697 func.return_type,
6698 new_args,
6699 new_args_for_cmds,
6700 cmd_args,
6701 new_init_args,
6703 self.is_immediate = True
6705 def WriteCommandDescription(self, file):
6706 """Overridden from Function"""
6707 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6708 self.original_name)
6710 def WriteServiceImplementation(self, file):
6711 """Overridden from Function"""
6712 self.type_handler.WriteImmediateServiceImplementation(self, file)
6714 def WriteHandlerImplementation(self, file):
6715 """Overridden from Function"""
6716 self.type_handler.WriteImmediateHandlerImplementation(self, file)
6718 def WriteServiceUnitTest(self, file):
6719 """Writes the service implementation for a command."""
6720 self.type_handler.WriteImmediateServiceUnitTest(self, file)
6722 def WriteValidationCode(self, file):
6723 """Overridden from Function"""
6724 self.type_handler.WriteImmediateValidationCode(self, file)
6726 def WriteCmdArgFlag(self, file):
6727 """Overridden from Function"""
6728 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6730 def WriteCmdComputeSize(self, file):
6731 """Overridden from Function"""
6732 self.type_handler.WriteImmediateCmdComputeSize(self, file)
6734 def WriteCmdSetHeader(self, file):
6735 """Overridden from Function"""
6736 self.type_handler.WriteImmediateCmdSetHeader(self, file)
6738 def WriteCmdInit(self, file):
6739 """Overridden from Function"""
6740 self.type_handler.WriteImmediateCmdInit(self, file)
6742 def WriteCmdSet(self, file):
6743 """Overridden from Function"""
6744 self.type_handler.WriteImmediateCmdSet(self, file)
6746 def WriteCmdHelper(self, file):
6747 """Overridden from Function"""
6748 self.type_handler.WriteImmediateCmdHelper(self, file)
6750 def WriteFormatTest(self, file):
6751 """Overridden from Function"""
6752 self.type_handler.WriteImmediateFormatTest(self, file)
6755 class BucketFunction(Function):
6756 """A class that represnets a bucket version of a function command."""
6758 def __init__(self, func):
6759 new_args = []
6760 for arg in func.GetOriginalArgs():
6761 new_arg = arg.GetBucketVersion()
6762 if new_arg:
6763 new_args.append(new_arg)
6765 cmd_args = []
6766 new_args_for_cmds = []
6767 for arg in func.args_for_cmds:
6768 new_arg = arg.GetBucketVersion()
6769 if new_arg:
6770 new_args_for_cmds.append(new_arg)
6771 new_arg.AddCmdArgs(cmd_args)
6773 new_init_args = []
6774 for arg in new_args_for_cmds:
6775 arg.AddInitArgs(new_init_args)
6777 Function.__init__(
6778 self,
6779 func.original_name,
6780 "%sBucket" % func.name,
6781 func.info,
6782 func.return_type,
6783 new_args,
6784 new_args_for_cmds,
6785 cmd_args,
6786 new_init_args,
6789 # def InitFunction(self):
6790 # """Overridden from Function"""
6791 # pass
6793 def WriteCommandDescription(self, file):
6794 """Overridden from Function"""
6795 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6796 self.original_name)
6798 def WriteServiceImplementation(self, file):
6799 """Overridden from Function"""
6800 self.type_handler.WriteBucketServiceImplementation(self, file)
6802 def WriteHandlerImplementation(self, file):
6803 """Overridden from Function"""
6804 self.type_handler.WriteBucketHandlerImplementation(self, file)
6806 def WriteServiceUnitTest(self, file):
6807 """Writes the service implementation for a command."""
6808 self.type_handler.WriteBucketServiceUnitTest(self, file)
6811 def CreateArg(arg_string):
6812 """Creates an Argument."""
6813 arg_parts = arg_string.split()
6814 if len(arg_parts) == 1 and arg_parts[0] == 'void':
6815 return None
6816 # Is this a pointer argument?
6817 elif arg_string.find('*') >= 0:
6818 if arg_parts[0] == 'NonImmediate':
6819 return NonImmediatePointerArgument(
6820 arg_parts[-1],
6821 " ".join(arg_parts[1:-1]))
6822 else:
6823 return PointerArgument(
6824 arg_parts[-1],
6825 " ".join(arg_parts[0:-1]))
6826 # Is this a resource argument? Must come after pointer check.
6827 elif arg_parts[0].startswith('GLidBind'):
6828 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6829 elif arg_parts[0].startswith('GLidZero'):
6830 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6831 elif arg_parts[0].startswith('GLid'):
6832 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6833 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
6834 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6835 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
6836 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6837 elif arg_parts[0].startswith('GLboolean'):
6838 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6839 elif arg_parts[0].startswith('GLintUniformLocation'):
6840 return UniformLocationArgument(arg_parts[-1])
6841 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
6842 not arg_parts[0].startswith('GLintptr')):
6843 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6844 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
6845 arg_parts[0].startswith('GLintptrNotNegative')):
6846 return SizeNotNegativeArgument(arg_parts[-1],
6847 " ".join(arg_parts[0:-1]),
6848 arg_parts[0][0:-11])
6849 elif arg_parts[0].startswith('GLsize'):
6850 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6851 else:
6852 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6855 class GLGenerator(object):
6856 """A class to generate GL command buffers."""
6858 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6860 def __init__(self, verbose):
6861 self.original_functions = []
6862 self.functions = []
6863 self.verbose = verbose
6864 self.errors = 0
6865 self._function_info = {}
6866 self._empty_type_handler = TypeHandler()
6867 self._empty_function_info = FunctionInfo({}, self._empty_type_handler)
6868 self.pepper_interfaces = []
6869 self.interface_info = {}
6871 self._type_handlers = {
6872 'Bind': BindHandler(),
6873 'Create': CreateHandler(),
6874 'Custom': CustomHandler(),
6875 'Data': DataHandler(),
6876 'Delete': DeleteHandler(),
6877 'DELn': DELnHandler(),
6878 'GENn': GENnHandler(),
6879 'GETn': GETnHandler(),
6880 'GLchar': GLcharHandler(),
6881 'GLcharN': GLcharNHandler(),
6882 'HandWritten': HandWrittenHandler(),
6883 'Is': IsHandler(),
6884 'Manual': ManualHandler(),
6885 'PUT': PUTHandler(),
6886 'PUTn': PUTnHandler(),
6887 'PUTXn': PUTXnHandler(),
6888 'StateSet': StateSetHandler(),
6889 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6890 'StateSetFrontBack': StateSetFrontBackHandler(),
6891 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6892 'StateSetNamedParameter': StateSetNamedParameter(),
6893 'STRn': STRnHandler(),
6894 'Todo': TodoHandler(),
6897 for func_name in _FUNCTION_INFO:
6898 info = _FUNCTION_INFO[func_name]
6899 type = ''
6900 if 'type' in info:
6901 type = info['type']
6902 self._function_info[func_name] = FunctionInfo(info,
6903 self.GetTypeHandler(type))
6904 for interface in _PEPPER_INTERFACES:
6905 interface = PepperInterface(interface)
6906 self.pepper_interfaces.append(interface)
6907 self.interface_info[interface.GetName()] = interface
6909 def AddFunction(self, func):
6910 """Adds a function."""
6911 self.functions.append(func)
6913 def GetTypeHandler(self, name):
6914 """Gets a type info for the given type."""
6915 if len(name):
6916 if name in self._type_handlers:
6917 return self._type_handlers[name]
6918 else:
6919 raise KeyError("no such type handler: %s" % name)
6920 return self._empty_type_handler
6922 def GetFunctionInfo(self, name):
6923 """Gets a type info for the given function name."""
6924 if name in self._function_info:
6925 return self._function_info[name]
6926 return self._empty_function_info
6928 def Log(self, msg):
6929 """Prints something if verbose is true."""
6930 if self.verbose:
6931 print msg
6933 def Error(self, msg):
6934 """Prints an error."""
6935 print "Error: %s" % msg
6936 self.errors += 1
6938 def WriteLicense(self, file):
6939 """Writes the license."""
6940 file.Write(_LICENSE)
6942 def WriteNamespaceOpen(self, file):
6943 """Writes the code for the namespace."""
6944 file.Write("namespace gpu {\n")
6945 file.Write("namespace gles2 {\n")
6946 file.Write("\n")
6948 def WriteNamespaceClose(self, file):
6949 """Writes the code to close the namespace."""
6950 file.Write("} // namespace gles2\n")
6951 file.Write("} // namespace gpu\n")
6952 file.Write("\n")
6954 def ParseArgs(self, arg_string):
6955 """Parses a function arg string."""
6956 args = []
6957 num_pointer_args = 0
6958 parts = arg_string.split(',')
6959 is_gl_enum = False
6960 for arg_string in parts:
6961 if arg_string.startswith('GLenum '):
6962 is_gl_enum = True
6963 arg = CreateArg(arg_string)
6964 if arg:
6965 args.append(arg)
6966 if arg.IsPointer():
6967 num_pointer_args += 1
6968 return (args, num_pointer_args, is_gl_enum)
6970 def ParseGLH(self, filename):
6971 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6972 f = open("gpu/command_buffer/cmd_buffer_functions.txt", "r")
6973 functions = f.read()
6974 f.close()
6975 for line in functions.splitlines():
6976 match = self._function_re.match(line)
6977 if match:
6978 func_name = match.group(2)[2:]
6979 func_info = self.GetFunctionInfo(func_name)
6980 if func_info.type != 'Noop':
6981 return_type = match.group(1).strip()
6982 arg_string = match.group(3)
6983 (args, num_pointer_args, is_gl_enum) = self.ParseArgs(arg_string)
6984 # comment in to find out which functions use bare enums.
6985 # if is_gl_enum:
6986 # self.Log("%s uses bare GLenum" % func_name)
6987 args_for_cmds = args
6988 if hasattr(func_info, 'cmd_args'):
6989 (args_for_cmds, num_pointer_args, is_gl_enum) = (
6990 self.ParseArgs(getattr(func_info, 'cmd_args')))
6991 cmd_args = []
6992 for arg in args_for_cmds:
6993 arg.AddCmdArgs(cmd_args)
6994 init_args = []
6995 for arg in args_for_cmds:
6996 arg.AddInitArgs(init_args)
6997 return_arg = CreateArg(return_type + " result")
6998 if return_arg:
6999 init_args.append(return_arg)
7000 f = Function(func_name, func_name, func_info, return_type, args,
7001 args_for_cmds, cmd_args, init_args, num_pointer_args)
7002 self.original_functions.append(f)
7003 gen_cmd = f.GetInfo('gen_cmd')
7004 if gen_cmd == True or gen_cmd == None:
7005 self.AddFunction(f)
7006 f.type_handler.AddImmediateFunction(self, f)
7007 f.type_handler.AddBucketFunction(self, f)
7009 self.Log("Auto Generated Functions : %d" %
7010 len([f for f in self.functions if f.can_auto_generate or
7011 (not f.IsType('') and not f.IsType('Custom') and
7012 not f.IsType('Todo'))]))
7014 funcs = [f for f in self.functions if not f.can_auto_generate and
7015 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
7016 self.Log("Non Auto Generated Functions: %d" % len(funcs))
7018 for f in funcs:
7019 self.Log(" %-10s %-20s gl%s" % (f.info.type, f.return_type, f.name))
7021 def WriteCommandIds(self, filename):
7022 """Writes the command buffer format"""
7023 file = CHeaderWriter(filename)
7024 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7025 id = 256
7026 for func in self.functions:
7027 file.Write(" %-60s /* %d */ \\\n" %
7028 ("OP(%s)" % func.name, id))
7029 id += 1
7030 file.Write("\n")
7032 file.Write("enum CommandId {\n")
7033 file.Write(" kStartPoint = cmd::kLastCommonId, "
7034 "// All GLES2 commands start after this.\n")
7035 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7036 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7037 file.Write("#undef GLES2_CMD_OP\n")
7038 file.Write(" kNumCommands\n")
7039 file.Write("};\n")
7040 file.Write("\n")
7041 file.Close()
7043 def WriteFormat(self, filename):
7044 """Writes the command buffer format"""
7045 file = CHeaderWriter(filename)
7046 for func in self.functions:
7047 if True:
7048 #gen_cmd = func.GetInfo('gen_cmd')
7049 #if gen_cmd == True or gen_cmd == None:
7050 func.WriteStruct(file)
7051 file.Write("\n")
7052 file.Close()
7054 def WriteDocs(self, filename):
7055 """Writes the command buffer doc version of the commands"""
7056 file = CWriter(filename)
7057 for func in self.functions:
7058 if True:
7059 #gen_cmd = func.GetInfo('gen_cmd')
7060 #if gen_cmd == True or gen_cmd == None:
7061 func.WriteDocs(file)
7062 file.Write("\n")
7063 file.Close()
7065 def WriteFormatTest(self, filename):
7066 """Writes the command buffer format test."""
7067 file = CHeaderWriter(
7068 filename,
7069 "// This file contains unit tests for gles2 commmands\n"
7070 "// It is included by gles2_cmd_format_test.cc\n"
7071 "\n")
7073 for func in self.functions:
7074 if True:
7075 #gen_cmd = func.GetInfo('gen_cmd')
7076 #if gen_cmd == True or gen_cmd == None:
7077 func.WriteFormatTest(file)
7079 file.Close()
7081 def WriteCmdHelperHeader(self, filename):
7082 """Writes the gles2 command helper."""
7083 file = CHeaderWriter(filename)
7085 for func in self.functions:
7086 if True:
7087 #gen_cmd = func.GetInfo('gen_cmd')
7088 #if gen_cmd == True or gen_cmd == None:
7089 func.WriteCmdHelper(file)
7091 file.Close()
7093 def WriteServiceContextStateHeader(self, filename):
7094 """Writes the service context state header."""
7095 file = CHeaderWriter(
7096 filename,
7097 "// It is included by context_state.h\n")
7098 file.Write("struct EnableFlags {\n")
7099 file.Write(" EnableFlags();\n")
7100 for capability in _CAPABILITY_FLAGS:
7101 file.Write(" bool %s;\n" % capability['name'])
7102 file.Write("};\n\n")
7104 for state_name in sorted(_STATES.keys()):
7105 state = _STATES[state_name]
7106 for item in state['states']:
7107 file.Write("%s %s;\n" % (item['type'], item['name']))
7108 file.Write("\n")
7110 file.Close()
7112 def WriteClientContextStateHeader(self, filename):
7113 """Writes the client context state header."""
7114 file = CHeaderWriter(
7115 filename,
7116 "// It is included by client_context_state.h\n")
7117 file.Write("struct EnableFlags {\n")
7118 file.Write(" EnableFlags();\n")
7119 for capability in _CAPABILITY_FLAGS:
7120 file.Write(" bool %s;\n" % capability['name'])
7121 file.Write("};\n\n")
7123 file.Close()
7125 def WriteContextStateGetters(self, file, class_name):
7126 """Writes the state getters."""
7127 for gl_type in ["GLint", "GLfloat"]:
7128 file.Write("""
7129 bool %s::GetStateAs%s(
7130 GLenum pname, %s* params, GLsizei* num_written) const {
7131 switch (pname) {
7132 """ % (class_name, gl_type, gl_type))
7133 for state_name in sorted(_STATES.keys()):
7134 state = _STATES[state_name]
7135 if 'enum' in state:
7136 file.Write(" case %s:\n" % state['enum'])
7137 file.Write(" *num_written = %d;\n" % len(state['states']))
7138 file.Write(" if (params) {\n")
7139 for ndx,item in enumerate(state['states']):
7140 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7141 (ndx, gl_type, item['name']))
7142 file.Write(" }\n")
7143 file.Write(" return true;\n")
7144 else:
7145 for item in state['states']:
7146 file.Write(" case %s:\n" % item['enum'])
7147 file.Write(" *num_written = 1;\n")
7148 file.Write(" if (params) {\n")
7149 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7150 (gl_type, item['name']))
7151 file.Write(" }\n")
7152 file.Write(" return true;\n")
7153 for capability in _CAPABILITY_FLAGS:
7154 file.Write(" case GL_%s:\n" % capability['name'].upper())
7155 file.Write(" *num_written = 1;\n")
7156 file.Write(" if (params) {\n")
7157 file.Write(
7158 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7159 (gl_type, capability['name']))
7160 file.Write(" }\n")
7161 file.Write(" return true;\n")
7162 file.Write(""" default:
7163 return false;
7166 """)
7168 def WriteServiceContextStateImpl(self, filename):
7169 """Writes the context state service implementation."""
7170 file = CHeaderWriter(
7171 filename,
7172 "// It is included by context_state.cc\n")
7173 code = []
7174 for capability in _CAPABILITY_FLAGS:
7175 code.append("%s(%s)" %
7176 (capability['name'],
7177 ('false', 'true')['default' in capability]))
7178 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7179 ",\n ".join(code))
7180 file.Write("\n")
7182 file.Write("void ContextState::Initialize() {\n")
7183 for state_name in sorted(_STATES.keys()):
7184 state = _STATES[state_name]
7185 for item in state['states']:
7186 file.Write(" %s = %s;\n" % (item['name'], item['default']))
7187 file.Write("}\n")
7189 file.Write("""
7190 void ContextState::InitCapabilities() const {
7191 """)
7192 for capability in _CAPABILITY_FLAGS:
7193 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7194 (capability['name'].upper(), capability['name']))
7195 file.Write("""}
7197 void ContextState::InitState() const {
7198 """)
7200 # We need to sort the keys so the expectations match
7201 for state_name in sorted(_STATES.keys()):
7202 state = _STATES[state_name]
7203 if state['type'] == 'FrontBack':
7204 num_states = len(state['states'])
7205 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7206 args = []
7207 for item in group:
7208 args.append('%s' % item['name'])
7209 file.Write(
7210 " gl%s(%s, %s);\n" %
7211 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7212 elif state['type'] == 'NamedParameter':
7213 for item in state['states']:
7214 if 'extension_flag' in item:
7215 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7216 item['extension_flag'])
7217 file.Write(" gl%s(%s, %s);\n" %
7218 (state['func'], item['enum'], item['name']))
7219 else:
7220 args = []
7221 for item in state['states']:
7222 args.append('%s' % item['name'])
7223 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
7224 file.Write("}\n")
7226 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7227 switch (cap) {
7228 """)
7229 for capability in _CAPABILITY_FLAGS:
7230 file.Write(" case GL_%s:\n" % capability['name'].upper())
7231 file.Write(" return enable_flags.%s;\n" % capability['name'])
7232 file.Write(""" default:
7233 NOTREACHED();
7234 return false;
7237 """)
7239 self.WriteContextStateGetters(file, "ContextState")
7240 file.Close()
7242 def WriteClientContextStateImpl(self, filename):
7243 """Writes the context state client side implementation."""
7244 file = CHeaderWriter(
7245 filename,
7246 "// It is included by client_context_state.cc\n")
7247 code = []
7248 for capability in _CAPABILITY_FLAGS:
7249 code.append("%s(%s)" %
7250 (capability['name'],
7251 ('false', 'true')['default' in capability]))
7252 file.Write(
7253 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7254 ",\n ".join(code))
7255 file.Write("\n")
7257 file.Write("""
7258 bool ClientContextState::SetCapabilityState(
7259 GLenum cap, bool enabled, bool* changed) {
7260 *changed = false;
7261 switch (cap) {
7262 """)
7263 for capability in _CAPABILITY_FLAGS:
7264 file.Write(" case GL_%s:\n" % capability['name'].upper())
7265 file.Write(""" if (enable_flags.%(name)s != enabled) {
7266 *changed = true;
7267 enable_flags.%(name)s = enabled;
7269 return true;
7270 """ % capability)
7271 file.Write(""" default:
7272 return false;
7275 """)
7276 file.Write("""bool ClientContextState::GetEnabled(
7277 GLenum cap, bool* enabled) const {
7278 switch (cap) {
7279 """)
7280 for capability in _CAPABILITY_FLAGS:
7281 file.Write(" case GL_%s:\n" % capability['name'].upper())
7282 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
7283 file.Write(" return true;\n")
7284 file.Write(""" default:
7285 return false;
7288 """)
7289 file.Close()
7291 def WriteServiceImplementation(self, filename):
7292 """Writes the service decorder implementation."""
7293 file = CHeaderWriter(
7294 filename,
7295 "// It is included by gles2_cmd_decoder.cc\n")
7297 for func in self.functions:
7298 if True:
7299 #gen_cmd = func.GetInfo('gen_cmd')
7300 #if gen_cmd == True or gen_cmd == None:
7301 func.WriteServiceImplementation(file)
7303 file.Write("""
7304 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7305 switch (cap) {
7306 """)
7307 for capability in _CAPABILITY_FLAGS:
7308 file.Write(" case GL_%s:\n" % capability['name'].upper())
7309 if 'state_flag' in capability:
7310 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7311 state_.enable_flags.%(name)s = enabled;
7312 %(state_flag)s = true;
7314 return false;
7315 """ % capability)
7316 else:
7317 file.Write(""" state_.enable_flags.%(name)s = enabled;
7318 return true;
7319 """ % capability)
7320 file.Write(""" default:
7321 NOTREACHED();
7322 return false;
7325 """)
7326 file.Close()
7328 def WriteServiceUnitTests(self, filename):
7329 """Writes the service decorder unit tests."""
7330 num_tests = len(self.functions)
7331 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
7332 count = 0
7333 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
7334 count += 1
7335 name = filename % count
7336 file = CHeaderWriter(
7337 name,
7338 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
7339 file.SetFileNum(count)
7340 end = test_num + FUNCTIONS_PER_FILE
7341 if end > num_tests:
7342 end = num_tests
7343 for idx in range(test_num, end):
7344 func = self.functions[idx]
7345 if True:
7346 #gen_cmd = func.GetInfo('gen_cmd')
7347 #if gen_cmd == True or gen_cmd == None:
7348 if func.GetInfo('unit_test') == False:
7349 file.Write("// TODO(gman): %s\n" % func.name)
7350 else:
7351 func.WriteServiceUnitTest(file)
7353 file.Close()
7354 file = CHeaderWriter(
7355 filename % 0,
7356 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7357 file.Write(
7358 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7359 """)
7360 for capability in _CAPABILITY_FLAGS:
7361 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7362 (capability['name'].upper(),
7363 ('false', 'true')['default' in capability]))
7364 file.Write("""}
7366 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7367 """)
7369 # We need to sort the keys so the expectations match
7370 for state_name in sorted(_STATES.keys()):
7371 state = _STATES[state_name]
7372 if state['type'] == 'FrontBack':
7373 num_states = len(state['states'])
7374 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7375 args = []
7376 for item in group:
7377 if 'expected' in item:
7378 args.append(item['expected'])
7379 else:
7380 args.append(item['default'])
7381 file.Write(
7382 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7383 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7384 file.Write(" .Times(1)\n")
7385 file.Write(" .RetiresOnSaturation();\n")
7386 elif state['type'] == 'NamedParameter':
7387 for item in state['states']:
7388 if 'extension_flag' in item:
7389 continue
7390 file.Write(
7391 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7392 (state['func'], item['enum'], item['default']))
7393 file.Write(" .Times(1)\n")
7394 file.Write(" .RetiresOnSaturation();\n")
7395 else:
7396 args = []
7397 for item in state['states']:
7398 if 'expected' in item:
7399 args.append(item['expected'])
7400 else:
7401 args.append(item['default'])
7402 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7403 (state['func'], ", ".join(args)))
7404 file.Write(" .Times(1)\n")
7405 file.Write(" .RetiresOnSaturation();\n")
7406 file.Write("""}
7407 """)
7408 file.Close()
7410 def WriteGLES2Header(self, filename):
7411 """Writes the GLES2 header."""
7412 file = CHeaderWriter(
7413 filename,
7414 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7416 for func in self.original_functions:
7417 func.WriteGLES2Header(file)
7419 file.Write("\n")
7420 file.Close()
7422 def WriteGLES2CLibImplementation(self, filename):
7423 """Writes the GLES2 c lib implementation."""
7424 file = CHeaderWriter(
7425 filename,
7426 "// These functions emulate GLES2 over command buffers.\n")
7428 for func in self.original_functions:
7429 func.WriteGLES2CLibImplementation(file)
7431 file.Write("""
7432 namespace gles2 {
7434 extern const NameToFunc g_gles2_function_table[] = {
7435 """)
7436 for func in self.original_functions:
7437 file.Write(
7438 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7439 (func.name, func.name))
7440 file.Write(""" { NULL, NULL, },
7443 } // namespace gles2
7444 """)
7445 file.Close()
7447 def WriteGLES2InterfaceHeader(self, filename):
7448 """Writes the GLES2 interface header."""
7449 file = CHeaderWriter(
7450 filename,
7451 "// This file is included by gles2_interface.h to declare the\n"
7452 "// GL api functions.\n")
7453 for func in self.original_functions:
7454 func.WriteGLES2InterfaceHeader(file)
7455 file.Close()
7457 def WriteGLES2InterfaceStub(self, filename):
7458 """Writes the GLES2 interface stub header."""
7459 file = CHeaderWriter(
7460 filename,
7461 "// This file is included by gles2_interface_stub.h.\n")
7462 for func in self.original_functions:
7463 func.WriteGLES2InterfaceStub(file)
7464 file.Close()
7466 def WriteGLES2InterfaceStubImpl(self, filename):
7467 """Writes the GLES2 interface header."""
7468 file = CHeaderWriter(
7469 filename,
7470 "// This file is included by gles2_interface_stub.cc.\n")
7471 for func in self.original_functions:
7472 func.WriteGLES2InterfaceStubImpl(file)
7473 file.Close()
7475 def WriteGLES2ImplementationHeader(self, filename):
7476 """Writes the GLES2 Implementation header."""
7477 file = CHeaderWriter(
7478 filename,
7479 "// This file is included by gles2_implementation.h to declare the\n"
7480 "// GL api functions.\n")
7481 for func in self.original_functions:
7482 func.WriteGLES2ImplementationHeader(file)
7483 file.Close()
7485 def WriteGLES2Implementation(self, filename):
7486 """Writes the GLES2 Implementation."""
7487 file = CHeaderWriter(
7488 filename,
7489 "// This file is included by gles2_implementation.cc to define the\n"
7490 "// GL api functions.\n")
7491 for func in self.original_functions:
7492 func.WriteGLES2Implementation(file)
7493 file.Close()
7495 def WriteGLES2TraceImplementationHeader(self, filename):
7496 """Writes the GLES2 Trace Implementation header."""
7497 file = CHeaderWriter(
7498 filename,
7499 "// This file is included by gles2_trace_implementation.h\n")
7500 for func in self.original_functions:
7501 func.WriteGLES2TraceImplementationHeader(file)
7502 file.Close()
7504 def WriteGLES2TraceImplementation(self, filename):
7505 """Writes the GLES2 Trace Implementation."""
7506 file = CHeaderWriter(
7507 filename,
7508 "// This file is included by gles2_trace_implementation.cc\n")
7509 for func in self.original_functions:
7510 func.WriteGLES2TraceImplementation(file)
7511 file.Close()
7513 def WriteGLES2ImplementationUnitTests(self, filename):
7514 """Writes the GLES2 helper header."""
7515 file = CHeaderWriter(
7516 filename,
7517 "// This file is included by gles2_implementation.h to declare the\n"
7518 "// GL api functions.\n")
7519 for func in self.original_functions:
7520 func.WriteGLES2ImplementationUnitTest(file)
7521 file.Close()
7523 def WriteServiceUtilsHeader(self, filename):
7524 """Writes the gles2 auto generated utility header."""
7525 file = CHeaderWriter(filename)
7526 for enum in sorted(_ENUM_LISTS.keys()):
7527 file.Write("ValueValidator<%s> %s;\n" %
7528 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7529 file.Write("\n")
7530 file.Close()
7532 def WriteServiceUtilsImplementation(self, filename):
7533 """Writes the gles2 auto generated utility implementation."""
7534 file = CHeaderWriter(filename)
7535 enums = sorted(_ENUM_LISTS.keys())
7536 for enum in enums:
7537 if len(_ENUM_LISTS[enum]['valid']) > 0:
7538 file.Write("static const %s valid_%s_table[] = {\n" %
7539 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7540 for value in _ENUM_LISTS[enum]['valid']:
7541 file.Write(" %s,\n" % value)
7542 file.Write("};\n")
7543 file.Write("\n")
7544 file.Write("Validators::Validators()\n")
7545 pre = ': '
7546 post = ','
7547 for count, enum in enumerate(enums):
7548 if count + 1 == len(enums):
7549 post = ' {'
7550 if len(_ENUM_LISTS[enum]['valid']) > 0:
7551 code = """ %(pre)s%(name)s(
7552 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7554 else:
7555 code = """ %(pre)s%(name)s()%(post)s
7557 file.Write(code % {
7558 'name': ToUnderscore(enum),
7559 'pre': pre,
7560 'post': post,
7562 pre = ' '
7563 file.Write("}\n\n");
7564 file.Close()
7566 def WriteCommonUtilsHeader(self, filename):
7567 """Writes the gles2 common utility header."""
7568 file = CHeaderWriter(filename)
7569 enums = sorted(_ENUM_LISTS.keys())
7570 for enum in enums:
7571 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7572 file.Write("static std::string GetString%s(uint32 value);\n" % enum)
7573 file.Write("\n")
7574 file.Close()
7576 def WriteCommonUtilsImpl(self, filename):
7577 """Writes the gles2 common utility header."""
7578 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7579 dict = {}
7580 for fname in ['../../third_party/khronos/GLES2/gl2.h',
7581 '../../third_party/khronos/GLES2/gl2ext.h',
7582 '../../gpu/GLES2/gl2chromium.h',
7583 '../../gpu/GLES2/gl2extchromium.h']:
7584 lines = open(fname).readlines()
7585 for line in lines:
7586 m = enum_re.match(line)
7587 if m:
7588 name = m.group(1)
7589 value = m.group(2)
7590 if len(value) <= 10 and not value in dict:
7591 dict[value] = name
7593 file = CHeaderWriter(filename)
7594 file.Write("static const GLES2Util::EnumToString "
7595 "enum_to_string_table[] = {\n")
7596 for value in dict:
7597 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
7598 file.Write("""};
7600 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7601 enum_to_string_table;
7602 const size_t GLES2Util::enum_to_string_table_len_ =
7603 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7605 """)
7607 enums = sorted(_ENUM_LISTS.keys())
7608 for enum in enums:
7609 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7610 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7611 enum)
7612 if len(_ENUM_LISTS[enum]['valid']) > 0:
7613 file.Write(" static const EnumToString string_table[] = {\n")
7614 for value in _ENUM_LISTS[enum]['valid']:
7615 file.Write(' { %s, "%s" },\n' % (value, value))
7616 file.Write(""" };
7617 return GLES2Util::GetQualifiedEnumString(
7618 string_table, arraysize(string_table), value);
7621 """)
7622 else:
7623 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7624 NULL, 0, value);
7627 """)
7628 file.Close()
7630 def WritePepperGLES2Interface(self, filename, dev):
7631 """Writes the Pepper OpenGLES interface definition."""
7632 file = CHeaderWriter(
7633 filename,
7634 "// OpenGL ES interface.\n")
7636 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7637 if dev:
7638 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7639 else:
7640 file.Write("\n#ifndef __gl2_h_\n")
7641 for (k, v) in _GL_TYPES.iteritems():
7642 file.Write("typedef %s %s;\n" % (v, k))
7643 file.Write("#ifdef _WIN64\n")
7644 for (k, v) in _GL_TYPES_64.iteritems():
7645 file.Write("typedef %s %s;\n" % (v, k))
7646 file.Write("#else\n")
7647 for (k, v) in _GL_TYPES_32.iteritems():
7648 file.Write("typedef %s %s;\n" % (v, k))
7649 file.Write("#endif // _WIN64\n")
7650 file.Write("#endif // __gl2_h_\n\n")
7652 for interface in self.pepper_interfaces:
7653 if interface.dev != dev:
7654 continue
7655 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7656 (interface.GetInterfaceName(), interface.GetInterfaceString()))
7657 file.Write("#define %s %s_1_0\n" %
7658 (interface.GetInterfaceName(), interface.GetInterfaceName()))
7660 file.Write("\nstruct %s {\n" % interface.GetStructName())
7661 for func in self.original_functions:
7662 if not func.InPepperInterface(interface):
7663 continue
7665 original_arg = func.MakeTypedPepperArgString("")
7666 context_arg = "PP_Resource context"
7667 if len(original_arg):
7668 arg = context_arg + ", " + original_arg
7669 else:
7670 arg = context_arg
7671 file.Write(" %s (*%s)(%s);\n" %
7672 (func.return_type, func.GetPepperName(), arg))
7673 file.Write("};\n\n")
7676 file.Close()
7678 def WritePepperGLES2Implementation(self, filename):
7679 """Writes the Pepper OpenGLES interface implementation."""
7681 file = CWriter(filename)
7682 file.Write(_LICENSE)
7683 file.Write(_DO_NOT_EDIT_WARNING)
7685 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7686 file.Write("#include \"base/logging.h\"\n")
7687 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7688 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7689 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7691 file.Write("namespace ppapi {\n\n")
7692 file.Write("namespace {\n\n")
7694 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7695 " Enter3D;\n\n")
7697 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
7698 " enter) {\n")
7699 file.Write(" DCHECK(enter);\n")
7700 file.Write(" DCHECK(enter->succeeded());\n")
7701 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
7702 "gles2_impl();\n");
7703 file.Write("}\n\n");
7705 for func in self.original_functions:
7706 if not func.InAnyPepperExtension():
7707 continue
7709 original_arg = func.MakeTypedPepperArgString("")
7710 context_arg = "PP_Resource context_id"
7711 if len(original_arg):
7712 arg = context_arg + ", " + original_arg
7713 else:
7714 arg = context_arg
7715 file.Write("%s %s(%s) {\n" %
7716 (func.return_type, func.GetPepperName(), arg))
7717 file.Write(" Enter3D enter(context_id, true);\n")
7718 file.Write(" if (enter.succeeded()) {\n")
7720 return_str = "" if func.return_type == "void" else "return "
7721 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
7722 (return_str, func.original_name,
7723 func.MakeOriginalArgString("")))
7724 file.Write(" }")
7725 if func.return_type == "void":
7726 file.Write("\n")
7727 else:
7728 file.Write(" else {\n")
7729 error_return = "0"
7730 if func.GetInfo("error_return"):
7731 error_return = func.GetInfo("error_return")
7732 elif func.return_type == "GLboolean":
7733 error_return = "GL_FALSE"
7734 elif "*" in func.return_type:
7735 error_return = "NULL"
7736 file.Write(" return %s;\n" % error_return)
7737 file.Write(" }\n")
7738 file.Write("}\n\n")
7740 file.Write("} // namespace\n")
7742 for interface in self.pepper_interfaces:
7743 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7744 (interface.GetStructName(), interface.GetName()))
7745 file.Write(" static const struct %s "
7746 "ppb_opengles2 = {\n" % interface.GetStructName())
7747 file.Write(" &")
7748 file.Write(",\n &".join(
7749 f.GetPepperName() for f in self.original_functions
7750 if f.InPepperInterface(interface)))
7751 file.Write("\n")
7753 file.Write(" };\n")
7754 file.Write(" return &ppb_opengles2;\n")
7755 file.Write("}\n")
7757 file.Write("} // namespace ppapi\n")
7758 file.Close()
7760 def WriteGLES2ToPPAPIBridge(self, filename):
7761 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7763 file = CWriter(filename)
7764 file.Write(_LICENSE)
7765 file.Write(_DO_NOT_EDIT_WARNING)
7767 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7768 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7769 file.Write("#endif\n")
7770 file.Write("#include <GLES2/gl2.h>\n")
7771 file.Write("#include <GLES2/gl2ext.h>\n")
7772 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7774 for func in self.original_functions:
7775 if not func.InAnyPepperExtension():
7776 continue
7778 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
7780 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7781 (func.return_type, func.GetPepperName(),
7782 func.MakeTypedPepperArgString("")))
7783 return_str = "" if func.return_type == "void" else "return "
7784 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
7785 original_arg = func.MakeOriginalArgString("")
7786 context_arg = "glGetCurrentContextPPAPI()"
7787 if len(original_arg):
7788 arg = context_arg + ", " + original_arg
7789 else:
7790 arg = context_arg
7791 if interface.GetName():
7792 file.Write(" const struct %s* ext = %s;\n" %
7793 (interface.GetStructName(), interface_str))
7794 file.Write(" if (ext)\n")
7795 file.Write(" %sext->%s(%s);\n" %
7796 (return_str, func.GetPepperName(), arg))
7797 if return_str:
7798 file.Write(" %s0;\n" % return_str)
7799 else:
7800 file.Write(" %s%s->%s(%s);\n" %
7801 (return_str, interface_str, func.GetPepperName(), arg))
7802 file.Write("}\n\n")
7803 file.Close()
7805 def main(argv):
7806 """This is the main function."""
7807 parser = OptionParser()
7808 parser.add_option(
7809 "-g", "--generate-implementation-templates", action="store_true",
7810 help="generates files that are generally hand edited..")
7811 parser.add_option(
7812 "--output-dir",
7813 help="base directory for resulting files, under chrome/src. default is "
7814 "empty. Use this if you want the result stored under gen.")
7815 parser.add_option(
7816 "-v", "--verbose", action="store_true",
7817 help="prints more output.")
7819 (options, args) = parser.parse_args(args=argv)
7821 # Add in states and capabilites to GLState
7822 for state_name in sorted(_STATES.keys()):
7823 state = _STATES[state_name]
7824 if 'enum' in state:
7825 _ENUM_LISTS['GLState']['valid'].append(state['enum'])
7826 else:
7827 for item in state['states']:
7828 if 'extension_flag' in item:
7829 continue
7830 _ENUM_LISTS['GLState']['valid'].append(item['enum'])
7831 for capability in _CAPABILITY_FLAGS:
7832 _ENUM_LISTS['GLState']['valid'].append("GL_%s" % capability['name'].upper())
7834 # This script lives under gpu/command_buffer, cd to base directory.
7835 os.chdir(os.path.dirname(__file__) + "/../..")
7837 gen = GLGenerator(options.verbose)
7838 gen.ParseGLH("common/GLES2/gl2.h")
7840 # Support generating files under gen/
7841 if options.output_dir != None:
7842 os.chdir(options.output_dir)
7844 gen.WritePepperGLES2Interface("ppapi/c/ppb_opengles2.h", False)
7845 gen.WritePepperGLES2Interface("ppapi/c/dev/ppb_opengles2ext_dev.h", True)
7846 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
7847 gen.WritePepperGLES2Implementation(
7848 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7849 os.chdir("gpu/command_buffer")
7850 gen.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7851 gen.WriteFormat("common/gles2_cmd_format_autogen.h")
7852 gen.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7853 gen.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7854 gen.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7855 gen.WriteGLES2InterfaceStubImpl(
7856 "client/gles2_interface_stub_impl_autogen.h")
7857 gen.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7858 gen.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7859 gen.WriteGLES2ImplementationUnitTests(
7860 "client/gles2_implementation_unittest_autogen.h")
7861 gen.WriteGLES2TraceImplementationHeader(
7862 "client/gles2_trace_implementation_autogen.h")
7863 gen.WriteGLES2TraceImplementation(
7864 "client/gles2_trace_implementation_impl_autogen.h")
7865 gen.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7866 gen.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7867 gen.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7868 gen.WriteServiceContextStateHeader("service/context_state_autogen.h")
7869 gen.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7870 gen.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7871 gen.WriteClientContextStateImpl(
7872 "client/client_context_state_impl_autogen.h")
7873 gen.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7874 gen.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7875 gen.WriteServiceUtilsImplementation(
7876 "service/gles2_cmd_validation_implementation_autogen.h")
7877 gen.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7878 gen.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7879 gen.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7881 if gen.errors > 0:
7882 print "%d errors" % gen.errors
7883 return 1
7884 return 0
7887 if __name__ == '__main__':
7888 sys.exit(main(sys.argv[1:]))