blob: cee626c9cd5403e4b92de12f0f2fe17002530041 [file] [log] [blame]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001#!/usr/bin/python3 -i
2#
Mike Schuchardt21638df2019-03-16 10:52:02 -07003# Copyright (c) 2015-2019 The Khronos Group Inc.
4# Copyright (c) 2015-2019 Valve Corporation
5# Copyright (c) 2015-2019 LunarG, Inc.
6# Copyright (c) 2015-2019 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,
Mike Schuchardt21638df2019-03-16 10:52:02 -070034 conventions = None,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070035 filename = None,
36 directory = '.',
37 apiname = None,
38 profile = None,
39 versions = '.*',
40 emitversions = '.*',
41 defaultExtensions = None,
42 addExtensions = None,
43 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060044 emitExtensions = None,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070045 sortProcedure = regSortFeatures,
46 prefixText = "",
47 genFuncPointers = True,
48 protectFile = True,
49 protectFeature = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070050 apicall = '',
51 apientry = '',
52 apientryp = '',
53 alignFuncParam = 0,
54 library_name = '',
Mark Lobodzinski62f71562017-10-24 13:41:18 -060055 expandEnumerants = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070056 helper_file_type = ''):
Mike Schuchardt21638df2019-03-16 10:52:02 -070057 GeneratorOptions.__init__(self, conventions, filename, directory, apiname, profile,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070058 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060059 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070060 self.prefixText = prefixText
61 self.genFuncPointers = genFuncPointers
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070062 self.protectFile = protectFile
63 self.protectFeature = protectFeature
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070064 self.apicall = apicall
65 self.apientry = apientry
66 self.apientryp = apientryp
67 self.alignFuncParam = alignFuncParam
68 self.library_name = library_name
69 self.helper_file_type = helper_file_type
70#
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070071# HelperFileOutputGenerator - subclass of OutputGenerator. Outputs Vulkan helper files
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070072class HelperFileOutputGenerator(OutputGenerator):
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -070073 """Generate helper file based on XML element attributes"""
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070074 def __init__(self,
75 errFile = sys.stderr,
76 warnFile = sys.stderr,
77 diagFile = sys.stdout):
78 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
79 # Internal state - accumulators for different inner block text
Mark Lobodzinski5380d132016-12-28 14:45:34 -070080 self.enum_output = '' # string built up of enum string routines
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070081 # Internal state - accumulators for different inner block text
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070082 self.structNames = [] # List of Vulkan struct typenames
83 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070084 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -060085 self.object_types = [] # List of all handle types
John Zulaufd7435c62018-03-16 11:52:57 -060086 self.object_type_aliases = [] # Aliases to handles types (for handles that were extensions)
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060087 self.debug_report_object_types = [] # Handy copy of debug_report_object_type enum data
Mark Young1ded24b2017-05-30 14:53:50 -060088 self.core_object_types = [] # Handy copy of core_object_type enum data
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -060089 self.device_extension_info = dict() # Dict of device extension name defines and ifdef values
90 self.instance_extension_info = dict() # Dict of instance extension name defines and ifdef values
Mark Lobodzinskib836ac92019-07-18 16:14:43 -060091 self.structextends_list = [] # List of structs which extend another struct via pNext
92
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060093
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070094 # Named tuples to store struct and command data
95 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070096 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl'])
Mark Lobodzinski5380d132016-12-28 14:45:34 -070097 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members', 'ifdef_protect'])
Petr Krause91f7a12017-12-14 20:57:36 +010098
99 self.custom_construct_params = {
100 # safe_VkGraphicsPipelineCreateInfo needs to know if subpass has color and\or depth\stencil attachments to use its pointers
101 'VkGraphicsPipelineCreateInfo' :
102 ', const bool uses_color_attachment, const bool uses_depthstencil_attachment',
103 # safe_VkPipelineViewportStateCreateInfo needs to know if viewport and scissor is dynamic to use its pointers
104 'VkPipelineViewportStateCreateInfo' :
105 ', const bool is_dynamic_viewports, const bool is_dynamic_scissors',
106 }
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700107 #
108 # Called once at the beginning of each run
109 def beginFile(self, genOpts):
110 OutputGenerator.beginFile(self, genOpts)
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700111 # Initialize members that require the tree
112 self.handle_types = GetHandleTypes(self.registry.tree)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700113 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700114 self.helper_file_type = genOpts.helper_file_type
115 self.library_name = genOpts.library_name
116 # File Comment
117 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
118 file_comment += '// See helper_file_generator.py for modifications\n'
119 write(file_comment, file=self.outFile)
120 # Copyright Notice
121 copyright = ''
122 copyright += '\n'
123 copyright += '/***************************************************************************\n'
124 copyright += ' *\n'
Mike Schuchardt21638df2019-03-16 10:52:02 -0700125 copyright += ' * Copyright (c) 2015-2019 The Khronos Group Inc.\n'
126 copyright += ' * Copyright (c) 2015-2019 Valve Corporation\n'
127 copyright += ' * Copyright (c) 2015-2019 LunarG, Inc.\n'
128 copyright += ' * Copyright (c) 2015-2019 Google Inc.\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700129 copyright += ' *\n'
130 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
131 copyright += ' * you may not use this file except in compliance with the License.\n'
132 copyright += ' * You may obtain a copy of the License at\n'
133 copyright += ' *\n'
134 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
135 copyright += ' *\n'
136 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
137 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
138 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
139 copyright += ' * See the License for the specific language governing permissions and\n'
140 copyright += ' * limitations under the License.\n'
141 copyright += ' *\n'
142 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Mark Lobodzinskia9c963d2016-12-28 07:45:35 -0700143 copyright += ' * Author: Courtney Goeltzenleuchter <courtneygo@google.com>\n'
144 copyright += ' * Author: Tobin Ehlis <tobine@google.com>\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600145 copyright += ' * Author: Chris Forbes <chrisforbes@google.com>\n'
John Zulaufde972ac2017-10-26 12:07:05 -0600146 copyright += ' * Author: John Zulauf<jzulauf@lunarg.com>\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700147 copyright += ' *\n'
148 copyright += ' ****************************************************************************/\n'
149 write(copyright, file=self.outFile)
150 #
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -0700151 # Write generated file content to output file
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700152 def endFile(self):
153 dest_file = ''
154 dest_file += self.OutputDestFile()
Mark Lobodzinskiafe10542017-01-03 13:22:44 -0700155 # Remove blank lines at EOF
156 if dest_file.endswith('\n'):
157 dest_file = dest_file[:-1]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700158 write(dest_file, file=self.outFile);
159 # Finish processing in superclass
160 OutputGenerator.endFile(self)
161 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600162 # Override parent class to be notified of the beginning of an extension
163 def beginFeature(self, interface, emit):
164 # Start processing in superclass
165 OutputGenerator.beginFeature(self, interface, emit)
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600166 self.featureExtraProtect = GetFeatureProtect(interface)
167
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600168 if self.featureName == 'VK_VERSION_1_0' or self.featureName == 'VK_VERSION_1_1':
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600169 return
John Zulauff6feb2a2018-04-12 14:24:57 -0600170 name = self.featureName
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600171 nameElem = interface[0][1]
John Zulauff6feb2a2018-04-12 14:24:57 -0600172 name_define = nameElem.get('name')
173 if 'EXTENSION_NAME' not in name_define:
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600174 print("Error in vk.xml file -- extension name is not available")
John Zulauf072677c2018-04-12 15:34:39 -0600175 requires = interface.get('requires')
176 if requires is not None:
177 required_extensions = requires.split(',')
178 else:
179 required_extensions = list()
180 info = { 'define': name_define, 'ifdef':self.featureExtraProtect, 'reqs':required_extensions }
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600181 if interface.get('type') == 'instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600182 self.instance_extension_info[name] = info
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600183 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600184 self.device_extension_info[name] = info
185
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600186 #
187 # Override parent class to be notified of the end of an extension
188 def endFeature(self):
189 # Finish processing in superclass
190 OutputGenerator.endFeature(self)
191 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700192 # Grab group (e.g. C "enum" type) info to output for enum-string conversion helper
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700193 def genGroup(self, groupinfo, groupName, alias):
194 OutputGenerator.genGroup(self, groupinfo, groupName, alias)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700195 groupElem = groupinfo.elem
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700196 # For enum_string_header
197 if self.helper_file_type == 'enum_string_header':
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700198 value_set = set()
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700199 for elem in groupElem.findall('enum'):
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100200 if elem.get('supported') != 'disabled' and elem.get('alias') is None:
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700201 value_set.add(elem.get('name'))
Tobias Hector30ad4fc2018-12-10 12:21:17 +0000202 if value_set != set():
203 self.enum_output += self.GenerateEnumStringConversion(groupName, value_set)
Mark Young1ded24b2017-05-30 14:53:50 -0600204 elif self.helper_file_type == 'object_types_header':
205 if groupName == 'VkDebugReportObjectTypeEXT':
206 for elem in groupElem.findall('enum'):
207 if elem.get('supported') != 'disabled':
Petr Krausf64607e2019-08-09 18:27:09 +0200208 if elem.get('alias') is None: # TODO: Strangely the "alias" fn parameter does not work
209 item_name = elem.get('name')
210 if self.debug_report_object_types.count(item_name) == 0: # TODO: Strangely there are duplicates
211 self.debug_report_object_types.append(item_name)
Mark Young1ded24b2017-05-30 14:53:50 -0600212 elif groupName == 'VkObjectType':
213 for elem in groupElem.findall('enum'):
214 if elem.get('supported') != 'disabled':
Petr Krausf64607e2019-08-09 18:27:09 +0200215 if elem.get('alias') is None: # TODO: Strangely the "alias" fn parameter does not work
216 item_name = elem.get('name')
217 self.core_object_types.append(item_name)
Mark Young1ded24b2017-05-30 14:53:50 -0600218
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700219 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700220 # Called for each type -- if the type is a struct/union, grab the metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700221 def genType(self, typeinfo, name, alias):
222 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700223 typeElem = typeinfo.elem
224 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
225 # Otherwise, emit the tag text.
226 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600227 if category == 'handle':
John Zulaufd7435c62018-03-16 11:52:57 -0600228 if alias:
229 self.object_type_aliases.append((name,alias))
230 else:
231 self.object_types.append(name)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600232 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700233 self.structNames.append(name)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700234 self.genStruct(typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700235 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700236 # Check if the parameter passed in is a pointer
237 def paramIsPointer(self, param):
238 ispointer = False
239 for elem in param:
Raul Tambre7b300182019-05-04 11:25:14 +0300240 if elem.tag == 'type' and elem.tail is not None and '*' in elem.tail:
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700241 ispointer = True
242 return ispointer
243 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700244 # Check if the parameter passed in is a static array
245 def paramIsStaticArray(self, param):
246 isstaticarray = 0
247 paramname = param.find('name')
248 if (paramname.tail is not None) and ('[' in paramname.tail):
249 isstaticarray = paramname.tail.count('[')
250 return isstaticarray
251 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700252 # Retrieve the type and name for a parameter
253 def getTypeNameTuple(self, param):
254 type = ''
255 name = ''
256 for elem in param:
257 if elem.tag == 'type':
258 type = noneStr(elem.text)
259 elif elem.tag == 'name':
260 name = noneStr(elem.text)
261 return (type, name)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700262 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
263 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
264 def parseLateXMath(self, source):
265 name = 'ERROR'
266 decoratedName = 'ERROR'
267 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700268 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
269 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 -0700270 if not match or match.group(1) != match.group(4):
271 raise 'Unrecognized latexmath expression'
272 name = match.group(2)
mizhenc27f6c72017-03-31 09:08:16 -0600273 # Need to add 1 for ceiling function; otherwise, the allocated packet
274 # size will be less than needed during capture for some title which use
275 # this in VkPipelineMultisampleStateCreateInfo. based on ceiling function
276 # definition,it is '{0}%{1}?{0}/{1} + 1:{0}/{1}'.format(*match.group(2, 3)),
277 # its value <= '{}/{} + 1'.
278 if match.group(1) == 'ceil':
279 decoratedName = '{}/{} + 1'.format(*match.group(2, 3))
280 else:
281 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700282 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700283 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600284 match = re.match(r'latexmath\s*\:\s*\[\s*(\\textrm\{)?(\w+)\}?\s*\\over\s*(\d+)\s*\]', source)
285 name = match.group(2)
286 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700287 return name, decoratedName
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700288 #
289 # Retrieve the value of the len tag
290 def getLen(self, param):
291 result = None
292 len = param.attrib.get('len')
293 if len and len != 'null-terminated':
294 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
295 # have a null terminated array of strings. We strip the null-terminated from the
296 # 'len' field and only return the parameter specifying the string count
297 if 'null-terminated' in len:
298 result = len.split(',')[0]
299 else:
300 result = len
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700301 if 'latexmath' in len:
302 param_type, param_name = self.getTypeNameTuple(param)
303 len_name, result = self.parseLateXMath(len)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700304 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
305 result = str(result).replace('::', '->')
306 return result
307 #
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600308 # Check if a structure is or contains a dispatchable (dispatchable = True) or
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700309 # non-dispatchable (dispatchable = False) handle
310 def TypeContainsObjectHandle(self, handle_type, dispatchable):
311 if dispatchable:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700312 type_check = self.handle_types.IsDispatchable
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700313 else:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700314 type_check = self.handle_types.IsNonDispatchable
315 if type_check(handle_type):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700316 return True
317 # if handle_type is a struct, search its members
318 if handle_type in self.structNames:
319 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == handle_type), None)
320 if member_index is not None:
321 for item in self.structMembers[member_index].members:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700322 if type_check(item.type):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700323 return True
324 return False
325 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700326 # Generate local ready-access data describing Vulkan structures and unions from the XML metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700327 def genStruct(self, typeinfo, typeName, alias):
328 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700329 members = typeinfo.elem.findall('.//member')
330 # Iterate over members once to get length parameters for arrays
331 lens = set()
332 for member in members:
333 len = self.getLen(member)
334 if len:
335 lens.add(len)
336 # Generate member info
337 membersInfo = []
338 for member in members:
339 # Get the member's type and name
340 info = self.getTypeNameTuple(member)
341 type = info[0]
342 name = info[1]
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700343 cdecl = self.makeCParamDecl(member, 1)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700344 # Process VkStructureType
345 if type == 'VkStructureType':
346 # Extract the required struct type value from the comments
347 # embedded in the original text defining the 'typeinfo' element
348 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
349 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
350 if result:
351 value = result.group(0)
Mike Schuchardt08368cb2018-05-22 14:52:04 -0600352 # Store the required type value
353 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700354 # Store pointer/array/string info
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700355 isstaticarray = self.paramIsStaticArray(member)
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600356 structextends = False
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700357 membersInfo.append(self.CommandParam(type=type,
358 name=name,
359 ispointer=self.paramIsPointer(member),
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700360 isstaticarray=isstaticarray,
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700361 isconst=True if 'const' in cdecl else False,
362 iscount=True if name in lens else False,
363 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600364 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700365 cdecl=cdecl))
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600366 # If this struct extends another, keep its name in list for further processing
367 if typeinfo.elem.attrib.get('structextends') is not None:
368 self.structextends_list.append(typeName)
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700369 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo, ifdef_protect=self.featureExtraProtect))
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700370 #
371 # Enum_string_header: Create a routine to convert an enumerated value into a string
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700372 def GenerateEnumStringConversion(self, groupName, value_list):
373 outstring = '\n'
Mike Schuchardt21638df2019-03-16 10:52:02 -0700374 if self.featureExtraProtect is not None:
375 outstring += '\n#ifdef %s\n\n' % self.featureExtraProtect
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700376 outstring += 'static inline const char* string_%s(%s input_value)\n' % (groupName, groupName)
377 outstring += '{\n'
378 outstring += ' switch ((%s)input_value)\n' % groupName
379 outstring += ' {\n'
Karl Schultz7fd3f6e2018-07-05 17:21:05 -0600380 # Emit these in a repeatable order so file is generated with the same contents each time.
381 # This helps compiler caching systems like ccache.
382 for item in sorted(value_list):
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700383 outstring += ' case %s:\n' % item
384 outstring += ' return "%s";\n' % item
385 outstring += ' default:\n'
386 outstring += ' return "Unhandled %s";\n' % groupName
387 outstring += ' }\n'
388 outstring += '}\n'
unknown84220292019-07-01 17:09:36 -0600389
390 bitsIndex = groupName.find('Bits')
391 if (bitsIndex != -1):
392 outstring += '\n'
393 flagsName = groupName[0:bitsIndex] + "s" + groupName[bitsIndex+4:]
394 outstring += 'static inline std::string string_%s(%s input_value)\n' % (flagsName, flagsName)
395 outstring += '{\n'
396 outstring += ' std::string ret;\n'
397 outstring += ' int index = 0;\n'
398 outstring += ' while(input_value) {\n'
399 outstring += ' if (input_value & 1) {\n'
400 outstring += ' if( !ret.empty()) ret.append("|");\n'
401 outstring += ' ret.append(string_%s(static_cast<%s>(1 << index)));\n' % (groupName, groupName)
402 outstring += ' }\n'
403 outstring += ' ++index;\n'
404 outstring += ' input_value >>= 1;\n'
405 outstring += ' }\n'
406 outstring += ' if( ret.empty()) ret.append(string_%s(static_cast<%s>(0)));\n' % (groupName, groupName)
407 outstring += ' return ret;\n'
408 outstring += '}\n'
409
Mike Schuchardt21638df2019-03-16 10:52:02 -0700410 if self.featureExtraProtect is not None:
411 outstring += '#endif // %s\n' % self.featureExtraProtect
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700412 return outstring
413 #
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600414 # Tack on a helper which, given an index into a VkPhysicalDeviceFeatures structure, will print the corresponding feature name
415 def DeIndexPhysDevFeatures(self):
416 pdev_members = None
417 for name, members, ifdef in self.structMembers:
418 if name == 'VkPhysicalDeviceFeatures':
419 pdev_members = members
420 break
421 deindex = '\n'
Mark Young2ee6aea2018-02-21 15:30:27 -0700422 deindex += 'static inline const char * GetPhysDevFeatureString(uint32_t index) {\n'
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600423 deindex += ' const char * IndexToPhysDevFeatureString[] = {\n'
424 for feature in pdev_members:
425 deindex += ' "%s",\n' % feature.name
426 deindex += ' };\n\n'
427 deindex += ' return IndexToPhysDevFeatureString[index];\n'
428 deindex += '}\n'
429 return deindex
430 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700431 # Combine enum string helper header file preamble with body text and return
432 def GenerateEnumStringHelperHeader(self):
433 enum_string_helper_header = '\n'
434 enum_string_helper_header += '#pragma once\n'
435 enum_string_helper_header += '#ifdef _WIN32\n'
436 enum_string_helper_header += '#pragma warning( disable : 4065 )\n'
437 enum_string_helper_header += '#endif\n'
438 enum_string_helper_header += '\n'
David Pinedoddbb7fb2019-07-22 11:36:51 -0600439 enum_string_helper_header += '#include <string>\n'
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700440 enum_string_helper_header += '#include <vulkan/vulkan.h>\n'
441 enum_string_helper_header += '\n'
442 enum_string_helper_header += self.enum_output
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600443 enum_string_helper_header += self.DeIndexPhysDevFeatures()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700444 return enum_string_helper_header
445 #
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700446 # Helper function for declaring a counter variable only once
447 def DeclareCounter(self, string_var, declare_flag):
448 if declare_flag == False:
449 string_var += ' uint32_t i = 0;\n'
450 declare_flag = True
451 return string_var, declare_flag
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700452 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700453 # Combine safe struct helper header file preamble with body text and return
454 def GenerateSafeStructHelperHeader(self):
455 safe_struct_helper_header = '\n'
456 safe_struct_helper_header += '#pragma once\n'
457 safe_struct_helper_header += '#include <vulkan/vulkan.h>\n'
Mark Lobodzinskidb8affe2019-08-08 13:25:07 -0600458 safe_struct_helper_header += '#include <vulkan/vk_layer.h>\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700459 safe_struct_helper_header += '\n'
Mark Lobodzinski7245fce2019-07-18 16:18:51 -0600460 safe_struct_helper_header += 'void *SafePnextCopy(const void *pNext);\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600461 safe_struct_helper_header += 'void FreePnextChain(const void *head);\n'
Mark Lobodzinski7245fce2019-07-18 16:18:51 -0600462 safe_struct_helper_header += 'void FreePnextChain(void *head);\n'
Mark Lobodzinski256ba552019-08-13 14:59:17 -0600463 safe_struct_helper_header += 'const char *SafeStringCopy(const char *in_string);\n'
Mark Lobodzinski7245fce2019-07-18 16:18:51 -0600464 safe_struct_helper_header += '\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700465 safe_struct_helper_header += self.GenerateSafeStructHeader()
466 return safe_struct_helper_header
467 #
468 # safe_struct header: build function prototypes for header file
469 def GenerateSafeStructHeader(self):
470 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700471 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700472 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700473 safe_struct_header += '\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100474 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700475 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
476 safe_struct_header += 'struct safe_%s {\n' % (item.name)
477 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700478 if member.type in self.structNames:
479 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
480 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
481 if member.ispointer:
482 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
483 else:
484 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
485 continue
486 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
487 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
488 else:
489 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100490 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 -0600491 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700492 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700493 safe_struct_header += ' safe_%s();\n' % item.name
494 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100495 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
496 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700497 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
498 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
499 safe_struct_header += '};\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100500 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700501 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700502 return safe_struct_header
503 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600504 # Generate extension helper header file
505 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600506
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600507 V_1_1_level_feature_set = [
508 'VK_VERSION_1_1',
509 ]
510
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600511 V_1_0_instance_extensions_promoted_to_V_1_1_core = [
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600512 'vk_khr_device_group_creation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600513 'vk_khr_external_fence_capabilities',
John Zulauf2012bca2018-04-25 15:28:47 -0600514 'vk_khr_external_memory_capabilities',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600515 'vk_khr_external_semaphore_capabilities',
516 'vk_khr_get_physical_device_properties_2',
517 ]
518
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600519 V_1_0_device_extensions_promoted_to_V_1_1_core = [
John Zulauf2012bca2018-04-25 15:28:47 -0600520 'vk_khr_16bit_storage',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600521 'vk_khr_bind_memory_2',
John Zulauf2012bca2018-04-25 15:28:47 -0600522 'vk_khr_dedicated_allocation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600523 'vk_khr_descriptor_update_template',
John Zulauf2012bca2018-04-25 15:28:47 -0600524 'vk_khr_device_group',
525 'vk_khr_external_fence',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600526 'vk_khr_external_memory',
527 'vk_khr_external_semaphore',
John Zulauf2012bca2018-04-25 15:28:47 -0600528 'vk_khr_get_memory_requirements_2',
529 'vk_khr_maintenance1',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600530 'vk_khr_maintenance2',
John Zulauf2012bca2018-04-25 15:28:47 -0600531 'vk_khr_maintenance3',
532 'vk_khr_multiview',
John Zulauf16826822018-04-25 15:40:32 -0600533 'vk_khr_relaxed_block_layout',
John Zulauf2012bca2018-04-25 15:28:47 -0600534 'vk_khr_sampler_ycbcr_conversion',
John Zulauf16826822018-04-25 15:40:32 -0600535 'vk_khr_shader_draw_parameters',
536 'vk_khr_storage_buffer_storage_class',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600537 'vk_khr_variable_pointers',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600538 ]
John Zulauf16826822018-04-25 15:40:32 -0600539
John Zulauff6feb2a2018-04-12 14:24:57 -0600540 output = [
541 '',
542 '#ifndef VK_EXTENSION_HELPER_H_',
543 '#define VK_EXTENSION_HELPER_H_',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600544 '#include <unordered_set>',
John Zulauf072677c2018-04-12 15:34:39 -0600545 '#include <string>',
546 '#include <unordered_map>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600547 '#include <utility>',
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600548 '#include <set>',
Mark Lobodzinskif94196f2019-07-11 11:46:09 -0600549 '#include <vector>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600550 '',
John Zulauf072677c2018-04-12 15:34:39 -0600551 '#include <vulkan/vulkan.h>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600552 '']
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600553
John Zulauff6feb2a2018-04-12 14:24:57 -0600554 def guarded(ifdef, value):
555 if ifdef is not None:
556 return '\n'.join([ '#ifdef %s' % ifdef, value, '#endif' ])
557 else:
558 return value
John Zulauf380bd942018-04-10 13:12:34 -0600559
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600560 for type in ['Instance', 'Device']:
John Zulauff6feb2a2018-04-12 14:24:57 -0600561 struct_type = '%sExtensions' % type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600562 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600563 extension_dict = self.instance_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600564 promoted_ext_list = V_1_0_instance_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600565 struct_decl = 'struct %s {' % struct_type
566 instance_struct_type = struct_type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600567 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600568 extension_dict = self.device_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600569 promoted_ext_list = V_1_0_device_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600570 struct_decl = 'struct %s : public %s {' % (struct_type, instance_struct_type)
571
572 extension_items = sorted(extension_dict.items())
573
574 field_name = { ext_name: re.sub('_extension_name', '', info['define'].lower()) for ext_name, info in extension_items }
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600575
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600576 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600577 instance_field_name = field_name
John Zulauf072677c2018-04-12 15:34:39 -0600578 instance_extension_dict = extension_dict
579 else:
580 # Get complete field name and extension data for both Instance and Device extensions
581 field_name.update(instance_field_name)
582 extension_dict = extension_dict.copy() # Don't modify the self.<dict> we're pointing to
583 extension_dict.update(instance_extension_dict)
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600584
John Zulauf072677c2018-04-12 15:34:39 -0600585 # Output the data member list
John Zulauff6feb2a2018-04-12 14:24:57 -0600586 struct = [struct_decl]
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600587 struct.extend([ ' bool vk_feature_version_1_1{false};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600588 struct.extend([ ' bool %s{false};' % field_name[ext_name] for ext_name, info in extension_items])
John Zulauf072677c2018-04-12 15:34:39 -0600589
590 # Construct the extension information map -- mapping name to data member (field), and required extensions
591 # The map is contained within a static function member for portability reasons.
592 info_type = '%sInfo' % type
593 info_map_type = '%sMap' % info_type
594 req_type = '%sReq' % type
595 req_vec_type = '%sVec' % req_type
596 struct.extend([
597 '',
598 ' struct %s {' % req_type,
599 ' const bool %s::* enabled;' % struct_type,
600 ' const char *name;',
601 ' };',
602 ' typedef std::vector<%s> %s;' % (req_type, req_vec_type),
603 ' struct %s {' % info_type,
604 ' %s(bool %s::* state_, const %s requires_): state(state_), requires(requires_) {}' % ( info_type, struct_type, req_vec_type),
605 ' bool %s::* state;' % struct_type,
606 ' %s requires;' % req_vec_type,
607 ' };',
608 '',
609 ' typedef std::unordered_map<std::string,%s> %s;' % (info_type, info_map_type),
610 ' static const %s &get_info(const char *name) {' %info_type,
611 ' static const %s info_map = {' % info_map_type ])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600612 struct.extend([
613 ' std::make_pair("VK_VERSION_1_1", %sInfo(&%sExtensions::vk_feature_version_1_1, {})),' % (type, type)])
John Zulauf072677c2018-04-12 15:34:39 -0600614
615 field_format = '&' + struct_type + '::%s'
616 req_format = '{' + field_format+ ', %s}'
617 req_indent = '\n '
618 req_join = ',' + req_indent
619 info_format = (' std::make_pair(%s, ' + info_type + '(' + field_format + ', {%s})),')
620 def format_info(ext_name, info):
621 reqs = req_join.join([req_format % (field_name[req], extension_dict[req]['define']) for req in info['reqs']])
622 return info_format % (info['define'], field_name[ext_name], '{%s}' % (req_indent + reqs) if reqs else '')
623
624 struct.extend([guarded(info['ifdef'], format_info(ext_name, info)) for ext_name, info in extension_items])
625 struct.extend([
626 ' };',
627 '',
628 ' static const %s empty_info {nullptr, %s()};' % (info_type, req_vec_type),
629 ' %s::const_iterator info = info_map.find(name);' % info_map_type,
630 ' if ( info != info_map.cend()) {',
631 ' return info->second;',
632 ' }',
633 ' return empty_info;',
634 ' }',
635 ''])
636
John Zulauff6feb2a2018-04-12 14:24:57 -0600637 if type == 'Instance':
638 struct.extend([
639 ' uint32_t NormalizeApiVersion(uint32_t specified_version) {',
640 ' uint32_t api_version = (specified_version < VK_API_VERSION_1_1) ? VK_API_VERSION_1_0 : VK_API_VERSION_1_1;',
641 ' return api_version;',
642 ' }',
643 '',
644 ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {'])
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600645 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600646 struct.extend([
John Zulauf072677c2018-04-12 15:34:39 -0600647 ' %s() = default;' % struct_type,
648 ' %s(const %s& instance_ext) : %s(instance_ext) {}' % (struct_type, instance_struct_type, instance_struct_type),
649 '',
650 ' uint32_t InitFromDeviceCreateInfo(const %s *instance_extensions, uint32_t requested_api_version,' % instance_struct_type,
651 ' const VkDeviceCreateInfo *pCreateInfo) {',
652 ' // Initialize: this to defaults, base class fields to input.',
653 ' assert(instance_extensions);',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600654 ' *this = %s(*instance_extensions);' % struct_type,
Mark Lobodzinskid5f83b92018-12-14 11:02:08 -0700655 '']),
656 struct.extend([
John Zulauff6feb2a2018-04-12 14:24:57 -0600657 '',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600658 ' static const std::vector<const char *> V_1_1_promoted_%s_apis = {' % type.lower() ])
John Zulauff6feb2a2018-04-12 14:24:57 -0600659 struct.extend([' %s_EXTENSION_NAME,' % ext_name.upper() for ext_name in promoted_ext_list])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600660 struct.extend([' "VK_VERSION_1_1",'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600661 struct.extend([
662 ' };',
663 '',
John Zulauf072677c2018-04-12 15:34:39 -0600664 ' // Initialize struct data, robust to invalid pCreateInfo',
665 ' if (pCreateInfo->ppEnabledExtensionNames) {',
666 ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {',
667 ' if (!pCreateInfo->ppEnabledExtensionNames[i]) continue;',
668 ' auto info = get_info(pCreateInfo->ppEnabledExtensionNames[i]);',
669 ' if(info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600670 ' }',
671 ' }',
672 ' uint32_t api_version = NormalizeApiVersion(requested_api_version);',
673 ' if (api_version >= VK_API_VERSION_1_1) {',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600674 ' for (auto promoted_ext : V_1_1_promoted_%s_apis) {' % type.lower(),
John Zulauf072677c2018-04-12 15:34:39 -0600675 ' auto info = get_info(promoted_ext);',
676 ' assert(info.state);',
677 ' if (info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600678 ' }',
679 ' }',
680 ' return api_version;',
681 ' }',
John Zulauf072677c2018-04-12 15:34:39 -0600682 '};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600683
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700684 # Output reference lists of instance/device extension names
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600685 struct.extend(['', 'static const std::set<std::string> k%sExtensionNames = {' % type])
686 struct.extend([guarded(info['ifdef'], ' %s,' % info['define']) for ext_name, info in extension_items])
687 struct.extend(['};', ''])
John Zulauff6feb2a2018-04-12 14:24:57 -0600688 output.extend(struct)
689
690 output.extend(['', '#endif // VK_EXTENSION_HELPER_H_'])
691 return '\n'.join(output)
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600692 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600693 # Combine object types helper header file preamble with body text and return
694 def GenerateObjectTypesHelperHeader(self):
695 object_types_helper_header = '\n'
696 object_types_helper_header += '#pragma once\n'
697 object_types_helper_header += '\n'
698 object_types_helper_header += self.GenerateObjectTypesHeader()
699 return object_types_helper_header
700 #
701 # Object types header: create object enum type header file
702 def GenerateObjectTypesHeader(self):
John Zulauf4fea6622019-04-01 11:38:18 -0600703 object_types_header = '#include "cast_utils.h"\n'
704 object_types_header += '\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700705 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600706 object_types_header += 'typedef enum VulkanObjectType {\n'
707 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
708 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600709 type_list = [];
John Zulaufd7435c62018-03-16 11:52:57 -0600710 enum_entry_map = {}
John Zulauf2c2ccd42019-04-05 13:13:13 -0600711 non_dispatchable = {}
712 dispatchable = {}
713 object_type_info = {}
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600714
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600715 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600716 for item in self.object_types:
717 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600718 enum_entry = 'kVulkanObjectType%s' % fixup_name
John Zulaufd7435c62018-03-16 11:52:57 -0600719 enum_entry_map[item] = enum_entry
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600720 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600721 object_types_header += ' = %d,\n' % enum_num
722 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600723 type_list.append(enum_entry)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600724 object_type_info[enum_entry] = { 'VkType': item }
725 # We'll want lists of the dispatchable and non dispatchable handles below with access to the same info
Mike Schuchardtf8690262019-07-11 10:08:33 -0700726 if self.handle_types.IsNonDispatchable(item):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600727 non_dispatchable[item] = enum_entry
728 else:
729 dispatchable[item] = enum_entry
730
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600731 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
John Zulaufd7435c62018-03-16 11:52:57 -0600732 object_types_header += ' // Aliases for backwards compatibilty of "promoted" types\n'
733 for (name, alias) in self.object_type_aliases:
734 fixup_name = name[2:]
735 object_types_header += ' kVulkanObjectType{} = {},\n'.format(fixup_name, enum_entry_map[alias])
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600736 object_types_header += '} VulkanObjectType;\n\n'
737
738 # Output name string helper
739 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600740 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
locke-lunargb4c57852019-06-14 23:20:05 -0600741 object_types_header += ' "VkNonDispatchableHandle",\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600742 for item in self.object_types:
locke-lunargb4c57852019-06-14 23:20:05 -0600743 object_types_header += ' "%s",\n' % item
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600744 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600745
Petr Krausf64607e2019-08-09 18:27:09 +0200746 # Helpers to create unified dict key from k<Name>, VK_OBJECT_TYPE_<Name>, and VK_DEBUG_REPORT_OBJECT_TYPE_<Name>
747 def dro_to_key(raw_key): return re.search('^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$', raw_key).group(1).lower().replace("_","")
748 def vko_to_key(raw_key): return re.search('^VK_OBJECT_TYPE_(.*)', raw_key).group(1).lower().replace("_","")
749 def kenum_to_key(raw_key): return re.search('^kVulkanObjectType(.*)', raw_key).group(1).lower()
750
751 dro_dict = {dro_to_key(dro) : dro for dro in self.debug_report_object_types}
752 vko_dict = {vko_to_key(vko) : vko for vko in self.core_object_types}
John Zulauf311a4892018-03-12 15:48:06 -0600753
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600754 # Output a conversion routine from the layer object definitions to the debug report definitions
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600755 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600756 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 -0600757 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Petr Krausf64607e2019-08-09 18:27:09 +0200758 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n' # no unknown handle, so this must be here explicitly
John Zulauf2c2ccd42019-04-05 13:13:13 -0600759
John Zulauf311a4892018-03-12 15:48:06 -0600760 for object_type in type_list:
Petr Krausf64607e2019-08-09 18:27:09 +0200761 # VK_DEBUG_REPORT is not updated anymore; there might be missing object types
762 kenum_type = dro_dict.get(kenum_to_key(object_type), 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT')
763 object_types_header += ' %s, // %s\n' % (kenum_type, object_type)
764 object_type_info[object_type]['DbgType'] = kenum_type
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600765 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600766
767 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600768 # 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 -0600769 object_types_header += '\n'
770 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
771 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Petr Krausf64607e2019-08-09 18:27:09 +0200772 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n' # no unknown handle, so must be here explicitly
John Zulauf311a4892018-03-12 15:48:06 -0600773
Mark Young1ded24b2017-05-30 14:53:50 -0600774 for object_type in type_list:
Petr Krausf64607e2019-08-09 18:27:09 +0200775 kenum_type = vko_dict[kenum_to_key(object_type)]
776 object_types_header += ' %s, // %s\n' % (kenum_type, object_type)
777 object_type_info[object_type]['VkoType'] = kenum_type
Mark Young1ded24b2017-05-30 14:53:50 -0600778 object_types_header += '};\n'
779
Petr Krausf64607e2019-08-09 18:27:09 +0200780 # Create a functions to convert between VkDebugReportObjectTypeEXT and VkObjectType
781 object_types_header += '\n'
782 object_types_header += 'static inline VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj) {\n'
783 object_types_header += ' switch (debug_report_obj) {\n'
784 for dr_object_type in self.debug_report_object_types:
785 object_types_header += ' case %s: return %s;\n' % (dr_object_type, vko_dict[dro_to_key(dr_object_type)])
786 object_types_header += ' default: return VK_OBJECT_TYPE_UNKNOWN;\n'
787 object_types_header += ' }\n'
788 object_types_header += '}\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700789
Petr Krausf64607e2019-08-09 18:27:09 +0200790 object_types_header += '\n'
791 object_types_header += 'static inline VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj) {\n'
792 object_types_header += ' switch (core_report_obj) {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700793 for core_object_type in self.core_object_types:
Petr Krausf64607e2019-08-09 18:27:09 +0200794 # VK_DEBUG_REPORT is not updated anymore; there might be missing object types
795 dr_object_type = dro_dict.get(vko_to_key(core_object_type))
796 if dr_object_type is not None:
797 object_types_header += ' case %s: return %s;\n' % (core_object_type, dr_object_type)
798 object_types_header += ' default: return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
799 object_types_header += ' }\n'
800 object_types_header += '}\n'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600801
Petr Krausf64607e2019-08-09 18:27:09 +0200802 #
803 object_types_header += '\n'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600804 traits_format = Outdent('''
805 template <> struct VkHandleInfo<{vk_type}> {{
806 static const VulkanObjectType kVulkanObjectType = {obj_type};
807 static const VkDebugReportObjectTypeEXT kDebugReportObjectType = {dbg_type};
808 static const VkObjectType kVkObjectType = {vko_type};
809 static const char* Typename() {{
810 return "{vk_type}";
811 }}
812 }};
813 template <> struct VulkanObjectTypeInfo<{obj_type}> {{
814 typedef {vk_type} Type;
815 }};
816 ''')
817
818 object_types_header += Outdent('''
819 // Traits objects from each type statically map from Vk<handleType> to the various enums
820 template <typename VkType> struct VkHandleInfo {};
821 template <VulkanObjectType id> struct VulkanObjectTypeInfo {};
822
823 // The following line must match the vulkan_core.h condition guarding VK_DEFINE_NON_DISPATCHABLE_HANDLE
824 #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || \
825 defined(_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
826 #define TYPESAFE_NONDISPATCHABLE_HANDLES
827 #else
828 VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkNonDispatchableHandle)
829 ''') +'\n'
830 object_types_header += traits_format.format(vk_type='VkNonDispatchableHandle', obj_type='kVulkanObjectTypeUnknown',
831 dbg_type='VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT',
832 vko_type='VK_OBJECT_TYPE_UNKNOWN') + '\n'
833 object_types_header += '#endif // VK_DEFINE_HANDLE logic duplication\n'
834
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700835 for vk_type, object_type in sorted(dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600836 info = object_type_info[object_type]
837 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
838 vko_type=info['VkoType'])
839 object_types_header += '#ifdef TYPESAFE_NONDISPATCHABLE_HANDLES\n'
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700840 for vk_type, object_type in sorted(non_dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600841 info = object_type_info[object_type]
842 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
843 vko_type=info['VkoType'])
844 object_types_header += '#endif // TYPESAFE_NONDISPATCHABLE_HANDLES\n'
845
846 object_types_header += Outdent('''
847 struct VulkanTypedHandle {
848 uint64_t handle;
849 VulkanObjectType type;
850 template <typename Handle>
John Zulauf4fea6622019-04-01 11:38:18 -0600851 VulkanTypedHandle(Handle handle_, VulkanObjectType type_) :
852 handle(CastToUint64(handle_)),
853 type(type_) {
854 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
855 // For 32 bit it's not always safe to check for traits <-> type
856 // as all non-dispatchable handles have the same type-id and thus traits,
857 // but on 64 bit we can validate the passed type matches the passed handle
858 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
859 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
860 }
861 template <typename Handle>
862 Handle Cast() const {
863 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
864 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
865 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
866 return CastFromUint64<Handle>(handle);
867 }
John Zulauf2c2ccd42019-04-05 13:13:13 -0600868 VulkanTypedHandle() :
869 handle(VK_NULL_HANDLE),
870 type(kVulkanObjectTypeUnknown) {}
871 }; ''') +'\n'
872
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600873 return object_types_header
874 #
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600875 # Generate pNext handling function
Mark Lobodzinski3628d2f2019-08-13 14:12:20 -0600876 def build_safe_struct_utility_funcs(self):
Mark Lobodzinski256ba552019-08-13 14:59:17 -0600877 # Construct Safe-struct helper functions
878
879 string_copy_proc = '\n\n'
880 string_copy_proc += 'const char *SafeStringCopy(const char *in_string) {\n'
881 string_copy_proc += ' if (nullptr == in_string) return nullptr;\n'
882 string_copy_proc += ' char* dest = new char[std::strlen(in_string) + 1];\n'
883 string_copy_proc += ' return std::strcpy(dest, in_string);\n'
884 string_copy_proc += '}\n'
885
886 build_pnext_proc = '\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600887 build_pnext_proc += 'void *SafePnextCopy(const void *pNext) {\n'
888 build_pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600889 build_pnext_proc += ' void *cur_ext_struct = NULL;\n'
890 build_pnext_proc += ' bool unrecognized_stype = true;\n\n'
891 build_pnext_proc += ' while (unrecognized_stype) {\n'
892 build_pnext_proc += ' unrecognized_stype = false;\n'
893 build_pnext_proc += ' if (cur_pnext == nullptr) {\n'
894 build_pnext_proc += ' return nullptr;\n'
895 build_pnext_proc += ' } else {\n'
896 build_pnext_proc += ' VkBaseOutStructure *header = reinterpret_cast<VkBaseOutStructure *>(cur_pnext);\n\n'
Mark Lobodzinskidb8affe2019-08-08 13:25:07 -0600897 build_pnext_proc += ' switch (header->sType) {\n\n'
898 # Add special-case code to copy beloved secret loader structs
899 build_pnext_proc += ' // Special-case Loader Instance Struct passed to/from layer in pNext chain\n'
900 build_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO: {\n'
901 build_pnext_proc += ' VkLayerInstanceCreateInfo *safe_struct = new VkLayerInstanceCreateInfo;\n'
902 build_pnext_proc += ' memcpy((void *)safe_struct, (void *)cur_pnext, sizeof(VkLayerInstanceCreateInfo));\n'
903 build_pnext_proc += ' safe_struct->pNext = SafePnextCopy(safe_struct->pNext);\n'
904 build_pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
905 build_pnext_proc += ' } break;\n\n'
906 build_pnext_proc += ' // Special-case Loader Device Struct passed to/from layer in pNext chain\n'
907 build_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO: {\n'
908 build_pnext_proc += ' VkLayerDeviceCreateInfo *safe_struct = new VkLayerDeviceCreateInfo;\n'
909 build_pnext_proc += ' memcpy((void *)safe_struct, (void *)cur_pnext, sizeof(VkLayerDeviceCreateInfo));\n'
910 build_pnext_proc += ' safe_struct->pNext = SafePnextCopy(safe_struct->pNext);\n'
911 build_pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
912 build_pnext_proc += ' } break;\n\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600913
914 free_pnext_proc = '\n\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600915 free_pnext_proc += '// Free a const pNext extension chain\n'
916 free_pnext_proc += 'void FreePnextChain(const void *head) {\n'
917 free_pnext_proc += ' FreePnextChain(const_cast<void *>(head));\n'
918 free_pnext_proc += '}\n\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600919 free_pnext_proc += '// Free a pNext extension chain\n'
920 free_pnext_proc += 'void FreePnextChain(void *head) {\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600921 free_pnext_proc += ' if (nullptr == head) return;\n'
922 free_pnext_proc += ' VkBaseOutStructure *header = reinterpret_cast<VkBaseOutStructure *>(head);\n\n'
Mark Lobodzinskidb8affe2019-08-08 13:25:07 -0600923 free_pnext_proc += ' switch (header->sType) {\n\n'
924 free_pnext_proc += ' // Special-case Loader Instance Struct passed to/from layer in pNext chain\n'
925 free_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO: {\n'
926 free_pnext_proc += ' if (header->pNext) FreePnextChain(header->pNext);\n'
927 free_pnext_proc += ' delete reinterpret_cast<VkLayerInstanceCreateInfo *>(head);\n'
928 free_pnext_proc += ' } break;\n\n'
929 free_pnext_proc += ' // Special-case Loader Device Struct passed to/from layer in pNext chain\n'
930 free_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO: {\n'
931 free_pnext_proc += ' if (header->pNext) FreePnextChain(header->pNext);\n'
932 free_pnext_proc += ' delete reinterpret_cast<VkLayerDeviceCreateInfo *>(head);\n'
933 free_pnext_proc += ' } break;\n\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600934
935 for item in self.structextends_list:
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600936
937 struct = next((v for v in self.structMembers if v.name == item), None)
938 if struct is None:
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600939 continue
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600940
941 if struct.ifdef_protect is not None:
942 build_pnext_proc += '#ifdef %s\n' % struct.ifdef_protect
943 free_pnext_proc += '#ifdef %s\n' % struct.ifdef_protect
944 build_pnext_proc += ' case %s: {\n' % self.structTypes[item].value
945 build_pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
946 build_pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
947 build_pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
948 build_pnext_proc += ' } break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600949
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600950 free_pnext_proc += ' case %s:\n' % self.structTypes[item].value
951 free_pnext_proc += ' delete reinterpret_cast<safe_%s *>(header);\n' % item
952 free_pnext_proc += ' break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600953
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600954 if struct.ifdef_protect is not None:
955 build_pnext_proc += '#endif // %s\n' % struct.ifdef_protect
956 free_pnext_proc += '#endif // %s\n' % struct.ifdef_protect
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600957 build_pnext_proc += '\n'
958 free_pnext_proc += '\n'
959
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600960 build_pnext_proc += ' default:\n'
961 build_pnext_proc += ' // Encountered an unknown sType -- skip (do not copy) this entry in the chain\n'
962 build_pnext_proc += ' unrecognized_stype = true;\n'
963 build_pnext_proc += ' cur_pnext = header->pNext;\n'
964 build_pnext_proc += ' break;\n'
965 build_pnext_proc += ' }\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600966 build_pnext_proc += ' }\n'
967 build_pnext_proc += ' }\n'
968 build_pnext_proc += ' return cur_ext_struct;\n'
969 build_pnext_proc += '}\n\n'
970
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600971 free_pnext_proc += ' default:\n'
972 free_pnext_proc += ' // Do nothing -- skip unrecognized sTypes\n'
973 free_pnext_proc += ' break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600974 free_pnext_proc += ' }\n'
975 free_pnext_proc += '}\n'
976
Mark Lobodzinski256ba552019-08-13 14:59:17 -0600977 pnext_procs = string_copy_proc + build_pnext_proc + free_pnext_proc
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600978 return pnext_procs
979 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700980 # Determine if a structure needs a safe_struct helper function
981 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700982 def NeedSafeStruct(self, structure):
Mark Lobodzinskib6cc5412019-07-19 09:56:58 -0600983 if 'VkBase' in structure.name:
984 return False
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700985 if 'sType' == structure.name:
986 return True
987 for member in structure.members:
988 if member.ispointer == True:
989 return True
990 return False
991 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700992 # Combine safe struct helper source file preamble with body text and return
993 def GenerateSafeStructHelperSource(self):
994 safe_struct_helper_source = '\n'
995 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
996 safe_struct_helper_source += '#include <string.h>\n'
Mark Lobodzinski256ba552019-08-13 14:59:17 -0600997 safe_struct_helper_source += '#include <cstring>\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700998 safe_struct_helper_source += '\n'
999 safe_struct_helper_source += self.GenerateSafeStructSource()
Mark Lobodzinski3628d2f2019-08-13 14:12:20 -06001000 safe_struct_helper_source += self.build_safe_struct_utility_funcs()
Mark Lobodzinskib836ac92019-07-18 16:14:43 -06001001
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001002 return safe_struct_helper_source
1003 #
1004 # safe_struct source -- create bodies of safe struct helper functions
1005 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001006 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001007 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
1008 'VkXcbSurfaceCreateInfoKHR',
1009 'VkWaylandSurfaceCreateInfoKHR',
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001010 'VkAndroidSurfaceCreateInfoKHR',
1011 'VkWin32SurfaceCreateInfoKHR'
1012 ]
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001013
1014 # For abstract types just want to save the pointer away
1015 # since we cannot make a copy.
1016 abstract_types = ['AHardwareBuffer',
1017 'ANativeWindow',
1018 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001019 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001020 if self.NeedSafeStruct(item) == False:
1021 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001022 if item.name in wsi_structs:
1023 continue
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001024 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001025 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
1026 ss_name = "safe_%s" % item.name
1027 init_list = '' # list of members in struct constructor initializer
1028 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
1029 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
1030 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
1031 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +01001032
1033 custom_construct_txt = {
1034 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
1035 'VkWriteDescriptorSet' :
1036 ' switch (descriptorType) {\n'
1037 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
1038 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
1039 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
1040 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
1041 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
1042 ' if (descriptorCount && in_struct->pImageInfo) {\n'
1043 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
1044 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1045 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
1046 ' }\n'
1047 ' }\n'
1048 ' break;\n'
1049 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
1050 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
1051 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
1052 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
1053 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
1054 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
1055 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1056 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
1057 ' }\n'
1058 ' }\n'
1059 ' break;\n'
1060 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
1061 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
1062 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
1063 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
1064 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1065 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
1066 ' }\n'
1067 ' }\n'
1068 ' break;\n'
1069 ' default:\n'
1070 ' break;\n'
1071 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001072 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +01001073 ' if (in_struct->pCode) {\n'
1074 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
1075 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
1076 ' }\n',
1077 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
1078 'VkGraphicsPipelineCreateInfo' :
1079 ' if (stageCount && in_struct->pStages) {\n'
1080 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1081 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1082 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
1083 ' }\n'
1084 ' }\n'
1085 ' if (in_struct->pVertexInputState)\n'
1086 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
1087 ' else\n'
1088 ' pVertexInputState = NULL;\n'
1089 ' if (in_struct->pInputAssemblyState)\n'
1090 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
1091 ' else\n'
1092 ' pInputAssemblyState = NULL;\n'
1093 ' bool has_tessellation_stage = false;\n'
1094 ' if (stageCount && pStages)\n'
1095 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1096 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1097 ' has_tessellation_stage = true;\n'
1098 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
1099 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
1100 ' else\n'
1101 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1102 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
1103 ' if (in_struct->pViewportState && has_rasterization) {\n'
1104 ' bool is_dynamic_viewports = false;\n'
1105 ' bool is_dynamic_scissors = false;\n'
1106 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
1107 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
1108 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
1109 ' is_dynamic_viewports = true;\n'
1110 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
1111 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
1112 ' is_dynamic_scissors = true;\n'
1113 ' }\n'
1114 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
1115 ' } else\n'
1116 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1117 ' if (in_struct->pRasterizationState)\n'
1118 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
1119 ' else\n'
1120 ' pRasterizationState = NULL;\n'
1121 ' if (in_struct->pMultisampleState && has_rasterization)\n'
1122 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
1123 ' else\n'
1124 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1125 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
1126 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
1127 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
1128 ' else\n'
1129 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1130 ' // needs a tracked subpass state usesColorAttachment\n'
1131 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
1132 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
1133 ' else\n'
1134 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1135 ' if (in_struct->pDynamicState)\n'
1136 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
1137 ' else\n'
1138 ' pDynamicState = NULL;\n',
1139 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
1140 'VkPipelineViewportStateCreateInfo' :
1141 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
1142 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
1143 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
1144 ' }\n'
1145 ' else\n'
1146 ' pViewports = NULL;\n'
1147 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
1148 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
1149 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
1150 ' }\n'
1151 ' else\n'
1152 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001153 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
1154 'VkDescriptorSetLayoutBinding' :
1155 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
1156 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
1157 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
1158 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1159 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
1160 ' }\n'
1161 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +01001162 }
1163
1164 custom_copy_txt = {
1165 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
1166 'VkGraphicsPipelineCreateInfo' :
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001167 ' pNext = SafePnextCopy(src.pNext);\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001168 ' if (stageCount && src.pStages) {\n'
1169 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1170 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1171 ' pStages[i].initialize(&src.pStages[i]);\n'
1172 ' }\n'
1173 ' }\n'
1174 ' if (src.pVertexInputState)\n'
1175 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
1176 ' else\n'
1177 ' pVertexInputState = NULL;\n'
1178 ' if (src.pInputAssemblyState)\n'
1179 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
1180 ' else\n'
1181 ' pInputAssemblyState = NULL;\n'
1182 ' bool has_tessellation_stage = false;\n'
1183 ' if (stageCount && pStages)\n'
1184 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1185 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1186 ' has_tessellation_stage = true;\n'
1187 ' if (src.pTessellationState && has_tessellation_stage)\n'
1188 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
1189 ' else\n'
1190 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1191 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
1192 ' if (src.pViewportState && has_rasterization) {\n'
1193 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
1194 ' } else\n'
1195 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1196 ' if (src.pRasterizationState)\n'
1197 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
1198 ' else\n'
1199 ' pRasterizationState = NULL;\n'
1200 ' if (src.pMultisampleState && has_rasterization)\n'
1201 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
1202 ' else\n'
1203 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1204 ' if (src.pDepthStencilState && has_rasterization)\n'
1205 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
1206 ' else\n'
1207 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1208 ' if (src.pColorBlendState && has_rasterization)\n'
1209 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1210 ' else\n'
1211 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1212 ' if (src.pDynamicState)\n'
1213 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1214 ' else\n'
1215 ' pDynamicState = NULL;\n',
1216 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1217 'VkPipelineViewportStateCreateInfo' :
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001218 ' pNext = SafePnextCopy(src.pNext);\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001219 ' if (src.pViewports) {\n'
1220 ' pViewports = new VkViewport[src.viewportCount];\n'
1221 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1222 ' }\n'
1223 ' else\n'
1224 ' pViewports = NULL;\n'
1225 ' if (src.pScissors) {\n'
1226 ' pScissors = new VkRect2D[src.scissorCount];\n'
1227 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1228 ' }\n'
1229 ' else\n'
1230 ' pScissors = NULL;\n',
1231 }
1232
Mike Schuchardt81485762017-09-04 11:38:42 -06001233 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1234 ' if (pCode)\n'
1235 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001236 copy_pnext = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001237 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001238 m_type = member.type
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001239 if member.name == 'pNext':
1240 copy_pnext = ' pNext = SafePnextCopy(in_struct->pNext);\n'
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001241 if member.type in self.structNames:
1242 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1243 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1244 m_type = 'safe_%s' % member.type
1245 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1246 # 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 -07001247 if m_type in ['void', 'char']:
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001248 if member.name != 'pNext':
1249 # For these exceptions just copy initial value over for now
1250 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1251 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinski692f3f32019-08-13 14:00:52 -06001252 default_init_list += '\n %s(nullptr),' % (member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001253 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001254 default_init_list += '\n %s(nullptr),' % (member.name)
1255 init_list += '\n %s(nullptr),' % (member.name)
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001256 if m_type in abstract_types:
1257 construct_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1258 else:
1259 init_func_txt += ' %s = nullptr;\n' % (member.name)
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001260 if not member.isstaticarray and (member.len is None or '/' in member.len):
1261 construct_txt += ' if (in_struct->%s) {\n' % member.name
1262 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1263 construct_txt += ' }\n'
1264 destruct_txt += ' if (%s)\n' % member.name
1265 destruct_txt += ' delete %s;\n' % member.name
1266 else:
1267 construct_txt += ' if (in_struct->%s) {\n' % member.name
1268 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1269 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1270 construct_txt += ' }\n'
1271 destruct_txt += ' if (%s)\n' % member.name
1272 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001273 elif member.isstaticarray or member.len is not None:
1274 if member.len is None:
1275 # Extract length of static array by grabbing val between []
1276 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1277 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1278 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1279 construct_txt += ' }\n'
1280 else:
1281 # Init array ptr to NULL
1282 default_init_list += '\n %s(nullptr),' % member.name
1283 init_list += '\n %s(nullptr),' % member.name
1284 init_func_txt += ' %s = nullptr;\n' % member.name
1285 array_element = 'in_struct->%s[i]' % member.name
1286 if member.type in self.structNames:
1287 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1288 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1289 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1290 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1291 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1292 destruct_txt += ' if (%s)\n' % member.name
1293 destruct_txt += ' delete[] %s;\n' % member.name
1294 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1295 if 'safe_' in m_type:
1296 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001297 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001298 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1299 construct_txt += ' }\n'
1300 construct_txt += ' }\n'
1301 elif member.ispointer == True:
1302 construct_txt += ' if (in_struct->%s)\n' % member.name
1303 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1304 construct_txt += ' else\n'
1305 construct_txt += ' %s = NULL;\n' % member.name
1306 destruct_txt += ' if (%s)\n' % member.name
1307 destruct_txt += ' delete %s;\n' % member.name
1308 elif 'safe_' in m_type:
1309 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1310 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1311 else:
1312 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1313 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1314 if '' != init_list:
1315 init_list = init_list[:-1] # hack off final comma
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001316
1317
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001318 if item.name in custom_construct_txt:
1319 construct_txt = custom_construct_txt[item.name]
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001320
1321 construct_txt = copy_pnext + construct_txt
1322
Mike Schuchardt81485762017-09-04 11:38:42 -06001323 if item.name in custom_destruct_txt:
1324 destruct_txt = custom_destruct_txt[item.name]
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001325
1326 if copy_pnext:
1327 destruct_txt += ' if (pNext)\n FreePnextChain(pNext);\n'
1328
Petr Krause91f7a12017-12-14 20:57:36 +01001329 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 -07001330 if '' != default_init_list:
1331 default_init_list = " :%s" % (default_init_list[:-1])
1332 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1333 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1334 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001335 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1336 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1337 copy_construct_txt = re.sub('(new \\w+)\\(in_struct->', '\\1(*src.', construct_txt) # Pass object to copy constructors
1338 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001339 if item.name in custom_copy_txt:
1340 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001341 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 -06001342 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 -07001343 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 -07001344 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001345 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 -07001346 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1347 init_copy = copy_construct_init.replace('src.', 'src->')
1348 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001349 safe_struct_body.append("\nvoid %s::initialize(const %s* src)\n{\n%s%s}" % (ss_name, ss_name, init_copy, init_construct))
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001350 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001351 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1352 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001353 #
John Zulaufde972ac2017-10-26 12:07:05 -06001354 # Generate the type map
1355 def GenerateTypeMapHelperHeader(self):
1356 prefix = 'Lvl'
1357 fprefix = 'lvl_'
1358 typemap = prefix + 'TypeMap'
1359 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001360 type_member = 'Type'
1361 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001362 id_decl = 'static const VkStructureType '
Locke6b6b7382019-04-16 15:08:49 -06001363 generic_header = 'VkBaseOutStructure'
John Zulaufde972ac2017-10-26 12:07:05 -06001364 typename_func = fprefix + 'typename'
1365 idname_func = fprefix + 'stype_name'
1366 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001367 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001368
1369 explanatory_comment = '\n'.join((
1370 '// These empty generic templates are specialized for each type with sType',
1371 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001372 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001373
1374 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1375 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001376 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1377 typemap_format += '}};\n'
1378
1379 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1380 idmap_format = ''.join((
1381 'template <> struct {template}<{id_value}> {{\n',
1382 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001383 '}};\n'))
1384
1385 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1386 utilities_format = '\n'.join((
John Zulaufde972ac2017-10-26 12:07:05 -06001387 '// Find an entry of the given type in the pNext chain',
1388 'template <typename T> const T *{find_func}(const void *next) {{',
1389 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1390 ' const T *found = nullptr;',
1391 ' while (current) {{',
1392 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1393 ' found = reinterpret_cast<const T*>(current);',
1394 ' current = nullptr;',
1395 ' }} else {{',
1396 ' current = current->pNext;',
1397 ' }}',
1398 ' }}',
1399 ' return found;',
1400 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001401 '',
1402 '// Init the header of an sType struct with pNext',
1403 'template <typename T> T {init_func}(void *p_next) {{',
1404 ' T out = {{}};',
1405 ' out.sType = {type_map}<T>::kSType;',
1406 ' out.pNext = p_next;',
1407 ' return out;',
1408 '}}',
1409 '',
1410 '// Init the header of an sType struct',
1411 'template <typename T> T {init_func}() {{',
1412 ' T out = {{}};',
1413 ' out.sType = {type_map}<T>::kSType;',
1414 ' return out;',
1415 '}}',
1416
Mike Schuchardt97662b02017-12-06 13:31:29 -07001417 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001418
1419 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001420
1421 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001422 code.append('\n'.join((
1423 '#pragma once',
1424 '#include <vulkan/vulkan.h>\n',
1425 explanatory_comment, '',
1426 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001427 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001428
1429 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001430 for item in self.structMembers:
1431 typename = item.name
1432 info = self.structTypes.get(typename)
1433 if not info:
1434 continue
1435
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001436 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001437 code.append('#ifdef %s' % item.ifdef_protect)
1438
1439 code.append('// Map type {} to id {}'.format(typename, info.value))
1440 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001441 id_decl=id_decl, id_member=id_member))
1442 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001443
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001444 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001445 code.append('#endif // %s' % item.ifdef_protect)
1446
John Zulauf65ac9d52018-01-23 11:20:50 -07001447 # Generate utilities for all types
1448 code.append('\n'.join((
1449 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1450 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1451 find_func=find_func, init_func=init_func), ''
1452 )))
1453
John Zulaufde972ac2017-10-26 12:07:05 -06001454 return "\n".join(code)
1455
1456 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001457 # Create a helper file and return it as a string
1458 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001459 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001460 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001461 elif self.helper_file_type == 'safe_struct_header':
1462 return self.GenerateSafeStructHelperHeader()
1463 elif self.helper_file_type == 'safe_struct_source':
1464 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001465 elif self.helper_file_type == 'object_types_header':
1466 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001467 elif self.helper_file_type == 'extension_helper_header':
1468 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001469 elif self.helper_file_type == 'typemap_helper_header':
1470 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001471 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001472 return 'Bad Helper File Generator Option %s' % self.helper_file_type