2 # -*- coding: utf-8 -*-
4 from __future__
import with_statement
10 from subprocess
import Popen
, PIPE
13 # Local module: generator for texture lookup builtins
14 from texture_builtins
import generate_texture_functions
16 builtins_dir
= path
.join(path
.dirname(path
.abspath(__file__
)), "..")
18 # Get the path to the standalone GLSL compiler
20 print "Usage:", argv
[0], "<path to compiler>"
25 # Read the files in builtins/ir/*...add them to the supplied dictionary.
26 def read_ir_files(fs
):
27 for filename
in glob(path
.join(path
.join(builtins_dir
, 'ir'), '*.ir')):
28 function_name
= path
.basename(filename
).split('.')[0]
29 with
open(filename
) as f
:
30 fs
[function_name
] = f
.read()
32 # Return a dictionary containing all builtin definitions (even generated)
33 def get_builtin_definitions():
35 generate_texture_functions(fs
)
40 # Work around MSVC's 65535 byte limit by outputting an array of characters
41 # rather than actual string literals.
43 #t = "/* Warning: length " + repr(len(s)) + " too large */\n"
45 for c
in re
.sub('\s\s+', ' ', s
):
50 return '{' + t
[:-1] + '}'
52 t
= s
.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n"\n "')
53 return ' "' + t
+ '"\n'
55 def write_function_definitions():
56 fs
= get_builtin_definitions()
57 for k
, v
in sorted(fs
.iteritems()):
58 print 'static const char builtin_' + k
+ '[] ='
59 print stringify(v
), ';'
61 def run_compiler(args
):
62 command
= [compiler
, '--dump-lir'] + args
63 p
= Popen(command
, 1, stdout
=PIPE
, shell
=False)
64 output
= p
.communicate()[0]
66 # Clean up output a bit by killing whitespace before a closing paren.
67 kill_paren_whitespace
= re
.compile(r
'[ \n]*\)', re
.MULTILINE
)
68 output
= kill_paren_whitespace
.sub(')', output
)
70 # Also toss any duplicate newlines
71 output
= output
.replace('\n\n', '\n')
73 return (output
, p
.returncode
)
75 def write_profile(filename
, profile
):
76 (proto_ir
, returncode
) = run_compiler([filename
])
79 print '#error builtins profile', profile
, 'failed to compile'
82 # Kill any global variable declarations. We don't want them.
83 kill_globals
= re
.compile(r
'^\(declare.*\n', re
.MULTILINE
)
84 proto_ir
= kill_globals
.sub('', proto_ir
)
86 print 'static const char prototypes_for_' + profile
+ '[] ='
87 print stringify(proto_ir
), ';'
89 # Print a table of all the functions (not signatures) referenced.
90 # This is done so we can avoid bothering with a hash table in the C++ code.
92 function_names
= set()
93 for func
in re
.finditer(r
'\(function (.+)\n', proto_ir
):
94 function_names
.add(func
.group(1))
96 print 'static const char *functions_for_' + profile
+ ' [] = {'
97 for func
in sorted(function_names
):
98 print ' builtin_' + func
+ ','
101 def write_profiles():
102 profiles
= get_profile_list()
103 for (filename
, profile
) in profiles
:
104 write_profile(filename
, profile
)
106 def get_profile_list():
108 for extension
in ['frag', 'vert']:
109 path_glob
= path
.join(
110 path
.join(builtins_dir
, 'profiles'), '*.' + extension
)
111 profile_files
.extend(glob(path_glob
))
113 for pfile
in sorted(profile_files
):
114 profiles
.append((pfile
, path
.basename(pfile
).replace('.', '_')))
117 if __name__
== "__main__":
118 print """/* DO NOT MODIFY - automatically generated by generate_builtins.py */
120 * Copyright © 2010 Intel Corporation
122 * Permission is hereby granted, free of charge, to any person obtaining a
123 * copy of this software and associated documentation files (the "Software"),
124 * to deal in the Software without restriction, including without limitation
125 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
126 * and/or sell copies of the Software, and to permit persons to whom the
127 * Software is furnished to do so, subject to the following conditions:
129 * The above copyright notice and this permission notice (including the next
130 * paragraph) shall be included in all copies or substantial portions of the
133 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
134 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
135 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
136 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
137 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
138 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
139 * DEALINGS IN THE SOFTWARE.
143 #include "main/core.h" /* for struct gl_shader */
144 #include "glsl_parser_extras.h"
145 #include "ir_reader.h"
149 extern "C" struct gl_shader *
150 _mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type);
153 read_builtins(GLenum target, const char *protos, const char **functions, unsigned count)
155 struct gl_context fakeCtx;
156 fakeCtx.API = API_OPENGL;
157 fakeCtx.Const.GLSLVersion = 130;
158 fakeCtx.Extensions.ARB_ES2_compatibility = true;
159 gl_shader *sh = _mesa_new_shader(NULL, 0, target);
160 struct _mesa_glsl_parse_state *st =
161 new(sh) _mesa_glsl_parse_state(&fakeCtx, target, sh);
163 st->language_version = 130;
164 st->symbols->language_version = 130;
165 st->ARB_texture_rectangle_enable = true;
166 st->EXT_texture_array_enable = true;
167 _mesa_glsl_initialize_types(st);
169 sh->ir = new(sh) exec_list;
170 sh->symbols = st->symbols;
172 /* Read the IR containing the prototypes */
173 _mesa_glsl_read_ir(st, sh->ir, protos, true);
175 /* Read ALL the function bodies, telling the IR reader not to scan for
176 * prototypes (we've already created them). The IR reader will skip any
177 * signature that does not already exist as a prototype.
179 for (unsigned i = 0; i < count; i++) {
180 _mesa_glsl_read_ir(st, sh->ir, functions[i], false);
183 printf("error reading builtin: %.35s ...\\n", functions[i]);
184 printf("Info log:\\n%s\\n", st->info_log);
190 reparent_ir(sh->ir, sh);
197 write_function_definitions()
200 profiles
= get_profile_list()
202 print 'static gl_shader *builtin_profiles[%d];' % len(profiles
)
205 void *builtin_mem_ctx = NULL;
208 _mesa_glsl_release_functions(void)
210 ralloc_free(builtin_mem_ctx);
211 builtin_mem_ctx = NULL;
212 memset(builtin_profiles, 0, sizeof(builtin_profiles));
216 _mesa_read_profile(struct _mesa_glsl_parse_state *state,
218 const char *prototypes,
219 const char **functions,
222 gl_shader *sh = builtin_profiles[profile_index];
225 sh = read_builtins(GL_VERTEX_SHADER, prototypes, functions, count);
226 ralloc_steal(builtin_mem_ctx, sh);
227 builtin_profiles[profile_index] = sh;
230 state->builtins_to_link[state->num_builtins_to_link] = sh;
231 state->num_builtins_to_link++;
235 _mesa_glsl_initialize_functions(struct _mesa_glsl_parse_state *state)
237 /* If we've already initialized the built-ins, bail early. */
238 if (state->num_builtins_to_link > 0)
241 if (builtin_mem_ctx == NULL) {
242 builtin_mem_ctx = ralloc_context(NULL); // "GLSL built-in functions"
243 memset(&builtin_profiles, 0, sizeof(builtin_profiles));
248 for (filename
, profile
) in profiles
:
249 if profile
.endswith('_vert'):
250 check
= 'state->target == vertex_shader && '
251 elif profile
.endswith('_frag'):
252 check
= 'state->target == fragment_shader && '
254 version
= re
.sub(r
'_(vert|frag)$', '', profile
)
255 if version
.isdigit():
256 check
+= 'state->language_version == ' + version
257 else: # an extension name
258 check
+= 'state->' + version
+ '_enable'
260 print ' if (' + check
+ ') {'
261 print ' _mesa_read_profile(state, %d,' % i
262 print ' prototypes_for_' + profile
+ ','
263 print ' functions_for_' + profile
+ ','
264 print ' Elements(functions_for_' + profile
+ '));'