blob: 5b5b4bfed32fbd027b1328d78bc04f12aab6bc53 [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'
458 safe_struct_helper_header += '\n'
Mark Lobodzinski7245fce2019-07-18 16:18:51 -0600459 safe_struct_helper_header += 'void *SafePnextCopy(const void *pNext);\n'
Petr Krausec689c02019-08-20 03:30:56 +0200460 safe_struct_helper_header += 'void FreePnextChain(const void *pNext);\n'
Petr Kraus956e9712019-08-18 16:22:59 +0200461 safe_struct_helper_header += 'char *SafeStringCopy(const char *in_string);\n'
Mark Lobodzinski7245fce2019-07-18 16:18:51 -0600462 safe_struct_helper_header += '\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700463 safe_struct_helper_header += self.GenerateSafeStructHeader()
464 return safe_struct_helper_header
465 #
466 # safe_struct header: build function prototypes for header file
467 def GenerateSafeStructHeader(self):
468 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700469 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700470 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700471 safe_struct_header += '\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100472 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700473 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
474 safe_struct_header += 'struct safe_%s {\n' % (item.name)
475 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700476 if member.type in self.structNames:
477 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
478 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
479 if member.ispointer:
480 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
481 else:
482 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
483 continue
484 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
485 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
486 else:
487 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100488 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 -0600489 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700490 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700491 safe_struct_header += ' safe_%s();\n' % item.name
492 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100493 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
494 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700495 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
496 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
497 safe_struct_header += '};\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100498 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700499 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700500 return safe_struct_header
501 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600502 # Generate extension helper header file
503 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600504
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600505 V_1_1_level_feature_set = [
506 'VK_VERSION_1_1',
507 ]
508
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600509 V_1_0_instance_extensions_promoted_to_V_1_1_core = [
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600510 'vk_khr_device_group_creation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600511 'vk_khr_external_fence_capabilities',
John Zulauf2012bca2018-04-25 15:28:47 -0600512 'vk_khr_external_memory_capabilities',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600513 'vk_khr_external_semaphore_capabilities',
514 'vk_khr_get_physical_device_properties_2',
515 ]
516
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600517 V_1_0_device_extensions_promoted_to_V_1_1_core = [
John Zulauf2012bca2018-04-25 15:28:47 -0600518 'vk_khr_16bit_storage',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600519 'vk_khr_bind_memory_2',
John Zulauf2012bca2018-04-25 15:28:47 -0600520 'vk_khr_dedicated_allocation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600521 'vk_khr_descriptor_update_template',
John Zulauf2012bca2018-04-25 15:28:47 -0600522 'vk_khr_device_group',
523 'vk_khr_external_fence',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600524 'vk_khr_external_memory',
525 'vk_khr_external_semaphore',
John Zulauf2012bca2018-04-25 15:28:47 -0600526 'vk_khr_get_memory_requirements_2',
527 'vk_khr_maintenance1',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600528 'vk_khr_maintenance2',
John Zulauf2012bca2018-04-25 15:28:47 -0600529 'vk_khr_maintenance3',
530 'vk_khr_multiview',
John Zulauf16826822018-04-25 15:40:32 -0600531 'vk_khr_relaxed_block_layout',
John Zulauf2012bca2018-04-25 15:28:47 -0600532 'vk_khr_sampler_ycbcr_conversion',
John Zulauf16826822018-04-25 15:40:32 -0600533 'vk_khr_shader_draw_parameters',
534 'vk_khr_storage_buffer_storage_class',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600535 'vk_khr_variable_pointers',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600536 ]
John Zulauf16826822018-04-25 15:40:32 -0600537
John Zulauff6feb2a2018-04-12 14:24:57 -0600538 output = [
539 '',
540 '#ifndef VK_EXTENSION_HELPER_H_',
541 '#define VK_EXTENSION_HELPER_H_',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600542 '#include <unordered_set>',
John Zulauf072677c2018-04-12 15:34:39 -0600543 '#include <string>',
544 '#include <unordered_map>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600545 '#include <utility>',
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600546 '#include <set>',
Mark Lobodzinskif94196f2019-07-11 11:46:09 -0600547 '#include <vector>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600548 '',
John Zulauf072677c2018-04-12 15:34:39 -0600549 '#include <vulkan/vulkan.h>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600550 '']
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600551
John Zulauff6feb2a2018-04-12 14:24:57 -0600552 def guarded(ifdef, value):
553 if ifdef is not None:
554 return '\n'.join([ '#ifdef %s' % ifdef, value, '#endif' ])
555 else:
556 return value
John Zulauf380bd942018-04-10 13:12:34 -0600557
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600558 for type in ['Instance', 'Device']:
John Zulauff6feb2a2018-04-12 14:24:57 -0600559 struct_type = '%sExtensions' % type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600560 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600561 extension_dict = self.instance_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600562 promoted_ext_list = V_1_0_instance_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600563 struct_decl = 'struct %s {' % struct_type
564 instance_struct_type = struct_type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600565 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600566 extension_dict = self.device_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600567 promoted_ext_list = V_1_0_device_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600568 struct_decl = 'struct %s : public %s {' % (struct_type, instance_struct_type)
569
570 extension_items = sorted(extension_dict.items())
571
572 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 -0600573
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600574 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600575 instance_field_name = field_name
John Zulauf072677c2018-04-12 15:34:39 -0600576 instance_extension_dict = extension_dict
577 else:
578 # Get complete field name and extension data for both Instance and Device extensions
579 field_name.update(instance_field_name)
580 extension_dict = extension_dict.copy() # Don't modify the self.<dict> we're pointing to
581 extension_dict.update(instance_extension_dict)
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600582
John Zulauf072677c2018-04-12 15:34:39 -0600583 # Output the data member list
John Zulauff6feb2a2018-04-12 14:24:57 -0600584 struct = [struct_decl]
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600585 struct.extend([ ' bool vk_feature_version_1_1{false};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600586 struct.extend([ ' bool %s{false};' % field_name[ext_name] for ext_name, info in extension_items])
John Zulauf072677c2018-04-12 15:34:39 -0600587
588 # Construct the extension information map -- mapping name to data member (field), and required extensions
589 # The map is contained within a static function member for portability reasons.
590 info_type = '%sInfo' % type
591 info_map_type = '%sMap' % info_type
592 req_type = '%sReq' % type
593 req_vec_type = '%sVec' % req_type
594 struct.extend([
595 '',
596 ' struct %s {' % req_type,
597 ' const bool %s::* enabled;' % struct_type,
598 ' const char *name;',
599 ' };',
600 ' typedef std::vector<%s> %s;' % (req_type, req_vec_type),
601 ' struct %s {' % info_type,
602 ' %s(bool %s::* state_, const %s requires_): state(state_), requires(requires_) {}' % ( info_type, struct_type, req_vec_type),
603 ' bool %s::* state;' % struct_type,
604 ' %s requires;' % req_vec_type,
605 ' };',
606 '',
607 ' typedef std::unordered_map<std::string,%s> %s;' % (info_type, info_map_type),
608 ' static const %s &get_info(const char *name) {' %info_type,
609 ' static const %s info_map = {' % info_map_type ])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600610 struct.extend([
611 ' std::make_pair("VK_VERSION_1_1", %sInfo(&%sExtensions::vk_feature_version_1_1, {})),' % (type, type)])
John Zulauf072677c2018-04-12 15:34:39 -0600612
613 field_format = '&' + struct_type + '::%s'
614 req_format = '{' + field_format+ ', %s}'
615 req_indent = '\n '
616 req_join = ',' + req_indent
617 info_format = (' std::make_pair(%s, ' + info_type + '(' + field_format + ', {%s})),')
618 def format_info(ext_name, info):
619 reqs = req_join.join([req_format % (field_name[req], extension_dict[req]['define']) for req in info['reqs']])
620 return info_format % (info['define'], field_name[ext_name], '{%s}' % (req_indent + reqs) if reqs else '')
621
622 struct.extend([guarded(info['ifdef'], format_info(ext_name, info)) for ext_name, info in extension_items])
623 struct.extend([
624 ' };',
625 '',
626 ' static const %s empty_info {nullptr, %s()};' % (info_type, req_vec_type),
627 ' %s::const_iterator info = info_map.find(name);' % info_map_type,
628 ' if ( info != info_map.cend()) {',
629 ' return info->second;',
630 ' }',
631 ' return empty_info;',
632 ' }',
633 ''])
634
John Zulauff6feb2a2018-04-12 14:24:57 -0600635 if type == 'Instance':
636 struct.extend([
637 ' uint32_t NormalizeApiVersion(uint32_t specified_version) {',
638 ' uint32_t api_version = (specified_version < VK_API_VERSION_1_1) ? VK_API_VERSION_1_0 : VK_API_VERSION_1_1;',
639 ' return api_version;',
640 ' }',
641 '',
642 ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {'])
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600643 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600644 struct.extend([
John Zulauf072677c2018-04-12 15:34:39 -0600645 ' %s() = default;' % struct_type,
646 ' %s(const %s& instance_ext) : %s(instance_ext) {}' % (struct_type, instance_struct_type, instance_struct_type),
647 '',
648 ' uint32_t InitFromDeviceCreateInfo(const %s *instance_extensions, uint32_t requested_api_version,' % instance_struct_type,
649 ' const VkDeviceCreateInfo *pCreateInfo) {',
650 ' // Initialize: this to defaults, base class fields to input.',
651 ' assert(instance_extensions);',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600652 ' *this = %s(*instance_extensions);' % struct_type,
Mark Lobodzinskid5f83b92018-12-14 11:02:08 -0700653 '']),
654 struct.extend([
John Zulauff6feb2a2018-04-12 14:24:57 -0600655 '',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600656 ' static const std::vector<const char *> V_1_1_promoted_%s_apis = {' % type.lower() ])
John Zulauff6feb2a2018-04-12 14:24:57 -0600657 struct.extend([' %s_EXTENSION_NAME,' % ext_name.upper() for ext_name in promoted_ext_list])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600658 struct.extend([' "VK_VERSION_1_1",'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600659 struct.extend([
660 ' };',
661 '',
John Zulauf072677c2018-04-12 15:34:39 -0600662 ' // Initialize struct data, robust to invalid pCreateInfo',
663 ' if (pCreateInfo->ppEnabledExtensionNames) {',
664 ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {',
665 ' if (!pCreateInfo->ppEnabledExtensionNames[i]) continue;',
666 ' auto info = get_info(pCreateInfo->ppEnabledExtensionNames[i]);',
667 ' if(info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600668 ' }',
669 ' }',
670 ' uint32_t api_version = NormalizeApiVersion(requested_api_version);',
671 ' if (api_version >= VK_API_VERSION_1_1) {',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600672 ' for (auto promoted_ext : V_1_1_promoted_%s_apis) {' % type.lower(),
John Zulauf072677c2018-04-12 15:34:39 -0600673 ' auto info = get_info(promoted_ext);',
674 ' assert(info.state);',
675 ' if (info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600676 ' }',
677 ' }',
678 ' return api_version;',
679 ' }',
John Zulauf072677c2018-04-12 15:34:39 -0600680 '};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600681
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700682 # Output reference lists of instance/device extension names
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600683 struct.extend(['', 'static const std::set<std::string> k%sExtensionNames = {' % type])
684 struct.extend([guarded(info['ifdef'], ' %s,' % info['define']) for ext_name, info in extension_items])
685 struct.extend(['};', ''])
John Zulauff6feb2a2018-04-12 14:24:57 -0600686 output.extend(struct)
687
688 output.extend(['', '#endif // VK_EXTENSION_HELPER_H_'])
689 return '\n'.join(output)
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600690 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600691 # Combine object types helper header file preamble with body text and return
692 def GenerateObjectTypesHelperHeader(self):
693 object_types_helper_header = '\n'
694 object_types_helper_header += '#pragma once\n'
695 object_types_helper_header += '\n'
696 object_types_helper_header += self.GenerateObjectTypesHeader()
697 return object_types_helper_header
698 #
699 # Object types header: create object enum type header file
700 def GenerateObjectTypesHeader(self):
John Zulauf4fea6622019-04-01 11:38:18 -0600701 object_types_header = '#include "cast_utils.h"\n'
702 object_types_header += '\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700703 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600704 object_types_header += 'typedef enum VulkanObjectType {\n'
705 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
706 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600707 type_list = [];
John Zulaufd7435c62018-03-16 11:52:57 -0600708 enum_entry_map = {}
John Zulauf2c2ccd42019-04-05 13:13:13 -0600709 non_dispatchable = {}
710 dispatchable = {}
711 object_type_info = {}
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600712
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600713 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600714 for item in self.object_types:
715 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600716 enum_entry = 'kVulkanObjectType%s' % fixup_name
John Zulaufd7435c62018-03-16 11:52:57 -0600717 enum_entry_map[item] = enum_entry
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600718 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600719 object_types_header += ' = %d,\n' % enum_num
720 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600721 type_list.append(enum_entry)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600722 object_type_info[enum_entry] = { 'VkType': item }
723 # 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 -0700724 if self.handle_types.IsNonDispatchable(item):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600725 non_dispatchable[item] = enum_entry
726 else:
727 dispatchable[item] = enum_entry
728
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600729 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
John Zulaufd7435c62018-03-16 11:52:57 -0600730 object_types_header += ' // Aliases for backwards compatibilty of "promoted" types\n'
731 for (name, alias) in self.object_type_aliases:
732 fixup_name = name[2:]
733 object_types_header += ' kVulkanObjectType{} = {},\n'.format(fixup_name, enum_entry_map[alias])
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600734 object_types_header += '} VulkanObjectType;\n\n'
735
736 # Output name string helper
737 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600738 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
locke-lunargb4c57852019-06-14 23:20:05 -0600739 object_types_header += ' "VkNonDispatchableHandle",\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600740 for item in self.object_types:
locke-lunargb4c57852019-06-14 23:20:05 -0600741 object_types_header += ' "%s",\n' % item
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600742 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600743
Petr Krausf64607e2019-08-09 18:27:09 +0200744 # Helpers to create unified dict key from k<Name>, VK_OBJECT_TYPE_<Name>, and VK_DEBUG_REPORT_OBJECT_TYPE_<Name>
745 def dro_to_key(raw_key): return re.search('^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$', raw_key).group(1).lower().replace("_","")
746 def vko_to_key(raw_key): return re.search('^VK_OBJECT_TYPE_(.*)', raw_key).group(1).lower().replace("_","")
747 def kenum_to_key(raw_key): return re.search('^kVulkanObjectType(.*)', raw_key).group(1).lower()
748
749 dro_dict = {dro_to_key(dro) : dro for dro in self.debug_report_object_types}
750 vko_dict = {vko_to_key(vko) : vko for vko in self.core_object_types}
John Zulauf311a4892018-03-12 15:48:06 -0600751
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600752 # Output a conversion routine from the layer object definitions to the debug report definitions
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600753 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600754 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 -0600755 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Petr Krausf64607e2019-08-09 18:27:09 +0200756 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 -0600757
John Zulauf311a4892018-03-12 15:48:06 -0600758 for object_type in type_list:
Petr Krausf64607e2019-08-09 18:27:09 +0200759 # VK_DEBUG_REPORT is not updated anymore; there might be missing object types
760 kenum_type = dro_dict.get(kenum_to_key(object_type), 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT')
761 object_types_header += ' %s, // %s\n' % (kenum_type, object_type)
762 object_type_info[object_type]['DbgType'] = kenum_type
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600763 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600764
765 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600766 # 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 -0600767 object_types_header += '\n'
768 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
769 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Petr Krausf64607e2019-08-09 18:27:09 +0200770 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n' # no unknown handle, so must be here explicitly
John Zulauf311a4892018-03-12 15:48:06 -0600771
Mark Young1ded24b2017-05-30 14:53:50 -0600772 for object_type in type_list:
Petr Krausf64607e2019-08-09 18:27:09 +0200773 kenum_type = vko_dict[kenum_to_key(object_type)]
774 object_types_header += ' %s, // %s\n' % (kenum_type, object_type)
775 object_type_info[object_type]['VkoType'] = kenum_type
Mark Young1ded24b2017-05-30 14:53:50 -0600776 object_types_header += '};\n'
777
Petr Krausf64607e2019-08-09 18:27:09 +0200778 # Create a functions to convert between VkDebugReportObjectTypeEXT and VkObjectType
779 object_types_header += '\n'
780 object_types_header += 'static inline VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj) {\n'
781 object_types_header += ' switch (debug_report_obj) {\n'
782 for dr_object_type in self.debug_report_object_types:
783 object_types_header += ' case %s: return %s;\n' % (dr_object_type, vko_dict[dro_to_key(dr_object_type)])
784 object_types_header += ' default: return VK_OBJECT_TYPE_UNKNOWN;\n'
785 object_types_header += ' }\n'
786 object_types_header += '}\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700787
Petr Krausf64607e2019-08-09 18:27:09 +0200788 object_types_header += '\n'
789 object_types_header += 'static inline VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj) {\n'
790 object_types_header += ' switch (core_report_obj) {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700791 for core_object_type in self.core_object_types:
Petr Krausf64607e2019-08-09 18:27:09 +0200792 # VK_DEBUG_REPORT is not updated anymore; there might be missing object types
793 dr_object_type = dro_dict.get(vko_to_key(core_object_type))
794 if dr_object_type is not None:
795 object_types_header += ' case %s: return %s;\n' % (core_object_type, dr_object_type)
796 object_types_header += ' default: return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
797 object_types_header += ' }\n'
798 object_types_header += '}\n'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600799
Petr Krausf64607e2019-08-09 18:27:09 +0200800 #
801 object_types_header += '\n'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600802 traits_format = Outdent('''
803 template <> struct VkHandleInfo<{vk_type}> {{
804 static const VulkanObjectType kVulkanObjectType = {obj_type};
805 static const VkDebugReportObjectTypeEXT kDebugReportObjectType = {dbg_type};
806 static const VkObjectType kVkObjectType = {vko_type};
807 static const char* Typename() {{
808 return "{vk_type}";
809 }}
810 }};
811 template <> struct VulkanObjectTypeInfo<{obj_type}> {{
812 typedef {vk_type} Type;
813 }};
814 ''')
815
816 object_types_header += Outdent('''
817 // Traits objects from each type statically map from Vk<handleType> to the various enums
818 template <typename VkType> struct VkHandleInfo {};
819 template <VulkanObjectType id> struct VulkanObjectTypeInfo {};
820
821 // The following line must match the vulkan_core.h condition guarding VK_DEFINE_NON_DISPATCHABLE_HANDLE
822 #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || \
823 defined(_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
824 #define TYPESAFE_NONDISPATCHABLE_HANDLES
825 #else
826 VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkNonDispatchableHandle)
827 ''') +'\n'
828 object_types_header += traits_format.format(vk_type='VkNonDispatchableHandle', obj_type='kVulkanObjectTypeUnknown',
829 dbg_type='VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT',
830 vko_type='VK_OBJECT_TYPE_UNKNOWN') + '\n'
831 object_types_header += '#endif // VK_DEFINE_HANDLE logic duplication\n'
832
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700833 for vk_type, object_type in sorted(dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600834 info = object_type_info[object_type]
835 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
836 vko_type=info['VkoType'])
837 object_types_header += '#ifdef TYPESAFE_NONDISPATCHABLE_HANDLES\n'
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700838 for vk_type, object_type in sorted(non_dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600839 info = object_type_info[object_type]
840 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
841 vko_type=info['VkoType'])
842 object_types_header += '#endif // TYPESAFE_NONDISPATCHABLE_HANDLES\n'
843
844 object_types_header += Outdent('''
845 struct VulkanTypedHandle {
846 uint64_t handle;
847 VulkanObjectType type;
848 template <typename Handle>
John Zulauf4fea6622019-04-01 11:38:18 -0600849 VulkanTypedHandle(Handle handle_, VulkanObjectType type_) :
850 handle(CastToUint64(handle_)),
851 type(type_) {
852 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
853 // For 32 bit it's not always safe to check for traits <-> type
854 // as all non-dispatchable handles have the same type-id and thus traits,
855 // but on 64 bit we can validate the passed type matches the passed handle
856 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
857 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
858 }
859 template <typename Handle>
860 Handle Cast() const {
861 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
862 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
863 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
864 return CastFromUint64<Handle>(handle);
865 }
John Zulauf2c2ccd42019-04-05 13:13:13 -0600866 VulkanTypedHandle() :
867 handle(VK_NULL_HANDLE),
868 type(kVulkanObjectTypeUnknown) {}
869 }; ''') +'\n'
870
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600871 return object_types_header
872 #
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600873 # Generate pNext handling function
Mark Lobodzinski3628d2f2019-08-13 14:12:20 -0600874 def build_safe_struct_utility_funcs(self):
Mark Lobodzinski256ba552019-08-13 14:59:17 -0600875 # Construct Safe-struct helper functions
876
877 string_copy_proc = '\n\n'
Petr Kraus956e9712019-08-18 16:22:59 +0200878 string_copy_proc += 'char *SafeStringCopy(const char *in_string) {\n'
Mark Lobodzinski256ba552019-08-13 14:59:17 -0600879 string_copy_proc += ' if (nullptr == in_string) return nullptr;\n'
880 string_copy_proc += ' char* dest = new char[std::strlen(in_string) + 1];\n'
881 string_copy_proc += ' return std::strcpy(dest, in_string);\n'
882 string_copy_proc += '}\n'
883
884 build_pnext_proc = '\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600885 build_pnext_proc += 'void *SafePnextCopy(const void *pNext) {\n'
Petr Krausec689c02019-08-20 03:30:56 +0200886 build_pnext_proc += ' if (!pNext) return nullptr;\n'
887 build_pnext_proc += '\n'
888 build_pnext_proc += ' void *safe_pNext;\n'
889 build_pnext_proc += ' const VkBaseOutStructure *header = reinterpret_cast<const VkBaseOutStructure *>(pNext);\n'
890 build_pnext_proc += '\n'
891 build_pnext_proc += ' switch (header->sType) {\n'
Mark Lobodzinskidb8affe2019-08-08 13:25:07 -0600892 # Add special-case code to copy beloved secret loader structs
Petr Krausec689c02019-08-20 03:30:56 +0200893 build_pnext_proc += ' // Special-case Loader Instance Struct passed to/from layer in pNext chain\n'
894 build_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO: {\n'
895 build_pnext_proc += ' VkLayerInstanceCreateInfo *struct_copy = new VkLayerInstanceCreateInfo;\n'
896 build_pnext_proc += ' // TODO: Uses original VkLayerInstanceLink* chain, which should be okay for our uses\n'
897 build_pnext_proc += ' memcpy(struct_copy, pNext, sizeof(VkLayerInstanceCreateInfo));\n'
898 build_pnext_proc += ' struct_copy->pNext = SafePnextCopy(header->pNext);\n'
899 build_pnext_proc += ' safe_pNext = struct_copy;\n'
900 build_pnext_proc += ' break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600901 build_pnext_proc += ' }\n'
Petr Krausec689c02019-08-20 03:30:56 +0200902 build_pnext_proc += ' // Special-case Loader Device Struct passed to/from layer in pNext chain\n'
903 build_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO: {\n'
904 build_pnext_proc += ' VkLayerDeviceCreateInfo *struct_copy = new VkLayerDeviceCreateInfo;\n'
905 build_pnext_proc += ' // TODO: Uses original VkLayerDeviceLink*, which should be okay for our uses\n'
906 build_pnext_proc += ' memcpy(struct_copy, pNext, sizeof(VkLayerDeviceCreateInfo));\n'
907 build_pnext_proc += ' struct_copy->pNext = SafePnextCopy(header->pNext);\n'
908 build_pnext_proc += ' safe_pNext = struct_copy;\n'
909 build_pnext_proc += ' break;\n'
910 build_pnext_proc += ' }\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600911
Petr Krausec689c02019-08-20 03:30:56 +0200912 free_pnext_proc = '\n'
913 free_pnext_proc += 'void FreePnextChain(const void *pNext) {\n'
914 free_pnext_proc += ' if (!pNext) return;\n'
915 free_pnext_proc += '\n'
916 free_pnext_proc += ' auto header = reinterpret_cast<const VkBaseOutStructure *>(pNext);\n'
917 free_pnext_proc += '\n'
918 free_pnext_proc += ' switch (header->sType) {\n'
919 free_pnext_proc += ' // Special-case Loader Instance Struct passed to/from layer in pNext chain\n'
920 free_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO:\n'
921 free_pnext_proc += ' FreePnextChain(header->pNext);\n'
922 free_pnext_proc += ' delete reinterpret_cast<const VkLayerInstanceCreateInfo *>(pNext);\n'
923 free_pnext_proc += ' break;\n'
924 free_pnext_proc += ' // Special-case Loader Device Struct passed to/from layer in pNext chain\n'
925 free_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO:\n'
926 free_pnext_proc += ' FreePnextChain(header->pNext);\n'
927 free_pnext_proc += ' delete reinterpret_cast<const VkLayerDeviceCreateInfo *>(pNext);\n'
928 free_pnext_proc += ' break;\n'
929
930 chain_structs = tuple(s for s in self.structMembers if s.name in self.structextends_list)
931 ifdefs = sorted({cs.ifdef_protect for cs in chain_structs}, key = lambda i : i if i is not None else '')
932 for ifdef in ifdefs:
933 if ifdef is not None:
934 build_pnext_proc += '#ifdef %s\n' % ifdef
935 free_pnext_proc += '#ifdef %s\n' % ifdef
936
937 assorted_chain_structs = tuple(s for s in chain_structs if s.ifdef_protect == ifdef)
938 for struct in assorted_chain_structs:
939 build_pnext_proc += ' case %s:\n' % self.structTypes[struct.name].value
940 build_pnext_proc += ' safe_pNext = new safe_%s(reinterpret_cast<const %s *>(pNext));\n' % (struct.name, struct.name)
941 build_pnext_proc += ' break;\n'
942
943 free_pnext_proc += ' case %s:\n' % self.structTypes[struct.name].value
944 free_pnext_proc += ' delete reinterpret_cast<const safe_%s *>(header);\n' % struct.name
945 free_pnext_proc += ' break;\n'
946
947 if ifdef is not None:
948 build_pnext_proc += '#endif // %s\n' % ifdef
949 free_pnext_proc += '#endif // %s\n' % ifdef
950
951 build_pnext_proc += ' default: // Encountered an unknown sType -- skip (do not copy) this entry in the chain\n'
952 build_pnext_proc += ' safe_pNext = SafePnextCopy(header->pNext);\n'
953 build_pnext_proc += ' break;\n'
954 build_pnext_proc += ' }\n'
955 build_pnext_proc += '\n'
956 build_pnext_proc += ' return safe_pNext;\n'
957 build_pnext_proc += '}\n'
958
959 free_pnext_proc += ' default: // Encountered an unknown sType -- panic, there should be none such in safe chain\n'
960 free_pnext_proc += ' assert(false);\n'
961 free_pnext_proc += ' FreePnextChain(header->pNext);\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600962 free_pnext_proc += ' break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600963 free_pnext_proc += ' }\n'
964 free_pnext_proc += '}\n'
965
Mark Lobodzinski256ba552019-08-13 14:59:17 -0600966 pnext_procs = string_copy_proc + build_pnext_proc + free_pnext_proc
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600967 return pnext_procs
968 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700969 # Determine if a structure needs a safe_struct helper function
970 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700971 def NeedSafeStruct(self, structure):
Mark Lobodzinskib6cc5412019-07-19 09:56:58 -0600972 if 'VkBase' in structure.name:
973 return False
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700974 if 'sType' == structure.name:
975 return True
976 for member in structure.members:
977 if member.ispointer == True:
978 return True
979 return False
980 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700981 # Combine safe struct helper source file preamble with body text and return
982 def GenerateSafeStructHelperSource(self):
983 safe_struct_helper_source = '\n'
984 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
Petr Krausec689c02019-08-20 03:30:56 +0200985 safe_struct_helper_source += '\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700986 safe_struct_helper_source += '#include <string.h>\n'
Petr Krausec689c02019-08-20 03:30:56 +0200987 safe_struct_helper_source += '#include <cassert>\n'
Mark Lobodzinski256ba552019-08-13 14:59:17 -0600988 safe_struct_helper_source += '#include <cstring>\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700989 safe_struct_helper_source += '\n'
Petr Krausec689c02019-08-20 03:30:56 +0200990 safe_struct_helper_source += '#include <vulkan/vk_layer.h>\n'
991 safe_struct_helper_source += '\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700992 safe_struct_helper_source += self.GenerateSafeStructSource()
Mark Lobodzinski3628d2f2019-08-13 14:12:20 -0600993 safe_struct_helper_source += self.build_safe_struct_utility_funcs()
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600994
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700995 return safe_struct_helper_source
996 #
997 # safe_struct source -- create bodies of safe struct helper functions
998 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700999 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001000 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
1001 'VkXcbSurfaceCreateInfoKHR',
1002 'VkWaylandSurfaceCreateInfoKHR',
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001003 'VkAndroidSurfaceCreateInfoKHR',
1004 'VkWin32SurfaceCreateInfoKHR'
1005 ]
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001006
1007 # For abstract types just want to save the pointer away
1008 # since we cannot make a copy.
1009 abstract_types = ['AHardwareBuffer',
1010 'ANativeWindow',
1011 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001012 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001013 if self.NeedSafeStruct(item) == False:
1014 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001015 if item.name in wsi_structs:
1016 continue
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001017 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001018 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
1019 ss_name = "safe_%s" % item.name
1020 init_list = '' # list of members in struct constructor initializer
1021 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
1022 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
1023 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
1024 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +01001025
1026 custom_construct_txt = {
1027 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
1028 'VkWriteDescriptorSet' :
1029 ' switch (descriptorType) {\n'
1030 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
1031 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
1032 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
1033 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
1034 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
1035 ' if (descriptorCount && in_struct->pImageInfo) {\n'
1036 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
Mark Lobodzinski22a1c992019-08-15 11:20:06 -06001037 ' for (uint32_t i = 0; i < descriptorCount; ++i) {\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001038 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
1039 ' }\n'
1040 ' }\n'
1041 ' break;\n'
1042 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
1043 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
1044 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
1045 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
1046 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
1047 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
Mark Lobodzinski22a1c992019-08-15 11:20:06 -06001048 ' for (uint32_t i = 0; i < descriptorCount; ++i) {\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001049 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
1050 ' }\n'
1051 ' }\n'
1052 ' break;\n'
1053 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
1054 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
1055 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
1056 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
Mark Lobodzinski22a1c992019-08-15 11:20:06 -06001057 ' for (uint32_t i = 0; i < descriptorCount; ++i) {\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001058 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
1059 ' }\n'
1060 ' }\n'
1061 ' break;\n'
1062 ' default:\n'
1063 ' break;\n'
1064 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001065 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +01001066 ' if (in_struct->pCode) {\n'
1067 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
1068 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
1069 ' }\n',
1070 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
1071 'VkGraphicsPipelineCreateInfo' :
1072 ' if (stageCount && in_struct->pStages) {\n'
1073 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
Mark Lobodzinski22a1c992019-08-15 11:20:06 -06001074 ' for (uint32_t i = 0; i < stageCount; ++i) {\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001075 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
1076 ' }\n'
1077 ' }\n'
1078 ' if (in_struct->pVertexInputState)\n'
1079 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
1080 ' else\n'
1081 ' pVertexInputState = NULL;\n'
1082 ' if (in_struct->pInputAssemblyState)\n'
1083 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
1084 ' else\n'
1085 ' pInputAssemblyState = NULL;\n'
1086 ' bool has_tessellation_stage = false;\n'
1087 ' if (stageCount && pStages)\n'
Mark Lobodzinski22a1c992019-08-15 11:20:06 -06001088 ' for (uint32_t i = 0; i < stageCount && !has_tessellation_stage; ++i)\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001089 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1090 ' has_tessellation_stage = true;\n'
1091 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
1092 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
1093 ' else\n'
1094 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1095 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
1096 ' if (in_struct->pViewportState && has_rasterization) {\n'
1097 ' bool is_dynamic_viewports = false;\n'
1098 ' bool is_dynamic_scissors = false;\n'
1099 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
1100 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
1101 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
1102 ' is_dynamic_viewports = true;\n'
1103 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
1104 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
1105 ' is_dynamic_scissors = true;\n'
1106 ' }\n'
1107 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
1108 ' } else\n'
1109 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1110 ' if (in_struct->pRasterizationState)\n'
1111 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
1112 ' else\n'
1113 ' pRasterizationState = NULL;\n'
1114 ' if (in_struct->pMultisampleState && has_rasterization)\n'
1115 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
1116 ' else\n'
1117 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1118 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
1119 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
1120 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
1121 ' else\n'
1122 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1123 ' // needs a tracked subpass state usesColorAttachment\n'
1124 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
1125 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
1126 ' else\n'
1127 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1128 ' if (in_struct->pDynamicState)\n'
1129 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
1130 ' else\n'
1131 ' pDynamicState = NULL;\n',
1132 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
1133 'VkPipelineViewportStateCreateInfo' :
1134 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
1135 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
1136 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
1137 ' }\n'
1138 ' else\n'
1139 ' pViewports = NULL;\n'
1140 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
1141 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
1142 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
1143 ' }\n'
1144 ' else\n'
1145 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001146 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
1147 'VkDescriptorSetLayoutBinding' :
1148 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
1149 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
1150 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
Mark Lobodzinski22a1c992019-08-15 11:20:06 -06001151 ' for (uint32_t i = 0; i < descriptorCount; ++i) {\n'
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001152 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
1153 ' }\n'
1154 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +01001155 }
1156
1157 custom_copy_txt = {
1158 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
1159 'VkGraphicsPipelineCreateInfo' :
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001160 ' pNext = SafePnextCopy(src.pNext);\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001161 ' if (stageCount && src.pStages) {\n'
1162 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
Mark Lobodzinski22a1c992019-08-15 11:20:06 -06001163 ' for (uint32_t i = 0; i < stageCount; ++i) {\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001164 ' pStages[i].initialize(&src.pStages[i]);\n'
1165 ' }\n'
1166 ' }\n'
1167 ' if (src.pVertexInputState)\n'
1168 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
1169 ' else\n'
1170 ' pVertexInputState = NULL;\n'
1171 ' if (src.pInputAssemblyState)\n'
1172 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
1173 ' else\n'
1174 ' pInputAssemblyState = NULL;\n'
1175 ' bool has_tessellation_stage = false;\n'
1176 ' if (stageCount && pStages)\n'
Mark Lobodzinski22a1c992019-08-15 11:20:06 -06001177 ' for (uint32_t i = 0; i < stageCount && !has_tessellation_stage; ++i)\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001178 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1179 ' has_tessellation_stage = true;\n'
1180 ' if (src.pTessellationState && has_tessellation_stage)\n'
1181 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
1182 ' else\n'
1183 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1184 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
1185 ' if (src.pViewportState && has_rasterization) {\n'
1186 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
1187 ' } else\n'
1188 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1189 ' if (src.pRasterizationState)\n'
1190 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
1191 ' else\n'
1192 ' pRasterizationState = NULL;\n'
1193 ' if (src.pMultisampleState && has_rasterization)\n'
1194 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
1195 ' else\n'
1196 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1197 ' if (src.pDepthStencilState && has_rasterization)\n'
1198 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
1199 ' else\n'
1200 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1201 ' if (src.pColorBlendState && has_rasterization)\n'
1202 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1203 ' else\n'
1204 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1205 ' if (src.pDynamicState)\n'
1206 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1207 ' else\n'
1208 ' pDynamicState = NULL;\n',
1209 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1210 'VkPipelineViewportStateCreateInfo' :
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001211 ' pNext = SafePnextCopy(src.pNext);\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001212 ' if (src.pViewports) {\n'
1213 ' pViewports = new VkViewport[src.viewportCount];\n'
1214 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1215 ' }\n'
1216 ' else\n'
1217 ' pViewports = NULL;\n'
1218 ' if (src.pScissors) {\n'
1219 ' pScissors = new VkRect2D[src.scissorCount];\n'
1220 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1221 ' }\n'
1222 ' else\n'
1223 ' pScissors = NULL;\n',
1224 }
1225
Mike Schuchardt81485762017-09-04 11:38:42 -06001226 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1227 ' if (pCode)\n'
1228 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001229 copy_pnext = ''
Mark Lobodzinskia27a75e2019-08-13 14:10:03 -06001230 copy_strings = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001231 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001232 m_type = member.type
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001233 if member.name == 'pNext':
1234 copy_pnext = ' pNext = SafePnextCopy(in_struct->pNext);\n'
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001235 if member.type in self.structNames:
1236 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1237 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1238 m_type = 'safe_%s' % member.type
1239 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1240 # 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 -07001241 if m_type in ['void', 'char']:
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001242 if member.name != 'pNext':
Mark Lobodzinskia27a75e2019-08-13 14:10:03 -06001243 if m_type == 'char':
1244 # Create deep copies of strings
1245 if member.len:
Petr Kraus956e9712019-08-18 16:22:59 +02001246 copy_strings += ' char **tmp_%s = new char *[in_struct->%s];\n' % (member.name, member.len)
Mark Lobodzinskia27a75e2019-08-13 14:10:03 -06001247 copy_strings += ' for (uint32_t i = 0; i < %s; ++i) {\n' % member.len
Petr Kraus956e9712019-08-18 16:22:59 +02001248 copy_strings += ' tmp_%s[i] = SafeStringCopy(in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskia27a75e2019-08-13 14:10:03 -06001249 copy_strings += ' }\n'
Petr Kraus956e9712019-08-18 16:22:59 +02001250 copy_strings += ' %s = tmp_%s;\n' % (member.name, member.name)
Mark Lobodzinskia27a75e2019-08-13 14:10:03 -06001251
1252 destruct_txt += ' if (%s) {\n' % member.name
1253 destruct_txt += ' for (uint32_t i = 0; i < %s; ++i) {\n' % member.len
1254 destruct_txt += ' delete [] %s[i];\n' % member.name
1255 destruct_txt += ' }\n'
1256 destruct_txt += ' delete [] %s;\n' % member.name
1257 destruct_txt += ' }\n'
1258 else:
1259 copy_strings += ' %s = SafeStringCopy(in_struct->%s);\n' % (member.name, member.name)
1260 destruct_txt += ' if (%s) delete [] %s;\n' % (member.name, member.name)
1261 else:
1262 # For these exceptions just copy initial value over for now
1263 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1264 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinski692f3f32019-08-13 14:00:52 -06001265 default_init_list += '\n %s(nullptr),' % (member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001266 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001267 default_init_list += '\n %s(nullptr),' % (member.name)
1268 init_list += '\n %s(nullptr),' % (member.name)
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001269 if m_type in abstract_types:
1270 construct_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1271 else:
1272 init_func_txt += ' %s = nullptr;\n' % (member.name)
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001273 if not member.isstaticarray and (member.len is None or '/' in member.len):
1274 construct_txt += ' if (in_struct->%s) {\n' % member.name
1275 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1276 construct_txt += ' }\n'
1277 destruct_txt += ' if (%s)\n' % member.name
1278 destruct_txt += ' delete %s;\n' % member.name
1279 else:
1280 construct_txt += ' if (in_struct->%s) {\n' % member.name
1281 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1282 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1283 construct_txt += ' }\n'
1284 destruct_txt += ' if (%s)\n' % member.name
1285 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001286 elif member.isstaticarray or member.len is not None:
1287 if member.len is None:
1288 # Extract length of static array by grabbing val between []
1289 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
Mark Lobodzinski22a1c992019-08-15 11:20:06 -06001290 construct_txt += ' for (uint32_t i = 0; i < %s; ++i) {\n' % static_array_size.group(1)
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001291 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1292 construct_txt += ' }\n'
1293 else:
1294 # Init array ptr to NULL
1295 default_init_list += '\n %s(nullptr),' % member.name
1296 init_list += '\n %s(nullptr),' % member.name
1297 init_func_txt += ' %s = nullptr;\n' % member.name
1298 array_element = 'in_struct->%s[i]' % member.name
1299 if member.type in self.structNames:
1300 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1301 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1302 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1303 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1304 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1305 destruct_txt += ' if (%s)\n' % member.name
1306 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinski22a1c992019-08-15 11:20:06 -06001307 construct_txt += ' for (uint32_t i = 0; i < %s; ++i) {\n' % (member.len)
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001308 if 'safe_' in m_type:
1309 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001310 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001311 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1312 construct_txt += ' }\n'
1313 construct_txt += ' }\n'
1314 elif member.ispointer == True:
1315 construct_txt += ' if (in_struct->%s)\n' % member.name
1316 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1317 construct_txt += ' else\n'
1318 construct_txt += ' %s = NULL;\n' % member.name
1319 destruct_txt += ' if (%s)\n' % member.name
1320 destruct_txt += ' delete %s;\n' % member.name
1321 elif 'safe_' in m_type:
1322 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1323 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1324 else:
1325 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1326 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1327 if '' != init_list:
1328 init_list = init_list[:-1] # hack off final comma
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001329
1330
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001331 if item.name in custom_construct_txt:
1332 construct_txt = custom_construct_txt[item.name]
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001333
Mark Lobodzinskia27a75e2019-08-13 14:10:03 -06001334 construct_txt = copy_pnext + copy_strings + construct_txt
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001335
Mike Schuchardt81485762017-09-04 11:38:42 -06001336 if item.name in custom_destruct_txt:
1337 destruct_txt = custom_destruct_txt[item.name]
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001338
1339 if copy_pnext:
1340 destruct_txt += ' if (pNext)\n FreePnextChain(pNext);\n'
1341
Petr Krause91f7a12017-12-14 20:57:36 +01001342 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 -07001343 if '' != default_init_list:
1344 default_init_list = " :%s" % (default_init_list[:-1])
1345 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1346 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1347 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001348 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1349 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1350 copy_construct_txt = re.sub('(new \\w+)\\(in_struct->', '\\1(*src.', construct_txt) # Pass object to copy constructors
1351 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001352 if item.name in custom_copy_txt:
1353 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001354 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 -06001355 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 -07001356 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 -07001357 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001358 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 -07001359 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1360 init_copy = copy_construct_init.replace('src.', 'src->')
1361 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001362 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 +01001363 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001364 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1365 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001366 #
John Zulaufde972ac2017-10-26 12:07:05 -06001367 # Generate the type map
1368 def GenerateTypeMapHelperHeader(self):
1369 prefix = 'Lvl'
1370 fprefix = 'lvl_'
1371 typemap = prefix + 'TypeMap'
1372 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001373 type_member = 'Type'
1374 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001375 id_decl = 'static const VkStructureType '
Locke6b6b7382019-04-16 15:08:49 -06001376 generic_header = 'VkBaseOutStructure'
John Zulaufde972ac2017-10-26 12:07:05 -06001377 typename_func = fprefix + 'typename'
1378 idname_func = fprefix + 'stype_name'
1379 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001380 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001381
1382 explanatory_comment = '\n'.join((
1383 '// These empty generic templates are specialized for each type with sType',
1384 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001385 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001386
1387 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1388 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001389 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1390 typemap_format += '}};\n'
1391
1392 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1393 idmap_format = ''.join((
1394 'template <> struct {template}<{id_value}> {{\n',
1395 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001396 '}};\n'))
1397
1398 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1399 utilities_format = '\n'.join((
John Zulaufde972ac2017-10-26 12:07:05 -06001400 '// Find an entry of the given type in the pNext chain',
1401 'template <typename T> const T *{find_func}(const void *next) {{',
1402 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1403 ' const T *found = nullptr;',
1404 ' while (current) {{',
1405 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1406 ' found = reinterpret_cast<const T*>(current);',
1407 ' current = nullptr;',
1408 ' }} else {{',
1409 ' current = current->pNext;',
1410 ' }}',
1411 ' }}',
1412 ' return found;',
1413 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001414 '',
1415 '// Init the header of an sType struct with pNext',
1416 'template <typename T> T {init_func}(void *p_next) {{',
1417 ' T out = {{}};',
1418 ' out.sType = {type_map}<T>::kSType;',
1419 ' out.pNext = p_next;',
1420 ' return out;',
1421 '}}',
1422 '',
1423 '// Init the header of an sType struct',
1424 'template <typename T> T {init_func}() {{',
1425 ' T out = {{}};',
1426 ' out.sType = {type_map}<T>::kSType;',
1427 ' return out;',
1428 '}}',
1429
Mike Schuchardt97662b02017-12-06 13:31:29 -07001430 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001431
1432 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001433
1434 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001435 code.append('\n'.join((
1436 '#pragma once',
1437 '#include <vulkan/vulkan.h>\n',
1438 explanatory_comment, '',
1439 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001440 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001441
1442 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001443 for item in self.structMembers:
1444 typename = item.name
1445 info = self.structTypes.get(typename)
1446 if not info:
1447 continue
1448
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001449 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001450 code.append('#ifdef %s' % item.ifdef_protect)
1451
1452 code.append('// Map type {} to id {}'.format(typename, info.value))
1453 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001454 id_decl=id_decl, id_member=id_member))
1455 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001456
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001457 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001458 code.append('#endif // %s' % item.ifdef_protect)
1459
John Zulauf65ac9d52018-01-23 11:20:50 -07001460 # Generate utilities for all types
1461 code.append('\n'.join((
1462 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1463 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1464 find_func=find_func, init_func=init_func), ''
1465 )))
1466
John Zulaufde972ac2017-10-26 12:07:05 -06001467 return "\n".join(code)
1468
1469 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001470 # Create a helper file and return it as a string
1471 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001472 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001473 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001474 elif self.helper_file_type == 'safe_struct_header':
1475 return self.GenerateSafeStructHelperHeader()
1476 elif self.helper_file_type == 'safe_struct_source':
1477 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001478 elif self.helper_file_type == 'object_types_header':
1479 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001480 elif self.helper_file_type == 'extension_helper_header':
1481 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001482 elif self.helper_file_type == 'typemap_helper_header':
1483 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001484 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001485 return 'Bad Helper File Generator Option %s' % self.helper_file_type