blob: e3225a620bacb40de17e54afb0c679e31205fce3 [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'
455 safe_struct_helper_header += '\n'
Mark Lobodzinski7245fce2019-07-18 16:18:51 -0600456 safe_struct_helper_header += 'void *SafePnextCopy(const void *pNext);\n'
457 safe_struct_helper_header += 'void FreePnextChain(void *head);\n'
458 safe_struct_helper_header += '\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700459 safe_struct_helper_header += self.GenerateSafeStructHeader()
460 return safe_struct_helper_header
461 #
462 # safe_struct header: build function prototypes for header file
463 def GenerateSafeStructHeader(self):
464 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700465 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700466 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700467 safe_struct_header += '\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100468 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700469 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
470 safe_struct_header += 'struct safe_%s {\n' % (item.name)
471 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700472 if member.type in self.structNames:
473 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
474 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
475 if member.ispointer:
476 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
477 else:
478 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
479 continue
480 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
481 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
482 else:
483 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100484 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 -0600485 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700486 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700487 safe_struct_header += ' safe_%s();\n' % item.name
488 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100489 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
490 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700491 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
492 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
493 safe_struct_header += '};\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100494 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700495 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700496 return safe_struct_header
497 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600498 # Generate extension helper header file
499 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600500
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600501 V_1_1_level_feature_set = [
502 'VK_VERSION_1_1',
503 ]
504
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600505 V_1_0_instance_extensions_promoted_to_V_1_1_core = [
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600506 'vk_khr_device_group_creation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600507 'vk_khr_external_fence_capabilities',
John Zulauf2012bca2018-04-25 15:28:47 -0600508 'vk_khr_external_memory_capabilities',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600509 'vk_khr_external_semaphore_capabilities',
510 'vk_khr_get_physical_device_properties_2',
511 ]
512
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600513 V_1_0_device_extensions_promoted_to_V_1_1_core = [
John Zulauf2012bca2018-04-25 15:28:47 -0600514 'vk_khr_16bit_storage',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600515 'vk_khr_bind_memory_2',
John Zulauf2012bca2018-04-25 15:28:47 -0600516 'vk_khr_dedicated_allocation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600517 'vk_khr_descriptor_update_template',
John Zulauf2012bca2018-04-25 15:28:47 -0600518 'vk_khr_device_group',
519 'vk_khr_external_fence',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600520 'vk_khr_external_memory',
521 'vk_khr_external_semaphore',
John Zulauf2012bca2018-04-25 15:28:47 -0600522 'vk_khr_get_memory_requirements_2',
523 'vk_khr_maintenance1',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600524 'vk_khr_maintenance2',
John Zulauf2012bca2018-04-25 15:28:47 -0600525 'vk_khr_maintenance3',
526 'vk_khr_multiview',
John Zulauf16826822018-04-25 15:40:32 -0600527 'vk_khr_relaxed_block_layout',
John Zulauf2012bca2018-04-25 15:28:47 -0600528 'vk_khr_sampler_ycbcr_conversion',
John Zulauf16826822018-04-25 15:40:32 -0600529 'vk_khr_shader_draw_parameters',
530 'vk_khr_storage_buffer_storage_class',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600531 'vk_khr_variable_pointers',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600532 ]
John Zulauf16826822018-04-25 15:40:32 -0600533
John Zulauff6feb2a2018-04-12 14:24:57 -0600534 output = [
535 '',
536 '#ifndef VK_EXTENSION_HELPER_H_',
537 '#define VK_EXTENSION_HELPER_H_',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600538 '#include <unordered_set>',
John Zulauf072677c2018-04-12 15:34:39 -0600539 '#include <string>',
540 '#include <unordered_map>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600541 '#include <utility>',
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600542 '#include <set>',
Mark Lobodzinskif94196f2019-07-11 11:46:09 -0600543 '#include <vector>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600544 '',
John Zulauf072677c2018-04-12 15:34:39 -0600545 '#include <vulkan/vulkan.h>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600546 '']
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600547
John Zulauff6feb2a2018-04-12 14:24:57 -0600548 def guarded(ifdef, value):
549 if ifdef is not None:
550 return '\n'.join([ '#ifdef %s' % ifdef, value, '#endif' ])
551 else:
552 return value
John Zulauf380bd942018-04-10 13:12:34 -0600553
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600554 for type in ['Instance', 'Device']:
John Zulauff6feb2a2018-04-12 14:24:57 -0600555 struct_type = '%sExtensions' % type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600556 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600557 extension_dict = self.instance_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600558 promoted_ext_list = V_1_0_instance_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600559 struct_decl = 'struct %s {' % struct_type
560 instance_struct_type = struct_type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600561 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600562 extension_dict = self.device_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600563 promoted_ext_list = V_1_0_device_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600564 struct_decl = 'struct %s : public %s {' % (struct_type, instance_struct_type)
565
566 extension_items = sorted(extension_dict.items())
567
568 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 -0600569
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600570 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600571 instance_field_name = field_name
John Zulauf072677c2018-04-12 15:34:39 -0600572 instance_extension_dict = extension_dict
573 else:
574 # Get complete field name and extension data for both Instance and Device extensions
575 field_name.update(instance_field_name)
576 extension_dict = extension_dict.copy() # Don't modify the self.<dict> we're pointing to
577 extension_dict.update(instance_extension_dict)
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600578
John Zulauf072677c2018-04-12 15:34:39 -0600579 # Output the data member list
John Zulauff6feb2a2018-04-12 14:24:57 -0600580 struct = [struct_decl]
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600581 struct.extend([ ' bool vk_feature_version_1_1{false};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600582 struct.extend([ ' bool %s{false};' % field_name[ext_name] for ext_name, info in extension_items])
John Zulauf072677c2018-04-12 15:34:39 -0600583
584 # Construct the extension information map -- mapping name to data member (field), and required extensions
585 # The map is contained within a static function member for portability reasons.
586 info_type = '%sInfo' % type
587 info_map_type = '%sMap' % info_type
588 req_type = '%sReq' % type
589 req_vec_type = '%sVec' % req_type
590 struct.extend([
591 '',
592 ' struct %s {' % req_type,
593 ' const bool %s::* enabled;' % struct_type,
594 ' const char *name;',
595 ' };',
596 ' typedef std::vector<%s> %s;' % (req_type, req_vec_type),
597 ' struct %s {' % info_type,
598 ' %s(bool %s::* state_, const %s requires_): state(state_), requires(requires_) {}' % ( info_type, struct_type, req_vec_type),
599 ' bool %s::* state;' % struct_type,
600 ' %s requires;' % req_vec_type,
601 ' };',
602 '',
603 ' typedef std::unordered_map<std::string,%s> %s;' % (info_type, info_map_type),
604 ' static const %s &get_info(const char *name) {' %info_type,
605 ' static const %s info_map = {' % info_map_type ])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600606 struct.extend([
607 ' std::make_pair("VK_VERSION_1_1", %sInfo(&%sExtensions::vk_feature_version_1_1, {})),' % (type, type)])
John Zulauf072677c2018-04-12 15:34:39 -0600608
609 field_format = '&' + struct_type + '::%s'
610 req_format = '{' + field_format+ ', %s}'
611 req_indent = '\n '
612 req_join = ',' + req_indent
613 info_format = (' std::make_pair(%s, ' + info_type + '(' + field_format + ', {%s})),')
614 def format_info(ext_name, info):
615 reqs = req_join.join([req_format % (field_name[req], extension_dict[req]['define']) for req in info['reqs']])
616 return info_format % (info['define'], field_name[ext_name], '{%s}' % (req_indent + reqs) if reqs else '')
617
618 struct.extend([guarded(info['ifdef'], format_info(ext_name, info)) for ext_name, info in extension_items])
619 struct.extend([
620 ' };',
621 '',
622 ' static const %s empty_info {nullptr, %s()};' % (info_type, req_vec_type),
623 ' %s::const_iterator info = info_map.find(name);' % info_map_type,
624 ' if ( info != info_map.cend()) {',
625 ' return info->second;',
626 ' }',
627 ' return empty_info;',
628 ' }',
629 ''])
630
John Zulauff6feb2a2018-04-12 14:24:57 -0600631 if type == 'Instance':
632 struct.extend([
633 ' uint32_t NormalizeApiVersion(uint32_t specified_version) {',
634 ' uint32_t api_version = (specified_version < VK_API_VERSION_1_1) ? VK_API_VERSION_1_0 : VK_API_VERSION_1_1;',
635 ' return api_version;',
636 ' }',
637 '',
638 ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {'])
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600639 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600640 struct.extend([
John Zulauf072677c2018-04-12 15:34:39 -0600641 ' %s() = default;' % struct_type,
642 ' %s(const %s& instance_ext) : %s(instance_ext) {}' % (struct_type, instance_struct_type, instance_struct_type),
643 '',
644 ' uint32_t InitFromDeviceCreateInfo(const %s *instance_extensions, uint32_t requested_api_version,' % instance_struct_type,
645 ' const VkDeviceCreateInfo *pCreateInfo) {',
646 ' // Initialize: this to defaults, base class fields to input.',
647 ' assert(instance_extensions);',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600648 ' *this = %s(*instance_extensions);' % struct_type,
Mark Lobodzinskid5f83b92018-12-14 11:02:08 -0700649 '']),
650 struct.extend([
John Zulauff6feb2a2018-04-12 14:24:57 -0600651 '',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600652 ' static const std::vector<const char *> V_1_1_promoted_%s_apis = {' % type.lower() ])
John Zulauff6feb2a2018-04-12 14:24:57 -0600653 struct.extend([' %s_EXTENSION_NAME,' % ext_name.upper() for ext_name in promoted_ext_list])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600654 struct.extend([' "VK_VERSION_1_1",'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600655 struct.extend([
656 ' };',
657 '',
John Zulauf072677c2018-04-12 15:34:39 -0600658 ' // Initialize struct data, robust to invalid pCreateInfo',
659 ' if (pCreateInfo->ppEnabledExtensionNames) {',
660 ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {',
661 ' if (!pCreateInfo->ppEnabledExtensionNames[i]) continue;',
662 ' auto info = get_info(pCreateInfo->ppEnabledExtensionNames[i]);',
663 ' if(info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600664 ' }',
665 ' }',
666 ' uint32_t api_version = NormalizeApiVersion(requested_api_version);',
667 ' if (api_version >= VK_API_VERSION_1_1) {',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600668 ' for (auto promoted_ext : V_1_1_promoted_%s_apis) {' % type.lower(),
John Zulauf072677c2018-04-12 15:34:39 -0600669 ' auto info = get_info(promoted_ext);',
670 ' assert(info.state);',
671 ' if (info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600672 ' }',
673 ' }',
674 ' return api_version;',
675 ' }',
John Zulauf072677c2018-04-12 15:34:39 -0600676 '};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600677
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700678 # Output reference lists of instance/device extension names
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600679 struct.extend(['', 'static const std::set<std::string> k%sExtensionNames = {' % type])
680 struct.extend([guarded(info['ifdef'], ' %s,' % info['define']) for ext_name, info in extension_items])
681 struct.extend(['};', ''])
John Zulauff6feb2a2018-04-12 14:24:57 -0600682 output.extend(struct)
683
684 output.extend(['', '#endif // VK_EXTENSION_HELPER_H_'])
685 return '\n'.join(output)
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600686 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600687 # Combine object types helper header file preamble with body text and return
688 def GenerateObjectTypesHelperHeader(self):
689 object_types_helper_header = '\n'
690 object_types_helper_header += '#pragma once\n'
691 object_types_helper_header += '\n'
692 object_types_helper_header += self.GenerateObjectTypesHeader()
693 return object_types_helper_header
694 #
695 # Object types header: create object enum type header file
696 def GenerateObjectTypesHeader(self):
John Zulauf4fea6622019-04-01 11:38:18 -0600697 object_types_header = '#include "cast_utils.h"\n'
698 object_types_header += '\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700699 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600700 object_types_header += 'typedef enum VulkanObjectType {\n'
701 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
702 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600703 type_list = [];
John Zulaufd7435c62018-03-16 11:52:57 -0600704 enum_entry_map = {}
John Zulauf2c2ccd42019-04-05 13:13:13 -0600705 non_dispatchable = {}
706 dispatchable = {}
707 object_type_info = {}
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600708
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600709 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600710 for item in self.object_types:
711 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600712 enum_entry = 'kVulkanObjectType%s' % fixup_name
John Zulaufd7435c62018-03-16 11:52:57 -0600713 enum_entry_map[item] = enum_entry
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600714 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600715 object_types_header += ' = %d,\n' % enum_num
716 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600717 type_list.append(enum_entry)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600718 object_type_info[enum_entry] = { 'VkType': item }
719 # 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 -0700720 if self.handle_types.IsNonDispatchable(item):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600721 non_dispatchable[item] = enum_entry
722 else:
723 dispatchable[item] = enum_entry
724
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600725 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
John Zulaufd7435c62018-03-16 11:52:57 -0600726 object_types_header += ' // Aliases for backwards compatibilty of "promoted" types\n'
727 for (name, alias) in self.object_type_aliases:
728 fixup_name = name[2:]
729 object_types_header += ' kVulkanObjectType{} = {},\n'.format(fixup_name, enum_entry_map[alias])
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600730 object_types_header += '} VulkanObjectType;\n\n'
731
732 # Output name string helper
733 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600734 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
locke-lunargb4c57852019-06-14 23:20:05 -0600735 object_types_header += ' "VkNonDispatchableHandle",\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600736 for item in self.object_types:
locke-lunargb4c57852019-06-14 23:20:05 -0600737 object_types_header += ' "%s",\n' % item
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600738 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600739
John Zulauf311a4892018-03-12 15:48:06 -0600740 # Key creation helper for map comprehensions that convert between k<Name> and VK<Name> symbols
741 def to_key(regex, raw_key): return re.search(regex, raw_key).group(1).lower().replace("_","")
742
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600743 # Output a conversion routine from the layer object definitions to the debug report definitions
John Zulauf311a4892018-03-12 15:48:06 -0600744 # As the VK_DEBUG_REPORT types are not being updated, specify UNKNOWN for unmatched types
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600745 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600746 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 -0600747 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700748 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000749
John Zulauf311a4892018-03-12 15:48:06 -0600750 dbg_re = '^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$'
751 dbg_map = {to_key(dbg_re, dbg) : dbg for dbg in self.debug_report_object_types}
752 dbg_default = 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600753
John Zulauf311a4892018-03-12 15:48:06 -0600754 for object_type in type_list:
755 vk_object_type = dbg_map.get(object_type.replace("kVulkanObjectType", "").lower(), dbg_default)
756 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600757 object_type_info[object_type]['DbgType'] = vk_object_type
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600758 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600759
760 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600761 # 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 -0600762 object_types_header += '\n'
763 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
764 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700765 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
John Zulauf311a4892018-03-12 15:48:06 -0600766
767 vko_re = '^VK_OBJECT_TYPE_(.*)'
768 vko_map = {to_key(vko_re, vko) : vko for vko in self.core_object_types}
Mark Young1ded24b2017-05-30 14:53:50 -0600769 for object_type in type_list:
John Zulauf311a4892018-03-12 15:48:06 -0600770 vk_object_type = vko_map[object_type.replace("kVulkanObjectType", "").lower()]
771 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600772 object_type_info[object_type]['VkoType'] = vk_object_type
Mark Young1ded24b2017-05-30 14:53:50 -0600773 object_types_header += '};\n'
774
Mark Young6ba8abe2017-11-09 10:37:04 -0700775 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
776 object_types_header += '\n'
777 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600778 object_types_header += 'static inline VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700779 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
780 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
781 for core_object_type in self.core_object_types:
782 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
783 core_target_type = core_target_type.replace("_", "")
784 for dr_object_type in self.debug_report_object_types:
785 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
786 dr_target_type = dr_target_type[:-4]
787 dr_target_type = dr_target_type.replace("_", "")
788 if core_target_type == dr_target_type:
789 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
790 object_types_header += ' return %s;\n' % core_object_type
791 break
792 object_types_header += ' }\n'
793 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
794 object_types_header += '}\n'
795
796 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
797 object_types_header += '\n'
798 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600799 object_types_header += 'static inline VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700800 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
801 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
802 for core_object_type in self.core_object_types:
803 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
804 core_target_type = core_target_type.replace("_", "")
805 for dr_object_type in self.debug_report_object_types:
806 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
807 dr_target_type = dr_target_type[:-4]
808 dr_target_type = dr_target_type.replace("_", "")
809 if core_target_type == dr_target_type:
810 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
811 object_types_header += ' return %s;\n' % dr_object_type
812 break
813 object_types_header += ' }\n'
814 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
815 object_types_header += '}\n'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600816
817 traits_format = Outdent('''
818 template <> struct VkHandleInfo<{vk_type}> {{
819 static const VulkanObjectType kVulkanObjectType = {obj_type};
820 static const VkDebugReportObjectTypeEXT kDebugReportObjectType = {dbg_type};
821 static const VkObjectType kVkObjectType = {vko_type};
822 static const char* Typename() {{
823 return "{vk_type}";
824 }}
825 }};
826 template <> struct VulkanObjectTypeInfo<{obj_type}> {{
827 typedef {vk_type} Type;
828 }};
829 ''')
830
831 object_types_header += Outdent('''
832 // Traits objects from each type statically map from Vk<handleType> to the various enums
833 template <typename VkType> struct VkHandleInfo {};
834 template <VulkanObjectType id> struct VulkanObjectTypeInfo {};
835
836 // The following line must match the vulkan_core.h condition guarding VK_DEFINE_NON_DISPATCHABLE_HANDLE
837 #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || \
838 defined(_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
839 #define TYPESAFE_NONDISPATCHABLE_HANDLES
840 #else
841 VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkNonDispatchableHandle)
842 ''') +'\n'
843 object_types_header += traits_format.format(vk_type='VkNonDispatchableHandle', obj_type='kVulkanObjectTypeUnknown',
844 dbg_type='VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT',
845 vko_type='VK_OBJECT_TYPE_UNKNOWN') + '\n'
846 object_types_header += '#endif // VK_DEFINE_HANDLE logic duplication\n'
847
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700848 for vk_type, object_type in sorted(dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600849 info = object_type_info[object_type]
850 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
851 vko_type=info['VkoType'])
852 object_types_header += '#ifdef TYPESAFE_NONDISPATCHABLE_HANDLES\n'
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700853 for vk_type, object_type in sorted(non_dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600854 info = object_type_info[object_type]
855 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
856 vko_type=info['VkoType'])
857 object_types_header += '#endif // TYPESAFE_NONDISPATCHABLE_HANDLES\n'
858
859 object_types_header += Outdent('''
860 struct VulkanTypedHandle {
861 uint64_t handle;
862 VulkanObjectType type;
863 template <typename Handle>
John Zulauf4fea6622019-04-01 11:38:18 -0600864 VulkanTypedHandle(Handle handle_, VulkanObjectType type_) :
865 handle(CastToUint64(handle_)),
866 type(type_) {
867 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
868 // For 32 bit it's not always safe to check for traits <-> type
869 // as all non-dispatchable handles have the same type-id and thus traits,
870 // but on 64 bit we can validate the passed type matches the passed handle
871 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
872 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
873 }
874 template <typename Handle>
875 Handle Cast() const {
876 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
877 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
878 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
879 return CastFromUint64<Handle>(handle);
880 }
John Zulauf2c2ccd42019-04-05 13:13:13 -0600881 VulkanTypedHandle() :
882 handle(VK_NULL_HANDLE),
883 type(kVulkanObjectTypeUnknown) {}
884 }; ''') +'\n'
885
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600886 return object_types_header
887 #
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600888 # Generate pNext handling function
889 def build_pnext_chain_processing_func(self):
890 # Construct helper functions to build and free pNext extension chains
891 build_pnext_proc = '\n\n'
892 build_pnext_proc += 'void *SafePnextCopy(const void *pNext) {\n'
893 build_pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
894 build_pnext_proc += ' void *cur_ext_struct = NULL;\n\n'
895 build_pnext_proc += ' if (cur_pnext == nullptr) {\n'
896 build_pnext_proc += ' return nullptr;\n'
897 build_pnext_proc += ' } else {\n'
898 build_pnext_proc += ' VkBaseOutStructure *header = reinterpret_cast<VkBaseOutStructure *>(cur_pnext);\n\n'
899 build_pnext_proc += ' switch (header->sType) {\n'
900
901 free_pnext_proc = '\n\n'
902 free_pnext_proc += '// Free a pNext extension chain\n'
903 free_pnext_proc += 'void FreePnextChain(void *head) {\n'
904 free_pnext_proc += ' VkBaseOutStructure *curr_ptr = reinterpret_cast<VkBaseOutStructure *>(head);\n'
905 free_pnext_proc += ' while (curr_ptr) {\n'
906 free_pnext_proc += ' VkBaseOutStructure *header = curr_ptr;\n'
907 free_pnext_proc += ' curr_ptr = reinterpret_cast<VkBaseOutStructure *>(header->pNext);\n\n'
908 free_pnext_proc += ' switch (header->sType) {\n';
909
910 for item in self.structextends_list:
911 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == item), None)
912 if member_index is None:
913 continue
914 struct_info = self.structMembers[member_index][1]
915 feature_protect = self.structMembers[member_index][2]
916
917 if feature_protect is not None:
918 build_pnext_proc += '#ifdef %s\n' % feature_protect
919 free_pnext_proc += '#ifdef %s\n' % feature_protect
920 build_pnext_proc += ' case %s: {\n' % self.structTypes[item].value
921 build_pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
922 build_pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
923 build_pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
924 build_pnext_proc += ' } break;\n'
925
926 free_pnext_proc += ' case %s:\n' % self.structTypes[item].value
927 free_pnext_proc += ' delete reinterpret_cast<safe_%s *>(header);\n' % item
928 free_pnext_proc += ' break;\n'
929
930 if feature_protect is not None:
931 build_pnext_proc += '#endif // %s\n' % feature_protect
932 free_pnext_proc += '#endif // %s\n' % feature_protect
933 build_pnext_proc += '\n'
934 free_pnext_proc += '\n'
935
936 build_pnext_proc += ' default:\n'
937 build_pnext_proc += ' break;\n'
938 build_pnext_proc += ' }\n'
939 build_pnext_proc += ' }\n'
940 build_pnext_proc += ' return cur_ext_struct;\n'
941 build_pnext_proc += '}\n\n'
942
943 free_pnext_proc += ' default:\n'
944 free_pnext_proc += ' assert(0);\n'
945 free_pnext_proc += ' }\n'
946 free_pnext_proc += ' }\n'
947 free_pnext_proc += '}\n'
948
949 pnext_procs = build_pnext_proc + free_pnext_proc
950 return pnext_procs
951 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700952 # Determine if a structure needs a safe_struct helper function
953 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700954 def NeedSafeStruct(self, structure):
Mark Lobodzinskib6cc5412019-07-19 09:56:58 -0600955 if 'VkBase' in structure.name:
956 return False
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700957 if 'sType' == structure.name:
958 return True
959 for member in structure.members:
960 if member.ispointer == True:
961 return True
962 return False
963 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700964 # Combine safe struct helper source file preamble with body text and return
965 def GenerateSafeStructHelperSource(self):
966 safe_struct_helper_source = '\n'
967 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600968 safe_struct_helper_source += '#include <assert.h>\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700969 safe_struct_helper_source += '#include <string.h>\n'
970 safe_struct_helper_source += '\n'
971 safe_struct_helper_source += self.GenerateSafeStructSource()
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600972 safe_struct_helper_source += self.build_pnext_chain_processing_func()
973
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700974 return safe_struct_helper_source
975 #
976 # safe_struct source -- create bodies of safe struct helper functions
977 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700978 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700979 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
980 'VkXcbSurfaceCreateInfoKHR',
981 'VkWaylandSurfaceCreateInfoKHR',
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700982 'VkAndroidSurfaceCreateInfoKHR',
983 'VkWin32SurfaceCreateInfoKHR'
984 ]
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -0600985
986 # For abstract types just want to save the pointer away
987 # since we cannot make a copy.
988 abstract_types = ['AHardwareBuffer',
989 'ANativeWindow',
990 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700991 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700992 if self.NeedSafeStruct(item) == False:
993 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700994 if item.name in wsi_structs:
995 continue
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100996 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700997 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
998 ss_name = "safe_%s" % item.name
999 init_list = '' # list of members in struct constructor initializer
1000 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
1001 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
1002 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
1003 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +01001004
1005 custom_construct_txt = {
1006 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
1007 'VkWriteDescriptorSet' :
1008 ' switch (descriptorType) {\n'
1009 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
1010 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
1011 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
1012 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
1013 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
1014 ' if (descriptorCount && in_struct->pImageInfo) {\n'
1015 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
1016 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1017 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
1018 ' }\n'
1019 ' }\n'
1020 ' break;\n'
1021 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
1022 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
1023 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
1024 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
1025 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
1026 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
1027 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1028 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
1029 ' }\n'
1030 ' }\n'
1031 ' break;\n'
1032 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
1033 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
1034 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
1035 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
1036 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1037 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
1038 ' }\n'
1039 ' }\n'
1040 ' break;\n'
1041 ' default:\n'
1042 ' break;\n'
1043 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001044 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +01001045 ' if (in_struct->pCode) {\n'
1046 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
1047 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
1048 ' }\n',
1049 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
1050 'VkGraphicsPipelineCreateInfo' :
1051 ' if (stageCount && in_struct->pStages) {\n'
1052 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1053 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1054 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
1055 ' }\n'
1056 ' }\n'
1057 ' if (in_struct->pVertexInputState)\n'
1058 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
1059 ' else\n'
1060 ' pVertexInputState = NULL;\n'
1061 ' if (in_struct->pInputAssemblyState)\n'
1062 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
1063 ' else\n'
1064 ' pInputAssemblyState = NULL;\n'
1065 ' bool has_tessellation_stage = false;\n'
1066 ' if (stageCount && pStages)\n'
1067 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1068 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1069 ' has_tessellation_stage = true;\n'
1070 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
1071 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
1072 ' else\n'
1073 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1074 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
1075 ' if (in_struct->pViewportState && has_rasterization) {\n'
1076 ' bool is_dynamic_viewports = false;\n'
1077 ' bool is_dynamic_scissors = false;\n'
1078 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
1079 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
1080 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
1081 ' is_dynamic_viewports = true;\n'
1082 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
1083 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
1084 ' is_dynamic_scissors = true;\n'
1085 ' }\n'
1086 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
1087 ' } else\n'
1088 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1089 ' if (in_struct->pRasterizationState)\n'
1090 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
1091 ' else\n'
1092 ' pRasterizationState = NULL;\n'
1093 ' if (in_struct->pMultisampleState && has_rasterization)\n'
1094 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
1095 ' else\n'
1096 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1097 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
1098 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
1099 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
1100 ' else\n'
1101 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1102 ' // needs a tracked subpass state usesColorAttachment\n'
1103 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
1104 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
1105 ' else\n'
1106 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1107 ' if (in_struct->pDynamicState)\n'
1108 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
1109 ' else\n'
1110 ' pDynamicState = NULL;\n',
1111 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
1112 'VkPipelineViewportStateCreateInfo' :
1113 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
1114 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
1115 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
1116 ' }\n'
1117 ' else\n'
1118 ' pViewports = NULL;\n'
1119 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
1120 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
1121 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
1122 ' }\n'
1123 ' else\n'
1124 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001125 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
1126 'VkDescriptorSetLayoutBinding' :
1127 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
1128 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
1129 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
1130 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1131 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
1132 ' }\n'
1133 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +01001134 }
1135
1136 custom_copy_txt = {
1137 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
1138 'VkGraphicsPipelineCreateInfo' :
1139 ' if (stageCount && src.pStages) {\n'
1140 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1141 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1142 ' pStages[i].initialize(&src.pStages[i]);\n'
1143 ' }\n'
1144 ' }\n'
1145 ' if (src.pVertexInputState)\n'
1146 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
1147 ' else\n'
1148 ' pVertexInputState = NULL;\n'
1149 ' if (src.pInputAssemblyState)\n'
1150 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
1151 ' else\n'
1152 ' pInputAssemblyState = NULL;\n'
1153 ' bool has_tessellation_stage = false;\n'
1154 ' if (stageCount && pStages)\n'
1155 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1156 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1157 ' has_tessellation_stage = true;\n'
1158 ' if (src.pTessellationState && has_tessellation_stage)\n'
1159 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
1160 ' else\n'
1161 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1162 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
1163 ' if (src.pViewportState && has_rasterization) {\n'
1164 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
1165 ' } else\n'
1166 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1167 ' if (src.pRasterizationState)\n'
1168 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
1169 ' else\n'
1170 ' pRasterizationState = NULL;\n'
1171 ' if (src.pMultisampleState && has_rasterization)\n'
1172 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
1173 ' else\n'
1174 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1175 ' if (src.pDepthStencilState && has_rasterization)\n'
1176 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
1177 ' else\n'
1178 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1179 ' if (src.pColorBlendState && has_rasterization)\n'
1180 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1181 ' else\n'
1182 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1183 ' if (src.pDynamicState)\n'
1184 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1185 ' else\n'
1186 ' pDynamicState = NULL;\n',
1187 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1188 'VkPipelineViewportStateCreateInfo' :
1189 ' if (src.pViewports) {\n'
1190 ' pViewports = new VkViewport[src.viewportCount];\n'
1191 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1192 ' }\n'
1193 ' else\n'
1194 ' pViewports = NULL;\n'
1195 ' if (src.pScissors) {\n'
1196 ' pScissors = new VkRect2D[src.scissorCount];\n'
1197 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1198 ' }\n'
1199 ' else\n'
1200 ' pScissors = NULL;\n',
1201 }
1202
Mike Schuchardt81485762017-09-04 11:38:42 -06001203 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1204 ' if (pCode)\n'
1205 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001206
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001207 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001208 m_type = member.type
1209 if member.type in self.structNames:
1210 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1211 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1212 m_type = 'safe_%s' % member.type
1213 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1214 # 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 -07001215 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001216 # For these exceptions just copy initial value over for now
1217 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1218 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001219 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001220 default_init_list += '\n %s(nullptr),' % (member.name)
1221 init_list += '\n %s(nullptr),' % (member.name)
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001222 if m_type in abstract_types:
1223 construct_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1224 else:
1225 init_func_txt += ' %s = nullptr;\n' % (member.name)
1226 if 'pNext' != member.name and 'void' not in m_type:
1227 if not member.isstaticarray and (member.len is None or '/' in member.len):
1228 construct_txt += ' if (in_struct->%s) {\n' % member.name
1229 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1230 construct_txt += ' }\n'
1231 destruct_txt += ' if (%s)\n' % member.name
1232 destruct_txt += ' delete %s;\n' % member.name
1233 else:
1234 construct_txt += ' if (in_struct->%s) {\n' % member.name
1235 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1236 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1237 construct_txt += ' }\n'
1238 destruct_txt += ' if (%s)\n' % member.name
1239 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001240 elif member.isstaticarray or member.len is not None:
1241 if member.len is None:
1242 # Extract length of static array by grabbing val between []
1243 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1244 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1245 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1246 construct_txt += ' }\n'
1247 else:
1248 # Init array ptr to NULL
1249 default_init_list += '\n %s(nullptr),' % member.name
1250 init_list += '\n %s(nullptr),' % member.name
1251 init_func_txt += ' %s = nullptr;\n' % member.name
1252 array_element = 'in_struct->%s[i]' % member.name
1253 if member.type in self.structNames:
1254 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1255 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1256 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1257 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1258 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1259 destruct_txt += ' if (%s)\n' % member.name
1260 destruct_txt += ' delete[] %s;\n' % member.name
1261 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1262 if 'safe_' in m_type:
1263 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001264 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001265 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1266 construct_txt += ' }\n'
1267 construct_txt += ' }\n'
1268 elif member.ispointer == True:
1269 construct_txt += ' if (in_struct->%s)\n' % member.name
1270 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1271 construct_txt += ' else\n'
1272 construct_txt += ' %s = NULL;\n' % member.name
1273 destruct_txt += ' if (%s)\n' % member.name
1274 destruct_txt += ' delete %s;\n' % member.name
1275 elif 'safe_' in m_type:
1276 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1277 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1278 else:
1279 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1280 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1281 if '' != init_list:
1282 init_list = init_list[:-1] # hack off final comma
1283 if item.name in custom_construct_txt:
1284 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001285 if item.name in custom_destruct_txt:
1286 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001287 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 -07001288 if '' != default_init_list:
1289 default_init_list = " :%s" % (default_init_list[:-1])
1290 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1291 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1292 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1293 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1294 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1295 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001296 if item.name in custom_copy_txt:
1297 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001298 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 -06001299 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 -07001300 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 -07001301 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001302 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 -07001303 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1304 init_copy = copy_construct_init.replace('src.', 'src->')
1305 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001306 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 +01001307 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001308 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1309 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001310 #
John Zulaufde972ac2017-10-26 12:07:05 -06001311 # Generate the type map
1312 def GenerateTypeMapHelperHeader(self):
1313 prefix = 'Lvl'
1314 fprefix = 'lvl_'
1315 typemap = prefix + 'TypeMap'
1316 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001317 type_member = 'Type'
1318 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001319 id_decl = 'static const VkStructureType '
Locke6b6b7382019-04-16 15:08:49 -06001320 generic_header = 'VkBaseOutStructure'
John Zulaufde972ac2017-10-26 12:07:05 -06001321 typename_func = fprefix + 'typename'
1322 idname_func = fprefix + 'stype_name'
1323 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001324 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001325
1326 explanatory_comment = '\n'.join((
1327 '// These empty generic templates are specialized for each type with sType',
1328 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001329 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001330
1331 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1332 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001333 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1334 typemap_format += '}};\n'
1335
1336 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1337 idmap_format = ''.join((
1338 'template <> struct {template}<{id_value}> {{\n',
1339 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001340 '}};\n'))
1341
1342 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1343 utilities_format = '\n'.join((
John Zulaufde972ac2017-10-26 12:07:05 -06001344 '// Find an entry of the given type in the pNext chain',
1345 'template <typename T> const T *{find_func}(const void *next) {{',
1346 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1347 ' const T *found = nullptr;',
1348 ' while (current) {{',
1349 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1350 ' found = reinterpret_cast<const T*>(current);',
1351 ' current = nullptr;',
1352 ' }} else {{',
1353 ' current = current->pNext;',
1354 ' }}',
1355 ' }}',
1356 ' return found;',
1357 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001358 '',
1359 '// Init the header of an sType struct with pNext',
1360 'template <typename T> T {init_func}(void *p_next) {{',
1361 ' T out = {{}};',
1362 ' out.sType = {type_map}<T>::kSType;',
1363 ' out.pNext = p_next;',
1364 ' return out;',
1365 '}}',
1366 '',
1367 '// Init the header of an sType struct',
1368 'template <typename T> T {init_func}() {{',
1369 ' T out = {{}};',
1370 ' out.sType = {type_map}<T>::kSType;',
1371 ' return out;',
1372 '}}',
1373
Mike Schuchardt97662b02017-12-06 13:31:29 -07001374 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001375
1376 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001377
1378 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001379 code.append('\n'.join((
1380 '#pragma once',
1381 '#include <vulkan/vulkan.h>\n',
1382 explanatory_comment, '',
1383 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001384 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001385
1386 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001387 for item in self.structMembers:
1388 typename = item.name
1389 info = self.structTypes.get(typename)
1390 if not info:
1391 continue
1392
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001393 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001394 code.append('#ifdef %s' % item.ifdef_protect)
1395
1396 code.append('// Map type {} to id {}'.format(typename, info.value))
1397 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001398 id_decl=id_decl, id_member=id_member))
1399 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001400
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001401 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001402 code.append('#endif // %s' % item.ifdef_protect)
1403
John Zulauf65ac9d52018-01-23 11:20:50 -07001404 # Generate utilities for all types
1405 code.append('\n'.join((
1406 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1407 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1408 find_func=find_func, init_func=init_func), ''
1409 )))
1410
John Zulaufde972ac2017-10-26 12:07:05 -06001411 return "\n".join(code)
1412
1413 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001414 # Create a helper file and return it as a string
1415 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001416 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001417 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001418 elif self.helper_file_type == 'safe_struct_header':
1419 return self.GenerateSafeStructHelperHeader()
1420 elif self.helper_file_type == 'safe_struct_source':
1421 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001422 elif self.helper_file_type == 'object_types_header':
1423 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001424 elif self.helper_file_type == 'extension_helper_header':
1425 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001426 elif self.helper_file_type == 'typemap_helper_header':
1427 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001428 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001429 return 'Bad Helper File Generator Option %s' % self.helper_file_type