blob: ca9ffc5b67aafc0234e7e0be8e8561d0f6a83a58 [file] [log] [blame]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001#!/usr/bin/python3 -i
2#
Mark Lobodzinski733f7f42017-01-10 11:42:22 -07003# Copyright (c) 2015-2017 The Khronos Group Inc.
4# Copyright (c) 2015-2017 Valve Corporation
5# Copyright (c) 2015-2017 LunarG, Inc.
6# Copyright (c) 2015-2017 Google Inc.
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07007#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19#
20# Author: Mark Lobodzinski <mark@lunarg.com>
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070021# Author: Tobin Ehlis <tobine@google.com>
John Zulaufd7435c62018-03-16 11:52:57 -060022# Author: John Zulauf <jzulauf@lunarg.com>
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070023
24import os,re,sys
25import xml.etree.ElementTree as etree
26from generator import *
27from collections import namedtuple
Mark Lobodzinski62f71562017-10-24 13:41:18 -060028from common_codegen import *
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070029
30#
31# HelperFileOutputGeneratorOptions - subclass of GeneratorOptions.
32class HelperFileOutputGeneratorOptions(GeneratorOptions):
33 def __init__(self,
34 filename = None,
35 directory = '.',
36 apiname = None,
37 profile = None,
38 versions = '.*',
39 emitversions = '.*',
40 defaultExtensions = None,
41 addExtensions = None,
42 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060043 emitExtensions = None,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070044 sortProcedure = regSortFeatures,
45 prefixText = "",
46 genFuncPointers = True,
47 protectFile = True,
48 protectFeature = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070049 apicall = '',
50 apientry = '',
51 apientryp = '',
52 alignFuncParam = 0,
53 library_name = '',
Mark Lobodzinski62f71562017-10-24 13:41:18 -060054 expandEnumerants = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070055 helper_file_type = ''):
56 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
57 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060058 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070059 self.prefixText = prefixText
60 self.genFuncPointers = genFuncPointers
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070061 self.protectFile = protectFile
62 self.protectFeature = protectFeature
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070063 self.apicall = apicall
64 self.apientry = apientry
65 self.apientryp = apientryp
66 self.alignFuncParam = alignFuncParam
67 self.library_name = library_name
68 self.helper_file_type = helper_file_type
69#
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070070# HelperFileOutputGenerator - subclass of OutputGenerator. Outputs Vulkan helper files
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070071class HelperFileOutputGenerator(OutputGenerator):
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -070072 """Generate helper file based on XML element attributes"""
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070073 def __init__(self,
74 errFile = sys.stderr,
75 warnFile = sys.stderr,
76 diagFile = sys.stdout):
77 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
78 # Internal state - accumulators for different inner block text
Mark Lobodzinski5380d132016-12-28 14:45:34 -070079 self.enum_output = '' # string built up of enum string routines
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070080 # Internal state - accumulators for different inner block text
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070081 self.structNames = [] # List of Vulkan struct typenames
82 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070083 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -060084 self.object_types = [] # List of all handle types
John Zulaufd7435c62018-03-16 11:52:57 -060085 self.object_type_aliases = [] # Aliases to handles types (for handles that were extensions)
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060086 self.debug_report_object_types = [] # Handy copy of debug_report_object_type enum data
Mark Young1ded24b2017-05-30 14:53:50 -060087 self.core_object_types = [] # Handy copy of core_object_type enum data
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -060088 self.device_extension_info = dict() # Dict of device extension name defines and ifdef values
89 self.instance_extension_info = dict() # Dict of instance extension name defines and ifdef values
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060090
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070091 # Named tuples to store struct and command data
92 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070093 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl'])
Mark Lobodzinski5380d132016-12-28 14:45:34 -070094 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members', 'ifdef_protect'])
Petr Krause91f7a12017-12-14 20:57:36 +010095
96 self.custom_construct_params = {
97 # safe_VkGraphicsPipelineCreateInfo needs to know if subpass has color and\or depth\stencil attachments to use its pointers
98 'VkGraphicsPipelineCreateInfo' :
99 ', const bool uses_color_attachment, const bool uses_depthstencil_attachment',
100 # safe_VkPipelineViewportStateCreateInfo needs to know if viewport and scissor is dynamic to use its pointers
101 'VkPipelineViewportStateCreateInfo' :
102 ', const bool is_dynamic_viewports, const bool is_dynamic_scissors',
103 }
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700104 #
105 # Called once at the beginning of each run
106 def beginFile(self, genOpts):
107 OutputGenerator.beginFile(self, genOpts)
108 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700109 self.helper_file_type = genOpts.helper_file_type
110 self.library_name = genOpts.library_name
111 # File Comment
112 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
113 file_comment += '// See helper_file_generator.py for modifications\n'
114 write(file_comment, file=self.outFile)
115 # Copyright Notice
116 copyright = ''
117 copyright += '\n'
118 copyright += '/***************************************************************************\n'
119 copyright += ' *\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700120 copyright += ' * Copyright (c) 2015-2017 The Khronos Group Inc.\n'
121 copyright += ' * Copyright (c) 2015-2017 Valve Corporation\n'
122 copyright += ' * Copyright (c) 2015-2017 LunarG, Inc.\n'
123 copyright += ' * Copyright (c) 2015-2017 Google Inc.\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700124 copyright += ' *\n'
125 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
126 copyright += ' * you may not use this file except in compliance with the License.\n'
127 copyright += ' * You may obtain a copy of the License at\n'
128 copyright += ' *\n'
129 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
130 copyright += ' *\n'
131 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
132 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
133 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
134 copyright += ' * See the License for the specific language governing permissions and\n'
135 copyright += ' * limitations under the License.\n'
136 copyright += ' *\n'
137 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Mark Lobodzinskia9c963d2016-12-28 07:45:35 -0700138 copyright += ' * Author: Courtney Goeltzenleuchter <courtneygo@google.com>\n'
139 copyright += ' * Author: Tobin Ehlis <tobine@google.com>\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600140 copyright += ' * Author: Chris Forbes <chrisforbes@google.com>\n'
John Zulaufde972ac2017-10-26 12:07:05 -0600141 copyright += ' * Author: John Zulauf<jzulauf@lunarg.com>\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700142 copyright += ' *\n'
143 copyright += ' ****************************************************************************/\n'
144 write(copyright, file=self.outFile)
145 #
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -0700146 # Write generated file content to output file
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700147 def endFile(self):
148 dest_file = ''
149 dest_file += self.OutputDestFile()
Mark Lobodzinskiafe10542017-01-03 13:22:44 -0700150 # Remove blank lines at EOF
151 if dest_file.endswith('\n'):
152 dest_file = dest_file[:-1]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700153 write(dest_file, file=self.outFile);
154 # Finish processing in superclass
155 OutputGenerator.endFile(self)
156 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600157 # Override parent class to be notified of the beginning of an extension
158 def beginFeature(self, interface, emit):
159 # Start processing in superclass
160 OutputGenerator.beginFeature(self, interface, emit)
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600161 self.featureExtraProtect = GetFeatureProtect(interface)
162
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600163 if self.featureName == 'VK_VERSION_1_0' or self.featureName == 'VK_VERSION_1_1':
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600164 return
165 nameElem = interface[0][1]
166 name = nameElem.get('name')
167 if 'EXTENSION_NAME' not in name:
168 print("Error in vk.xml file -- extension name is not available")
169 if interface.get('type') == 'instance':
170 self.instance_extension_info[name] = self.featureExtraProtect
171 else:
172 self.device_extension_info[name] = self.featureExtraProtect
173 #
174 # Override parent class to be notified of the end of an extension
175 def endFeature(self):
176 # Finish processing in superclass
177 OutputGenerator.endFeature(self)
178 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700179 # Grab group (e.g. C "enum" type) info to output for enum-string conversion helper
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700180 def genGroup(self, groupinfo, groupName, alias):
181 OutputGenerator.genGroup(self, groupinfo, groupName, alias)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700182 groupElem = groupinfo.elem
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700183 # For enum_string_header
184 if self.helper_file_type == 'enum_string_header':
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700185 value_set = set()
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700186 for elem in groupElem.findall('enum'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700187 if elem.get('supported') != 'disabled' and elem.get('alias') == None:
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700188 value_set.add(elem.get('name'))
189 self.enum_output += self.GenerateEnumStringConversion(groupName, value_set)
Mark Young1ded24b2017-05-30 14:53:50 -0600190 elif self.helper_file_type == 'object_types_header':
191 if groupName == 'VkDebugReportObjectTypeEXT':
192 for elem in groupElem.findall('enum'):
193 if elem.get('supported') != 'disabled':
194 item_name = elem.get('name')
195 self.debug_report_object_types.append(item_name)
196 elif groupName == 'VkObjectType':
197 for elem in groupElem.findall('enum'):
198 if elem.get('supported') != 'disabled':
199 item_name = elem.get('name')
200 self.core_object_types.append(item_name)
201
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700202 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700203 # Called for each type -- if the type is a struct/union, grab the metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700204 def genType(self, typeinfo, name, alias):
205 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700206 typeElem = typeinfo.elem
207 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
208 # Otherwise, emit the tag text.
209 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600210 if category == 'handle':
John Zulaufd7435c62018-03-16 11:52:57 -0600211 if alias:
212 self.object_type_aliases.append((name,alias))
213 else:
214 self.object_types.append(name)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600215 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700216 self.structNames.append(name)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700217 self.genStruct(typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700218 #
219 # Generate a VkStructureType based on a structure typename
220 def genVkStructureType(self, typename):
221 # Add underscore between lowercase then uppercase
222 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
223 # Change to uppercase
224 value = value.upper()
225 # Add STRUCTURE_TYPE_
226 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
227 #
228 # Check if the parameter passed in is a pointer
229 def paramIsPointer(self, param):
230 ispointer = False
231 for elem in param:
232 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
233 ispointer = True
234 return ispointer
235 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700236 # Check if the parameter passed in is a static array
237 def paramIsStaticArray(self, param):
238 isstaticarray = 0
239 paramname = param.find('name')
240 if (paramname.tail is not None) and ('[' in paramname.tail):
241 isstaticarray = paramname.tail.count('[')
242 return isstaticarray
243 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700244 # Retrieve the type and name for a parameter
245 def getTypeNameTuple(self, param):
246 type = ''
247 name = ''
248 for elem in param:
249 if elem.tag == 'type':
250 type = noneStr(elem.text)
251 elif elem.tag == 'name':
252 name = noneStr(elem.text)
253 return (type, name)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700254 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
255 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
256 def parseLateXMath(self, source):
257 name = 'ERROR'
258 decoratedName = 'ERROR'
259 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700260 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
261 match = re.match(r'latexmath\s*\:\s*\[\s*\\l(\w+)\s*\{\s*\\mathit\s*\{\s*(\w+)\s*\}\s*\\over\s*(\d+)\s*\}\s*\\r(\w+)\s*\]', source)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700262 if not match or match.group(1) != match.group(4):
263 raise 'Unrecognized latexmath expression'
264 name = match.group(2)
mizhenc27f6c72017-03-31 09:08:16 -0600265 # Need to add 1 for ceiling function; otherwise, the allocated packet
266 # size will be less than needed during capture for some title which use
267 # this in VkPipelineMultisampleStateCreateInfo. based on ceiling function
268 # definition,it is '{0}%{1}?{0}/{1} + 1:{0}/{1}'.format(*match.group(2, 3)),
269 # its value <= '{}/{} + 1'.
270 if match.group(1) == 'ceil':
271 decoratedName = '{}/{} + 1'.format(*match.group(2, 3))
272 else:
273 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700274 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700275 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Mark Young0f183a82017-02-28 09:58:04 -0700276 match = re.match(r'latexmath\s*\:\s*\[\s*(\w+)\s*\\over\s*(\d+)\s*\]', source)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700277 name = match.group(1)
278 decoratedName = '{}/{}'.format(*match.group(1, 2))
279 return name, decoratedName
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700280 #
281 # Retrieve the value of the len tag
282 def getLen(self, param):
283 result = None
284 len = param.attrib.get('len')
285 if len and len != 'null-terminated':
286 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
287 # have a null terminated array of strings. We strip the null-terminated from the
288 # 'len' field and only return the parameter specifying the string count
289 if 'null-terminated' in len:
290 result = len.split(',')[0]
291 else:
292 result = len
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700293 if 'latexmath' in len:
294 param_type, param_name = self.getTypeNameTuple(param)
295 len_name, result = self.parseLateXMath(len)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700296 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
297 result = str(result).replace('::', '->')
298 return result
299 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700300 # Check if a structure is or contains a dispatchable (dispatchable = True) or
301 # non-dispatchable (dispatchable = False) handle
302 def TypeContainsObjectHandle(self, handle_type, dispatchable):
303 if dispatchable:
304 type_key = 'VK_DEFINE_HANDLE'
305 else:
306 type_key = 'VK_DEFINE_NON_DISPATCHABLE_HANDLE'
307 handle = self.registry.tree.find("types/type/[name='" + handle_type + "'][@category='handle']")
308 if handle is not None and handle.find('type').text == type_key:
309 return True
310 # if handle_type is a struct, search its members
311 if handle_type in self.structNames:
312 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == handle_type), None)
313 if member_index is not None:
314 for item in self.structMembers[member_index].members:
315 handle = self.registry.tree.find("types/type/[name='" + item.type + "'][@category='handle']")
316 if handle is not None and handle.find('type').text == type_key:
317 return True
318 return False
319 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700320 # Generate local ready-access data describing Vulkan structures and unions from the XML metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700321 def genStruct(self, typeinfo, typeName, alias):
322 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700323 members = typeinfo.elem.findall('.//member')
324 # Iterate over members once to get length parameters for arrays
325 lens = set()
326 for member in members:
327 len = self.getLen(member)
328 if len:
329 lens.add(len)
330 # Generate member info
331 membersInfo = []
332 for member in members:
333 # Get the member's type and name
334 info = self.getTypeNameTuple(member)
335 type = info[0]
336 name = info[1]
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700337 cdecl = self.makeCParamDecl(member, 1)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700338 # Process VkStructureType
339 if type == 'VkStructureType':
340 # Extract the required struct type value from the comments
341 # embedded in the original text defining the 'typeinfo' element
342 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
343 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
344 if result:
345 value = result.group(0)
346 else:
347 value = self.genVkStructureType(typeName)
348 # Store the required type value
349 self.structTypes[typeName] = self.StructType(name=name, value=value)
350 # Store pointer/array/string info
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700351 isstaticarray = self.paramIsStaticArray(member)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700352 membersInfo.append(self.CommandParam(type=type,
353 name=name,
354 ispointer=self.paramIsPointer(member),
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700355 isstaticarray=isstaticarray,
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700356 isconst=True if 'const' in cdecl else False,
357 iscount=True if name in lens else False,
358 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600359 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700360 cdecl=cdecl))
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700361 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo, ifdef_protect=self.featureExtraProtect))
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700362 #
363 # Enum_string_header: Create a routine to convert an enumerated value into a string
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700364 def GenerateEnumStringConversion(self, groupName, value_list):
365 outstring = '\n'
366 outstring += 'static inline const char* string_%s(%s input_value)\n' % (groupName, groupName)
367 outstring += '{\n'
368 outstring += ' switch ((%s)input_value)\n' % groupName
369 outstring += ' {\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700370 for item in value_list:
371 outstring += ' case %s:\n' % item
372 outstring += ' return "%s";\n' % item
373 outstring += ' default:\n'
374 outstring += ' return "Unhandled %s";\n' % groupName
375 outstring += ' }\n'
376 outstring += '}\n'
377 return outstring
378 #
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600379 # Tack on a helper which, given an index into a VkPhysicalDeviceFeatures structure, will print the corresponding feature name
380 def DeIndexPhysDevFeatures(self):
381 pdev_members = None
382 for name, members, ifdef in self.structMembers:
383 if name == 'VkPhysicalDeviceFeatures':
384 pdev_members = members
385 break
386 deindex = '\n'
Mark Young2ee6aea2018-02-21 15:30:27 -0700387 deindex += 'static inline const char * GetPhysDevFeatureString(uint32_t index) {\n'
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600388 deindex += ' const char * IndexToPhysDevFeatureString[] = {\n'
389 for feature in pdev_members:
390 deindex += ' "%s",\n' % feature.name
391 deindex += ' };\n\n'
392 deindex += ' return IndexToPhysDevFeatureString[index];\n'
393 deindex += '}\n'
394 return deindex
395 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700396 # Combine enum string helper header file preamble with body text and return
397 def GenerateEnumStringHelperHeader(self):
398 enum_string_helper_header = '\n'
399 enum_string_helper_header += '#pragma once\n'
400 enum_string_helper_header += '#ifdef _WIN32\n'
401 enum_string_helper_header += '#pragma warning( disable : 4065 )\n'
402 enum_string_helper_header += '#endif\n'
403 enum_string_helper_header += '\n'
404 enum_string_helper_header += '#include <vulkan/vulkan.h>\n'
405 enum_string_helper_header += '\n'
406 enum_string_helper_header += self.enum_output
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600407 enum_string_helper_header += self.DeIndexPhysDevFeatures()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700408 return enum_string_helper_header
409 #
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700410 # Helper function for declaring a counter variable only once
411 def DeclareCounter(self, string_var, declare_flag):
412 if declare_flag == False:
413 string_var += ' uint32_t i = 0;\n'
414 declare_flag = True
415 return string_var, declare_flag
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700416 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700417 # Combine safe struct helper header file preamble with body text and return
418 def GenerateSafeStructHelperHeader(self):
419 safe_struct_helper_header = '\n'
420 safe_struct_helper_header += '#pragma once\n'
421 safe_struct_helper_header += '#include <vulkan/vulkan.h>\n'
422 safe_struct_helper_header += '\n'
423 safe_struct_helper_header += self.GenerateSafeStructHeader()
424 return safe_struct_helper_header
425 #
426 # safe_struct header: build function prototypes for header file
427 def GenerateSafeStructHeader(self):
428 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700429 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700430 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700431 safe_struct_header += '\n'
432 if item.ifdef_protect != None:
433 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
434 safe_struct_header += 'struct safe_%s {\n' % (item.name)
435 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700436 if member.type in self.structNames:
437 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
438 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
439 if member.ispointer:
440 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
441 else:
442 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
443 continue
444 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
445 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
446 else:
447 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100448 safe_struct_header += ' safe_%s(const %s* in_struct%s);\n' % (item.name, item.name, self.custom_construct_params.get(item.name, ''))
Mark Lobodzinski5cd08512017-09-12 09:50:25 -0600449 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700450 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700451 safe_struct_header += ' safe_%s();\n' % item.name
452 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100453 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
454 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700455 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
456 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
457 safe_struct_header += '};\n'
458 if item.ifdef_protect != None:
459 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700460 return safe_struct_header
461 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600462 # Generate extension helper header file
463 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600464
465 V_1_0_instance_extensions_promoted_to_core = [
466 'vk_khr_device_group_creation',
467 'vk_khr_external_memory_capabilities',
468 'vk_khr_external_fence_capabilities',
469 'vk_khr_external_semaphore_capabilities',
470 'vk_khr_get_physical_device_properties_2',
471 ]
472
473 V_1_0_device_extensions_promoted_to_core = [
474 'vk_khr_bind_memory_2',
475 'vk_khr_device_group',
476 'vk_khr_descriptor_update_template',
477 'vk_khr_sampler_ycbcr_conversion',
478 'vk_khr_get_memory_requirements_2',
479 'vk_khr_maintenance3',
480 'vk_khr_maintenance1',
481 'vk_khr_multiview',
482 'vk_khr_external_memory',
483 'vk_khr_external_semaphore',
484 'vk_khr_16bit_storage',
485 'vk_khr_external_fence',
486 'vk_khr_maintenance2',
487 'vk_khr_variable_pointers',
488 'vk_khr_dedicated_allocation',
489 ]
490
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600491 extension_helper_header = '\n'
492 extension_helper_header += '#ifndef VK_EXTENSION_HELPER_H_\n'
493 extension_helper_header += '#define VK_EXTENSION_HELPER_H_\n'
494 struct = '\n'
Tobin Ehlis84154d32017-06-09 15:46:14 -0600495 extension_helper_header += '#include <vulkan/vulkan.h>\n'
Tobin Ehlisd922d4c2017-06-14 09:43:04 -0600496 extension_helper_header += '#include <string.h>\n'
Tobin Ehlis84154d32017-06-09 15:46:14 -0600497 extension_helper_header += '#include <utility>\n'
498 extension_helper_header += '\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600499 extension_helper_header += '\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600500 extension_dict = dict()
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600501 promoted_ext_list = []
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600502 for type in ['Instance', 'Device']:
503 if type == 'Instance':
504 extension_dict = self.instance_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600505 promoted_ext_list = V_1_0_instance_extensions_promoted_to_core
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600506 struct += 'struct InstanceExtensions { \n'
507 else:
508 extension_dict = self.device_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600509 promoted_ext_list = V_1_0_device_extensions_promoted_to_core
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600510 struct += 'struct DeviceExtensions : public InstanceExtensions { \n'
511 for ext_name, ifdef in extension_dict.items():
512 bool_name = ext_name.lower()
513 bool_name = re.sub('_extension_name', '', bool_name)
514 struct += ' bool %s{false};\n' % bool_name
515 struct += '\n'
516 if type == 'Instance':
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600517 struct += ' uint32_t NormalizeApiVersion(uint32_t specified_version) {\n'
518 struct += ' uint32_t api_version = specified_version & ~VK_VERSION_PATCH(~0);\n'
519 struct += ' if (!(api_version == VK_API_VERSION_1_0) && !(api_version == VK_API_VERSION_1_1)) {\n'
520 struct += ' api_version = VK_API_VERSION_1_1;\n'
521 struct += ' }\n'
522 struct += ' return api_version;\n'
523 struct += ' }\n'
524 struct += '\n'
525
526 struct += ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600527 else:
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600528 struct += ' uint32_t InitFromDeviceCreateInfo(const InstanceExtensions *instance_extensions, uint32_t requested_api_version, const VkDeviceCreateInfo *pCreateInfo) {\n'
529 struct += '\n'
530
531 struct += ' static const std::vector<const char *> V_1_0_promoted_%s_extensions = {\n' % type.lower()
532 for ext_name in promoted_ext_list:
533 struct += ' %s_EXTENSION_NAME,\n' % ext_name.upper()
534 struct += ' };\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600535 struct += '\n'
536 struct += ' static const std::pair<char const *, bool %sExtensions::*> known_extensions[]{\n' % type
537 for ext_name, ifdef in extension_dict.items():
538 if ifdef is not None:
539 struct += '#ifdef %s\n' % ifdef
540 bool_name = ext_name.lower()
541 bool_name = re.sub('_extension_name', '', bool_name)
542 struct += ' {%s, &%sExtensions::%s},\n' % (ext_name, type, bool_name)
543 if ifdef is not None:
544 struct += '#endif\n'
545 struct += ' };\n'
546 struct += '\n'
547 struct += ' // Initialize struct data\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600548
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600549 for ext_name, ifdef in self.instance_extension_info.items():
550 bool_name = ext_name.lower()
551 bool_name = re.sub('_extension_name', '', bool_name)
552 if type == 'Device':
553 struct += ' %s = instance_extensions->%s;\n' % (bool_name, bool_name)
554 struct += '\n'
555 struct += ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {\n'
556 struct += ' for (auto ext : known_extensions) {\n'
557 struct += ' if (!strcmp(ext.first, pCreateInfo->ppEnabledExtensionNames[i])) {\n'
558 struct += ' this->*(ext.second) = true;\n'
559 struct += ' break;\n'
560 struct += ' }\n'
561 struct += ' }\n'
562 struct += ' }\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600563 struct += ' uint32_t api_version = NormalizeApiVersion(requested_api_version);\n'
564 struct += ' if (api_version >= VK_API_VERSION_1_1) {\n'
565 struct += ' for (auto promoted_ext : V_1_0_promoted_%s_extensions) {\n' % type.lower()
566 struct += ' for (auto ext : known_extensions) {\n'
567 struct += ' if (!strcmp(ext.first, promoted_ext)) {\n'
568 struct += ' this->*(ext.second) = true;\n'
569 struct += ' break;\n'
570 struct += ' }\n'
571 struct += ' }\n'
572 struct += ' }\n'
573 struct += ' }\n'
574 struct += ' return api_version;\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600575 struct += ' }\n'
576 struct += '};\n'
577 struct += '\n'
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700578 # Output reference lists of instance/device extension names
579 struct += 'static const char * const k%sExtensionNames = \n' % type
580 for ext_name, ifdef in extension_dict.items():
581 if ifdef is not None:
582 struct += '#ifdef %s\n' % ifdef
583 struct += ' %s\n' % ext_name
584 if ifdef is not None:
585 struct += '#endif\n'
586 struct += ';\n\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600587 extension_helper_header += struct
588 extension_helper_header += '\n'
589 extension_helper_header += '#endif // VK_EXTENSION_HELPER_H_\n'
590 return extension_helper_header
591 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600592 # Combine object types helper header file preamble with body text and return
593 def GenerateObjectTypesHelperHeader(self):
594 object_types_helper_header = '\n'
595 object_types_helper_header += '#pragma once\n'
596 object_types_helper_header += '\n'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600597 object_types_helper_header += '#include <vulkan/vulkan.h>\n\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600598 object_types_helper_header += self.GenerateObjectTypesHeader()
599 return object_types_helper_header
600 #
601 # Object types header: create object enum type header file
602 def GenerateObjectTypesHeader(self):
Mark Young6ba8abe2017-11-09 10:37:04 -0700603 object_types_header = ''
604 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600605 object_types_header += 'typedef enum VulkanObjectType {\n'
606 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
607 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600608 type_list = [];
John Zulaufd7435c62018-03-16 11:52:57 -0600609 enum_entry_map = {}
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600610
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600611 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600612 for item in self.object_types:
613 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600614 enum_entry = 'kVulkanObjectType%s' % fixup_name
John Zulaufd7435c62018-03-16 11:52:57 -0600615 enum_entry_map[item] = enum_entry
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600616 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600617 object_types_header += ' = %d,\n' % enum_num
618 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600619 type_list.append(enum_entry)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600620 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
John Zulaufd7435c62018-03-16 11:52:57 -0600621 object_types_header += ' // Aliases for backwards compatibilty of "promoted" types\n'
622 for (name, alias) in self.object_type_aliases:
623 fixup_name = name[2:]
624 object_types_header += ' kVulkanObjectType{} = {},\n'.format(fixup_name, enum_entry_map[alias])
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600625 object_types_header += '} VulkanObjectType;\n\n'
626
627 # Output name string helper
628 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600629 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600630 object_types_header += ' "Unknown",\n'
631 for item in self.object_types:
632 fixup_name = item[2:]
633 object_types_header += ' "%s",\n' % fixup_name
634 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600635
John Zulauf311a4892018-03-12 15:48:06 -0600636 # Key creation helper for map comprehensions that convert between k<Name> and VK<Name> symbols
637 def to_key(regex, raw_key): return re.search(regex, raw_key).group(1).lower().replace("_","")
638
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600639 # Output a conversion routine from the layer object definitions to the debug report definitions
John Zulauf311a4892018-03-12 15:48:06 -0600640 # As the VK_DEBUG_REPORT types are not being updated, specify UNKNOWN for unmatched types
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600641 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600642 object_types_header += '// Helper array to get Vulkan VK_EXT_debug_report object type enum from the internal layers version\n'
Mark Lobodzinskic51dbb72017-04-13 14:25:39 -0600643 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700644 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000645
John Zulauf311a4892018-03-12 15:48:06 -0600646 dbg_re = '^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$'
647 dbg_map = {to_key(dbg_re, dbg) : dbg for dbg in self.debug_report_object_types}
648 dbg_default = 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT'
649 for object_type in type_list:
650 vk_object_type = dbg_map.get(object_type.replace("kVulkanObjectType", "").lower(), dbg_default)
651 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600652 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600653
654 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600655 # This will intentionally *fail* for unmatched types as the VK_OBJECT_TYPE list should match the kVulkanObjectType list
Mark Young1ded24b2017-05-30 14:53:50 -0600656 object_types_header += '\n'
657 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
658 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700659 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
John Zulauf311a4892018-03-12 15:48:06 -0600660
661 vko_re = '^VK_OBJECT_TYPE_(.*)'
662 vko_map = {to_key(vko_re, vko) : vko for vko in self.core_object_types}
Mark Young1ded24b2017-05-30 14:53:50 -0600663 for object_type in type_list:
John Zulauf311a4892018-03-12 15:48:06 -0600664 vk_object_type = vko_map[object_type.replace("kVulkanObjectType", "").lower()]
665 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Young1ded24b2017-05-30 14:53:50 -0600666 object_types_header += '};\n'
667
Mark Young6ba8abe2017-11-09 10:37:04 -0700668 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
669 object_types_header += '\n'
670 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
671 object_types_header += 'static VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
672 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
673 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
674 for core_object_type in self.core_object_types:
675 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
676 core_target_type = core_target_type.replace("_", "")
677 for dr_object_type in self.debug_report_object_types:
678 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
679 dr_target_type = dr_target_type[:-4]
680 dr_target_type = dr_target_type.replace("_", "")
681 if core_target_type == dr_target_type:
682 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
683 object_types_header += ' return %s;\n' % core_object_type
684 break
685 object_types_header += ' }\n'
686 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
687 object_types_header += '}\n'
688
689 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
690 object_types_header += '\n'
691 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
692 object_types_header += 'static VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
693 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
694 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
695 for core_object_type in self.core_object_types:
696 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
697 core_target_type = core_target_type.replace("_", "")
698 for dr_object_type in self.debug_report_object_types:
699 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
700 dr_target_type = dr_target_type[:-4]
701 dr_target_type = dr_target_type.replace("_", "")
702 if core_target_type == dr_target_type:
703 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
704 object_types_header += ' return %s;\n' % dr_object_type
705 break
706 object_types_header += ' }\n'
707 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
708 object_types_header += '}\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600709 return object_types_header
710 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700711 # Determine if a structure needs a safe_struct helper function
712 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700713 def NeedSafeStruct(self, structure):
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700714 if 'sType' == structure.name:
715 return True
716 for member in structure.members:
717 if member.ispointer == True:
718 return True
719 return False
720 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700721 # Combine safe struct helper source file preamble with body text and return
722 def GenerateSafeStructHelperSource(self):
723 safe_struct_helper_source = '\n'
724 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
725 safe_struct_helper_source += '#include <string.h>\n'
726 safe_struct_helper_source += '\n'
727 safe_struct_helper_source += self.GenerateSafeStructSource()
728 return safe_struct_helper_source
729 #
730 # safe_struct source -- create bodies of safe struct helper functions
731 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700732 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700733 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
734 'VkXcbSurfaceCreateInfoKHR',
735 'VkWaylandSurfaceCreateInfoKHR',
736 'VkMirSurfaceCreateInfoKHR',
737 'VkAndroidSurfaceCreateInfoKHR',
738 'VkWin32SurfaceCreateInfoKHR'
739 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700740 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700741 if self.NeedSafeStruct(item) == False:
742 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700743 if item.name in wsi_structs:
744 continue
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700745 if item.ifdef_protect != None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700746 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
747 ss_name = "safe_%s" % item.name
748 init_list = '' # list of members in struct constructor initializer
749 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
750 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
751 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
752 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +0100753
754 custom_construct_txt = {
755 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
756 'VkWriteDescriptorSet' :
757 ' switch (descriptorType) {\n'
758 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
759 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
760 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
761 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
762 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
763 ' if (descriptorCount && in_struct->pImageInfo) {\n'
764 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
765 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
766 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
767 ' }\n'
768 ' }\n'
769 ' break;\n'
770 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
771 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
772 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
773 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
774 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
775 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
776 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
777 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
778 ' }\n'
779 ' }\n'
780 ' break;\n'
781 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
782 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
783 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
784 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
785 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
786 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
787 ' }\n'
788 ' }\n'
789 ' break;\n'
790 ' default:\n'
791 ' break;\n'
792 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100793 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +0100794 ' if (in_struct->pCode) {\n'
795 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
796 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
797 ' }\n',
798 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
799 'VkGraphicsPipelineCreateInfo' :
800 ' if (stageCount && in_struct->pStages) {\n'
801 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
802 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
803 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
804 ' }\n'
805 ' }\n'
806 ' if (in_struct->pVertexInputState)\n'
807 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
808 ' else\n'
809 ' pVertexInputState = NULL;\n'
810 ' if (in_struct->pInputAssemblyState)\n'
811 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
812 ' else\n'
813 ' pInputAssemblyState = NULL;\n'
814 ' bool has_tessellation_stage = false;\n'
815 ' if (stageCount && pStages)\n'
816 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
817 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
818 ' has_tessellation_stage = true;\n'
819 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
820 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
821 ' else\n'
822 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
823 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
824 ' if (in_struct->pViewportState && has_rasterization) {\n'
825 ' bool is_dynamic_viewports = false;\n'
826 ' bool is_dynamic_scissors = false;\n'
827 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
828 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
829 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
830 ' is_dynamic_viewports = true;\n'
831 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
832 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
833 ' is_dynamic_scissors = true;\n'
834 ' }\n'
835 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
836 ' } else\n'
837 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
838 ' if (in_struct->pRasterizationState)\n'
839 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
840 ' else\n'
841 ' pRasterizationState = NULL;\n'
842 ' if (in_struct->pMultisampleState && has_rasterization)\n'
843 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
844 ' else\n'
845 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
846 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
847 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
848 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
849 ' else\n'
850 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
851 ' // needs a tracked subpass state usesColorAttachment\n'
852 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
853 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
854 ' else\n'
855 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
856 ' if (in_struct->pDynamicState)\n'
857 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
858 ' else\n'
859 ' pDynamicState = NULL;\n',
860 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
861 'VkPipelineViewportStateCreateInfo' :
862 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
863 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
864 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
865 ' }\n'
866 ' else\n'
867 ' pViewports = NULL;\n'
868 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
869 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
870 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
871 ' }\n'
872 ' else\n'
873 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100874 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
875 'VkDescriptorSetLayoutBinding' :
876 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
877 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
878 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
879 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
880 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
881 ' }\n'
882 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +0100883 }
884
885 custom_copy_txt = {
886 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
887 'VkGraphicsPipelineCreateInfo' :
888 ' if (stageCount && src.pStages) {\n'
889 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
890 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
891 ' pStages[i].initialize(&src.pStages[i]);\n'
892 ' }\n'
893 ' }\n'
894 ' if (src.pVertexInputState)\n'
895 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
896 ' else\n'
897 ' pVertexInputState = NULL;\n'
898 ' if (src.pInputAssemblyState)\n'
899 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
900 ' else\n'
901 ' pInputAssemblyState = NULL;\n'
902 ' bool has_tessellation_stage = false;\n'
903 ' if (stageCount && pStages)\n'
904 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
905 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
906 ' has_tessellation_stage = true;\n'
907 ' if (src.pTessellationState && has_tessellation_stage)\n'
908 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
909 ' else\n'
910 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
911 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
912 ' if (src.pViewportState && has_rasterization) {\n'
913 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
914 ' } else\n'
915 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
916 ' if (src.pRasterizationState)\n'
917 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
918 ' else\n'
919 ' pRasterizationState = NULL;\n'
920 ' if (src.pMultisampleState && has_rasterization)\n'
921 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
922 ' else\n'
923 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
924 ' if (src.pDepthStencilState && has_rasterization)\n'
925 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
926 ' else\n'
927 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
928 ' if (src.pColorBlendState && has_rasterization)\n'
929 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
930 ' else\n'
931 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
932 ' if (src.pDynamicState)\n'
933 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
934 ' else\n'
935 ' pDynamicState = NULL;\n',
936 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
937 'VkPipelineViewportStateCreateInfo' :
938 ' if (src.pViewports) {\n'
939 ' pViewports = new VkViewport[src.viewportCount];\n'
940 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
941 ' }\n'
942 ' else\n'
943 ' pViewports = NULL;\n'
944 ' if (src.pScissors) {\n'
945 ' pScissors = new VkRect2D[src.scissorCount];\n'
946 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
947 ' }\n'
948 ' else\n'
949 ' pScissors = NULL;\n',
950 }
951
Mike Schuchardt81485762017-09-04 11:38:42 -0600952 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
953 ' if (pCode)\n'
954 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700955
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700956 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700957 m_type = member.type
958 if member.type in self.structNames:
959 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
960 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
961 m_type = 'safe_%s' % member.type
962 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
963 # Ptr types w/o a safe_struct, for non-null case need to allocate new ptr and copy data in
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700964 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700965 # For these exceptions just copy initial value over for now
966 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
967 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700968 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700969 default_init_list += '\n %s(nullptr),' % (member.name)
970 init_list += '\n %s(nullptr),' % (member.name)
971 init_func_txt += ' %s = nullptr;\n' % (member.name)
972 if 'pNext' != member.name and 'void' not in m_type:
Mark Lobodzinski51160a12017-01-18 11:05:48 -0700973 if not member.isstaticarray and (member.len is None or '/' in member.len):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700974 construct_txt += ' if (in_struct->%s) {\n' % member.name
975 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
976 construct_txt += ' }\n'
977 destruct_txt += ' if (%s)\n' % member.name
978 destruct_txt += ' delete %s;\n' % member.name
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700979 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700980 construct_txt += ' if (in_struct->%s) {\n' % member.name
981 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
982 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
983 construct_txt += ' }\n'
984 destruct_txt += ' if (%s)\n' % member.name
985 destruct_txt += ' delete[] %s;\n' % member.name
986 elif member.isstaticarray or member.len is not None:
987 if member.len is None:
988 # Extract length of static array by grabbing val between []
989 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
990 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
991 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
992 construct_txt += ' }\n'
993 else:
994 # Init array ptr to NULL
995 default_init_list += '\n %s(nullptr),' % member.name
996 init_list += '\n %s(nullptr),' % member.name
997 init_func_txt += ' %s = nullptr;\n' % member.name
998 array_element = 'in_struct->%s[i]' % member.name
999 if member.type in self.structNames:
1000 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1001 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1002 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1003 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1004 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1005 destruct_txt += ' if (%s)\n' % member.name
1006 destruct_txt += ' delete[] %s;\n' % member.name
1007 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1008 if 'safe_' in m_type:
1009 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001010 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001011 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1012 construct_txt += ' }\n'
1013 construct_txt += ' }\n'
1014 elif member.ispointer == True:
1015 construct_txt += ' if (in_struct->%s)\n' % member.name
1016 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1017 construct_txt += ' else\n'
1018 construct_txt += ' %s = NULL;\n' % member.name
1019 destruct_txt += ' if (%s)\n' % member.name
1020 destruct_txt += ' delete %s;\n' % member.name
1021 elif 'safe_' in m_type:
1022 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1023 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1024 else:
1025 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1026 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1027 if '' != init_list:
1028 init_list = init_list[:-1] # hack off final comma
1029 if item.name in custom_construct_txt:
1030 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001031 if item.name in custom_destruct_txt:
1032 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001033 safe_struct_body.append("\n%s::%s(const %s* in_struct%s) :%s\n{\n%s}" % (ss_name, ss_name, item.name, self.custom_construct_params.get(item.name, ''), init_list, construct_txt))
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001034 if '' != default_init_list:
1035 default_init_list = " :%s" % (default_init_list[:-1])
1036 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1037 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1038 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1039 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1040 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1041 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001042 if item.name in custom_copy_txt:
1043 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001044 copy_assign_txt = ' if (&src == this) return *this;\n\n' + destruct_txt + '\n' + copy_construct_init + copy_construct_txt + '\n return *this;'
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001045 safe_struct_body.append("\n%s::%s(const %s& src)\n{\n%s%s}" % (ss_name, ss_name, ss_name, copy_construct_init, copy_construct_txt)) # Copy constructor
Chris Forbesfb633832017-10-03 18:11:54 -07001046 safe_struct_body.append("\n%s& %s::operator=(const %s& src)\n{\n%s\n}" % (ss_name, ss_name, ss_name, copy_assign_txt)) # Copy assignment operator
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001047 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001048 safe_struct_body.append("\nvoid %s::initialize(const %s* in_struct%s)\n{\n%s%s}" % (ss_name, item.name, self.custom_construct_params.get(item.name, ''), init_func_txt, construct_txt))
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001049 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1050 init_copy = copy_construct_init.replace('src.', 'src->')
1051 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001052 safe_struct_body.append("\nvoid %s::initialize(const %s* src)\n{\n%s%s}" % (ss_name, ss_name, init_copy, init_construct))
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001053 if item.ifdef_protect != None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001054 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1055 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001056 #
John Zulaufde972ac2017-10-26 12:07:05 -06001057 # Generate the type map
1058 def GenerateTypeMapHelperHeader(self):
1059 prefix = 'Lvl'
1060 fprefix = 'lvl_'
1061 typemap = prefix + 'TypeMap'
1062 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001063 type_member = 'Type'
1064 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001065 id_decl = 'static const VkStructureType '
John Zulaufde972ac2017-10-26 12:07:05 -06001066 generic_header = prefix + 'GenericHeader'
1067 typename_func = fprefix + 'typename'
1068 idname_func = fprefix + 'stype_name'
1069 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001070 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001071
1072 explanatory_comment = '\n'.join((
1073 '// These empty generic templates are specialized for each type with sType',
1074 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001075 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001076
1077 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1078 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001079 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1080 typemap_format += '}};\n'
1081
1082 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1083 idmap_format = ''.join((
1084 'template <> struct {template}<{id_value}> {{\n',
1085 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001086 '}};\n'))
1087
1088 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1089 utilities_format = '\n'.join((
1090 '// Header "base class" for pNext chain traversal',
1091 'struct {header} {{',
1092 ' VkStructureType sType;',
1093 ' const {header} *pNext;',
1094 '}};',
1095 '',
1096 '// Find an entry of the given type in the pNext chain',
1097 'template <typename T> const T *{find_func}(const void *next) {{',
1098 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1099 ' const T *found = nullptr;',
1100 ' while (current) {{',
1101 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1102 ' found = reinterpret_cast<const T*>(current);',
1103 ' current = nullptr;',
1104 ' }} else {{',
1105 ' current = current->pNext;',
1106 ' }}',
1107 ' }}',
1108 ' return found;',
1109 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001110 '',
1111 '// Init the header of an sType struct with pNext',
1112 'template <typename T> T {init_func}(void *p_next) {{',
1113 ' T out = {{}};',
1114 ' out.sType = {type_map}<T>::kSType;',
1115 ' out.pNext = p_next;',
1116 ' return out;',
1117 '}}',
1118 '',
1119 '// Init the header of an sType struct',
1120 'template <typename T> T {init_func}() {{',
1121 ' T out = {{}};',
1122 ' out.sType = {type_map}<T>::kSType;',
1123 ' return out;',
1124 '}}',
1125
Mike Schuchardt97662b02017-12-06 13:31:29 -07001126 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001127
1128 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001129
1130 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001131 code.append('\n'.join((
1132 '#pragma once',
1133 '#include <vulkan/vulkan.h>\n',
1134 explanatory_comment, '',
1135 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001136 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001137
1138 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001139 for item in self.structMembers:
1140 typename = item.name
1141 info = self.structTypes.get(typename)
1142 if not info:
1143 continue
1144
1145 if item.ifdef_protect != None:
1146 code.append('#ifdef %s' % item.ifdef_protect)
1147
1148 code.append('// Map type {} to id {}'.format(typename, info.value))
1149 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001150 id_decl=id_decl, id_member=id_member))
1151 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001152
1153 if item.ifdef_protect != None:
1154 code.append('#endif // %s' % item.ifdef_protect)
1155
John Zulauf65ac9d52018-01-23 11:20:50 -07001156 # Generate utilities for all types
1157 code.append('\n'.join((
1158 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1159 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1160 find_func=find_func, init_func=init_func), ''
1161 )))
1162
John Zulaufde972ac2017-10-26 12:07:05 -06001163 return "\n".join(code)
1164
1165 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001166 # Create a helper file and return it as a string
1167 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001168 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001169 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001170 elif self.helper_file_type == 'safe_struct_header':
1171 return self.GenerateSafeStructHelperHeader()
1172 elif self.helper_file_type == 'safe_struct_source':
1173 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001174 elif self.helper_file_type == 'object_types_header':
1175 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001176 elif self.helper_file_type == 'extension_helper_header':
1177 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001178 elif self.helper_file_type == 'typemap_helper_header':
1179 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001180 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001181 return 'Bad Helper File Generator Option %s' % self.helper_file_type
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -07001182