mesa: glGet: add script to generate hash tables in build time
[mesa.git] / src / mesa / main / get_hash_generator.py
1 #!/usr/bin/python2
2 # coding=utf-8
3 # -*- Mode: Python; py-indent-offset: 4 -*-
4 #
5 # Copyright © 2012 Intel Corporation
6 #
7 # Based on code by Kristian Høgsberg <krh@bitplanet.net>,
8 # extracted from mesa/main/get.c
9 #
10 # Permission is hereby granted, free of charge, to any person obtaining a
11 # copy of this software and associated documentation files (the "Software"),
12 # to deal in the Software without restriction, including without limitation
13 # on the rights to use, copy, modify, merge, publish, distribute, sub
14 # license, and/or sell copies of the Software, and to permit persons to whom
15 # the Software is furnished to do so, subject to the following conditions:
16 #
17 # The above copyright notice and this permission notice (including the next
18 # paragraph) shall be included in all copies or substantial portions of the
19 # Software.
20 #
21 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 # FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
24 # IBM AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
27 # IN THE SOFTWARE.
28
29 # Generate a C header file containing hash tables of glGet parameter
30 # names for each GL API. The generated file is to be included by glGet.c
31
32 import os, sys, imp, getopt
33 from collections import defaultdict
34 import get_hash_params
35
36 cur_dir = os.path.dirname(sys.argv[0])
37 param_desc_file = "%s/get_hash_params.py" % cur_dir
38
39 GLAPI = "%s/../../mapi/glapi/gen" % cur_dir
40 sys.path.append(GLAPI)
41 import gl_XML
42
43 prime_factor = 89
44 prime_step = 281
45 hash_table_size = 1024
46
47 gl_apis=set(["GL", "GL_CORE", "GLES", "GLES2"])
48
49 def print_header():
50 print "typedef const unsigned short table_t[%d];\n" % (hash_table_size)
51 print "static const int prime_factor = %d, prime_step = %d;\n" % \
52 (prime_factor, prime_step)
53
54 def print_params(params):
55 print "static struct value_desc values[] = {"
56 for p in params:
57 print " { %s, %s }," % (p[0], p[1])
58
59 print "};\n"
60
61 def api_name(api):
62 return "API_OPEN%s" % api
63
64 def table_name(api):
65 return "table_" + api_name(api)
66
67 def print_table(api, table):
68 print "static table_t %s = {" % (table_name(api))
69
70 row_size = 4
71 for i in range(0, len(table), row_size):
72 row = table[i : i + row_size]
73 idx_val = ["[%4d] = %4d" % iv for iv in row]
74 print " " * 4 + ", ".join(idx_val) + ","
75
76 print "};\n"
77
78 def print_tables(tables):
79 for table in tables:
80 print_table(table["apis"][0], table["indices"])
81
82 print "static table_t *table_set[] = {"
83 for table in tables:
84 tname = table_name(table["apis"][0])
85 for api in table["apis"]:
86 print " [%s] = &%s," % (api_name(api), tname)
87 print "};\n"
88
89 print "#define table(api) (*table_set[api])"
90
91 # Merge tables with matching parameter lists (i.e. GL and GL_CORE)
92 def merge_tables(tables):
93 merged_tables = []
94 for api, indices in sorted(tables.items()):
95 matching_table = filter(lambda mt:mt["indices"] == indices,
96 merged_tables)
97 if matching_table:
98 matching_table[0]["apis"].append(api)
99 else:
100 merged_tables.append({"apis": [api], "indices": indices})
101
102 return merged_tables
103
104 def add_to_hash_table(table, hash_val, value):
105 while True:
106 index = hash_val & (hash_table_size - 1)
107 if index not in table:
108 table[index] = value
109 break
110 hash_val += prime_step
111
112 def die(msg):
113 sys.stderr.write("%s: %s\n" % (program, msg))
114 exit(1)
115
116 program = os.path.basename(sys.argv[0])
117
118 def generate_hash_tables(enum_list, enabled_apis, param_descriptors):
119 tables = defaultdict(lambda:{})
120
121 # the first entry should be invalid, so that get.c:find_value can use
122 # its index for the 'enum not found' condition.
123 params = [[0, ""]]
124
125 for param_block in param_descriptors:
126 if set(["apis", "params"]) != set(param_block):
127 die("missing fields (%s) in param descriptor file (%s)" %
128 (", ".join(set(["apis", "params"]) - set(param_block)),
129 param_desc_file))
130
131 valid_apis = set(param_block["apis"])
132 if valid_apis - gl_apis:
133 die("unknown API(s) in param descriptor file (%s): %s\n" %
134 (param_desc_file, ",".join(valid_apis - gl_apis)))
135
136 if not (valid_apis & enabled_apis):
137 continue
138
139 valid_apis &= enabled_apis
140
141 for param in param_block["params"]:
142 enum_name = param[0]
143 enum_val = enum_list[enum_name].value
144 hash_val = enum_val * prime_factor
145
146 for api in valid_apis:
147 add_to_hash_table(tables[api], hash_val, len(params))
148
149 params.append(["GL_" + enum_name, param[1]])
150
151 sorted_tables={}
152 for api, indices in tables.items():
153 sorted_tables[api] = sorted(indices.items())
154
155 return params, merge_tables(sorted_tables)
156
157 def opt_to_apis(feature):
158 _map = {"ES1": "GLES", "ES2": "GLES2", "GL": "GL"}
159 if feature not in _map:
160 return None
161
162 apis = set([_map[feature]])
163 if "GL" in apis:
164 apis.add("GL_CORE")
165
166 return apis
167
168 def show_usage():
169 sys.stderr.write(
170 """Usage: %s [OPTIONS]
171 -f <file> specify GL API XML file
172 -a [GL|ES1|ES2] specify APIs to generate hash tables for
173 """ % (program))
174 exit(1)
175
176 if __name__ == '__main__':
177 try:
178 (opts, args) = getopt.getopt(sys.argv[1:], "f:a:")
179 except Exception,e:
180 show_usage()
181
182 if len(args) != 0:
183 show_usage()
184
185 enabled_apis = set([])
186 api_desc_file = ""
187
188 for opt_name, opt_val in opts:
189 if opt_name == "-f":
190 api_desc_file = opt_val
191 if opt_name == "-a":
192 apis = opt_to_apis(opt_val.upper())
193 if not apis:
194 die("invalid API %s\n" % opt_val)
195
196 enabled_apis |= apis
197
198 if not api_desc_file:
199 die("missing descriptor file (-f)\n")
200
201 if len(enabled_apis) == 0:
202 die("need at least a single enabled API\n")
203
204 try:
205 api_desc = gl_XML.parse_GL_API(api_desc_file)
206 except Exception:
207 die("couldn't parse API specification file %s\n" % api_desc_file)
208
209 (params, hash_tables) = generate_hash_tables(api_desc.enums_by_name,
210 enabled_apis, get_hash_params.descriptor)
211
212 print_header()
213 print_params(params)
214 print_tables(hash_tables)