blob: cbf279d3d811b0ec09d63af53112f6ee7f314739 [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':
208 item_name = elem.get('name')
209 self.debug_report_object_types.append(item_name)
210 elif groupName == 'VkObjectType':
211 for elem in groupElem.findall('enum'):
212 if elem.get('supported') != 'disabled':
213 item_name = elem.get('name')
214 self.core_object_types.append(item_name)
215
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700216 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700217 # Called for each type -- if the type is a struct/union, grab the metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700218 def genType(self, typeinfo, name, alias):
219 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700220 typeElem = typeinfo.elem
221 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
222 # Otherwise, emit the tag text.
223 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600224 if category == 'handle':
John Zulaufd7435c62018-03-16 11:52:57 -0600225 if alias:
226 self.object_type_aliases.append((name,alias))
227 else:
228 self.object_types.append(name)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600229 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700230 self.structNames.append(name)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700231 self.genStruct(typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700232 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700233 # Check if the parameter passed in is a pointer
234 def paramIsPointer(self, param):
235 ispointer = False
236 for elem in param:
Raul Tambre7b300182019-05-04 11:25:14 +0300237 if elem.tag == 'type' and elem.tail is not None and '*' in elem.tail:
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700238 ispointer = True
239 return ispointer
240 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700241 # Check if the parameter passed in is a static array
242 def paramIsStaticArray(self, param):
243 isstaticarray = 0
244 paramname = param.find('name')
245 if (paramname.tail is not None) and ('[' in paramname.tail):
246 isstaticarray = paramname.tail.count('[')
247 return isstaticarray
248 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700249 # Retrieve the type and name for a parameter
250 def getTypeNameTuple(self, param):
251 type = ''
252 name = ''
253 for elem in param:
254 if elem.tag == 'type':
255 type = noneStr(elem.text)
256 elif elem.tag == 'name':
257 name = noneStr(elem.text)
258 return (type, name)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700259 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
260 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
261 def parseLateXMath(self, source):
262 name = 'ERROR'
263 decoratedName = 'ERROR'
264 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700265 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
266 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 -0700267 if not match or match.group(1) != match.group(4):
268 raise 'Unrecognized latexmath expression'
269 name = match.group(2)
mizhenc27f6c72017-03-31 09:08:16 -0600270 # Need to add 1 for ceiling function; otherwise, the allocated packet
271 # size will be less than needed during capture for some title which use
272 # this in VkPipelineMultisampleStateCreateInfo. based on ceiling function
273 # definition,it is '{0}%{1}?{0}/{1} + 1:{0}/{1}'.format(*match.group(2, 3)),
274 # its value <= '{}/{} + 1'.
275 if match.group(1) == 'ceil':
276 decoratedName = '{}/{} + 1'.format(*match.group(2, 3))
277 else:
278 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700279 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700280 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600281 match = re.match(r'latexmath\s*\:\s*\[\s*(\\textrm\{)?(\w+)\}?\s*\\over\s*(\d+)\s*\]', source)
282 name = match.group(2)
283 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700284 return name, decoratedName
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700285 #
286 # Retrieve the value of the len tag
287 def getLen(self, param):
288 result = None
289 len = param.attrib.get('len')
290 if len and len != 'null-terminated':
291 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
292 # have a null terminated array of strings. We strip the null-terminated from the
293 # 'len' field and only return the parameter specifying the string count
294 if 'null-terminated' in len:
295 result = len.split(',')[0]
296 else:
297 result = len
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700298 if 'latexmath' in len:
299 param_type, param_name = self.getTypeNameTuple(param)
300 len_name, result = self.parseLateXMath(len)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700301 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
302 result = str(result).replace('::', '->')
303 return result
304 #
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600305 # Check if a structure is or contains a dispatchable (dispatchable = True) or
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700306 # non-dispatchable (dispatchable = False) handle
307 def TypeContainsObjectHandle(self, handle_type, dispatchable):
308 if dispatchable:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700309 type_check = self.handle_types.IsDispatchable
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700310 else:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700311 type_check = self.handle_types.IsNonDispatchable
312 if type_check(handle_type):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700313 return True
314 # if handle_type is a struct, search its members
315 if handle_type in self.structNames:
316 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == handle_type), None)
317 if member_index is not None:
318 for item in self.structMembers[member_index].members:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700319 if type_check(item.type):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700320 return True
321 return False
322 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700323 # Generate local ready-access data describing Vulkan structures and unions from the XML metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700324 def genStruct(self, typeinfo, typeName, alias):
325 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700326 members = typeinfo.elem.findall('.//member')
327 # Iterate over members once to get length parameters for arrays
328 lens = set()
329 for member in members:
330 len = self.getLen(member)
331 if len:
332 lens.add(len)
333 # Generate member info
334 membersInfo = []
335 for member in members:
336 # Get the member's type and name
337 info = self.getTypeNameTuple(member)
338 type = info[0]
339 name = info[1]
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700340 cdecl = self.makeCParamDecl(member, 1)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700341 # Process VkStructureType
342 if type == 'VkStructureType':
343 # Extract the required struct type value from the comments
344 # embedded in the original text defining the 'typeinfo' element
345 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
346 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
347 if result:
348 value = result.group(0)
Mike Schuchardt08368cb2018-05-22 14:52:04 -0600349 # Store the required type value
350 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700351 # Store pointer/array/string info
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700352 isstaticarray = self.paramIsStaticArray(member)
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600353 structextends = False
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700354 membersInfo.append(self.CommandParam(type=type,
355 name=name,
356 ispointer=self.paramIsPointer(member),
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700357 isstaticarray=isstaticarray,
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700358 isconst=True if 'const' in cdecl else False,
359 iscount=True if name in lens else False,
360 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600361 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700362 cdecl=cdecl))
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600363 # If this struct extends another, keep its name in list for further processing
364 if typeinfo.elem.attrib.get('structextends') is not None:
365 self.structextends_list.append(typeName)
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700366 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo, ifdef_protect=self.featureExtraProtect))
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700367 #
368 # Enum_string_header: Create a routine to convert an enumerated value into a string
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700369 def GenerateEnumStringConversion(self, groupName, value_list):
370 outstring = '\n'
Mike Schuchardt21638df2019-03-16 10:52:02 -0700371 if self.featureExtraProtect is not None:
372 outstring += '\n#ifdef %s\n\n' % self.featureExtraProtect
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700373 outstring += 'static inline const char* string_%s(%s input_value)\n' % (groupName, groupName)
374 outstring += '{\n'
375 outstring += ' switch ((%s)input_value)\n' % groupName
376 outstring += ' {\n'
Karl Schultz7fd3f6e2018-07-05 17:21:05 -0600377 # Emit these in a repeatable order so file is generated with the same contents each time.
378 # This helps compiler caching systems like ccache.
379 for item in sorted(value_list):
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700380 outstring += ' case %s:\n' % item
381 outstring += ' return "%s";\n' % item
382 outstring += ' default:\n'
383 outstring += ' return "Unhandled %s";\n' % groupName
384 outstring += ' }\n'
385 outstring += '}\n'
unknown84220292019-07-01 17:09:36 -0600386
387 bitsIndex = groupName.find('Bits')
388 if (bitsIndex != -1):
389 outstring += '\n'
390 flagsName = groupName[0:bitsIndex] + "s" + groupName[bitsIndex+4:]
391 outstring += 'static inline std::string string_%s(%s input_value)\n' % (flagsName, flagsName)
392 outstring += '{\n'
393 outstring += ' std::string ret;\n'
394 outstring += ' int index = 0;\n'
395 outstring += ' while(input_value) {\n'
396 outstring += ' if (input_value & 1) {\n'
397 outstring += ' if( !ret.empty()) ret.append("|");\n'
398 outstring += ' ret.append(string_%s(static_cast<%s>(1 << index)));\n' % (groupName, groupName)
399 outstring += ' }\n'
400 outstring += ' ++index;\n'
401 outstring += ' input_value >>= 1;\n'
402 outstring += ' }\n'
403 outstring += ' if( ret.empty()) ret.append(string_%s(static_cast<%s>(0)));\n' % (groupName, groupName)
404 outstring += ' return ret;\n'
405 outstring += '}\n'
406
Mike Schuchardt21638df2019-03-16 10:52:02 -0700407 if self.featureExtraProtect is not None:
408 outstring += '#endif // %s\n' % self.featureExtraProtect
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700409 return outstring
410 #
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600411 # Tack on a helper which, given an index into a VkPhysicalDeviceFeatures structure, will print the corresponding feature name
412 def DeIndexPhysDevFeatures(self):
413 pdev_members = None
414 for name, members, ifdef in self.structMembers:
415 if name == 'VkPhysicalDeviceFeatures':
416 pdev_members = members
417 break
418 deindex = '\n'
Mark Young2ee6aea2018-02-21 15:30:27 -0700419 deindex += 'static inline const char * GetPhysDevFeatureString(uint32_t index) {\n'
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600420 deindex += ' const char * IndexToPhysDevFeatureString[] = {\n'
421 for feature in pdev_members:
422 deindex += ' "%s",\n' % feature.name
423 deindex += ' };\n\n'
424 deindex += ' return IndexToPhysDevFeatureString[index];\n'
425 deindex += '}\n'
426 return deindex
427 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700428 # Combine enum string helper header file preamble with body text and return
429 def GenerateEnumStringHelperHeader(self):
430 enum_string_helper_header = '\n'
431 enum_string_helper_header += '#pragma once\n'
432 enum_string_helper_header += '#ifdef _WIN32\n'
433 enum_string_helper_header += '#pragma warning( disable : 4065 )\n'
434 enum_string_helper_header += '#endif\n'
435 enum_string_helper_header += '\n'
David Pinedoddbb7fb2019-07-22 11:36:51 -0600436 enum_string_helper_header += '#include <string>\n'
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700437 enum_string_helper_header += '#include <vulkan/vulkan.h>\n'
438 enum_string_helper_header += '\n'
439 enum_string_helper_header += self.enum_output
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600440 enum_string_helper_header += self.DeIndexPhysDevFeatures()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700441 return enum_string_helper_header
442 #
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700443 # Helper function for declaring a counter variable only once
444 def DeclareCounter(self, string_var, declare_flag):
445 if declare_flag == False:
446 string_var += ' uint32_t i = 0;\n'
447 declare_flag = True
448 return string_var, declare_flag
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700449 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700450 # Combine safe struct helper header file preamble with body text and return
451 def GenerateSafeStructHelperHeader(self):
452 safe_struct_helper_header = '\n'
453 safe_struct_helper_header += '#pragma once\n'
454 safe_struct_helper_header += '#include <vulkan/vulkan.h>\n'
Mark Lobodzinskidb8affe2019-08-08 13:25:07 -0600455 safe_struct_helper_header += '#include <vulkan/vk_layer.h>\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700456 safe_struct_helper_header += '\n'
Mark Lobodzinski7245fce2019-07-18 16:18:51 -0600457 safe_struct_helper_header += 'void *SafePnextCopy(const void *pNext);\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600458 safe_struct_helper_header += 'void FreePnextChain(const void *head);\n'
Mark Lobodzinski7245fce2019-07-18 16:18:51 -0600459 safe_struct_helper_header += 'void FreePnextChain(void *head);\n'
460 safe_struct_helper_header += '\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700461 safe_struct_helper_header += self.GenerateSafeStructHeader()
462 return safe_struct_helper_header
463 #
464 # safe_struct header: build function prototypes for header file
465 def GenerateSafeStructHeader(self):
466 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700467 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700468 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700469 safe_struct_header += '\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100470 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700471 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
472 safe_struct_header += 'struct safe_%s {\n' % (item.name)
473 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700474 if member.type in self.structNames:
475 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
476 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
477 if member.ispointer:
478 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
479 else:
480 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
481 continue
482 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
483 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
484 else:
485 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100486 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 -0600487 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700488 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700489 safe_struct_header += ' safe_%s();\n' % item.name
490 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100491 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
492 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700493 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
494 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
495 safe_struct_header += '};\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100496 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700497 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700498 return safe_struct_header
499 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600500 # Generate extension helper header file
501 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600502
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600503 V_1_1_level_feature_set = [
504 'VK_VERSION_1_1',
505 ]
506
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600507 V_1_0_instance_extensions_promoted_to_V_1_1_core = [
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600508 'vk_khr_device_group_creation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600509 'vk_khr_external_fence_capabilities',
John Zulauf2012bca2018-04-25 15:28:47 -0600510 'vk_khr_external_memory_capabilities',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600511 'vk_khr_external_semaphore_capabilities',
512 'vk_khr_get_physical_device_properties_2',
513 ]
514
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600515 V_1_0_device_extensions_promoted_to_V_1_1_core = [
John Zulauf2012bca2018-04-25 15:28:47 -0600516 'vk_khr_16bit_storage',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600517 'vk_khr_bind_memory_2',
John Zulauf2012bca2018-04-25 15:28:47 -0600518 'vk_khr_dedicated_allocation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600519 'vk_khr_descriptor_update_template',
John Zulauf2012bca2018-04-25 15:28:47 -0600520 'vk_khr_device_group',
521 'vk_khr_external_fence',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600522 'vk_khr_external_memory',
523 'vk_khr_external_semaphore',
John Zulauf2012bca2018-04-25 15:28:47 -0600524 'vk_khr_get_memory_requirements_2',
525 'vk_khr_maintenance1',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600526 'vk_khr_maintenance2',
John Zulauf2012bca2018-04-25 15:28:47 -0600527 'vk_khr_maintenance3',
528 'vk_khr_multiview',
John Zulauf16826822018-04-25 15:40:32 -0600529 'vk_khr_relaxed_block_layout',
John Zulauf2012bca2018-04-25 15:28:47 -0600530 'vk_khr_sampler_ycbcr_conversion',
John Zulauf16826822018-04-25 15:40:32 -0600531 'vk_khr_shader_draw_parameters',
532 'vk_khr_storage_buffer_storage_class',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600533 'vk_khr_variable_pointers',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600534 ]
John Zulauf16826822018-04-25 15:40:32 -0600535
John Zulauff6feb2a2018-04-12 14:24:57 -0600536 output = [
537 '',
538 '#ifndef VK_EXTENSION_HELPER_H_',
539 '#define VK_EXTENSION_HELPER_H_',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600540 '#include <unordered_set>',
John Zulauf072677c2018-04-12 15:34:39 -0600541 '#include <string>',
542 '#include <unordered_map>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600543 '#include <utility>',
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600544 '#include <set>',
Mark Lobodzinskif94196f2019-07-11 11:46:09 -0600545 '#include <vector>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600546 '',
John Zulauf072677c2018-04-12 15:34:39 -0600547 '#include <vulkan/vulkan.h>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600548 '']
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600549
John Zulauff6feb2a2018-04-12 14:24:57 -0600550 def guarded(ifdef, value):
551 if ifdef is not None:
552 return '\n'.join([ '#ifdef %s' % ifdef, value, '#endif' ])
553 else:
554 return value
John Zulauf380bd942018-04-10 13:12:34 -0600555
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600556 for type in ['Instance', 'Device']:
John Zulauff6feb2a2018-04-12 14:24:57 -0600557 struct_type = '%sExtensions' % type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600558 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600559 extension_dict = self.instance_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600560 promoted_ext_list = V_1_0_instance_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600561 struct_decl = 'struct %s {' % struct_type
562 instance_struct_type = struct_type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600563 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600564 extension_dict = self.device_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600565 promoted_ext_list = V_1_0_device_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600566 struct_decl = 'struct %s : public %s {' % (struct_type, instance_struct_type)
567
568 extension_items = sorted(extension_dict.items())
569
570 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 -0600571
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600572 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600573 instance_field_name = field_name
John Zulauf072677c2018-04-12 15:34:39 -0600574 instance_extension_dict = extension_dict
575 else:
576 # Get complete field name and extension data for both Instance and Device extensions
577 field_name.update(instance_field_name)
578 extension_dict = extension_dict.copy() # Don't modify the self.<dict> we're pointing to
579 extension_dict.update(instance_extension_dict)
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600580
John Zulauf072677c2018-04-12 15:34:39 -0600581 # Output the data member list
John Zulauff6feb2a2018-04-12 14:24:57 -0600582 struct = [struct_decl]
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600583 struct.extend([ ' bool vk_feature_version_1_1{false};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600584 struct.extend([ ' bool %s{false};' % field_name[ext_name] for ext_name, info in extension_items])
John Zulauf072677c2018-04-12 15:34:39 -0600585
586 # Construct the extension information map -- mapping name to data member (field), and required extensions
587 # The map is contained within a static function member for portability reasons.
588 info_type = '%sInfo' % type
589 info_map_type = '%sMap' % info_type
590 req_type = '%sReq' % type
591 req_vec_type = '%sVec' % req_type
592 struct.extend([
593 '',
594 ' struct %s {' % req_type,
595 ' const bool %s::* enabled;' % struct_type,
596 ' const char *name;',
597 ' };',
598 ' typedef std::vector<%s> %s;' % (req_type, req_vec_type),
599 ' struct %s {' % info_type,
600 ' %s(bool %s::* state_, const %s requires_): state(state_), requires(requires_) {}' % ( info_type, struct_type, req_vec_type),
601 ' bool %s::* state;' % struct_type,
602 ' %s requires;' % req_vec_type,
603 ' };',
604 '',
605 ' typedef std::unordered_map<std::string,%s> %s;' % (info_type, info_map_type),
606 ' static const %s &get_info(const char *name) {' %info_type,
607 ' static const %s info_map = {' % info_map_type ])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600608 struct.extend([
609 ' std::make_pair("VK_VERSION_1_1", %sInfo(&%sExtensions::vk_feature_version_1_1, {})),' % (type, type)])
John Zulauf072677c2018-04-12 15:34:39 -0600610
611 field_format = '&' + struct_type + '::%s'
612 req_format = '{' + field_format+ ', %s}'
613 req_indent = '\n '
614 req_join = ',' + req_indent
615 info_format = (' std::make_pair(%s, ' + info_type + '(' + field_format + ', {%s})),')
616 def format_info(ext_name, info):
617 reqs = req_join.join([req_format % (field_name[req], extension_dict[req]['define']) for req in info['reqs']])
618 return info_format % (info['define'], field_name[ext_name], '{%s}' % (req_indent + reqs) if reqs else '')
619
620 struct.extend([guarded(info['ifdef'], format_info(ext_name, info)) for ext_name, info in extension_items])
621 struct.extend([
622 ' };',
623 '',
624 ' static const %s empty_info {nullptr, %s()};' % (info_type, req_vec_type),
625 ' %s::const_iterator info = info_map.find(name);' % info_map_type,
626 ' if ( info != info_map.cend()) {',
627 ' return info->second;',
628 ' }',
629 ' return empty_info;',
630 ' }',
631 ''])
632
John Zulauff6feb2a2018-04-12 14:24:57 -0600633 if type == 'Instance':
634 struct.extend([
635 ' uint32_t NormalizeApiVersion(uint32_t specified_version) {',
636 ' uint32_t api_version = (specified_version < VK_API_VERSION_1_1) ? VK_API_VERSION_1_0 : VK_API_VERSION_1_1;',
637 ' return api_version;',
638 ' }',
639 '',
640 ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {'])
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600641 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600642 struct.extend([
John Zulauf072677c2018-04-12 15:34:39 -0600643 ' %s() = default;' % struct_type,
644 ' %s(const %s& instance_ext) : %s(instance_ext) {}' % (struct_type, instance_struct_type, instance_struct_type),
645 '',
646 ' uint32_t InitFromDeviceCreateInfo(const %s *instance_extensions, uint32_t requested_api_version,' % instance_struct_type,
647 ' const VkDeviceCreateInfo *pCreateInfo) {',
648 ' // Initialize: this to defaults, base class fields to input.',
649 ' assert(instance_extensions);',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600650 ' *this = %s(*instance_extensions);' % struct_type,
Mark Lobodzinskid5f83b92018-12-14 11:02:08 -0700651 '']),
652 struct.extend([
John Zulauff6feb2a2018-04-12 14:24:57 -0600653 '',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600654 ' static const std::vector<const char *> V_1_1_promoted_%s_apis = {' % type.lower() ])
John Zulauff6feb2a2018-04-12 14:24:57 -0600655 struct.extend([' %s_EXTENSION_NAME,' % ext_name.upper() for ext_name in promoted_ext_list])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600656 struct.extend([' "VK_VERSION_1_1",'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600657 struct.extend([
658 ' };',
659 '',
John Zulauf072677c2018-04-12 15:34:39 -0600660 ' // Initialize struct data, robust to invalid pCreateInfo',
661 ' if (pCreateInfo->ppEnabledExtensionNames) {',
662 ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {',
663 ' if (!pCreateInfo->ppEnabledExtensionNames[i]) continue;',
664 ' auto info = get_info(pCreateInfo->ppEnabledExtensionNames[i]);',
665 ' if(info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600666 ' }',
667 ' }',
668 ' uint32_t api_version = NormalizeApiVersion(requested_api_version);',
669 ' if (api_version >= VK_API_VERSION_1_1) {',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600670 ' for (auto promoted_ext : V_1_1_promoted_%s_apis) {' % type.lower(),
John Zulauf072677c2018-04-12 15:34:39 -0600671 ' auto info = get_info(promoted_ext);',
672 ' assert(info.state);',
673 ' if (info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600674 ' }',
675 ' }',
676 ' return api_version;',
677 ' }',
John Zulauf072677c2018-04-12 15:34:39 -0600678 '};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600679
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700680 # Output reference lists of instance/device extension names
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600681 struct.extend(['', 'static const std::set<std::string> k%sExtensionNames = {' % type])
682 struct.extend([guarded(info['ifdef'], ' %s,' % info['define']) for ext_name, info in extension_items])
683 struct.extend(['};', ''])
John Zulauff6feb2a2018-04-12 14:24:57 -0600684 output.extend(struct)
685
686 output.extend(['', '#endif // VK_EXTENSION_HELPER_H_'])
687 return '\n'.join(output)
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600688 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600689 # Combine object types helper header file preamble with body text and return
690 def GenerateObjectTypesHelperHeader(self):
691 object_types_helper_header = '\n'
692 object_types_helper_header += '#pragma once\n'
693 object_types_helper_header += '\n'
694 object_types_helper_header += self.GenerateObjectTypesHeader()
695 return object_types_helper_header
696 #
697 # Object types header: create object enum type header file
698 def GenerateObjectTypesHeader(self):
John Zulauf4fea6622019-04-01 11:38:18 -0600699 object_types_header = '#include "cast_utils.h"\n'
700 object_types_header += '\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700701 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600702 object_types_header += 'typedef enum VulkanObjectType {\n'
703 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
704 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600705 type_list = [];
John Zulaufd7435c62018-03-16 11:52:57 -0600706 enum_entry_map = {}
John Zulauf2c2ccd42019-04-05 13:13:13 -0600707 non_dispatchable = {}
708 dispatchable = {}
709 object_type_info = {}
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600710
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600711 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600712 for item in self.object_types:
713 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600714 enum_entry = 'kVulkanObjectType%s' % fixup_name
John Zulaufd7435c62018-03-16 11:52:57 -0600715 enum_entry_map[item] = enum_entry
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600716 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600717 object_types_header += ' = %d,\n' % enum_num
718 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600719 type_list.append(enum_entry)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600720 object_type_info[enum_entry] = { 'VkType': item }
721 # 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 -0700722 if self.handle_types.IsNonDispatchable(item):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600723 non_dispatchable[item] = enum_entry
724 else:
725 dispatchable[item] = enum_entry
726
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600727 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
John Zulaufd7435c62018-03-16 11:52:57 -0600728 object_types_header += ' // Aliases for backwards compatibilty of "promoted" types\n'
729 for (name, alias) in self.object_type_aliases:
730 fixup_name = name[2:]
731 object_types_header += ' kVulkanObjectType{} = {},\n'.format(fixup_name, enum_entry_map[alias])
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600732 object_types_header += '} VulkanObjectType;\n\n'
733
734 # Output name string helper
735 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600736 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
locke-lunargb4c57852019-06-14 23:20:05 -0600737 object_types_header += ' "VkNonDispatchableHandle",\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600738 for item in self.object_types:
locke-lunargb4c57852019-06-14 23:20:05 -0600739 object_types_header += ' "%s",\n' % item
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600740 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600741
John Zulauf311a4892018-03-12 15:48:06 -0600742 # Key creation helper for map comprehensions that convert between k<Name> and VK<Name> symbols
743 def to_key(regex, raw_key): return re.search(regex, raw_key).group(1).lower().replace("_","")
744
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600745 # Output a conversion routine from the layer object definitions to the debug report definitions
John Zulauf311a4892018-03-12 15:48:06 -0600746 # As the VK_DEBUG_REPORT types are not being updated, specify UNKNOWN for unmatched types
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600747 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600748 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 -0600749 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700750 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000751
John Zulauf311a4892018-03-12 15:48:06 -0600752 dbg_re = '^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$'
753 dbg_map = {to_key(dbg_re, dbg) : dbg for dbg in self.debug_report_object_types}
754 dbg_default = 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600755
John Zulauf311a4892018-03-12 15:48:06 -0600756 for object_type in type_list:
757 vk_object_type = dbg_map.get(object_type.replace("kVulkanObjectType", "").lower(), dbg_default)
758 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600759 object_type_info[object_type]['DbgType'] = vk_object_type
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600760 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600761
762 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600763 # 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 -0600764 object_types_header += '\n'
765 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
766 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700767 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
John Zulauf311a4892018-03-12 15:48:06 -0600768
769 vko_re = '^VK_OBJECT_TYPE_(.*)'
770 vko_map = {to_key(vko_re, vko) : vko for vko in self.core_object_types}
Mark Young1ded24b2017-05-30 14:53:50 -0600771 for object_type in type_list:
John Zulauf311a4892018-03-12 15:48:06 -0600772 vk_object_type = vko_map[object_type.replace("kVulkanObjectType", "").lower()]
773 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600774 object_type_info[object_type]['VkoType'] = vk_object_type
Mark Young1ded24b2017-05-30 14:53:50 -0600775 object_types_header += '};\n'
776
Mark Young6ba8abe2017-11-09 10:37:04 -0700777 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
778 object_types_header += '\n'
779 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600780 object_types_header += 'static inline VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700781 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
782 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
783 for core_object_type in self.core_object_types:
784 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
785 core_target_type = core_target_type.replace("_", "")
786 for dr_object_type in self.debug_report_object_types:
787 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
788 dr_target_type = dr_target_type[:-4]
789 dr_target_type = dr_target_type.replace("_", "")
790 if core_target_type == dr_target_type:
791 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
792 object_types_header += ' return %s;\n' % core_object_type
793 break
794 object_types_header += ' }\n'
795 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
796 object_types_header += '}\n'
797
798 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
799 object_types_header += '\n'
800 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600801 object_types_header += 'static inline VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700802 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
803 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
804 for core_object_type in self.core_object_types:
805 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
806 core_target_type = core_target_type.replace("_", "")
807 for dr_object_type in self.debug_report_object_types:
808 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
809 dr_target_type = dr_target_type[:-4]
810 dr_target_type = dr_target_type.replace("_", "")
811 if core_target_type == dr_target_type:
812 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
813 object_types_header += ' return %s;\n' % dr_object_type
814 break
815 object_types_header += ' }\n'
816 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
817 object_types_header += '}\n'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600818
819 traits_format = Outdent('''
820 template <> struct VkHandleInfo<{vk_type}> {{
821 static const VulkanObjectType kVulkanObjectType = {obj_type};
822 static const VkDebugReportObjectTypeEXT kDebugReportObjectType = {dbg_type};
823 static const VkObjectType kVkObjectType = {vko_type};
824 static const char* Typename() {{
825 return "{vk_type}";
826 }}
827 }};
828 template <> struct VulkanObjectTypeInfo<{obj_type}> {{
829 typedef {vk_type} Type;
830 }};
831 ''')
832
833 object_types_header += Outdent('''
834 // Traits objects from each type statically map from Vk<handleType> to the various enums
835 template <typename VkType> struct VkHandleInfo {};
836 template <VulkanObjectType id> struct VulkanObjectTypeInfo {};
837
838 // The following line must match the vulkan_core.h condition guarding VK_DEFINE_NON_DISPATCHABLE_HANDLE
839 #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || \
840 defined(_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
841 #define TYPESAFE_NONDISPATCHABLE_HANDLES
842 #else
843 VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkNonDispatchableHandle)
844 ''') +'\n'
845 object_types_header += traits_format.format(vk_type='VkNonDispatchableHandle', obj_type='kVulkanObjectTypeUnknown',
846 dbg_type='VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT',
847 vko_type='VK_OBJECT_TYPE_UNKNOWN') + '\n'
848 object_types_header += '#endif // VK_DEFINE_HANDLE logic duplication\n'
849
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700850 for vk_type, object_type in sorted(dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600851 info = object_type_info[object_type]
852 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
853 vko_type=info['VkoType'])
854 object_types_header += '#ifdef TYPESAFE_NONDISPATCHABLE_HANDLES\n'
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700855 for vk_type, object_type in sorted(non_dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600856 info = object_type_info[object_type]
857 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
858 vko_type=info['VkoType'])
859 object_types_header += '#endif // TYPESAFE_NONDISPATCHABLE_HANDLES\n'
860
861 object_types_header += Outdent('''
862 struct VulkanTypedHandle {
863 uint64_t handle;
864 VulkanObjectType type;
865 template <typename Handle>
John Zulauf4fea6622019-04-01 11:38:18 -0600866 VulkanTypedHandle(Handle handle_, VulkanObjectType type_) :
867 handle(CastToUint64(handle_)),
868 type(type_) {
869 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
870 // For 32 bit it's not always safe to check for traits <-> type
871 // as all non-dispatchable handles have the same type-id and thus traits,
872 // but on 64 bit we can validate the passed type matches the passed handle
873 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
874 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
875 }
876 template <typename Handle>
877 Handle Cast() const {
878 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
879 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
880 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
881 return CastFromUint64<Handle>(handle);
882 }
John Zulauf2c2ccd42019-04-05 13:13:13 -0600883 VulkanTypedHandle() :
884 handle(VK_NULL_HANDLE),
885 type(kVulkanObjectTypeUnknown) {}
886 }; ''') +'\n'
887
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600888 return object_types_header
889 #
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600890 # Generate pNext handling function
891 def build_pnext_chain_processing_func(self):
892 # Construct helper functions to build and free pNext extension chains
893 build_pnext_proc = '\n\n'
894 build_pnext_proc += 'void *SafePnextCopy(const void *pNext) {\n'
895 build_pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600896 build_pnext_proc += ' void *cur_ext_struct = NULL;\n'
897 build_pnext_proc += ' bool unrecognized_stype = true;\n\n'
898 build_pnext_proc += ' while (unrecognized_stype) {\n'
899 build_pnext_proc += ' unrecognized_stype = false;\n'
900 build_pnext_proc += ' if (cur_pnext == nullptr) {\n'
901 build_pnext_proc += ' return nullptr;\n'
902 build_pnext_proc += ' } else {\n'
903 build_pnext_proc += ' VkBaseOutStructure *header = reinterpret_cast<VkBaseOutStructure *>(cur_pnext);\n\n'
Mark Lobodzinskidb8affe2019-08-08 13:25:07 -0600904 build_pnext_proc += ' switch (header->sType) {\n\n'
905 # Add special-case code to copy beloved secret loader structs
906 build_pnext_proc += ' // Special-case Loader Instance Struct passed to/from layer in pNext chain\n'
907 build_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO: {\n'
908 build_pnext_proc += ' VkLayerInstanceCreateInfo *safe_struct = new VkLayerInstanceCreateInfo;\n'
909 build_pnext_proc += ' memcpy((void *)safe_struct, (void *)cur_pnext, sizeof(VkLayerInstanceCreateInfo));\n'
910 build_pnext_proc += ' safe_struct->pNext = SafePnextCopy(safe_struct->pNext);\n'
911 build_pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
912 build_pnext_proc += ' } break;\n\n'
913 build_pnext_proc += ' // Special-case Loader Device Struct passed to/from layer in pNext chain\n'
914 build_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO: {\n'
915 build_pnext_proc += ' VkLayerDeviceCreateInfo *safe_struct = new VkLayerDeviceCreateInfo;\n'
916 build_pnext_proc += ' memcpy((void *)safe_struct, (void *)cur_pnext, sizeof(VkLayerDeviceCreateInfo));\n'
917 build_pnext_proc += ' safe_struct->pNext = SafePnextCopy(safe_struct->pNext);\n'
918 build_pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
919 build_pnext_proc += ' } break;\n\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600920
921 free_pnext_proc = '\n\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600922 free_pnext_proc += '// Free a const pNext extension chain\n'
923 free_pnext_proc += 'void FreePnextChain(const void *head) {\n'
924 free_pnext_proc += ' FreePnextChain(const_cast<void *>(head));\n'
925 free_pnext_proc += '}\n\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600926 free_pnext_proc += '// Free a pNext extension chain\n'
927 free_pnext_proc += 'void FreePnextChain(void *head) {\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600928 free_pnext_proc += ' if (nullptr == head) return;\n'
929 free_pnext_proc += ' VkBaseOutStructure *header = reinterpret_cast<VkBaseOutStructure *>(head);\n\n'
Mark Lobodzinskidb8affe2019-08-08 13:25:07 -0600930 free_pnext_proc += ' switch (header->sType) {\n\n'
931 free_pnext_proc += ' // Special-case Loader Instance Struct passed to/from layer in pNext chain\n'
932 free_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO: {\n'
933 free_pnext_proc += ' if (header->pNext) FreePnextChain(header->pNext);\n'
934 free_pnext_proc += ' delete reinterpret_cast<VkLayerInstanceCreateInfo *>(head);\n'
935 free_pnext_proc += ' } break;\n\n'
936 free_pnext_proc += ' // Special-case Loader Device Struct passed to/from layer in pNext chain\n'
937 free_pnext_proc += ' case VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO: {\n'
938 free_pnext_proc += ' if (header->pNext) FreePnextChain(header->pNext);\n'
939 free_pnext_proc += ' delete reinterpret_cast<VkLayerDeviceCreateInfo *>(head);\n'
940 free_pnext_proc += ' } break;\n\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600941
942 for item in self.structextends_list:
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600943
944 struct = next((v for v in self.structMembers if v.name == item), None)
945 if struct is None:
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600946 continue
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600947
948 if struct.ifdef_protect is not None:
949 build_pnext_proc += '#ifdef %s\n' % struct.ifdef_protect
950 free_pnext_proc += '#ifdef %s\n' % struct.ifdef_protect
951 build_pnext_proc += ' case %s: {\n' % self.structTypes[item].value
952 build_pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
953 build_pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
954 build_pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
955 build_pnext_proc += ' } break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600956
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600957 free_pnext_proc += ' case %s:\n' % self.structTypes[item].value
958 free_pnext_proc += ' delete reinterpret_cast<safe_%s *>(header);\n' % item
959 free_pnext_proc += ' break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600960
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600961 if struct.ifdef_protect is not None:
962 build_pnext_proc += '#endif // %s\n' % struct.ifdef_protect
963 free_pnext_proc += '#endif // %s\n' % struct.ifdef_protect
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600964 build_pnext_proc += '\n'
965 free_pnext_proc += '\n'
966
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600967 build_pnext_proc += ' default:\n'
968 build_pnext_proc += ' // Encountered an unknown sType -- skip (do not copy) this entry in the chain\n'
969 build_pnext_proc += ' unrecognized_stype = true;\n'
970 build_pnext_proc += ' cur_pnext = header->pNext;\n'
971 build_pnext_proc += ' break;\n'
972 build_pnext_proc += ' }\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600973 build_pnext_proc += ' }\n'
974 build_pnext_proc += ' }\n'
975 build_pnext_proc += ' return cur_ext_struct;\n'
976 build_pnext_proc += '}\n\n'
977
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600978 free_pnext_proc += ' default:\n'
979 free_pnext_proc += ' // Do nothing -- skip unrecognized sTypes\n'
980 free_pnext_proc += ' break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600981 free_pnext_proc += ' }\n'
982 free_pnext_proc += '}\n'
983
984 pnext_procs = build_pnext_proc + free_pnext_proc
985 return pnext_procs
986 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700987 # Determine if a structure needs a safe_struct helper function
988 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700989 def NeedSafeStruct(self, structure):
Mark Lobodzinskib6cc5412019-07-19 09:56:58 -0600990 if 'VkBase' in structure.name:
991 return False
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700992 if 'sType' == structure.name:
993 return True
994 for member in structure.members:
995 if member.ispointer == True:
996 return True
997 return False
998 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700999 # Combine safe struct helper source file preamble with body text and return
1000 def GenerateSafeStructHelperSource(self):
1001 safe_struct_helper_source = '\n'
1002 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -06001003 safe_struct_helper_source += '#include <assert.h>\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001004 safe_struct_helper_source += '#include <string.h>\n'
1005 safe_struct_helper_source += '\n'
1006 safe_struct_helper_source += self.GenerateSafeStructSource()
Mark Lobodzinskib836ac92019-07-18 16:14:43 -06001007 safe_struct_helper_source += self.build_pnext_chain_processing_func()
1008
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001009 return safe_struct_helper_source
1010 #
1011 # safe_struct source -- create bodies of safe struct helper functions
1012 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001013 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001014 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
1015 'VkXcbSurfaceCreateInfoKHR',
1016 'VkWaylandSurfaceCreateInfoKHR',
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001017 'VkAndroidSurfaceCreateInfoKHR',
1018 'VkWin32SurfaceCreateInfoKHR'
1019 ]
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001020
1021 # For abstract types just want to save the pointer away
1022 # since we cannot make a copy.
1023 abstract_types = ['AHardwareBuffer',
1024 'ANativeWindow',
1025 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001026 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001027 if self.NeedSafeStruct(item) == False:
1028 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001029 if item.name in wsi_structs:
1030 continue
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001031 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001032 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
1033 ss_name = "safe_%s" % item.name
1034 init_list = '' # list of members in struct constructor initializer
1035 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
1036 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
1037 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
1038 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +01001039
1040 custom_construct_txt = {
1041 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
1042 'VkWriteDescriptorSet' :
1043 ' switch (descriptorType) {\n'
1044 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
1045 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
1046 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
1047 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
1048 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
1049 ' if (descriptorCount && in_struct->pImageInfo) {\n'
1050 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
1051 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1052 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
1053 ' }\n'
1054 ' }\n'
1055 ' break;\n'
1056 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
1057 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
1058 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
1059 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
1060 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
1061 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
1062 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1063 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
1064 ' }\n'
1065 ' }\n'
1066 ' break;\n'
1067 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
1068 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
1069 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
1070 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
1071 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1072 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
1073 ' }\n'
1074 ' }\n'
1075 ' break;\n'
1076 ' default:\n'
1077 ' break;\n'
1078 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001079 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +01001080 ' if (in_struct->pCode) {\n'
1081 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
1082 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
1083 ' }\n',
1084 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
1085 'VkGraphicsPipelineCreateInfo' :
1086 ' if (stageCount && in_struct->pStages) {\n'
1087 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1088 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1089 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
1090 ' }\n'
1091 ' }\n'
1092 ' if (in_struct->pVertexInputState)\n'
1093 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
1094 ' else\n'
1095 ' pVertexInputState = NULL;\n'
1096 ' if (in_struct->pInputAssemblyState)\n'
1097 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
1098 ' else\n'
1099 ' pInputAssemblyState = NULL;\n'
1100 ' bool has_tessellation_stage = false;\n'
1101 ' if (stageCount && pStages)\n'
1102 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1103 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1104 ' has_tessellation_stage = true;\n'
1105 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
1106 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
1107 ' else\n'
1108 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1109 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
1110 ' if (in_struct->pViewportState && has_rasterization) {\n'
1111 ' bool is_dynamic_viewports = false;\n'
1112 ' bool is_dynamic_scissors = false;\n'
1113 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
1114 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
1115 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
1116 ' is_dynamic_viewports = true;\n'
1117 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
1118 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
1119 ' is_dynamic_scissors = true;\n'
1120 ' }\n'
1121 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
1122 ' } else\n'
1123 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1124 ' if (in_struct->pRasterizationState)\n'
1125 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
1126 ' else\n'
1127 ' pRasterizationState = NULL;\n'
1128 ' if (in_struct->pMultisampleState && has_rasterization)\n'
1129 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
1130 ' else\n'
1131 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1132 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
1133 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
1134 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
1135 ' else\n'
1136 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1137 ' // needs a tracked subpass state usesColorAttachment\n'
1138 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
1139 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
1140 ' else\n'
1141 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1142 ' if (in_struct->pDynamicState)\n'
1143 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
1144 ' else\n'
1145 ' pDynamicState = NULL;\n',
1146 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
1147 'VkPipelineViewportStateCreateInfo' :
1148 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
1149 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
1150 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
1151 ' }\n'
1152 ' else\n'
1153 ' pViewports = NULL;\n'
1154 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
1155 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
1156 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
1157 ' }\n'
1158 ' else\n'
1159 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001160 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
1161 'VkDescriptorSetLayoutBinding' :
1162 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
1163 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
1164 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
1165 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1166 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
1167 ' }\n'
1168 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +01001169 }
1170
1171 custom_copy_txt = {
1172 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
1173 'VkGraphicsPipelineCreateInfo' :
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001174 ' pNext = SafePnextCopy(src.pNext);\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001175 ' if (stageCount && src.pStages) {\n'
1176 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1177 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1178 ' pStages[i].initialize(&src.pStages[i]);\n'
1179 ' }\n'
1180 ' }\n'
1181 ' if (src.pVertexInputState)\n'
1182 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
1183 ' else\n'
1184 ' pVertexInputState = NULL;\n'
1185 ' if (src.pInputAssemblyState)\n'
1186 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
1187 ' else\n'
1188 ' pInputAssemblyState = NULL;\n'
1189 ' bool has_tessellation_stage = false;\n'
1190 ' if (stageCount && pStages)\n'
1191 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1192 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1193 ' has_tessellation_stage = true;\n'
1194 ' if (src.pTessellationState && has_tessellation_stage)\n'
1195 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
1196 ' else\n'
1197 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1198 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
1199 ' if (src.pViewportState && has_rasterization) {\n'
1200 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
1201 ' } else\n'
1202 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1203 ' if (src.pRasterizationState)\n'
1204 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
1205 ' else\n'
1206 ' pRasterizationState = NULL;\n'
1207 ' if (src.pMultisampleState && has_rasterization)\n'
1208 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
1209 ' else\n'
1210 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1211 ' if (src.pDepthStencilState && has_rasterization)\n'
1212 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
1213 ' else\n'
1214 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1215 ' if (src.pColorBlendState && has_rasterization)\n'
1216 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1217 ' else\n'
1218 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1219 ' if (src.pDynamicState)\n'
1220 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1221 ' else\n'
1222 ' pDynamicState = NULL;\n',
1223 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1224 'VkPipelineViewportStateCreateInfo' :
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001225 ' pNext = SafePnextCopy(src.pNext);\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001226 ' if (src.pViewports) {\n'
1227 ' pViewports = new VkViewport[src.viewportCount];\n'
1228 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1229 ' }\n'
1230 ' else\n'
1231 ' pViewports = NULL;\n'
1232 ' if (src.pScissors) {\n'
1233 ' pScissors = new VkRect2D[src.scissorCount];\n'
1234 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1235 ' }\n'
1236 ' else\n'
1237 ' pScissors = NULL;\n',
1238 }
1239
Mike Schuchardt81485762017-09-04 11:38:42 -06001240 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1241 ' if (pCode)\n'
1242 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001243
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001244 copy_pnext = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001245 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001246 m_type = member.type
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001247 if member.name == 'pNext':
1248 copy_pnext = ' pNext = SafePnextCopy(in_struct->pNext);\n'
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001249 if member.type in self.structNames:
1250 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1251 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1252 m_type = 'safe_%s' % member.type
1253 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1254 # 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 -07001255 if m_type in ['void', 'char']:
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001256 if member.name != 'pNext':
1257 # For these exceptions just copy initial value over for now
1258 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1259 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001260 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001261 default_init_list += '\n %s(nullptr),' % (member.name)
1262 init_list += '\n %s(nullptr),' % (member.name)
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001263 if m_type in abstract_types:
1264 construct_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1265 else:
1266 init_func_txt += ' %s = nullptr;\n' % (member.name)
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001267 if not member.isstaticarray and (member.len is None or '/' in member.len):
1268 construct_txt += ' if (in_struct->%s) {\n' % member.name
1269 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1270 construct_txt += ' }\n'
1271 destruct_txt += ' if (%s)\n' % member.name
1272 destruct_txt += ' delete %s;\n' % member.name
1273 else:
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.len)
1276 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1277 construct_txt += ' }\n'
1278 destruct_txt += ' if (%s)\n' % member.name
1279 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001280 elif member.isstaticarray or member.len is not None:
1281 if member.len is None:
1282 # Extract length of static array by grabbing val between []
1283 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1284 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1285 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1286 construct_txt += ' }\n'
1287 else:
1288 # Init array ptr to NULL
1289 default_init_list += '\n %s(nullptr),' % member.name
1290 init_list += '\n %s(nullptr),' % member.name
1291 init_func_txt += ' %s = nullptr;\n' % member.name
1292 array_element = 'in_struct->%s[i]' % member.name
1293 if member.type in self.structNames:
1294 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1295 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1296 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1297 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1298 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1299 destruct_txt += ' if (%s)\n' % member.name
1300 destruct_txt += ' delete[] %s;\n' % member.name
1301 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1302 if 'safe_' in m_type:
1303 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001304 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001305 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1306 construct_txt += ' }\n'
1307 construct_txt += ' }\n'
1308 elif member.ispointer == True:
1309 construct_txt += ' if (in_struct->%s)\n' % member.name
1310 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1311 construct_txt += ' else\n'
1312 construct_txt += ' %s = NULL;\n' % member.name
1313 destruct_txt += ' if (%s)\n' % member.name
1314 destruct_txt += ' delete %s;\n' % member.name
1315 elif 'safe_' in m_type:
1316 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1317 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1318 else:
1319 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1320 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1321 if '' != init_list:
1322 init_list = init_list[:-1] # hack off final comma
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001323
1324
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001325 if item.name in custom_construct_txt:
1326 construct_txt = custom_construct_txt[item.name]
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001327
1328 construct_txt = copy_pnext + construct_txt
1329
Mike Schuchardt81485762017-09-04 11:38:42 -06001330 if item.name in custom_destruct_txt:
1331 destruct_txt = custom_destruct_txt[item.name]
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001332
1333 if copy_pnext:
1334 destruct_txt += ' if (pNext)\n FreePnextChain(pNext);\n'
1335
Petr Krause91f7a12017-12-14 20:57:36 +01001336 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 -07001337 if '' != default_init_list:
1338 default_init_list = " :%s" % (default_init_list[:-1])
1339 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1340 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1341 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001342 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1343 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1344 copy_construct_txt = re.sub('(new \\w+)\\(in_struct->', '\\1(*src.', construct_txt) # Pass object to copy constructors
1345 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001346 if item.name in custom_copy_txt:
1347 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001348 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 -06001349 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 -07001350 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 -07001351 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001352 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 -07001353 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1354 init_copy = copy_construct_init.replace('src.', 'src->')
1355 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001356 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 +01001357 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001358 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1359 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001360 #
John Zulaufde972ac2017-10-26 12:07:05 -06001361 # Generate the type map
1362 def GenerateTypeMapHelperHeader(self):
1363 prefix = 'Lvl'
1364 fprefix = 'lvl_'
1365 typemap = prefix + 'TypeMap'
1366 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001367 type_member = 'Type'
1368 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001369 id_decl = 'static const VkStructureType '
Locke6b6b7382019-04-16 15:08:49 -06001370 generic_header = 'VkBaseOutStructure'
John Zulaufde972ac2017-10-26 12:07:05 -06001371 typename_func = fprefix + 'typename'
1372 idname_func = fprefix + 'stype_name'
1373 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001374 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001375
1376 explanatory_comment = '\n'.join((
1377 '// These empty generic templates are specialized for each type with sType',
1378 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001379 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001380
1381 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1382 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001383 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1384 typemap_format += '}};\n'
1385
1386 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1387 idmap_format = ''.join((
1388 'template <> struct {template}<{id_value}> {{\n',
1389 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001390 '}};\n'))
1391
1392 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1393 utilities_format = '\n'.join((
John Zulaufde972ac2017-10-26 12:07:05 -06001394 '// Find an entry of the given type in the pNext chain',
1395 'template <typename T> const T *{find_func}(const void *next) {{',
1396 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1397 ' const T *found = nullptr;',
1398 ' while (current) {{',
1399 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1400 ' found = reinterpret_cast<const T*>(current);',
1401 ' current = nullptr;',
1402 ' }} else {{',
1403 ' current = current->pNext;',
1404 ' }}',
1405 ' }}',
1406 ' return found;',
1407 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001408 '',
1409 '// Init the header of an sType struct with pNext',
1410 'template <typename T> T {init_func}(void *p_next) {{',
1411 ' T out = {{}};',
1412 ' out.sType = {type_map}<T>::kSType;',
1413 ' out.pNext = p_next;',
1414 ' return out;',
1415 '}}',
1416 '',
1417 '// Init the header of an sType struct',
1418 'template <typename T> T {init_func}() {{',
1419 ' T out = {{}};',
1420 ' out.sType = {type_map}<T>::kSType;',
1421 ' return out;',
1422 '}}',
1423
Mike Schuchardt97662b02017-12-06 13:31:29 -07001424 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001425
1426 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001427
1428 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001429 code.append('\n'.join((
1430 '#pragma once',
1431 '#include <vulkan/vulkan.h>\n',
1432 explanatory_comment, '',
1433 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001434 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001435
1436 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001437 for item in self.structMembers:
1438 typename = item.name
1439 info = self.structTypes.get(typename)
1440 if not info:
1441 continue
1442
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001443 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001444 code.append('#ifdef %s' % item.ifdef_protect)
1445
1446 code.append('// Map type {} to id {}'.format(typename, info.value))
1447 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001448 id_decl=id_decl, id_member=id_member))
1449 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001450
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001451 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001452 code.append('#endif // %s' % item.ifdef_protect)
1453
John Zulauf65ac9d52018-01-23 11:20:50 -07001454 # Generate utilities for all types
1455 code.append('\n'.join((
1456 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1457 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1458 find_func=find_func, init_func=init_func), ''
1459 )))
1460
John Zulaufde972ac2017-10-26 12:07:05 -06001461 return "\n".join(code)
1462
1463 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001464 # Create a helper file and return it as a string
1465 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001466 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001467 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001468 elif self.helper_file_type == 'safe_struct_header':
1469 return self.GenerateSafeStructHelperHeader()
1470 elif self.helper_file_type == 'safe_struct_source':
1471 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001472 elif self.helper_file_type == 'object_types_header':
1473 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001474 elif self.helper_file_type == 'extension_helper_header':
1475 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001476 elif self.helper_file_type == 'typemap_helper_header':
1477 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001478 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001479 return 'Bad Helper File Generator Option %s' % self.helper_file_type