blob: 4f1bd3738b7fa043356d9aaf745e1c3aed2b3bc1 [file] [log] [blame]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001#!/usr/bin/python3 -i
2#
Mark Lobodzinski733f7f42017-01-10 11:42:22 -07003# Copyright (c) 2015-2017 The Khronos Group Inc.
4# Copyright (c) 2015-2017 Valve Corporation
5# Copyright (c) 2015-2017 LunarG, Inc.
6# Copyright (c) 2015-2017 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,
34 filename = None,
35 directory = '.',
36 apiname = None,
37 profile = None,
38 versions = '.*',
39 emitversions = '.*',
40 defaultExtensions = None,
41 addExtensions = None,
42 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060043 emitExtensions = None,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070044 sortProcedure = regSortFeatures,
45 prefixText = "",
46 genFuncPointers = True,
47 protectFile = True,
48 protectFeature = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070049 apicall = '',
50 apientry = '',
51 apientryp = '',
52 alignFuncParam = 0,
53 library_name = '',
Mark Lobodzinski62f71562017-10-24 13:41:18 -060054 expandEnumerants = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070055 helper_file_type = ''):
56 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
57 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060058 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070059 self.prefixText = prefixText
60 self.genFuncPointers = genFuncPointers
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070061 self.protectFile = protectFile
62 self.protectFeature = protectFeature
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070063 self.apicall = apicall
64 self.apientry = apientry
65 self.apientryp = apientryp
66 self.alignFuncParam = alignFuncParam
67 self.library_name = library_name
68 self.helper_file_type = helper_file_type
69#
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070070# HelperFileOutputGenerator - subclass of OutputGenerator. Outputs Vulkan helper files
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070071class HelperFileOutputGenerator(OutputGenerator):
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -070072 """Generate helper file based on XML element attributes"""
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070073 def __init__(self,
74 errFile = sys.stderr,
75 warnFile = sys.stderr,
76 diagFile = sys.stdout):
77 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
78 # Internal state - accumulators for different inner block text
Mark Lobodzinski5380d132016-12-28 14:45:34 -070079 self.enum_output = '' # string built up of enum string routines
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070080 # Internal state - accumulators for different inner block text
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070081 self.structNames = [] # List of Vulkan struct typenames
82 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070083 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -060084 self.object_types = [] # List of all handle types
John Zulaufd7435c62018-03-16 11:52:57 -060085 self.object_type_aliases = [] # Aliases to handles types (for handles that were extensions)
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060086 self.debug_report_object_types = [] # Handy copy of debug_report_object_type enum data
Mark Young1ded24b2017-05-30 14:53:50 -060087 self.core_object_types = [] # Handy copy of core_object_type enum data
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -060088 self.device_extension_info = dict() # Dict of device extension name defines and ifdef values
89 self.instance_extension_info = dict() # Dict of instance extension name defines and ifdef values
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060090
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070091 # Named tuples to store struct and command data
92 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070093 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl'])
Mark Lobodzinski5380d132016-12-28 14:45:34 -070094 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members', 'ifdef_protect'])
Petr Krause91f7a12017-12-14 20:57:36 +010095
96 self.custom_construct_params = {
97 # safe_VkGraphicsPipelineCreateInfo needs to know if subpass has color and\or depth\stencil attachments to use its pointers
98 'VkGraphicsPipelineCreateInfo' :
99 ', const bool uses_color_attachment, const bool uses_depthstencil_attachment',
100 # safe_VkPipelineViewportStateCreateInfo needs to know if viewport and scissor is dynamic to use its pointers
101 'VkPipelineViewportStateCreateInfo' :
102 ', const bool is_dynamic_viewports, const bool is_dynamic_scissors',
103 }
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700104 #
105 # Called once at the beginning of each run
106 def beginFile(self, genOpts):
107 OutputGenerator.beginFile(self, genOpts)
108 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700109 self.helper_file_type = genOpts.helper_file_type
110 self.library_name = genOpts.library_name
111 # File Comment
112 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
113 file_comment += '// See helper_file_generator.py for modifications\n'
114 write(file_comment, file=self.outFile)
115 # Copyright Notice
116 copyright = ''
117 copyright += '\n'
118 copyright += '/***************************************************************************\n'
119 copyright += ' *\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700120 copyright += ' * Copyright (c) 2015-2017 The Khronos Group Inc.\n'
121 copyright += ' * Copyright (c) 2015-2017 Valve Corporation\n'
122 copyright += ' * Copyright (c) 2015-2017 LunarG, Inc.\n'
123 copyright += ' * Copyright (c) 2015-2017 Google Inc.\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700124 copyright += ' *\n'
125 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
126 copyright += ' * you may not use this file except in compliance with the License.\n'
127 copyright += ' * You may obtain a copy of the License at\n'
128 copyright += ' *\n'
129 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
130 copyright += ' *\n'
131 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
132 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
133 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
134 copyright += ' * See the License for the specific language governing permissions and\n'
135 copyright += ' * limitations under the License.\n'
136 copyright += ' *\n'
137 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Mark Lobodzinskia9c963d2016-12-28 07:45:35 -0700138 copyright += ' * Author: Courtney Goeltzenleuchter <courtneygo@google.com>\n'
139 copyright += ' * Author: Tobin Ehlis <tobine@google.com>\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600140 copyright += ' * Author: Chris Forbes <chrisforbes@google.com>\n'
John Zulaufde972ac2017-10-26 12:07:05 -0600141 copyright += ' * Author: John Zulauf<jzulauf@lunarg.com>\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700142 copyright += ' *\n'
143 copyright += ' ****************************************************************************/\n'
144 write(copyright, file=self.outFile)
145 #
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -0700146 # Write generated file content to output file
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700147 def endFile(self):
148 dest_file = ''
149 dest_file += self.OutputDestFile()
Mark Lobodzinskiafe10542017-01-03 13:22:44 -0700150 # Remove blank lines at EOF
151 if dest_file.endswith('\n'):
152 dest_file = dest_file[:-1]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700153 write(dest_file, file=self.outFile);
154 # Finish processing in superclass
155 OutputGenerator.endFile(self)
156 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600157 # Override parent class to be notified of the beginning of an extension
158 def beginFeature(self, interface, emit):
159 # Start processing in superclass
160 OutputGenerator.beginFeature(self, interface, emit)
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600161 self.featureExtraProtect = GetFeatureProtect(interface)
162
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600163 if self.featureName == 'VK_VERSION_1_0' or self.featureName == 'VK_VERSION_1_1':
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600164 return
John Zulauff6feb2a2018-04-12 14:24:57 -0600165 name = self.featureName
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600166 nameElem = interface[0][1]
John Zulauff6feb2a2018-04-12 14:24:57 -0600167 name_define = nameElem.get('name')
168 if 'EXTENSION_NAME' not in name_define:
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600169 print("Error in vk.xml file -- extension name is not available")
John Zulauf072677c2018-04-12 15:34:39 -0600170 requires = interface.get('requires')
171 if requires is not None:
172 required_extensions = requires.split(',')
173 else:
174 required_extensions = list()
175 info = { 'define': name_define, 'ifdef':self.featureExtraProtect, 'reqs':required_extensions }
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600176 if interface.get('type') == 'instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600177 self.instance_extension_info[name] = info
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600178 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600179 self.device_extension_info[name] = info
180
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600181 #
182 # Override parent class to be notified of the end of an extension
183 def endFeature(self):
184 # Finish processing in superclass
185 OutputGenerator.endFeature(self)
186 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700187 # Grab group (e.g. C "enum" type) info to output for enum-string conversion helper
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700188 def genGroup(self, groupinfo, groupName, alias):
189 OutputGenerator.genGroup(self, groupinfo, groupName, alias)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700190 groupElem = groupinfo.elem
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700191 # For enum_string_header
192 if self.helper_file_type == 'enum_string_header':
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700193 value_set = set()
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700194 for elem in groupElem.findall('enum'):
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100195 if elem.get('supported') != 'disabled' and elem.get('alias') is None:
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700196 value_set.add(elem.get('name'))
197 self.enum_output += self.GenerateEnumStringConversion(groupName, value_set)
Mark Young1ded24b2017-05-30 14:53:50 -0600198 elif self.helper_file_type == 'object_types_header':
199 if groupName == 'VkDebugReportObjectTypeEXT':
200 for elem in groupElem.findall('enum'):
201 if elem.get('supported') != 'disabled':
202 item_name = elem.get('name')
203 self.debug_report_object_types.append(item_name)
204 elif groupName == 'VkObjectType':
205 for elem in groupElem.findall('enum'):
206 if elem.get('supported') != 'disabled':
207 item_name = elem.get('name')
208 self.core_object_types.append(item_name)
209
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700210 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700211 # Called for each type -- if the type is a struct/union, grab the metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700212 def genType(self, typeinfo, name, alias):
213 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700214 typeElem = typeinfo.elem
215 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
216 # Otherwise, emit the tag text.
217 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600218 if category == 'handle':
John Zulaufd7435c62018-03-16 11:52:57 -0600219 if alias:
220 self.object_type_aliases.append((name,alias))
221 else:
222 self.object_types.append(name)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600223 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700224 self.structNames.append(name)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700225 self.genStruct(typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700226 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700227 # Check if the parameter passed in is a pointer
228 def paramIsPointer(self, param):
229 ispointer = False
230 for elem in param:
231 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
232 ispointer = True
233 return ispointer
234 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700235 # Check if the parameter passed in is a static array
236 def paramIsStaticArray(self, param):
237 isstaticarray = 0
238 paramname = param.find('name')
239 if (paramname.tail is not None) and ('[' in paramname.tail):
240 isstaticarray = paramname.tail.count('[')
241 return isstaticarray
242 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700243 # Retrieve the type and name for a parameter
244 def getTypeNameTuple(self, param):
245 type = ''
246 name = ''
247 for elem in param:
248 if elem.tag == 'type':
249 type = noneStr(elem.text)
250 elif elem.tag == 'name':
251 name = noneStr(elem.text)
252 return (type, name)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700253 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
254 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
255 def parseLateXMath(self, source):
256 name = 'ERROR'
257 decoratedName = 'ERROR'
258 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700259 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
260 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 -0700261 if not match or match.group(1) != match.group(4):
262 raise 'Unrecognized latexmath expression'
263 name = match.group(2)
mizhenc27f6c72017-03-31 09:08:16 -0600264 # Need to add 1 for ceiling function; otherwise, the allocated packet
265 # size will be less than needed during capture for some title which use
266 # this in VkPipelineMultisampleStateCreateInfo. based on ceiling function
267 # definition,it is '{0}%{1}?{0}/{1} + 1:{0}/{1}'.format(*match.group(2, 3)),
268 # its value <= '{}/{} + 1'.
269 if match.group(1) == 'ceil':
270 decoratedName = '{}/{} + 1'.format(*match.group(2, 3))
271 else:
272 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700273 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700274 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600275 match = re.match(r'latexmath\s*\:\s*\[\s*(\\textrm\{)?(\w+)\}?\s*\\over\s*(\d+)\s*\]', source)
276 name = match.group(2)
277 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700278 return name, decoratedName
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700279 #
280 # Retrieve the value of the len tag
281 def getLen(self, param):
282 result = None
283 len = param.attrib.get('len')
284 if len and len != 'null-terminated':
285 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
286 # have a null terminated array of strings. We strip the null-terminated from the
287 # 'len' field and only return the parameter specifying the string count
288 if 'null-terminated' in len:
289 result = len.split(',')[0]
290 else:
291 result = len
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700292 if 'latexmath' in len:
293 param_type, param_name = self.getTypeNameTuple(param)
294 len_name, result = self.parseLateXMath(len)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700295 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
296 result = str(result).replace('::', '->')
297 return result
298 #
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600299 # Check if a structure is or contains a dispatchable (dispatchable = True) or
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700300 # non-dispatchable (dispatchable = False) handle
301 def TypeContainsObjectHandle(self, handle_type, dispatchable):
302 if dispatchable:
303 type_key = 'VK_DEFINE_HANDLE'
304 else:
305 type_key = 'VK_DEFINE_NON_DISPATCHABLE_HANDLE'
306 handle = self.registry.tree.find("types/type/[name='" + handle_type + "'][@category='handle']")
307 if handle is not None and handle.find('type').text == type_key:
308 return True
309 # if handle_type is a struct, search its members
310 if handle_type in self.structNames:
311 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == handle_type), None)
312 if member_index is not None:
313 for item in self.structMembers[member_index].members:
314 handle = self.registry.tree.find("types/type/[name='" + item.type + "'][@category='handle']")
315 if handle is not None and handle.find('type').text == type_key:
316 return True
317 return False
318 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700319 # Generate local ready-access data describing Vulkan structures and unions from the XML metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700320 def genStruct(self, typeinfo, typeName, alias):
321 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700322 members = typeinfo.elem.findall('.//member')
323 # Iterate over members once to get length parameters for arrays
324 lens = set()
325 for member in members:
326 len = self.getLen(member)
327 if len:
328 lens.add(len)
329 # Generate member info
330 membersInfo = []
331 for member in members:
332 # Get the member's type and name
333 info = self.getTypeNameTuple(member)
334 type = info[0]
335 name = info[1]
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700336 cdecl = self.makeCParamDecl(member, 1)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700337 # Process VkStructureType
338 if type == 'VkStructureType':
339 # Extract the required struct type value from the comments
340 # embedded in the original text defining the 'typeinfo' element
341 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
342 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
343 if result:
344 value = result.group(0)
Mike Schuchardt08368cb2018-05-22 14:52:04 -0600345 # Store the required type value
346 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700347 # Store pointer/array/string info
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700348 isstaticarray = self.paramIsStaticArray(member)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700349 membersInfo.append(self.CommandParam(type=type,
350 name=name,
351 ispointer=self.paramIsPointer(member),
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700352 isstaticarray=isstaticarray,
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700353 isconst=True if 'const' in cdecl else False,
354 iscount=True if name in lens else False,
355 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600356 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700357 cdecl=cdecl))
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700358 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo, ifdef_protect=self.featureExtraProtect))
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700359 #
360 # Enum_string_header: Create a routine to convert an enumerated value into a string
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700361 def GenerateEnumStringConversion(self, groupName, value_list):
362 outstring = '\n'
363 outstring += 'static inline const char* string_%s(%s input_value)\n' % (groupName, groupName)
364 outstring += '{\n'
365 outstring += ' switch ((%s)input_value)\n' % groupName
366 outstring += ' {\n'
Karl Schultz7fd3f6e2018-07-05 17:21:05 -0600367 # Emit these in a repeatable order so file is generated with the same contents each time.
368 # This helps compiler caching systems like ccache.
369 for item in sorted(value_list):
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700370 outstring += ' case %s:\n' % item
371 outstring += ' return "%s";\n' % item
372 outstring += ' default:\n'
373 outstring += ' return "Unhandled %s";\n' % groupName
374 outstring += ' }\n'
375 outstring += '}\n'
376 return outstring
377 #
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600378 # Tack on a helper which, given an index into a VkPhysicalDeviceFeatures structure, will print the corresponding feature name
379 def DeIndexPhysDevFeatures(self):
380 pdev_members = None
381 for name, members, ifdef in self.structMembers:
382 if name == 'VkPhysicalDeviceFeatures':
383 pdev_members = members
384 break
385 deindex = '\n'
Mark Young2ee6aea2018-02-21 15:30:27 -0700386 deindex += 'static inline const char * GetPhysDevFeatureString(uint32_t index) {\n'
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600387 deindex += ' const char * IndexToPhysDevFeatureString[] = {\n'
388 for feature in pdev_members:
389 deindex += ' "%s",\n' % feature.name
390 deindex += ' };\n\n'
391 deindex += ' return IndexToPhysDevFeatureString[index];\n'
392 deindex += '}\n'
393 return deindex
394 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700395 # Combine enum string helper header file preamble with body text and return
396 def GenerateEnumStringHelperHeader(self):
397 enum_string_helper_header = '\n'
398 enum_string_helper_header += '#pragma once\n'
399 enum_string_helper_header += '#ifdef _WIN32\n'
400 enum_string_helper_header += '#pragma warning( disable : 4065 )\n'
401 enum_string_helper_header += '#endif\n'
402 enum_string_helper_header += '\n'
403 enum_string_helper_header += '#include <vulkan/vulkan.h>\n'
404 enum_string_helper_header += '\n'
405 enum_string_helper_header += self.enum_output
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600406 enum_string_helper_header += self.DeIndexPhysDevFeatures()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700407 return enum_string_helper_header
408 #
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700409 # Helper function for declaring a counter variable only once
410 def DeclareCounter(self, string_var, declare_flag):
411 if declare_flag == False:
412 string_var += ' uint32_t i = 0;\n'
413 declare_flag = True
414 return string_var, declare_flag
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700415 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700416 # Combine safe struct helper header file preamble with body text and return
417 def GenerateSafeStructHelperHeader(self):
418 safe_struct_helper_header = '\n'
419 safe_struct_helper_header += '#pragma once\n'
420 safe_struct_helper_header += '#include <vulkan/vulkan.h>\n'
421 safe_struct_helper_header += '\n'
422 safe_struct_helper_header += self.GenerateSafeStructHeader()
423 return safe_struct_helper_header
424 #
425 # safe_struct header: build function prototypes for header file
426 def GenerateSafeStructHeader(self):
427 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700428 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700429 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700430 safe_struct_header += '\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100431 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700432 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
433 safe_struct_header += 'struct safe_%s {\n' % (item.name)
434 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700435 if member.type in self.structNames:
436 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
437 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
438 if member.ispointer:
439 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
440 else:
441 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
442 continue
443 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
444 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
445 else:
446 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100447 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 -0600448 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700449 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700450 safe_struct_header += ' safe_%s();\n' % item.name
451 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100452 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
453 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700454 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
455 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
456 safe_struct_header += '};\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100457 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700458 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700459 return safe_struct_header
460 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600461 # Generate extension helper header file
462 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600463
464 V_1_0_instance_extensions_promoted_to_core = [
465 'vk_khr_device_group_creation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600466 'vk_khr_external_fence_capabilities',
John Zulauf2012bca2018-04-25 15:28:47 -0600467 'vk_khr_external_memory_capabilities',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600468 'vk_khr_external_semaphore_capabilities',
469 'vk_khr_get_physical_device_properties_2',
470 ]
471
472 V_1_0_device_extensions_promoted_to_core = [
John Zulauf2012bca2018-04-25 15:28:47 -0600473 'vk_khr_16bit_storage',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600474 'vk_khr_bind_memory_2',
John Zulauf2012bca2018-04-25 15:28:47 -0600475 'vk_khr_dedicated_allocation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600476 'vk_khr_descriptor_update_template',
John Zulauf2012bca2018-04-25 15:28:47 -0600477 'vk_khr_device_group',
478 'vk_khr_external_fence',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600479 'vk_khr_external_memory',
480 'vk_khr_external_semaphore',
John Zulauf2012bca2018-04-25 15:28:47 -0600481 'vk_khr_get_memory_requirements_2',
482 'vk_khr_maintenance1',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600483 'vk_khr_maintenance2',
John Zulauf2012bca2018-04-25 15:28:47 -0600484 'vk_khr_maintenance3',
485 'vk_khr_multiview',
John Zulauf16826822018-04-25 15:40:32 -0600486 'vk_khr_relaxed_block_layout',
John Zulauf2012bca2018-04-25 15:28:47 -0600487 'vk_khr_sampler_ycbcr_conversion',
John Zulauf16826822018-04-25 15:40:32 -0600488 'vk_khr_shader_draw_parameters',
489 'vk_khr_storage_buffer_storage_class',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600490 'vk_khr_variable_pointers',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600491 ]
John Zulauf16826822018-04-25 15:40:32 -0600492
John Zulauff6feb2a2018-04-12 14:24:57 -0600493 output = [
494 '',
495 '#ifndef VK_EXTENSION_HELPER_H_',
496 '#define VK_EXTENSION_HELPER_H_',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600497 '#include <unordered_set>',
John Zulauf072677c2018-04-12 15:34:39 -0600498 '#include <string>',
499 '#include <unordered_map>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600500 '#include <utility>',
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600501 '#include <set>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600502 '',
John Zulauf072677c2018-04-12 15:34:39 -0600503 '#include <vulkan/vulkan.h>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600504 '']
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600505
John Zulauff6feb2a2018-04-12 14:24:57 -0600506 def guarded(ifdef, value):
507 if ifdef is not None:
508 return '\n'.join([ '#ifdef %s' % ifdef, value, '#endif' ])
509 else:
510 return value
John Zulauf380bd942018-04-10 13:12:34 -0600511
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600512 for type in ['Instance', 'Device']:
John Zulauff6feb2a2018-04-12 14:24:57 -0600513 struct_type = '%sExtensions' % type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600514 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600515 extension_dict = self.instance_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600516 promoted_ext_list = V_1_0_instance_extensions_promoted_to_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600517 struct_decl = 'struct %s {' % struct_type
518 instance_struct_type = struct_type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600519 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600520 extension_dict = self.device_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600521 promoted_ext_list = V_1_0_device_extensions_promoted_to_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600522 struct_decl = 'struct %s : public %s {' % (struct_type, instance_struct_type)
523
524 extension_items = sorted(extension_dict.items())
525
526 field_name = { ext_name: re.sub('_extension_name', '', info['define'].lower()) for ext_name, info in extension_items }
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600527 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600528 instance_field_name = field_name
John Zulauf072677c2018-04-12 15:34:39 -0600529 instance_extension_dict = extension_dict
530 else:
531 # Get complete field name and extension data for both Instance and Device extensions
532 field_name.update(instance_field_name)
533 extension_dict = extension_dict.copy() # Don't modify the self.<dict> we're pointing to
534 extension_dict.update(instance_extension_dict)
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600535
John Zulauf072677c2018-04-12 15:34:39 -0600536 # Output the data member list
John Zulauff6feb2a2018-04-12 14:24:57 -0600537 struct = [struct_decl]
538 struct.extend([ ' bool %s{false};' % field_name[ext_name] for ext_name, info in extension_items])
John Zulauf072677c2018-04-12 15:34:39 -0600539
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600540 # Create struct entries for saving extension count and extension list from DeviceCreateInfo
541 struct.extend([
542 '',
543 ' std::unordered_set<std::string> device_extension_set;'])
544
John Zulauf072677c2018-04-12 15:34:39 -0600545 # Construct the extension information map -- mapping name to data member (field), and required extensions
546 # The map is contained within a static function member for portability reasons.
547 info_type = '%sInfo' % type
548 info_map_type = '%sMap' % info_type
549 req_type = '%sReq' % type
550 req_vec_type = '%sVec' % req_type
551 struct.extend([
552 '',
553 ' struct %s {' % req_type,
554 ' const bool %s::* enabled;' % struct_type,
555 ' const char *name;',
556 ' };',
557 ' typedef std::vector<%s> %s;' % (req_type, req_vec_type),
558 ' struct %s {' % info_type,
559 ' %s(bool %s::* state_, const %s requires_): state(state_), requires(requires_) {}' % ( info_type, struct_type, req_vec_type),
560 ' bool %s::* state;' % struct_type,
561 ' %s requires;' % req_vec_type,
562 ' };',
563 '',
564 ' typedef std::unordered_map<std::string,%s> %s;' % (info_type, info_map_type),
565 ' static const %s &get_info(const char *name) {' %info_type,
566 ' static const %s info_map = {' % info_map_type ])
567
568 field_format = '&' + struct_type + '::%s'
569 req_format = '{' + field_format+ ', %s}'
570 req_indent = '\n '
571 req_join = ',' + req_indent
572 info_format = (' std::make_pair(%s, ' + info_type + '(' + field_format + ', {%s})),')
573 def format_info(ext_name, info):
574 reqs = req_join.join([req_format % (field_name[req], extension_dict[req]['define']) for req in info['reqs']])
575 return info_format % (info['define'], field_name[ext_name], '{%s}' % (req_indent + reqs) if reqs else '')
576
577 struct.extend([guarded(info['ifdef'], format_info(ext_name, info)) for ext_name, info in extension_items])
578 struct.extend([
579 ' };',
580 '',
581 ' static const %s empty_info {nullptr, %s()};' % (info_type, req_vec_type),
582 ' %s::const_iterator info = info_map.find(name);' % info_map_type,
583 ' if ( info != info_map.cend()) {',
584 ' return info->second;',
585 ' }',
586 ' return empty_info;',
587 ' }',
588 ''])
589
John Zulauff6feb2a2018-04-12 14:24:57 -0600590 if type == 'Instance':
591 struct.extend([
592 ' uint32_t NormalizeApiVersion(uint32_t specified_version) {',
593 ' uint32_t api_version = (specified_version < VK_API_VERSION_1_1) ? VK_API_VERSION_1_0 : VK_API_VERSION_1_1;',
594 ' return api_version;',
595 ' }',
596 '',
597 ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {'])
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600598 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600599 struct.extend([
John Zulauf072677c2018-04-12 15:34:39 -0600600 ' %s() = default;' % struct_type,
601 ' %s(const %s& instance_ext) : %s(instance_ext) {}' % (struct_type, instance_struct_type, instance_struct_type),
602 '',
603 ' uint32_t InitFromDeviceCreateInfo(const %s *instance_extensions, uint32_t requested_api_version,' % instance_struct_type,
604 ' const VkDeviceCreateInfo *pCreateInfo) {',
605 ' // Initialize: this to defaults, base class fields to input.',
606 ' assert(instance_extensions);',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600607 ' *this = %s(*instance_extensions);' % struct_type,
608 '',
609 ' // Save pCreateInfo device extension list',
610 ' for (uint32_t extn = 0; extn < pCreateInfo->enabledExtensionCount; extn++) {',
611 ' device_extension_set.insert(pCreateInfo->ppEnabledExtensionNames[extn]);',
612 ' }']),
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600613
John Zulauff6feb2a2018-04-12 14:24:57 -0600614 struct.extend([
615 '',
616 ' static const std::vector<const char *> V_1_0_promoted_%s_extensions = {' % type.lower() ])
617 struct.extend([' %s_EXTENSION_NAME,' % ext_name.upper() for ext_name in promoted_ext_list])
618 struct.extend([
619 ' };',
620 '',
John Zulauf072677c2018-04-12 15:34:39 -0600621 ' // Initialize struct data, robust to invalid pCreateInfo',
622 ' if (pCreateInfo->ppEnabledExtensionNames) {',
623 ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {',
624 ' if (!pCreateInfo->ppEnabledExtensionNames[i]) continue;',
625 ' auto info = get_info(pCreateInfo->ppEnabledExtensionNames[i]);',
626 ' if(info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600627 ' }',
628 ' }',
629 ' uint32_t api_version = NormalizeApiVersion(requested_api_version);',
630 ' if (api_version >= VK_API_VERSION_1_1) {',
631 ' for (auto promoted_ext : V_1_0_promoted_%s_extensions) {' % type.lower(),
John Zulauf072677c2018-04-12 15:34:39 -0600632 ' auto info = get_info(promoted_ext);',
633 ' assert(info.state);',
634 ' if (info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600635 ' }',
636 ' }',
637 ' return api_version;',
638 ' }',
John Zulauf072677c2018-04-12 15:34:39 -0600639 '};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600640
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700641 # Output reference lists of instance/device extension names
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600642 struct.extend(['', 'static const std::set<std::string> k%sExtensionNames = {' % type])
643 struct.extend([guarded(info['ifdef'], ' %s,' % info['define']) for ext_name, info in extension_items])
644 struct.extend(['};', ''])
John Zulauff6feb2a2018-04-12 14:24:57 -0600645 output.extend(struct)
646
647 output.extend(['', '#endif // VK_EXTENSION_HELPER_H_'])
648 return '\n'.join(output)
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600649 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600650 # Combine object types helper header file preamble with body text and return
651 def GenerateObjectTypesHelperHeader(self):
652 object_types_helper_header = '\n'
653 object_types_helper_header += '#pragma once\n'
654 object_types_helper_header += '\n'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600655 object_types_helper_header += '#include <vulkan/vulkan.h>\n\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600656 object_types_helper_header += self.GenerateObjectTypesHeader()
657 return object_types_helper_header
658 #
659 # Object types header: create object enum type header file
660 def GenerateObjectTypesHeader(self):
Mark Young6ba8abe2017-11-09 10:37:04 -0700661 object_types_header = ''
662 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600663 object_types_header += 'typedef enum VulkanObjectType {\n'
664 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
665 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600666 type_list = [];
John Zulaufd7435c62018-03-16 11:52:57 -0600667 enum_entry_map = {}
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600668
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600669 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600670 for item in self.object_types:
671 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600672 enum_entry = 'kVulkanObjectType%s' % fixup_name
John Zulaufd7435c62018-03-16 11:52:57 -0600673 enum_entry_map[item] = enum_entry
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600674 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600675 object_types_header += ' = %d,\n' % enum_num
676 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600677 type_list.append(enum_entry)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600678 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
John Zulaufd7435c62018-03-16 11:52:57 -0600679 object_types_header += ' // Aliases for backwards compatibilty of "promoted" types\n'
680 for (name, alias) in self.object_type_aliases:
681 fixup_name = name[2:]
682 object_types_header += ' kVulkanObjectType{} = {},\n'.format(fixup_name, enum_entry_map[alias])
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600683 object_types_header += '} VulkanObjectType;\n\n'
684
685 # Output name string helper
686 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600687 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600688 object_types_header += ' "Unknown",\n'
689 for item in self.object_types:
690 fixup_name = item[2:]
691 object_types_header += ' "%s",\n' % fixup_name
692 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600693
John Zulauf311a4892018-03-12 15:48:06 -0600694 # Key creation helper for map comprehensions that convert between k<Name> and VK<Name> symbols
695 def to_key(regex, raw_key): return re.search(regex, raw_key).group(1).lower().replace("_","")
696
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600697 # Output a conversion routine from the layer object definitions to the debug report definitions
John Zulauf311a4892018-03-12 15:48:06 -0600698 # As the VK_DEBUG_REPORT types are not being updated, specify UNKNOWN for unmatched types
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600699 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600700 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 -0600701 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700702 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000703
John Zulauf311a4892018-03-12 15:48:06 -0600704 dbg_re = '^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$'
705 dbg_map = {to_key(dbg_re, dbg) : dbg for dbg in self.debug_report_object_types}
706 dbg_default = 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT'
707 for object_type in type_list:
708 vk_object_type = dbg_map.get(object_type.replace("kVulkanObjectType", "").lower(), dbg_default)
709 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600710 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600711
712 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600713 # 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 -0600714 object_types_header += '\n'
715 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
716 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700717 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
John Zulauf311a4892018-03-12 15:48:06 -0600718
719 vko_re = '^VK_OBJECT_TYPE_(.*)'
720 vko_map = {to_key(vko_re, vko) : vko for vko in self.core_object_types}
Mark Young1ded24b2017-05-30 14:53:50 -0600721 for object_type in type_list:
John Zulauf311a4892018-03-12 15:48:06 -0600722 vk_object_type = vko_map[object_type.replace("kVulkanObjectType", "").lower()]
723 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Young1ded24b2017-05-30 14:53:50 -0600724 object_types_header += '};\n'
725
Mark Young6ba8abe2017-11-09 10:37:04 -0700726 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
727 object_types_header += '\n'
728 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600729 object_types_header += 'static inline VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700730 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
731 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
732 for core_object_type in self.core_object_types:
733 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
734 core_target_type = core_target_type.replace("_", "")
735 for dr_object_type in self.debug_report_object_types:
736 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
737 dr_target_type = dr_target_type[:-4]
738 dr_target_type = dr_target_type.replace("_", "")
739 if core_target_type == dr_target_type:
740 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
741 object_types_header += ' return %s;\n' % core_object_type
742 break
743 object_types_header += ' }\n'
744 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
745 object_types_header += '}\n'
746
747 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
748 object_types_header += '\n'
749 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600750 object_types_header += 'static inline VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700751 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
752 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
753 for core_object_type in self.core_object_types:
754 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
755 core_target_type = core_target_type.replace("_", "")
756 for dr_object_type in self.debug_report_object_types:
757 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
758 dr_target_type = dr_target_type[:-4]
759 dr_target_type = dr_target_type.replace("_", "")
760 if core_target_type == dr_target_type:
761 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
762 object_types_header += ' return %s;\n' % dr_object_type
763 break
764 object_types_header += ' }\n'
765 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
766 object_types_header += '}\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600767 return object_types_header
768 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700769 # Determine if a structure needs a safe_struct helper function
770 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700771 def NeedSafeStruct(self, structure):
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700772 if 'sType' == structure.name:
773 return True
774 for member in structure.members:
775 if member.ispointer == True:
776 return True
777 return False
778 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700779 # Combine safe struct helper source file preamble with body text and return
780 def GenerateSafeStructHelperSource(self):
781 safe_struct_helper_source = '\n'
782 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
783 safe_struct_helper_source += '#include <string.h>\n'
784 safe_struct_helper_source += '\n'
785 safe_struct_helper_source += self.GenerateSafeStructSource()
786 return safe_struct_helper_source
787 #
788 # safe_struct source -- create bodies of safe struct helper functions
789 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700790 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700791 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
792 'VkXcbSurfaceCreateInfoKHR',
793 'VkWaylandSurfaceCreateInfoKHR',
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700794 'VkAndroidSurfaceCreateInfoKHR',
795 'VkWin32SurfaceCreateInfoKHR'
796 ]
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -0600797
798 # For abstract types just want to save the pointer away
799 # since we cannot make a copy.
800 abstract_types = ['AHardwareBuffer',
801 'ANativeWindow',
802 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700803 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700804 if self.NeedSafeStruct(item) == False:
805 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700806 if item.name in wsi_structs:
807 continue
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100808 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700809 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
810 ss_name = "safe_%s" % item.name
811 init_list = '' # list of members in struct constructor initializer
812 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
813 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
814 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
815 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +0100816
817 custom_construct_txt = {
818 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
819 'VkWriteDescriptorSet' :
820 ' switch (descriptorType) {\n'
821 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
822 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
823 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
824 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
825 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
826 ' if (descriptorCount && in_struct->pImageInfo) {\n'
827 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
828 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
829 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
830 ' }\n'
831 ' }\n'
832 ' break;\n'
833 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
834 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
835 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
836 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
837 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
838 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
839 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
840 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
841 ' }\n'
842 ' }\n'
843 ' break;\n'
844 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
845 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
846 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
847 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
848 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
849 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
850 ' }\n'
851 ' }\n'
852 ' break;\n'
853 ' default:\n'
854 ' break;\n'
855 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100856 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +0100857 ' if (in_struct->pCode) {\n'
858 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
859 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
860 ' }\n',
861 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
862 'VkGraphicsPipelineCreateInfo' :
863 ' if (stageCount && in_struct->pStages) {\n'
864 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
865 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
866 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
867 ' }\n'
868 ' }\n'
869 ' if (in_struct->pVertexInputState)\n'
870 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
871 ' else\n'
872 ' pVertexInputState = NULL;\n'
873 ' if (in_struct->pInputAssemblyState)\n'
874 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
875 ' else\n'
876 ' pInputAssemblyState = NULL;\n'
877 ' bool has_tessellation_stage = false;\n'
878 ' if (stageCount && pStages)\n'
879 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
880 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
881 ' has_tessellation_stage = true;\n'
882 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
883 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
884 ' else\n'
885 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
886 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
887 ' if (in_struct->pViewportState && has_rasterization) {\n'
888 ' bool is_dynamic_viewports = false;\n'
889 ' bool is_dynamic_scissors = false;\n'
890 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
891 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
892 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
893 ' is_dynamic_viewports = true;\n'
894 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
895 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
896 ' is_dynamic_scissors = true;\n'
897 ' }\n'
898 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
899 ' } else\n'
900 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
901 ' if (in_struct->pRasterizationState)\n'
902 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
903 ' else\n'
904 ' pRasterizationState = NULL;\n'
905 ' if (in_struct->pMultisampleState && has_rasterization)\n'
906 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
907 ' else\n'
908 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
909 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
910 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
911 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
912 ' else\n'
913 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
914 ' // needs a tracked subpass state usesColorAttachment\n'
915 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
916 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
917 ' else\n'
918 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
919 ' if (in_struct->pDynamicState)\n'
920 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
921 ' else\n'
922 ' pDynamicState = NULL;\n',
923 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
924 'VkPipelineViewportStateCreateInfo' :
925 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
926 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
927 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
928 ' }\n'
929 ' else\n'
930 ' pViewports = NULL;\n'
931 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
932 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
933 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
934 ' }\n'
935 ' else\n'
936 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100937 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
938 'VkDescriptorSetLayoutBinding' :
939 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
940 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
941 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
942 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
943 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
944 ' }\n'
945 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +0100946 }
947
948 custom_copy_txt = {
949 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
950 'VkGraphicsPipelineCreateInfo' :
951 ' if (stageCount && src.pStages) {\n'
952 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
953 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
954 ' pStages[i].initialize(&src.pStages[i]);\n'
955 ' }\n'
956 ' }\n'
957 ' if (src.pVertexInputState)\n'
958 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
959 ' else\n'
960 ' pVertexInputState = NULL;\n'
961 ' if (src.pInputAssemblyState)\n'
962 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
963 ' else\n'
964 ' pInputAssemblyState = NULL;\n'
965 ' bool has_tessellation_stage = false;\n'
966 ' if (stageCount && pStages)\n'
967 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
968 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
969 ' has_tessellation_stage = true;\n'
970 ' if (src.pTessellationState && has_tessellation_stage)\n'
971 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
972 ' else\n'
973 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
974 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
975 ' if (src.pViewportState && has_rasterization) {\n'
976 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
977 ' } else\n'
978 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
979 ' if (src.pRasterizationState)\n'
980 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
981 ' else\n'
982 ' pRasterizationState = NULL;\n'
983 ' if (src.pMultisampleState && has_rasterization)\n'
984 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
985 ' else\n'
986 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
987 ' if (src.pDepthStencilState && has_rasterization)\n'
988 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
989 ' else\n'
990 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
991 ' if (src.pColorBlendState && has_rasterization)\n'
992 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
993 ' else\n'
994 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
995 ' if (src.pDynamicState)\n'
996 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
997 ' else\n'
998 ' pDynamicState = NULL;\n',
999 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1000 'VkPipelineViewportStateCreateInfo' :
1001 ' if (src.pViewports) {\n'
1002 ' pViewports = new VkViewport[src.viewportCount];\n'
1003 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1004 ' }\n'
1005 ' else\n'
1006 ' pViewports = NULL;\n'
1007 ' if (src.pScissors) {\n'
1008 ' pScissors = new VkRect2D[src.scissorCount];\n'
1009 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1010 ' }\n'
1011 ' else\n'
1012 ' pScissors = NULL;\n',
1013 }
1014
Mike Schuchardt81485762017-09-04 11:38:42 -06001015 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1016 ' if (pCode)\n'
1017 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001018
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001019 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001020 m_type = member.type
1021 if member.type in self.structNames:
1022 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1023 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1024 m_type = 'safe_%s' % member.type
1025 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1026 # 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 -07001027 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001028 # For these exceptions just copy initial value over for now
1029 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1030 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001031 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001032 default_init_list += '\n %s(nullptr),' % (member.name)
1033 init_list += '\n %s(nullptr),' % (member.name)
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001034 if m_type in abstract_types:
1035 construct_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1036 else:
1037 init_func_txt += ' %s = nullptr;\n' % (member.name)
1038 if 'pNext' != member.name and 'void' not in m_type:
1039 if not member.isstaticarray and (member.len is None or '/' in member.len):
1040 construct_txt += ' if (in_struct->%s) {\n' % member.name
1041 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1042 construct_txt += ' }\n'
1043 destruct_txt += ' if (%s)\n' % member.name
1044 destruct_txt += ' delete %s;\n' % member.name
1045 else:
1046 construct_txt += ' if (in_struct->%s) {\n' % member.name
1047 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1048 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1049 construct_txt += ' }\n'
1050 destruct_txt += ' if (%s)\n' % member.name
1051 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001052 elif member.isstaticarray or member.len is not None:
1053 if member.len is None:
1054 # Extract length of static array by grabbing val between []
1055 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1056 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1057 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1058 construct_txt += ' }\n'
1059 else:
1060 # Init array ptr to NULL
1061 default_init_list += '\n %s(nullptr),' % member.name
1062 init_list += '\n %s(nullptr),' % member.name
1063 init_func_txt += ' %s = nullptr;\n' % member.name
1064 array_element = 'in_struct->%s[i]' % member.name
1065 if member.type in self.structNames:
1066 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1067 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1068 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1069 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1070 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1071 destruct_txt += ' if (%s)\n' % member.name
1072 destruct_txt += ' delete[] %s;\n' % member.name
1073 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1074 if 'safe_' in m_type:
1075 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001076 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001077 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1078 construct_txt += ' }\n'
1079 construct_txt += ' }\n'
1080 elif member.ispointer == True:
1081 construct_txt += ' if (in_struct->%s)\n' % member.name
1082 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1083 construct_txt += ' else\n'
1084 construct_txt += ' %s = NULL;\n' % member.name
1085 destruct_txt += ' if (%s)\n' % member.name
1086 destruct_txt += ' delete %s;\n' % member.name
1087 elif 'safe_' in m_type:
1088 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1089 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1090 else:
1091 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1092 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1093 if '' != init_list:
1094 init_list = init_list[:-1] # hack off final comma
1095 if item.name in custom_construct_txt:
1096 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001097 if item.name in custom_destruct_txt:
1098 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001099 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 -07001100 if '' != default_init_list:
1101 default_init_list = " :%s" % (default_init_list[:-1])
1102 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1103 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1104 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1105 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1106 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1107 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001108 if item.name in custom_copy_txt:
1109 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001110 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 -06001111 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 -07001112 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 -07001113 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001114 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 -07001115 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1116 init_copy = copy_construct_init.replace('src.', 'src->')
1117 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001118 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 +01001119 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001120 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1121 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001122 #
John Zulaufde972ac2017-10-26 12:07:05 -06001123 # Generate the type map
1124 def GenerateTypeMapHelperHeader(self):
1125 prefix = 'Lvl'
1126 fprefix = 'lvl_'
1127 typemap = prefix + 'TypeMap'
1128 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001129 type_member = 'Type'
1130 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001131 id_decl = 'static const VkStructureType '
John Zulaufde972ac2017-10-26 12:07:05 -06001132 generic_header = prefix + 'GenericHeader'
1133 typename_func = fprefix + 'typename'
1134 idname_func = fprefix + 'stype_name'
1135 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001136 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001137
1138 explanatory_comment = '\n'.join((
1139 '// These empty generic templates are specialized for each type with sType',
1140 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001141 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001142
1143 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1144 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001145 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1146 typemap_format += '}};\n'
1147
1148 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1149 idmap_format = ''.join((
1150 'template <> struct {template}<{id_value}> {{\n',
1151 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001152 '}};\n'))
1153
1154 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1155 utilities_format = '\n'.join((
1156 '// Header "base class" for pNext chain traversal',
1157 'struct {header} {{',
1158 ' VkStructureType sType;',
1159 ' const {header} *pNext;',
1160 '}};',
1161 '',
1162 '// Find an entry of the given type in the pNext chain',
1163 'template <typename T> const T *{find_func}(const void *next) {{',
1164 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1165 ' const T *found = nullptr;',
1166 ' while (current) {{',
1167 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1168 ' found = reinterpret_cast<const T*>(current);',
1169 ' current = nullptr;',
1170 ' }} else {{',
1171 ' current = current->pNext;',
1172 ' }}',
1173 ' }}',
1174 ' return found;',
1175 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001176 '',
1177 '// Init the header of an sType struct with pNext',
1178 'template <typename T> T {init_func}(void *p_next) {{',
1179 ' T out = {{}};',
1180 ' out.sType = {type_map}<T>::kSType;',
1181 ' out.pNext = p_next;',
1182 ' return out;',
1183 '}}',
1184 '',
1185 '// Init the header of an sType struct',
1186 'template <typename T> T {init_func}() {{',
1187 ' T out = {{}};',
1188 ' out.sType = {type_map}<T>::kSType;',
1189 ' return out;',
1190 '}}',
1191
Mike Schuchardt97662b02017-12-06 13:31:29 -07001192 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001193
1194 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001195
1196 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001197 code.append('\n'.join((
1198 '#pragma once',
1199 '#include <vulkan/vulkan.h>\n',
1200 explanatory_comment, '',
1201 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001202 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001203
1204 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001205 for item in self.structMembers:
1206 typename = item.name
1207 info = self.structTypes.get(typename)
1208 if not info:
1209 continue
1210
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001211 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001212 code.append('#ifdef %s' % item.ifdef_protect)
1213
1214 code.append('// Map type {} to id {}'.format(typename, info.value))
1215 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001216 id_decl=id_decl, id_member=id_member))
1217 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001218
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001219 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001220 code.append('#endif // %s' % item.ifdef_protect)
1221
John Zulauf65ac9d52018-01-23 11:20:50 -07001222 # Generate utilities for all types
1223 code.append('\n'.join((
1224 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1225 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1226 find_func=find_func, init_func=init_func), ''
1227 )))
1228
John Zulaufde972ac2017-10-26 12:07:05 -06001229 return "\n".join(code)
1230
1231 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001232 # Create a helper file and return it as a string
1233 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001234 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001235 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001236 elif self.helper_file_type == 'safe_struct_header':
1237 return self.GenerateSafeStructHelperHeader()
1238 elif self.helper_file_type == 'safe_struct_source':
1239 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001240 elif self.helper_file_type == 'object_types_header':
1241 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001242 elif self.helper_file_type == 'extension_helper_header':
1243 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001244 elif self.helper_file_type == 'typemap_helper_header':
1245 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001246 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001247 return 'Bad Helper File Generator Option %s' % self.helper_file_type