blob: 789399353b487d25ef0034f276e6ea923beefa59 [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'
456 safe_struct_helper_header += self.GenerateSafeStructHeader()
457 return safe_struct_helper_header
458 #
459 # safe_struct header: build function prototypes for header file
460 def GenerateSafeStructHeader(self):
461 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700462 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700463 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700464 safe_struct_header += '\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100465 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700466 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
467 safe_struct_header += 'struct safe_%s {\n' % (item.name)
468 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700469 if member.type in self.structNames:
470 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
471 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
472 if member.ispointer:
473 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
474 else:
475 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
476 continue
477 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
478 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
479 else:
480 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100481 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 -0600482 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700483 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700484 safe_struct_header += ' safe_%s();\n' % item.name
485 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100486 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
487 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700488 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
489 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
490 safe_struct_header += '};\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100491 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700492 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700493 return safe_struct_header
494 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600495 # Generate extension helper header file
496 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600497
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600498 V_1_1_level_feature_set = [
499 'VK_VERSION_1_1',
500 ]
501
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600502 V_1_0_instance_extensions_promoted_to_V_1_1_core = [
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600503 'vk_khr_device_group_creation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600504 'vk_khr_external_fence_capabilities',
John Zulauf2012bca2018-04-25 15:28:47 -0600505 'vk_khr_external_memory_capabilities',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600506 'vk_khr_external_semaphore_capabilities',
507 'vk_khr_get_physical_device_properties_2',
508 ]
509
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600510 V_1_0_device_extensions_promoted_to_V_1_1_core = [
John Zulauf2012bca2018-04-25 15:28:47 -0600511 'vk_khr_16bit_storage',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600512 'vk_khr_bind_memory_2',
John Zulauf2012bca2018-04-25 15:28:47 -0600513 'vk_khr_dedicated_allocation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600514 'vk_khr_descriptor_update_template',
John Zulauf2012bca2018-04-25 15:28:47 -0600515 'vk_khr_device_group',
516 'vk_khr_external_fence',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600517 'vk_khr_external_memory',
518 'vk_khr_external_semaphore',
John Zulauf2012bca2018-04-25 15:28:47 -0600519 'vk_khr_get_memory_requirements_2',
520 'vk_khr_maintenance1',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600521 'vk_khr_maintenance2',
John Zulauf2012bca2018-04-25 15:28:47 -0600522 'vk_khr_maintenance3',
523 'vk_khr_multiview',
John Zulauf16826822018-04-25 15:40:32 -0600524 'vk_khr_relaxed_block_layout',
John Zulauf2012bca2018-04-25 15:28:47 -0600525 'vk_khr_sampler_ycbcr_conversion',
John Zulauf16826822018-04-25 15:40:32 -0600526 'vk_khr_shader_draw_parameters',
527 'vk_khr_storage_buffer_storage_class',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600528 'vk_khr_variable_pointers',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600529 ]
John Zulauf16826822018-04-25 15:40:32 -0600530
John Zulauff6feb2a2018-04-12 14:24:57 -0600531 output = [
532 '',
533 '#ifndef VK_EXTENSION_HELPER_H_',
534 '#define VK_EXTENSION_HELPER_H_',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600535 '#include <unordered_set>',
John Zulauf072677c2018-04-12 15:34:39 -0600536 '#include <string>',
537 '#include <unordered_map>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600538 '#include <utility>',
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600539 '#include <set>',
Mark Lobodzinskif94196f2019-07-11 11:46:09 -0600540 '#include <vector>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600541 '',
John Zulauf072677c2018-04-12 15:34:39 -0600542 '#include <vulkan/vulkan.h>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600543 '']
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600544
John Zulauff6feb2a2018-04-12 14:24:57 -0600545 def guarded(ifdef, value):
546 if ifdef is not None:
547 return '\n'.join([ '#ifdef %s' % ifdef, value, '#endif' ])
548 else:
549 return value
John Zulauf380bd942018-04-10 13:12:34 -0600550
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600551 for type in ['Instance', 'Device']:
John Zulauff6feb2a2018-04-12 14:24:57 -0600552 struct_type = '%sExtensions' % type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600553 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600554 extension_dict = self.instance_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600555 promoted_ext_list = V_1_0_instance_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600556 struct_decl = 'struct %s {' % struct_type
557 instance_struct_type = struct_type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600558 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600559 extension_dict = self.device_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600560 promoted_ext_list = V_1_0_device_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600561 struct_decl = 'struct %s : public %s {' % (struct_type, instance_struct_type)
562
563 extension_items = sorted(extension_dict.items())
564
565 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 -0600566
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600567 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600568 instance_field_name = field_name
John Zulauf072677c2018-04-12 15:34:39 -0600569 instance_extension_dict = extension_dict
570 else:
571 # Get complete field name and extension data for both Instance and Device extensions
572 field_name.update(instance_field_name)
573 extension_dict = extension_dict.copy() # Don't modify the self.<dict> we're pointing to
574 extension_dict.update(instance_extension_dict)
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600575
John Zulauf072677c2018-04-12 15:34:39 -0600576 # Output the data member list
John Zulauff6feb2a2018-04-12 14:24:57 -0600577 struct = [struct_decl]
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600578 struct.extend([ ' bool vk_feature_version_1_1{false};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600579 struct.extend([ ' bool %s{false};' % field_name[ext_name] for ext_name, info in extension_items])
John Zulauf072677c2018-04-12 15:34:39 -0600580
581 # Construct the extension information map -- mapping name to data member (field), and required extensions
582 # The map is contained within a static function member for portability reasons.
583 info_type = '%sInfo' % type
584 info_map_type = '%sMap' % info_type
585 req_type = '%sReq' % type
586 req_vec_type = '%sVec' % req_type
587 struct.extend([
588 '',
589 ' struct %s {' % req_type,
590 ' const bool %s::* enabled;' % struct_type,
591 ' const char *name;',
592 ' };',
593 ' typedef std::vector<%s> %s;' % (req_type, req_vec_type),
594 ' struct %s {' % info_type,
595 ' %s(bool %s::* state_, const %s requires_): state(state_), requires(requires_) {}' % ( info_type, struct_type, req_vec_type),
596 ' bool %s::* state;' % struct_type,
597 ' %s requires;' % req_vec_type,
598 ' };',
599 '',
600 ' typedef std::unordered_map<std::string,%s> %s;' % (info_type, info_map_type),
601 ' static const %s &get_info(const char *name) {' %info_type,
602 ' static const %s info_map = {' % info_map_type ])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600603 struct.extend([
604 ' std::make_pair("VK_VERSION_1_1", %sInfo(&%sExtensions::vk_feature_version_1_1, {})),' % (type, type)])
John Zulauf072677c2018-04-12 15:34:39 -0600605
606 field_format = '&' + struct_type + '::%s'
607 req_format = '{' + field_format+ ', %s}'
608 req_indent = '\n '
609 req_join = ',' + req_indent
610 info_format = (' std::make_pair(%s, ' + info_type + '(' + field_format + ', {%s})),')
611 def format_info(ext_name, info):
612 reqs = req_join.join([req_format % (field_name[req], extension_dict[req]['define']) for req in info['reqs']])
613 return info_format % (info['define'], field_name[ext_name], '{%s}' % (req_indent + reqs) if reqs else '')
614
615 struct.extend([guarded(info['ifdef'], format_info(ext_name, info)) for ext_name, info in extension_items])
616 struct.extend([
617 ' };',
618 '',
619 ' static const %s empty_info {nullptr, %s()};' % (info_type, req_vec_type),
620 ' %s::const_iterator info = info_map.find(name);' % info_map_type,
621 ' if ( info != info_map.cend()) {',
622 ' return info->second;',
623 ' }',
624 ' return empty_info;',
625 ' }',
626 ''])
627
John Zulauff6feb2a2018-04-12 14:24:57 -0600628 if type == 'Instance':
629 struct.extend([
630 ' uint32_t NormalizeApiVersion(uint32_t specified_version) {',
631 ' uint32_t api_version = (specified_version < VK_API_VERSION_1_1) ? VK_API_VERSION_1_0 : VK_API_VERSION_1_1;',
632 ' return api_version;',
633 ' }',
634 '',
635 ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {'])
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600636 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600637 struct.extend([
John Zulauf072677c2018-04-12 15:34:39 -0600638 ' %s() = default;' % struct_type,
639 ' %s(const %s& instance_ext) : %s(instance_ext) {}' % (struct_type, instance_struct_type, instance_struct_type),
640 '',
641 ' uint32_t InitFromDeviceCreateInfo(const %s *instance_extensions, uint32_t requested_api_version,' % instance_struct_type,
642 ' const VkDeviceCreateInfo *pCreateInfo) {',
643 ' // Initialize: this to defaults, base class fields to input.',
644 ' assert(instance_extensions);',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600645 ' *this = %s(*instance_extensions);' % struct_type,
Mark Lobodzinskid5f83b92018-12-14 11:02:08 -0700646 '']),
647 struct.extend([
John Zulauff6feb2a2018-04-12 14:24:57 -0600648 '',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600649 ' static const std::vector<const char *> V_1_1_promoted_%s_apis = {' % type.lower() ])
John Zulauff6feb2a2018-04-12 14:24:57 -0600650 struct.extend([' %s_EXTENSION_NAME,' % ext_name.upper() for ext_name in promoted_ext_list])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600651 struct.extend([' "VK_VERSION_1_1",'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600652 struct.extend([
653 ' };',
654 '',
John Zulauf072677c2018-04-12 15:34:39 -0600655 ' // Initialize struct data, robust to invalid pCreateInfo',
656 ' if (pCreateInfo->ppEnabledExtensionNames) {',
657 ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {',
658 ' if (!pCreateInfo->ppEnabledExtensionNames[i]) continue;',
659 ' auto info = get_info(pCreateInfo->ppEnabledExtensionNames[i]);',
660 ' if(info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600661 ' }',
662 ' }',
663 ' uint32_t api_version = NormalizeApiVersion(requested_api_version);',
664 ' if (api_version >= VK_API_VERSION_1_1) {',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600665 ' for (auto promoted_ext : V_1_1_promoted_%s_apis) {' % type.lower(),
John Zulauf072677c2018-04-12 15:34:39 -0600666 ' auto info = get_info(promoted_ext);',
667 ' assert(info.state);',
668 ' if (info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600669 ' }',
670 ' }',
671 ' return api_version;',
672 ' }',
John Zulauf072677c2018-04-12 15:34:39 -0600673 '};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600674
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700675 # Output reference lists of instance/device extension names
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600676 struct.extend(['', 'static const std::set<std::string> k%sExtensionNames = {' % type])
677 struct.extend([guarded(info['ifdef'], ' %s,' % info['define']) for ext_name, info in extension_items])
678 struct.extend(['};', ''])
John Zulauff6feb2a2018-04-12 14:24:57 -0600679 output.extend(struct)
680
681 output.extend(['', '#endif // VK_EXTENSION_HELPER_H_'])
682 return '\n'.join(output)
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600683 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600684 # Combine object types helper header file preamble with body text and return
685 def GenerateObjectTypesHelperHeader(self):
686 object_types_helper_header = '\n'
687 object_types_helper_header += '#pragma once\n'
688 object_types_helper_header += '\n'
689 object_types_helper_header += self.GenerateObjectTypesHeader()
690 return object_types_helper_header
691 #
692 # Object types header: create object enum type header file
693 def GenerateObjectTypesHeader(self):
John Zulauf4fea6622019-04-01 11:38:18 -0600694 object_types_header = '#include "cast_utils.h"\n'
695 object_types_header += '\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700696 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600697 object_types_header += 'typedef enum VulkanObjectType {\n'
698 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
699 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600700 type_list = [];
John Zulaufd7435c62018-03-16 11:52:57 -0600701 enum_entry_map = {}
John Zulauf2c2ccd42019-04-05 13:13:13 -0600702 non_dispatchable = {}
703 dispatchable = {}
704 object_type_info = {}
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600705
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600706 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600707 for item in self.object_types:
708 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600709 enum_entry = 'kVulkanObjectType%s' % fixup_name
John Zulaufd7435c62018-03-16 11:52:57 -0600710 enum_entry_map[item] = enum_entry
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600711 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600712 object_types_header += ' = %d,\n' % enum_num
713 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600714 type_list.append(enum_entry)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600715 object_type_info[enum_entry] = { 'VkType': item }
716 # 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 -0700717 if self.handle_types.IsNonDispatchable(item):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600718 non_dispatchable[item] = enum_entry
719 else:
720 dispatchable[item] = enum_entry
721
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600722 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
John Zulaufd7435c62018-03-16 11:52:57 -0600723 object_types_header += ' // Aliases for backwards compatibilty of "promoted" types\n'
724 for (name, alias) in self.object_type_aliases:
725 fixup_name = name[2:]
726 object_types_header += ' kVulkanObjectType{} = {},\n'.format(fixup_name, enum_entry_map[alias])
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600727 object_types_header += '} VulkanObjectType;\n\n'
728
729 # Output name string helper
730 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600731 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
locke-lunargb4c57852019-06-14 23:20:05 -0600732 object_types_header += ' "VkNonDispatchableHandle",\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600733 for item in self.object_types:
locke-lunargb4c57852019-06-14 23:20:05 -0600734 object_types_header += ' "%s",\n' % item
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600735 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600736
John Zulauf311a4892018-03-12 15:48:06 -0600737 # Key creation helper for map comprehensions that convert between k<Name> and VK<Name> symbols
738 def to_key(regex, raw_key): return re.search(regex, raw_key).group(1).lower().replace("_","")
739
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600740 # Output a conversion routine from the layer object definitions to the debug report definitions
John Zulauf311a4892018-03-12 15:48:06 -0600741 # As the VK_DEBUG_REPORT types are not being updated, specify UNKNOWN for unmatched types
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600742 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600743 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 -0600744 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700745 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000746
John Zulauf311a4892018-03-12 15:48:06 -0600747 dbg_re = '^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$'
748 dbg_map = {to_key(dbg_re, dbg) : dbg for dbg in self.debug_report_object_types}
749 dbg_default = 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600750
John Zulauf311a4892018-03-12 15:48:06 -0600751 for object_type in type_list:
752 vk_object_type = dbg_map.get(object_type.replace("kVulkanObjectType", "").lower(), dbg_default)
753 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600754 object_type_info[object_type]['DbgType'] = vk_object_type
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600755 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600756
757 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600758 # 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 -0600759 object_types_header += '\n'
760 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
761 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700762 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
John Zulauf311a4892018-03-12 15:48:06 -0600763
764 vko_re = '^VK_OBJECT_TYPE_(.*)'
765 vko_map = {to_key(vko_re, vko) : vko for vko in self.core_object_types}
Mark Young1ded24b2017-05-30 14:53:50 -0600766 for object_type in type_list:
John Zulauf311a4892018-03-12 15:48:06 -0600767 vk_object_type = vko_map[object_type.replace("kVulkanObjectType", "").lower()]
768 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600769 object_type_info[object_type]['VkoType'] = vk_object_type
Mark Young1ded24b2017-05-30 14:53:50 -0600770 object_types_header += '};\n'
771
Mark Young6ba8abe2017-11-09 10:37:04 -0700772 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
773 object_types_header += '\n'
774 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600775 object_types_header += 'static inline VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700776 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
777 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
778 for core_object_type in self.core_object_types:
779 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
780 core_target_type = core_target_type.replace("_", "")
781 for dr_object_type in self.debug_report_object_types:
782 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
783 dr_target_type = dr_target_type[:-4]
784 dr_target_type = dr_target_type.replace("_", "")
785 if core_target_type == dr_target_type:
786 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
787 object_types_header += ' return %s;\n' % core_object_type
788 break
789 object_types_header += ' }\n'
790 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
791 object_types_header += '}\n'
792
793 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
794 object_types_header += '\n'
795 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600796 object_types_header += 'static inline VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700797 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
798 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
799 for core_object_type in self.core_object_types:
800 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
801 core_target_type = core_target_type.replace("_", "")
802 for dr_object_type in self.debug_report_object_types:
803 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
804 dr_target_type = dr_target_type[:-4]
805 dr_target_type = dr_target_type.replace("_", "")
806 if core_target_type == dr_target_type:
807 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
808 object_types_header += ' return %s;\n' % dr_object_type
809 break
810 object_types_header += ' }\n'
811 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
812 object_types_header += '}\n'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600813
814 traits_format = Outdent('''
815 template <> struct VkHandleInfo<{vk_type}> {{
816 static const VulkanObjectType kVulkanObjectType = {obj_type};
817 static const VkDebugReportObjectTypeEXT kDebugReportObjectType = {dbg_type};
818 static const VkObjectType kVkObjectType = {vko_type};
819 static const char* Typename() {{
820 return "{vk_type}";
821 }}
822 }};
823 template <> struct VulkanObjectTypeInfo<{obj_type}> {{
824 typedef {vk_type} Type;
825 }};
826 ''')
827
828 object_types_header += Outdent('''
829 // Traits objects from each type statically map from Vk<handleType> to the various enums
830 template <typename VkType> struct VkHandleInfo {};
831 template <VulkanObjectType id> struct VulkanObjectTypeInfo {};
832
833 // The following line must match the vulkan_core.h condition guarding VK_DEFINE_NON_DISPATCHABLE_HANDLE
834 #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || \
835 defined(_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
836 #define TYPESAFE_NONDISPATCHABLE_HANDLES
837 #else
838 VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkNonDispatchableHandle)
839 ''') +'\n'
840 object_types_header += traits_format.format(vk_type='VkNonDispatchableHandle', obj_type='kVulkanObjectTypeUnknown',
841 dbg_type='VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT',
842 vko_type='VK_OBJECT_TYPE_UNKNOWN') + '\n'
843 object_types_header += '#endif // VK_DEFINE_HANDLE logic duplication\n'
844
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700845 for vk_type, object_type in sorted(dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600846 info = object_type_info[object_type]
847 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
848 vko_type=info['VkoType'])
849 object_types_header += '#ifdef TYPESAFE_NONDISPATCHABLE_HANDLES\n'
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700850 for vk_type, object_type in sorted(non_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 += '#endif // TYPESAFE_NONDISPATCHABLE_HANDLES\n'
855
856 object_types_header += Outdent('''
857 struct VulkanTypedHandle {
858 uint64_t handle;
859 VulkanObjectType type;
860 template <typename Handle>
John Zulauf4fea6622019-04-01 11:38:18 -0600861 VulkanTypedHandle(Handle handle_, VulkanObjectType type_) :
862 handle(CastToUint64(handle_)),
863 type(type_) {
864 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
865 // For 32 bit it's not always safe to check for traits <-> type
866 // as all non-dispatchable handles have the same type-id and thus traits,
867 // but on 64 bit we can validate the passed type matches the passed handle
868 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
869 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
870 }
871 template <typename Handle>
872 Handle Cast() const {
873 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
874 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
875 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
876 return CastFromUint64<Handle>(handle);
877 }
John Zulauf2c2ccd42019-04-05 13:13:13 -0600878 VulkanTypedHandle() :
879 handle(VK_NULL_HANDLE),
880 type(kVulkanObjectTypeUnknown) {}
881 }; ''') +'\n'
882
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600883 return object_types_header
884 #
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600885 # Generate pNext handling function
886 def build_pnext_chain_processing_func(self):
887 # Construct helper functions to build and free pNext extension chains
888 build_pnext_proc = '\n\n'
889 build_pnext_proc += 'void *SafePnextCopy(const void *pNext) {\n'
890 build_pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
891 build_pnext_proc += ' void *cur_ext_struct = NULL;\n\n'
892 build_pnext_proc += ' if (cur_pnext == nullptr) {\n'
893 build_pnext_proc += ' return nullptr;\n'
894 build_pnext_proc += ' } else {\n'
895 build_pnext_proc += ' VkBaseOutStructure *header = reinterpret_cast<VkBaseOutStructure *>(cur_pnext);\n\n'
896 build_pnext_proc += ' switch (header->sType) {\n'
897
898 free_pnext_proc = '\n\n'
899 free_pnext_proc += '// Free a pNext extension chain\n'
900 free_pnext_proc += 'void FreePnextChain(void *head) {\n'
901 free_pnext_proc += ' VkBaseOutStructure *curr_ptr = reinterpret_cast<VkBaseOutStructure *>(head);\n'
902 free_pnext_proc += ' while (curr_ptr) {\n'
903 free_pnext_proc += ' VkBaseOutStructure *header = curr_ptr;\n'
904 free_pnext_proc += ' curr_ptr = reinterpret_cast<VkBaseOutStructure *>(header->pNext);\n\n'
905 free_pnext_proc += ' switch (header->sType) {\n';
906
907 for item in self.structextends_list:
908 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == item), None)
909 if member_index is None:
910 continue
911 struct_info = self.structMembers[member_index][1]
912 feature_protect = self.structMembers[member_index][2]
913
914 if feature_protect is not None:
915 build_pnext_proc += '#ifdef %s\n' % feature_protect
916 free_pnext_proc += '#ifdef %s\n' % feature_protect
917 build_pnext_proc += ' case %s: {\n' % self.structTypes[item].value
918 build_pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
919 build_pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
920 build_pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
921 build_pnext_proc += ' } break;\n'
922
923 free_pnext_proc += ' case %s:\n' % self.structTypes[item].value
924 free_pnext_proc += ' delete reinterpret_cast<safe_%s *>(header);\n' % item
925 free_pnext_proc += ' break;\n'
926
927 if feature_protect is not None:
928 build_pnext_proc += '#endif // %s\n' % feature_protect
929 free_pnext_proc += '#endif // %s\n' % feature_protect
930 build_pnext_proc += '\n'
931 free_pnext_proc += '\n'
932
933 build_pnext_proc += ' default:\n'
934 build_pnext_proc += ' break;\n'
935 build_pnext_proc += ' }\n'
936 build_pnext_proc += ' }\n'
937 build_pnext_proc += ' return cur_ext_struct;\n'
938 build_pnext_proc += '}\n\n'
939
940 free_pnext_proc += ' default:\n'
941 free_pnext_proc += ' assert(0);\n'
942 free_pnext_proc += ' }\n'
943 free_pnext_proc += ' }\n'
944 free_pnext_proc += '}\n'
945
946 pnext_procs = build_pnext_proc + free_pnext_proc
947 return pnext_procs
948 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700949 # Determine if a structure needs a safe_struct helper function
950 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700951 def NeedSafeStruct(self, structure):
Mark Lobodzinskib6cc5412019-07-19 09:56:58 -0600952 if 'VkBase' in structure.name:
953 return False
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700954 if 'sType' == structure.name:
955 return True
956 for member in structure.members:
957 if member.ispointer == True:
958 return True
959 return False
960 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700961 # Combine safe struct helper source file preamble with body text and return
962 def GenerateSafeStructHelperSource(self):
963 safe_struct_helper_source = '\n'
964 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600965 safe_struct_helper_source += '#include <assert.h>\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700966 safe_struct_helper_source += '#include <string.h>\n'
967 safe_struct_helper_source += '\n'
968 safe_struct_helper_source += self.GenerateSafeStructSource()
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600969 safe_struct_helper_source += self.build_pnext_chain_processing_func()
970
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700971 return safe_struct_helper_source
972 #
973 # safe_struct source -- create bodies of safe struct helper functions
974 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700975 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700976 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
977 'VkXcbSurfaceCreateInfoKHR',
978 'VkWaylandSurfaceCreateInfoKHR',
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700979 'VkAndroidSurfaceCreateInfoKHR',
980 'VkWin32SurfaceCreateInfoKHR'
981 ]
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -0600982
983 # For abstract types just want to save the pointer away
984 # since we cannot make a copy.
985 abstract_types = ['AHardwareBuffer',
986 'ANativeWindow',
987 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700988 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700989 if self.NeedSafeStruct(item) == False:
990 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700991 if item.name in wsi_structs:
992 continue
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100993 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700994 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
995 ss_name = "safe_%s" % item.name
996 init_list = '' # list of members in struct constructor initializer
997 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
998 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
999 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
1000 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +01001001
1002 custom_construct_txt = {
1003 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
1004 'VkWriteDescriptorSet' :
1005 ' switch (descriptorType) {\n'
1006 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
1007 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
1008 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
1009 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
1010 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
1011 ' if (descriptorCount && in_struct->pImageInfo) {\n'
1012 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
1013 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1014 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
1015 ' }\n'
1016 ' }\n'
1017 ' break;\n'
1018 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
1019 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
1020 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
1021 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
1022 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
1023 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
1024 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1025 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
1026 ' }\n'
1027 ' }\n'
1028 ' break;\n'
1029 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
1030 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
1031 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
1032 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
1033 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1034 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
1035 ' }\n'
1036 ' }\n'
1037 ' break;\n'
1038 ' default:\n'
1039 ' break;\n'
1040 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001041 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +01001042 ' if (in_struct->pCode) {\n'
1043 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
1044 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
1045 ' }\n',
1046 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
1047 'VkGraphicsPipelineCreateInfo' :
1048 ' if (stageCount && in_struct->pStages) {\n'
1049 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1050 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1051 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
1052 ' }\n'
1053 ' }\n'
1054 ' if (in_struct->pVertexInputState)\n'
1055 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
1056 ' else\n'
1057 ' pVertexInputState = NULL;\n'
1058 ' if (in_struct->pInputAssemblyState)\n'
1059 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
1060 ' else\n'
1061 ' pInputAssemblyState = NULL;\n'
1062 ' bool has_tessellation_stage = false;\n'
1063 ' if (stageCount && pStages)\n'
1064 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1065 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1066 ' has_tessellation_stage = true;\n'
1067 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
1068 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
1069 ' else\n'
1070 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1071 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
1072 ' if (in_struct->pViewportState && has_rasterization) {\n'
1073 ' bool is_dynamic_viewports = false;\n'
1074 ' bool is_dynamic_scissors = false;\n'
1075 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
1076 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
1077 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
1078 ' is_dynamic_viewports = true;\n'
1079 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
1080 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
1081 ' is_dynamic_scissors = true;\n'
1082 ' }\n'
1083 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
1084 ' } else\n'
1085 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1086 ' if (in_struct->pRasterizationState)\n'
1087 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
1088 ' else\n'
1089 ' pRasterizationState = NULL;\n'
1090 ' if (in_struct->pMultisampleState && has_rasterization)\n'
1091 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
1092 ' else\n'
1093 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1094 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
1095 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
1096 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
1097 ' else\n'
1098 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1099 ' // needs a tracked subpass state usesColorAttachment\n'
1100 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
1101 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
1102 ' else\n'
1103 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1104 ' if (in_struct->pDynamicState)\n'
1105 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
1106 ' else\n'
1107 ' pDynamicState = NULL;\n',
1108 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
1109 'VkPipelineViewportStateCreateInfo' :
1110 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
1111 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
1112 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
1113 ' }\n'
1114 ' else\n'
1115 ' pViewports = NULL;\n'
1116 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
1117 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
1118 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
1119 ' }\n'
1120 ' else\n'
1121 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001122 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
1123 'VkDescriptorSetLayoutBinding' :
1124 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
1125 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
1126 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
1127 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1128 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
1129 ' }\n'
1130 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +01001131 }
1132
1133 custom_copy_txt = {
1134 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
1135 'VkGraphicsPipelineCreateInfo' :
1136 ' if (stageCount && src.pStages) {\n'
1137 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1138 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1139 ' pStages[i].initialize(&src.pStages[i]);\n'
1140 ' }\n'
1141 ' }\n'
1142 ' if (src.pVertexInputState)\n'
1143 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
1144 ' else\n'
1145 ' pVertexInputState = NULL;\n'
1146 ' if (src.pInputAssemblyState)\n'
1147 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
1148 ' else\n'
1149 ' pInputAssemblyState = NULL;\n'
1150 ' bool has_tessellation_stage = false;\n'
1151 ' if (stageCount && pStages)\n'
1152 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1153 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1154 ' has_tessellation_stage = true;\n'
1155 ' if (src.pTessellationState && has_tessellation_stage)\n'
1156 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
1157 ' else\n'
1158 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1159 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
1160 ' if (src.pViewportState && has_rasterization) {\n'
1161 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
1162 ' } else\n'
1163 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1164 ' if (src.pRasterizationState)\n'
1165 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
1166 ' else\n'
1167 ' pRasterizationState = NULL;\n'
1168 ' if (src.pMultisampleState && has_rasterization)\n'
1169 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
1170 ' else\n'
1171 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1172 ' if (src.pDepthStencilState && has_rasterization)\n'
1173 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
1174 ' else\n'
1175 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1176 ' if (src.pColorBlendState && has_rasterization)\n'
1177 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1178 ' else\n'
1179 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1180 ' if (src.pDynamicState)\n'
1181 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1182 ' else\n'
1183 ' pDynamicState = NULL;\n',
1184 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1185 'VkPipelineViewportStateCreateInfo' :
1186 ' if (src.pViewports) {\n'
1187 ' pViewports = new VkViewport[src.viewportCount];\n'
1188 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1189 ' }\n'
1190 ' else\n'
1191 ' pViewports = NULL;\n'
1192 ' if (src.pScissors) {\n'
1193 ' pScissors = new VkRect2D[src.scissorCount];\n'
1194 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1195 ' }\n'
1196 ' else\n'
1197 ' pScissors = NULL;\n',
1198 }
1199
Mike Schuchardt81485762017-09-04 11:38:42 -06001200 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1201 ' if (pCode)\n'
1202 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001203
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001204 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001205 m_type = member.type
1206 if member.type in self.structNames:
1207 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1208 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1209 m_type = 'safe_%s' % member.type
1210 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1211 # 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 -07001212 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001213 # For these exceptions just copy initial value over for now
1214 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1215 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001216 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001217 default_init_list += '\n %s(nullptr),' % (member.name)
1218 init_list += '\n %s(nullptr),' % (member.name)
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001219 if m_type in abstract_types:
1220 construct_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1221 else:
1222 init_func_txt += ' %s = nullptr;\n' % (member.name)
1223 if 'pNext' != member.name and 'void' not in m_type:
1224 if not member.isstaticarray and (member.len is None or '/' in member.len):
1225 construct_txt += ' if (in_struct->%s) {\n' % member.name
1226 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1227 construct_txt += ' }\n'
1228 destruct_txt += ' if (%s)\n' % member.name
1229 destruct_txt += ' delete %s;\n' % member.name
1230 else:
1231 construct_txt += ' if (in_struct->%s) {\n' % member.name
1232 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1233 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1234 construct_txt += ' }\n'
1235 destruct_txt += ' if (%s)\n' % member.name
1236 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001237 elif member.isstaticarray or member.len is not None:
1238 if member.len is None:
1239 # Extract length of static array by grabbing val between []
1240 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1241 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1242 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1243 construct_txt += ' }\n'
1244 else:
1245 # Init array ptr to NULL
1246 default_init_list += '\n %s(nullptr),' % member.name
1247 init_list += '\n %s(nullptr),' % member.name
1248 init_func_txt += ' %s = nullptr;\n' % member.name
1249 array_element = 'in_struct->%s[i]' % member.name
1250 if member.type in self.structNames:
1251 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1252 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1253 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1254 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1255 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1256 destruct_txt += ' if (%s)\n' % member.name
1257 destruct_txt += ' delete[] %s;\n' % member.name
1258 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1259 if 'safe_' in m_type:
1260 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001261 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001262 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1263 construct_txt += ' }\n'
1264 construct_txt += ' }\n'
1265 elif member.ispointer == True:
1266 construct_txt += ' if (in_struct->%s)\n' % member.name
1267 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1268 construct_txt += ' else\n'
1269 construct_txt += ' %s = NULL;\n' % member.name
1270 destruct_txt += ' if (%s)\n' % member.name
1271 destruct_txt += ' delete %s;\n' % member.name
1272 elif 'safe_' in m_type:
1273 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1274 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1275 else:
1276 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1277 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1278 if '' != init_list:
1279 init_list = init_list[:-1] # hack off final comma
1280 if item.name in custom_construct_txt:
1281 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001282 if item.name in custom_destruct_txt:
1283 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001284 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 -07001285 if '' != default_init_list:
1286 default_init_list = " :%s" % (default_init_list[:-1])
1287 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1288 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1289 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1290 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1291 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1292 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001293 if item.name in custom_copy_txt:
1294 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001295 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 -06001296 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 -07001297 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 -07001298 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001299 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 -07001300 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1301 init_copy = copy_construct_init.replace('src.', 'src->')
1302 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001303 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 +01001304 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001305 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1306 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001307 #
John Zulaufde972ac2017-10-26 12:07:05 -06001308 # Generate the type map
1309 def GenerateTypeMapHelperHeader(self):
1310 prefix = 'Lvl'
1311 fprefix = 'lvl_'
1312 typemap = prefix + 'TypeMap'
1313 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001314 type_member = 'Type'
1315 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001316 id_decl = 'static const VkStructureType '
Locke6b6b7382019-04-16 15:08:49 -06001317 generic_header = 'VkBaseOutStructure'
John Zulaufde972ac2017-10-26 12:07:05 -06001318 typename_func = fprefix + 'typename'
1319 idname_func = fprefix + 'stype_name'
1320 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001321 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001322
1323 explanatory_comment = '\n'.join((
1324 '// These empty generic templates are specialized for each type with sType',
1325 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001326 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001327
1328 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1329 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001330 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1331 typemap_format += '}};\n'
1332
1333 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1334 idmap_format = ''.join((
1335 'template <> struct {template}<{id_value}> {{\n',
1336 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001337 '}};\n'))
1338
1339 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1340 utilities_format = '\n'.join((
John Zulaufde972ac2017-10-26 12:07:05 -06001341 '// Find an entry of the given type in the pNext chain',
1342 'template <typename T> const T *{find_func}(const void *next) {{',
1343 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1344 ' const T *found = nullptr;',
1345 ' while (current) {{',
1346 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1347 ' found = reinterpret_cast<const T*>(current);',
1348 ' current = nullptr;',
1349 ' }} else {{',
1350 ' current = current->pNext;',
1351 ' }}',
1352 ' }}',
1353 ' return found;',
1354 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001355 '',
1356 '// Init the header of an sType struct with pNext',
1357 'template <typename T> T {init_func}(void *p_next) {{',
1358 ' T out = {{}};',
1359 ' out.sType = {type_map}<T>::kSType;',
1360 ' out.pNext = p_next;',
1361 ' return out;',
1362 '}}',
1363 '',
1364 '// Init the header of an sType struct',
1365 'template <typename T> T {init_func}() {{',
1366 ' T out = {{}};',
1367 ' out.sType = {type_map}<T>::kSType;',
1368 ' return out;',
1369 '}}',
1370
Mike Schuchardt97662b02017-12-06 13:31:29 -07001371 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001372
1373 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001374
1375 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001376 code.append('\n'.join((
1377 '#pragma once',
1378 '#include <vulkan/vulkan.h>\n',
1379 explanatory_comment, '',
1380 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001381 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001382
1383 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001384 for item in self.structMembers:
1385 typename = item.name
1386 info = self.structTypes.get(typename)
1387 if not info:
1388 continue
1389
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001390 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001391 code.append('#ifdef %s' % item.ifdef_protect)
1392
1393 code.append('// Map type {} to id {}'.format(typename, info.value))
1394 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001395 id_decl=id_decl, id_member=id_member))
1396 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001397
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001398 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001399 code.append('#endif // %s' % item.ifdef_protect)
1400
John Zulauf65ac9d52018-01-23 11:20:50 -07001401 # Generate utilities for all types
1402 code.append('\n'.join((
1403 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1404 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1405 find_func=find_func, init_func=init_func), ''
1406 )))
1407
John Zulaufde972ac2017-10-26 12:07:05 -06001408 return "\n".join(code)
1409
1410 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001411 # Create a helper file and return it as a string
1412 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001413 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001414 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001415 elif self.helper_file_type == 'safe_struct_header':
1416 return self.GenerateSafeStructHelperHeader()
1417 elif self.helper_file_type == 'safe_struct_source':
1418 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001419 elif self.helper_file_type == 'object_types_header':
1420 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001421 elif self.helper_file_type == 'extension_helper_header':
1422 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001423 elif self.helper_file_type == 'typemap_helper_header':
1424 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001425 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001426 return 'Bad Helper File Generator Option %s' % self.helper_file_type