Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mesa
Path: blob/21.2-virgl/src/intel/isl/gen_format_layout.py
4547 views
1
# encoding=utf-8
2
# Copyright © 2016 Intel Corporation
3
4
# Permission is hereby granted, free of charge, to any person obtaining a copy
5
# of this software and associated documentation files (the "Software"), to deal
6
# in the Software without restriction, including without limitation the rights
7
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
# copies of the Software, and to permit persons to whom the Software is
9
# furnished to do so, subject to the following conditions:
10
11
# The above copyright notice and this permission notice shall be included in
12
# all copies or substantial portions of the Software.
13
14
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
# SOFTWARE.
21
22
"""Generates isl_format_layout.c."""
23
24
from __future__ import absolute_import, division, print_function
25
import argparse
26
import csv
27
import re
28
29
from mako import template
30
31
# Load the template, ensure that __future__.division is imported, and set the
32
# bytes encoding to be utf-8. This last bit is important to getting simple
33
# consistent behavior for python 3 when we get there.
34
TEMPLATE = template.Template(future_imports=['division'],
35
output_encoding='utf-8',
36
text="""\
37
/* This file is autogenerated by gen_format_layout.py. DO NOT EDIT! */
38
39
/*
40
* Copyright 2015 Intel Corporation
41
*
42
* Permission is hereby granted, free of charge, to any person obtaining a
43
* copy of this software and associated documentation files (the "Software"),
44
* to deal in the Software without restriction, including without limitation
45
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
46
* and/or sell copies of the Software, and to permit persons to whom the
47
* Software is furnished to do so, subject to the following conditions:
48
*
49
* The above copyright notice and this permission notice (including the next
50
* paragraph) shall be included in all copies or substantial portions of the
51
* Software.
52
*
53
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
54
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
55
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
56
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
57
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
58
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
59
* IN THE SOFTWARE.
60
*/
61
62
#include "isl/isl.h"
63
64
const uint16_t isl_format_name_offsets[] = { <% offset = 0 %>
65
% for format in formats:
66
[ISL_FORMAT_${format.name}] = ${offset}, <% offset += 11 + len(format.name) + 1 %>
67
% endfor
68
};
69
70
const char isl_format_names[] = {
71
% for format in formats:
72
"ISL_FORMAT_${format.name}\\0"
73
% endfor
74
};
75
76
const struct isl_format_layout
77
isl_format_layouts[] = {
78
% for format in formats:
79
[ISL_FORMAT_${format.name}] = {
80
.format = ISL_FORMAT_${format.name},
81
.bpb = ${format.bpb},
82
.bw = ${format.bw},
83
.bh = ${format.bh},
84
.bd = ${format.bd},
85
.channels = {
86
% for mask in ['r', 'g', 'b', 'a', 'l', 'i', 'p']:
87
<% channel = getattr(format, mask, None) %>\\
88
% if channel.type is not None:
89
.${mask} = { ISL_${channel.type}, ${channel.start}, ${channel.size} },
90
% else:
91
.${mask} = {},
92
% endif
93
% endfor
94
},
95
.uniform_channel_type = ISL_${format.uniform_channel_type},
96
.colorspace = ISL_COLORSPACE_${format.colorspace},
97
.txc = ISL_TXC_${format.txc},
98
},
99
100
% endfor
101
};
102
103
bool
104
isl_format_is_valid(enum isl_format format)
105
{
106
if (format >= sizeof(isl_format_layouts) / sizeof(isl_format_layouts[0]))
107
return false;
108
109
/* Only ISL_FORMAT_R32G32B32A32_FLOAT == 0 but that's a valid format.
110
* For all others, if this doesn't match then the entry in the table
111
* must not exist.
112
*/
113
return isl_format_layouts[format].format == format;
114
}
115
116
enum isl_format
117
isl_format_srgb_to_linear(enum isl_format format)
118
{
119
switch (format) {
120
% for srgb, rgb in srgb_to_linear_map:
121
case ISL_FORMAT_${srgb}:
122
return ISL_FORMAT_${rgb};
123
%endfor
124
default:
125
return format;
126
}
127
}
128
""")
129
130
131
class Channel(object):
132
"""Class representing a Channel.
133
134
Converts the csv encoded data into the format that the template (and thus
135
the consuming C code) expects.
136
137
"""
138
# If the csv file grew very large this class could be put behind a factory
139
# to increase efficiency. Right now though it's fast enough that It didn't
140
# seem worthwhile to add all of the boilerplate
141
_types = {
142
'x': 'void',
143
'r': 'raw',
144
'un': 'unorm',
145
'sn': 'snorm',
146
'uf': 'ufloat',
147
'sf': 'sfloat',
148
'ux': 'ufixed',
149
'sx': 'sfixed',
150
'ui': 'uint',
151
'si': 'sint',
152
'us': 'uscaled',
153
'ss': 'sscaled',
154
}
155
_splitter = re.compile(r'\s*(?P<type>[a-z]+)(?P<size>[0-9]+)')
156
157
def __init__(self, line):
158
# If the line is just whitespace then just set everything to None to
159
# save on the regex cost and let the template skip on None.
160
if line.isspace():
161
self.size = None
162
self.type = None
163
else:
164
grouped = self._splitter.match(line)
165
self.type = self._types[grouped.group('type')].upper()
166
self.size = int(grouped.group('size'))
167
168
# Default the start bit to -1
169
self.start = -1
170
171
172
class Format(object):
173
"""Class taht contains all values needed by the template."""
174
def __init__(self, line):
175
# pylint: disable=invalid-name
176
self.name = line[0].strip()
177
178
self.bpb = int(line[1])
179
self.bw = line[2].strip()
180
self.bh = line[3].strip()
181
self.bd = line[4].strip()
182
self.r = Channel(line[5])
183
self.g = Channel(line[6])
184
self.b = Channel(line[7])
185
self.a = Channel(line[8])
186
self.l = Channel(line[9])
187
self.i = Channel(line[10])
188
self.p = Channel(line[11])
189
190
# Set the start bit value for each channel
191
self.order = line[12].strip()
192
bit = 0
193
for c in self.order:
194
chan = getattr(self, c)
195
chan.start = bit
196
bit = bit + chan.size
197
198
# Set the uniform channel type, if the format has one.
199
#
200
# Iterate over all channels, not just those in self.order, because
201
# some formats have an empty 'order' field in the CSV (such as
202
# YCRCB_NORMAL).
203
self.uniform_channel_type = 'VOID'
204
for chan in self.channels:
205
if chan.type in (None, 'VOID'):
206
pass
207
elif self.uniform_channel_type == 'VOID':
208
self.uniform_channel_type = chan.type
209
elif self.uniform_channel_type == chan.type:
210
pass
211
else:
212
self.uniform_channel_type = 'VOID'
213
break
214
215
# alpha doesn't have a colorspace of it's own.
216
self.colorspace = line[13].strip().upper()
217
if self.colorspace in ['']:
218
self.colorspace = 'NONE'
219
220
# This sets it to the line value, or if it's an empty string 'NONE'
221
self.txc = line[14].strip().upper() or 'NONE'
222
223
224
@property
225
def channels(self):
226
yield self.r
227
yield self.g
228
yield self.b
229
yield self.a
230
yield self.l
231
yield self.i
232
yield self.p
233
234
235
def reader(csvfile):
236
"""Wrapper around csv.reader that skips comments and blanks."""
237
# csv.reader actually reads the file one line at a time (it was designed to
238
# open excel generated sheets), so hold the file until all of the lines are
239
# read.
240
with open(csvfile, 'r') as f:
241
for line in csv.reader(f):
242
if line and not line[0].startswith('#'):
243
yield line
244
245
def get_srgb_to_linear_map(formats):
246
"""Compute a map from sRGB to linear formats.
247
248
This function uses some probably somewhat fragile string munging to do
249
the conversion. However, we do assert that, if it's SRGB, the munging
250
succeeded so that gives some safety.
251
"""
252
names = {f.name for f in formats}
253
for fmt in formats:
254
if fmt.colorspace != 'SRGB':
255
continue
256
257
replacements = [
258
('_SRGB', ''),
259
('SRGB', 'RGB'),
260
('U8SRGB', 'FLT16'),
261
]
262
263
found = False
264
for rep in replacements:
265
rgb_name = fmt.name.replace(rep[0], rep[1])
266
if rgb_name in names:
267
found = True
268
yield fmt.name, rgb_name
269
break
270
271
# We should have found a format name
272
assert found
273
274
def main():
275
"""Main function."""
276
parser = argparse.ArgumentParser()
277
parser.add_argument('--csv', action='store', help='The CSV file to parse.')
278
parser.add_argument(
279
'--out',
280
action='store',
281
help='The location to put the generated C file.')
282
args = parser.parse_args()
283
284
# This generator opens and writes the file itself, and it does so in bytes
285
# mode. This solves both python 2 vs 3 problems and solves the locale
286
# problem: Unicode can be rendered even if the shell calling this script
287
# doesn't.
288
with open(args.out, 'wb') as f:
289
formats = [Format(l) for l in reader(args.csv)]
290
try:
291
# This basically does lazy evaluation and initialization, which
292
# saves on memory and startup overhead.
293
f.write(TEMPLATE.render(
294
formats = formats,
295
srgb_to_linear_map = list(get_srgb_to_linear_map(formats)),
296
))
297
except Exception:
298
# In the even there's an error this imports some helpers from mako
299
# to print a useful stack trace and prints it, then exits with
300
# status 1, if python is run with debug; otherwise it just raises
301
# the exception
302
if __debug__:
303
import sys
304
from mako import exceptions
305
print(exceptions.text_error_template().render(),
306
file=sys.stderr)
307
sys.exit(1)
308
raise
309
310
311
if __name__ == '__main__':
312
main()
313
314