blob: ab0ceed528a2a80fc6e0656614f2aae9a165eae4 [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>
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070022
23import os,re,sys
24import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
Mark Lobodzinski62f71562017-10-24 13:41:18 -060027from common_codegen import *
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070028
29#
30# HelperFileOutputGeneratorOptions - subclass of GeneratorOptions.
31class HelperFileOutputGeneratorOptions(GeneratorOptions):
32 def __init__(self,
33 filename = None,
34 directory = '.',
35 apiname = None,
36 profile = None,
37 versions = '.*',
38 emitversions = '.*',
39 defaultExtensions = None,
40 addExtensions = None,
41 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060042 emitExtensions = None,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070043 sortProcedure = regSortFeatures,
44 prefixText = "",
45 genFuncPointers = True,
46 protectFile = True,
47 protectFeature = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070048 apicall = '',
49 apientry = '',
50 apientryp = '',
51 alignFuncParam = 0,
52 library_name = '',
Mark Lobodzinski62f71562017-10-24 13:41:18 -060053 expandEnumerants = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070054 helper_file_type = ''):
55 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
56 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060057 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070058 self.prefixText = prefixText
59 self.genFuncPointers = genFuncPointers
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070060 self.protectFile = protectFile
61 self.protectFeature = protectFeature
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070062 self.apicall = apicall
63 self.apientry = apientry
64 self.apientryp = apientryp
65 self.alignFuncParam = alignFuncParam
66 self.library_name = library_name
67 self.helper_file_type = helper_file_type
68#
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070069# HelperFileOutputGenerator - subclass of OutputGenerator. Outputs Vulkan helper files
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070070class HelperFileOutputGenerator(OutputGenerator):
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -070071 """Generate helper file based on XML element attributes"""
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070072 def __init__(self,
73 errFile = sys.stderr,
74 warnFile = sys.stderr,
75 diagFile = sys.stdout):
76 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
77 # Internal state - accumulators for different inner block text
Mark Lobodzinski5380d132016-12-28 14:45:34 -070078 self.enum_output = '' # string built up of enum string routines
79 self.struct_size_h_output = '' # string built up of struct size header output
80 self.struct_size_c_output = '' # string built up of struct size source output
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
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
165 nameElem = interface[0][1]
166 name = nameElem.get('name')
167 if 'EXTENSION_NAME' not in name:
168 print("Error in vk.xml file -- extension name is not available")
169 if interface.get('type') == 'instance':
170 self.instance_extension_info[name] = self.featureExtraProtect
171 else:
172 self.device_extension_info[name] = self.featureExtraProtect
173 #
174 # Override parent class to be notified of the end of an extension
175 def endFeature(self):
176 # Finish processing in superclass
177 OutputGenerator.endFeature(self)
178 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700179 # Grab group (e.g. C "enum" type) info to output for enum-string conversion helper
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700180 def genGroup(self, groupinfo, groupName, alias):
181 OutputGenerator.genGroup(self, groupinfo, groupName, alias)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700182 groupElem = groupinfo.elem
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700183 # For enum_string_header
184 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700185 value_list = []
186 for elem in groupElem.findall('enum'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700187 if elem.get('supported') != 'disabled' and elem.get('alias') == None:
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700188 item_name = elem.get('name')
Mark Lobodzinskic8d02242017-09-28 15:12:02 -0600189 # Avoid duplicates
190 if item_name not in value_list:
191 value_list.append(item_name)
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700192 if value_list is not None:
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700193 #if alias:
194 # self.enum_output += self.GenerateEnumStringConversion(alias, value_list)
195 #else:
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700196 self.enum_output += self.GenerateEnumStringConversion(groupName, value_list)
Mark Young1ded24b2017-05-30 14:53:50 -0600197 elif self.helper_file_type == 'object_types_header':
198 if groupName == 'VkDebugReportObjectTypeEXT':
199 for elem in groupElem.findall('enum'):
200 if elem.get('supported') != 'disabled':
201 item_name = elem.get('name')
202 self.debug_report_object_types.append(item_name)
203 elif groupName == 'VkObjectType':
204 for elem in groupElem.findall('enum'):
205 if elem.get('supported') != 'disabled':
206 item_name = elem.get('name')
207 self.core_object_types.append(item_name)
208
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700209 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700210 # Called for each type -- if the type is a struct/union, grab the metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700211 def genType(self, typeinfo, name, alias):
212 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700213 typeElem = typeinfo.elem
214 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
215 # Otherwise, emit the tag text.
216 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600217 if category == 'handle':
218 self.object_types.append(name)
219 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700220 self.structNames.append(name)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700221 self.genStruct(typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700222 #
223 # Generate a VkStructureType based on a structure typename
224 def genVkStructureType(self, typename):
225 # Add underscore between lowercase then uppercase
226 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
227 # Change to uppercase
228 value = value.upper()
229 # Add STRUCTURE_TYPE_
230 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
231 #
232 # Check if the parameter passed in is a pointer
233 def paramIsPointer(self, param):
234 ispointer = False
235 for elem in param:
236 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
237 ispointer = True
238 return ispointer
239 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700240 # Check if the parameter passed in is a static array
241 def paramIsStaticArray(self, param):
242 isstaticarray = 0
243 paramname = param.find('name')
244 if (paramname.tail is not None) and ('[' in paramname.tail):
245 isstaticarray = paramname.tail.count('[')
246 return isstaticarray
247 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700248 # Retrieve the type and name for a parameter
249 def getTypeNameTuple(self, param):
250 type = ''
251 name = ''
252 for elem in param:
253 if elem.tag == 'type':
254 type = noneStr(elem.text)
255 elif elem.tag == 'name':
256 name = noneStr(elem.text)
257 return (type, name)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700258 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
259 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
260 def parseLateXMath(self, source):
261 name = 'ERROR'
262 decoratedName = 'ERROR'
263 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700264 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
265 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 -0700266 if not match or match.group(1) != match.group(4):
267 raise 'Unrecognized latexmath expression'
268 name = match.group(2)
mizhenc27f6c72017-03-31 09:08:16 -0600269 # Need to add 1 for ceiling function; otherwise, the allocated packet
270 # size will be less than needed during capture for some title which use
271 # this in VkPipelineMultisampleStateCreateInfo. based on ceiling function
272 # definition,it is '{0}%{1}?{0}/{1} + 1:{0}/{1}'.format(*match.group(2, 3)),
273 # its value <= '{}/{} + 1'.
274 if match.group(1) == 'ceil':
275 decoratedName = '{}/{} + 1'.format(*match.group(2, 3))
276 else:
277 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700278 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700279 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Mark Young0f183a82017-02-28 09:58:04 -0700280 match = re.match(r'latexmath\s*\:\s*\[\s*(\w+)\s*\\over\s*(\d+)\s*\]', source)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700281 name = match.group(1)
282 decoratedName = '{}/{}'.format(*match.group(1, 2))
283 return name, decoratedName
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700284 #
285 # Retrieve the value of the len tag
286 def getLen(self, param):
287 result = None
288 len = param.attrib.get('len')
289 if len and len != 'null-terminated':
290 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
291 # have a null terminated array of strings. We strip the null-terminated from the
292 # 'len' field and only return the parameter specifying the string count
293 if 'null-terminated' in len:
294 result = len.split(',')[0]
295 else:
296 result = len
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700297 if 'latexmath' in len:
298 param_type, param_name = self.getTypeNameTuple(param)
299 len_name, result = self.parseLateXMath(len)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700300 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
301 result = str(result).replace('::', '->')
302 return result
303 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700304 # Check if a structure is or contains a dispatchable (dispatchable = True) or
305 # non-dispatchable (dispatchable = False) handle
306 def TypeContainsObjectHandle(self, handle_type, dispatchable):
307 if dispatchable:
308 type_key = 'VK_DEFINE_HANDLE'
309 else:
310 type_key = 'VK_DEFINE_NON_DISPATCHABLE_HANDLE'
311 handle = self.registry.tree.find("types/type/[name='" + handle_type + "'][@category='handle']")
312 if handle is not None and handle.find('type').text == type_key:
313 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:
319 handle = self.registry.tree.find("types/type/[name='" + item.type + "'][@category='handle']")
320 if handle is not None and handle.find('type').text == type_key:
321 return True
322 return False
323 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700324 # Generate local ready-access data describing Vulkan structures and unions from the XML metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700325 def genStruct(self, typeinfo, typeName, alias):
326 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700327 members = typeinfo.elem.findall('.//member')
328 # Iterate over members once to get length parameters for arrays
329 lens = set()
330 for member in members:
331 len = self.getLen(member)
332 if len:
333 lens.add(len)
334 # Generate member info
335 membersInfo = []
336 for member in members:
337 # Get the member's type and name
338 info = self.getTypeNameTuple(member)
339 type = info[0]
340 name = info[1]
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700341 cdecl = self.makeCParamDecl(member, 1)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700342 # Process VkStructureType
343 if type == 'VkStructureType':
344 # Extract the required struct type value from the comments
345 # embedded in the original text defining the 'typeinfo' element
346 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
347 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
348 if result:
349 value = result.group(0)
350 else:
351 value = self.genVkStructureType(typeName)
352 # Store the required type value
353 self.structTypes[typeName] = self.StructType(name=name, value=value)
354 # Store pointer/array/string info
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700355 isstaticarray = self.paramIsStaticArray(member)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700356 membersInfo.append(self.CommandParam(type=type,
357 name=name,
358 ispointer=self.paramIsPointer(member),
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700359 isstaticarray=isstaticarray,
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700360 isconst=True if 'const' in cdecl else False,
361 iscount=True if name in lens else False,
362 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600363 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700364 cdecl=cdecl))
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700365 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo, ifdef_protect=self.featureExtraProtect))
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700366 #
367 # Enum_string_header: Create a routine to convert an enumerated value into a string
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700368 def GenerateEnumStringConversion(self, groupName, value_list):
369 outstring = '\n'
370 outstring += 'static inline const char* string_%s(%s input_value)\n' % (groupName, groupName)
371 outstring += '{\n'
372 outstring += ' switch ((%s)input_value)\n' % groupName
373 outstring += ' {\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700374 for item in value_list:
375 outstring += ' case %s:\n' % item
376 outstring += ' return "%s";\n' % item
377 outstring += ' default:\n'
378 outstring += ' return "Unhandled %s";\n' % groupName
379 outstring += ' }\n'
380 outstring += '}\n'
381 return outstring
382 #
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600383 # Tack on a helper which, given an index into a VkPhysicalDeviceFeatures structure, will print the corresponding feature name
384 def DeIndexPhysDevFeatures(self):
385 pdev_members = None
386 for name, members, ifdef in self.structMembers:
387 if name == 'VkPhysicalDeviceFeatures':
388 pdev_members = members
389 break
390 deindex = '\n'
Mark Young2ee6aea2018-02-21 15:30:27 -0700391 deindex += 'static inline const char * GetPhysDevFeatureString(uint32_t index) {\n'
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600392 deindex += ' const char * IndexToPhysDevFeatureString[] = {\n'
393 for feature in pdev_members:
394 deindex += ' "%s",\n' % feature.name
395 deindex += ' };\n\n'
396 deindex += ' return IndexToPhysDevFeatureString[index];\n'
397 deindex += '}\n'
398 return deindex
399 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700400 # Combine enum string helper header file preamble with body text and return
401 def GenerateEnumStringHelperHeader(self):
402 enum_string_helper_header = '\n'
403 enum_string_helper_header += '#pragma once\n'
404 enum_string_helper_header += '#ifdef _WIN32\n'
405 enum_string_helper_header += '#pragma warning( disable : 4065 )\n'
406 enum_string_helper_header += '#endif\n'
407 enum_string_helper_header += '\n'
408 enum_string_helper_header += '#include <vulkan/vulkan.h>\n'
409 enum_string_helper_header += '\n'
410 enum_string_helper_header += self.enum_output
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600411 enum_string_helper_header += self.DeIndexPhysDevFeatures()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700412 return enum_string_helper_header
413 #
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700414 # struct_size_header: build function prototypes for header file
415 def GenerateStructSizeHeader(self):
416 outstring = ''
417 outstring += 'size_t get_struct_chain_size(const void* struct_ptr);\n'
David Pinedob95caa02017-10-05 10:30:02 -0600418 outstring += 'size_t get_struct_size(const void* struct_ptr);\n'
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700419 for item in self.structMembers:
420 lower_case_name = item.name.lower()
421 if item.ifdef_protect != None:
422 outstring += '#ifdef %s\n' % item.ifdef_protect
423 outstring += 'size_t vk_size_%s(const %s* struct_ptr);\n' % (item.name.lower(), item.name)
424 if item.ifdef_protect != None:
425 outstring += '#endif // %s\n' % item.ifdef_protect
426 outstring += '#ifdef __cplusplus\n'
427 outstring += '}\n'
428 outstring += '#endif'
429 return outstring
430 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700431 # Combine struct size helper header file preamble with body text and return
432 def GenerateStructSizeHelperHeader(self):
433 struct_size_helper_header = '\n'
434 struct_size_helper_header += '#ifdef __cplusplus\n'
435 struct_size_helper_header += 'extern "C" {\n'
436 struct_size_helper_header += '#endif\n'
437 struct_size_helper_header += '\n'
438 struct_size_helper_header += '#include <stdio.h>\n'
439 struct_size_helper_header += '#include <stdlib.h>\n'
440 struct_size_helper_header += '#include <vulkan/vulkan.h>\n'
441 struct_size_helper_header += '\n'
442 struct_size_helper_header += '// Function Prototypes\n'
443 struct_size_helper_header += self.GenerateStructSizeHeader()
444 return struct_size_helper_header
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700445 #
446 # Helper function for declaring a counter variable only once
447 def DeclareCounter(self, string_var, declare_flag):
448 if declare_flag == False:
449 string_var += ' uint32_t i = 0;\n'
450 declare_flag = True
451 return string_var, declare_flag
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700452 #
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700453 # Build the header of the get_struct_chain_size function
454 def GenerateChainSizePreamble(self):
David Pinedob95caa02017-10-05 10:30:02 -0600455 preamble = '\nsize_t get_struct_chain_size(const void* struct_ptr) {\n'
456 preamble += ' // Use VkApplicationInfo as struct until actual type is resolved\n'
457 preamble += ' VkApplicationInfo* pNext = (VkApplicationInfo*)struct_ptr;\n'
458 preamble += ' size_t struct_size = 0;\n'
459 preamble += ' while (pNext) {\n'
460 preamble += ' switch (pNext->sType) {\n'
461 return preamble
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700462 #
463 # Build the footer of the get_struct_chain_size function
464 def GenerateChainSizePostamble(self):
465 postamble = ' default:\n'
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700466 postamble += ' struct_size += 0;\n'
Joey Bzdekb6875332017-10-19 14:24:05 -0600467 postamble += ' break;'
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700468 postamble += ' }\n'
469 postamble += ' pNext = (VkApplicationInfo*)pNext->pNext;\n'
470 postamble += ' }\n'
471 postamble += ' return struct_size;\n'
David Pinedob95caa02017-10-05 10:30:02 -0600472 postamble += '}\n'
473 return postamble
474 #
475 # Build the header of the get_struct_size function
476 def GenerateStructSizePreamble(self):
477 preamble = '\nsize_t get_struct_size(const void* struct_ptr) {\n'
478 preamble += ' switch (((VkApplicationInfo*)struct_ptr)->sType) {\n'
479 return preamble
480 #
481 # Build the footer of the get_struct_size function
482 def GenerateStructSizePostamble(self):
483 postamble = ' default:\n'
David Pinedob95caa02017-10-05 10:30:02 -0600484 postamble += ' return(0);\n'
485 postamble += ' }\n'
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700486 postamble += '}'
487 return postamble
488 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700489 # struct_size_helper source -- create bodies of struct size helper functions
490 def GenerateStructSizeSource(self):
David Pinedob95caa02017-10-05 10:30:02 -0600491 # Construct the bodies of the struct size functions, get_struct_chain_size(),
492 # and get_struct_size() simultaneously
493 struct_size_funcs = ''
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700494 chain_size = self.GenerateChainSizePreamble()
David Pinedob95caa02017-10-05 10:30:02 -0600495 struct_size = self.GenerateStructSizePreamble()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700496 for item in self.structMembers:
David Pinedob95caa02017-10-05 10:30:02 -0600497 struct_size_funcs += '\n'
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700498 lower_case_name = item.name.lower()
499 if item.ifdef_protect != None:
David Pinedob95caa02017-10-05 10:30:02 -0600500 struct_size_funcs += '#ifdef %s\n' % item.ifdef_protect
501 struct_size += '#ifdef %s\n' % item.ifdef_protect
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700502 chain_size += '#ifdef %s\n' % item.ifdef_protect
503 if item.name in self.structTypes:
504 chain_size += ' case %s: {\n' % self.structTypes[item.name].value
505 chain_size += ' struct_size += vk_size_%s((%s*)pNext);\n' % (item.name.lower(), item.name)
506 chain_size += ' break;\n'
507 chain_size += ' }\n'
David Pinedob95caa02017-10-05 10:30:02 -0600508 struct_size += ' case %s: \n' % self.structTypes[item.name].value
509 struct_size += ' return vk_size_%s((%s*)struct_ptr);\n' % (item.name.lower(), item.name)
510 struct_size_funcs += 'size_t vk_size_%s(const %s* struct_ptr) { \n' % (item.name.lower(), item.name)
511 struct_size_funcs += ' size_t struct_size = 0;\n'
512 struct_size_funcs += ' if (struct_ptr) {\n'
513 struct_size_funcs += ' struct_size = sizeof(%s);\n' % item.name
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700514 counter_declared = False
515 for member in item.members:
516 vulkan_type = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
517 if member.ispointer == True:
518 if vulkan_type is not None:
519 # If this is another Vulkan structure call generated size function
520 if member.len is not None:
David Pinedob95caa02017-10-05 10:30:02 -0600521 struct_size_funcs, counter_declared = self.DeclareCounter(struct_size_funcs, counter_declared)
522 struct_size_funcs += ' for (i = 0; i < struct_ptr->%s; i++) {\n' % member.len
523 struct_size_funcs += ' struct_size += vk_size_%s(&struct_ptr->%s[i]);\n' % (member.type.lower(), member.name)
524 struct_size_funcs += ' }\n'
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700525 else:
David Pinedob95caa02017-10-05 10:30:02 -0600526 struct_size_funcs += ' struct_size += vk_size_%s(struct_ptr->%s);\n' % (member.type.lower(), member.name)
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700527 else:
528 if member.type == 'char':
529 # Deal with sizes of character strings
530 if member.len is not None:
David Pinedob95caa02017-10-05 10:30:02 -0600531 struct_size_funcs, counter_declared = self.DeclareCounter(struct_size_funcs, counter_declared)
532 struct_size_funcs += ' for (i = 0; i < struct_ptr->%s; i++) {\n' % member.len
David Pinedofb264ce2018-02-28 16:20:42 -0700533 struct_size_funcs += ' struct_size += (sizeof(char*) + ROUNDUP_TO_4((sizeof(char) * (1 + strlen(struct_ptr->%s[i])))));\n' % (member.name)
David Pinedob95caa02017-10-05 10:30:02 -0600534 struct_size_funcs += ' }\n'
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700535 else:
David Pinedofb264ce2018-02-28 16:20:42 -0700536 struct_size_funcs += ' struct_size += (struct_ptr->%s != NULL) ? ROUNDUP_TO_4(sizeof(char)*(1+strlen(struct_ptr->%s))) : 0;\n' % (member.name, member.name)
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700537 else:
538 if member.len is not None:
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700539 # Avoid using 'sizeof(void)', which generates compile-time warnings/errors
540 checked_type = member.type
541 if checked_type == 'void':
542 checked_type = 'void*'
David Pinedob95caa02017-10-05 10:30:02 -0600543 struct_size_funcs += ' struct_size += (struct_ptr->%s ) * sizeof(%s);\n' % (member.len, checked_type)
544 struct_size_funcs += ' }\n'
545 struct_size_funcs += ' return struct_size;\n'
546 struct_size_funcs += '}\n'
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700547 if item.ifdef_protect != None:
David Pinedob95caa02017-10-05 10:30:02 -0600548 struct_size_funcs += '#endif // %s\n' % item.ifdef_protect
549 struct_size += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700550 chain_size += '#endif // %s\n' % item.ifdef_protect
551 chain_size += self.GenerateChainSizePostamble()
David Pinedob95caa02017-10-05 10:30:02 -0600552 struct_size += self.GenerateStructSizePostamble()
553 return_value = struct_size_funcs + chain_size + struct_size;
554 return return_value
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700555 #
556 # Combine struct size helper source file preamble with body text and return
557 def GenerateStructSizeHelperSource(self):
558 struct_size_helper_source = '\n'
559 struct_size_helper_source += '#include "vk_struct_size_helper.h"\n'
560 struct_size_helper_source += '#include <string.h>\n'
561 struct_size_helper_source += '#include <assert.h>\n'
562 struct_size_helper_source += '\n'
David Pinedofb264ce2018-02-28 16:20:42 -0700563 struct_size_helper_source += '#define ROUNDUP_TO_4(_len) ((((_len) + 3) >> 2) << 2)\n\n'
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700564 struct_size_helper_source += '// Function Definitions\n'
565 struct_size_helper_source += self.GenerateStructSizeSource()
566 return struct_size_helper_source
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700567 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700568 # Combine safe struct helper header file preamble with body text and return
569 def GenerateSafeStructHelperHeader(self):
570 safe_struct_helper_header = '\n'
571 safe_struct_helper_header += '#pragma once\n'
572 safe_struct_helper_header += '#include <vulkan/vulkan.h>\n'
573 safe_struct_helper_header += '\n'
574 safe_struct_helper_header += self.GenerateSafeStructHeader()
575 return safe_struct_helper_header
576 #
577 # safe_struct header: build function prototypes for header file
578 def GenerateSafeStructHeader(self):
579 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700580 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700581 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700582 safe_struct_header += '\n'
583 if item.ifdef_protect != None:
584 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
585 safe_struct_header += 'struct safe_%s {\n' % (item.name)
586 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700587 if member.type in self.structNames:
588 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
589 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
590 if member.ispointer:
591 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
592 else:
593 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
594 continue
595 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
596 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
597 else:
598 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100599 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 -0600600 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700601 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700602 safe_struct_header += ' safe_%s();\n' % item.name
603 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100604 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
605 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700606 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
607 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
608 safe_struct_header += '};\n'
609 if item.ifdef_protect != None:
610 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700611 return safe_struct_header
612 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600613 # Generate extension helper header file
614 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600615
616 V_1_0_instance_extensions_promoted_to_core = [
617 'vk_khr_device_group_creation',
618 'vk_khr_external_memory_capabilities',
619 'vk_khr_external_fence_capabilities',
620 'vk_khr_external_semaphore_capabilities',
621 'vk_khr_get_physical_device_properties_2',
622 ]
623
624 V_1_0_device_extensions_promoted_to_core = [
625 'vk_khr_bind_memory_2',
626 'vk_khr_device_group',
627 'vk_khr_descriptor_update_template',
628 'vk_khr_sampler_ycbcr_conversion',
629 'vk_khr_get_memory_requirements_2',
630 'vk_khr_maintenance3',
631 'vk_khr_maintenance1',
632 'vk_khr_multiview',
633 'vk_khr_external_memory',
634 'vk_khr_external_semaphore',
635 'vk_khr_16bit_storage',
636 'vk_khr_external_fence',
637 'vk_khr_maintenance2',
638 'vk_khr_variable_pointers',
639 'vk_khr_dedicated_allocation',
640 ]
641
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600642 extension_helper_header = '\n'
643 extension_helper_header += '#ifndef VK_EXTENSION_HELPER_H_\n'
644 extension_helper_header += '#define VK_EXTENSION_HELPER_H_\n'
645 struct = '\n'
Tobin Ehlis84154d32017-06-09 15:46:14 -0600646 extension_helper_header += '#include <vulkan/vulkan.h>\n'
Tobin Ehlisd922d4c2017-06-14 09:43:04 -0600647 extension_helper_header += '#include <string.h>\n'
Tobin Ehlis84154d32017-06-09 15:46:14 -0600648 extension_helper_header += '#include <utility>\n'
649 extension_helper_header += '\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600650 extension_helper_header += '\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600651 extension_dict = dict()
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600652 promoted_ext_list = []
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600653 for type in ['Instance', 'Device']:
654 if type == 'Instance':
655 extension_dict = self.instance_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600656 promoted_ext_list = V_1_0_instance_extensions_promoted_to_core
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600657 struct += 'struct InstanceExtensions { \n'
658 else:
659 extension_dict = self.device_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600660 promoted_ext_list = V_1_0_device_extensions_promoted_to_core
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600661 struct += 'struct DeviceExtensions : public InstanceExtensions { \n'
662 for ext_name, ifdef in extension_dict.items():
663 bool_name = ext_name.lower()
664 bool_name = re.sub('_extension_name', '', bool_name)
665 struct += ' bool %s{false};\n' % bool_name
666 struct += '\n'
667 if type == 'Instance':
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600668 struct += ' uint32_t NormalizeApiVersion(uint32_t specified_version) {\n'
669 struct += ' uint32_t api_version = specified_version & ~VK_VERSION_PATCH(~0);\n'
670 struct += ' if (!(api_version == VK_API_VERSION_1_0) && !(api_version == VK_API_VERSION_1_1)) {\n'
671 struct += ' api_version = VK_API_VERSION_1_1;\n'
672 struct += ' }\n'
673 struct += ' return api_version;\n'
674 struct += ' }\n'
675 struct += '\n'
676
677 struct += ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600678 else:
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600679 struct += ' uint32_t InitFromDeviceCreateInfo(const InstanceExtensions *instance_extensions, uint32_t requested_api_version, const VkDeviceCreateInfo *pCreateInfo) {\n'
680 struct += '\n'
681
682 struct += ' static const std::vector<const char *> V_1_0_promoted_%s_extensions = {\n' % type.lower()
683 for ext_name in promoted_ext_list:
684 struct += ' %s_EXTENSION_NAME,\n' % ext_name.upper()
685 struct += ' };\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600686 struct += '\n'
687 struct += ' static const std::pair<char const *, bool %sExtensions::*> known_extensions[]{\n' % type
688 for ext_name, ifdef in extension_dict.items():
689 if ifdef is not None:
690 struct += '#ifdef %s\n' % ifdef
691 bool_name = ext_name.lower()
692 bool_name = re.sub('_extension_name', '', bool_name)
693 struct += ' {%s, &%sExtensions::%s},\n' % (ext_name, type, bool_name)
694 if ifdef is not None:
695 struct += '#endif\n'
696 struct += ' };\n'
697 struct += '\n'
698 struct += ' // Initialize struct data\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600699
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600700 for ext_name, ifdef in self.instance_extension_info.items():
701 bool_name = ext_name.lower()
702 bool_name = re.sub('_extension_name', '', bool_name)
703 if type == 'Device':
704 struct += ' %s = instance_extensions->%s;\n' % (bool_name, bool_name)
705 struct += '\n'
706 struct += ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {\n'
707 struct += ' for (auto ext : known_extensions) {\n'
708 struct += ' if (!strcmp(ext.first, pCreateInfo->ppEnabledExtensionNames[i])) {\n'
709 struct += ' this->*(ext.second) = true;\n'
710 struct += ' break;\n'
711 struct += ' }\n'
712 struct += ' }\n'
713 struct += ' }\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600714 struct += ' uint32_t api_version = NormalizeApiVersion(requested_api_version);\n'
715 struct += ' if (api_version >= VK_API_VERSION_1_1) {\n'
716 struct += ' for (auto promoted_ext : V_1_0_promoted_%s_extensions) {\n' % type.lower()
717 struct += ' for (auto ext : known_extensions) {\n'
718 struct += ' if (!strcmp(ext.first, promoted_ext)) {\n'
719 struct += ' this->*(ext.second) = true;\n'
720 struct += ' break;\n'
721 struct += ' }\n'
722 struct += ' }\n'
723 struct += ' }\n'
724 struct += ' }\n'
725 struct += ' return api_version;\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600726 struct += ' }\n'
727 struct += '};\n'
728 struct += '\n'
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700729 # Output reference lists of instance/device extension names
730 struct += 'static const char * const k%sExtensionNames = \n' % type
731 for ext_name, ifdef in extension_dict.items():
732 if ifdef is not None:
733 struct += '#ifdef %s\n' % ifdef
734 struct += ' %s\n' % ext_name
735 if ifdef is not None:
736 struct += '#endif\n'
737 struct += ';\n\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600738 extension_helper_header += struct
739 extension_helper_header += '\n'
740 extension_helper_header += '#endif // VK_EXTENSION_HELPER_H_\n'
741 return extension_helper_header
742 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600743 # Combine object types helper header file preamble with body text and return
744 def GenerateObjectTypesHelperHeader(self):
745 object_types_helper_header = '\n'
746 object_types_helper_header += '#pragma once\n'
747 object_types_helper_header += '\n'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600748 object_types_helper_header += '#include <vulkan/vulkan.h>\n\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600749 object_types_helper_header += self.GenerateObjectTypesHeader()
750 return object_types_helper_header
751 #
752 # Object types header: create object enum type header file
753 def GenerateObjectTypesHeader(self):
Mark Young6ba8abe2017-11-09 10:37:04 -0700754 object_types_header = ''
755 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600756 object_types_header += 'typedef enum VulkanObjectType {\n'
757 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
758 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600759 type_list = [];
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600760
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600761 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600762 for item in self.object_types:
763 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600764 enum_entry = 'kVulkanObjectType%s' % fixup_name
765 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600766 object_types_header += ' = %d,\n' % enum_num
767 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600768 type_list.append(enum_entry)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600769 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600770 object_types_header += '} VulkanObjectType;\n\n'
771
772 # Output name string helper
773 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600774 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600775 object_types_header += ' "Unknown",\n'
776 for item in self.object_types:
777 fixup_name = item[2:]
778 object_types_header += ' "%s",\n' % fixup_name
779 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600780
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600781 # Output a conversion routine from the layer object definitions to the debug report definitions
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600782 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600783 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 -0600784 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700785 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600786 for object_type in type_list:
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600787 search_type = object_type.replace("kVulkanObjectType", "").lower()
788 for vk_object_type in self.debug_report_object_types:
789 target_type = vk_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
790 target_type = target_type[:-4]
791 target_type = target_type.replace("_", "")
792 if search_type == target_type:
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600793 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600794 break
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600795 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600796
797 # Output a conversion routine from the layer object definitions to the core object type definitions
798 object_types_header += '\n'
799 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
800 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700801 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600802 for object_type in type_list:
Mark Young1ded24b2017-05-30 14:53:50 -0600803 search_type = object_type.replace("kVulkanObjectType", "").lower()
804 for vk_object_type in self.core_object_types:
805 target_type = vk_object_type.replace("VK_OBJECT_TYPE_", "").lower()
806 target_type = target_type.replace("_", "")
807 if search_type == target_type:
808 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Young1ded24b2017-05-30 14:53:50 -0600809 break
Mark Young1ded24b2017-05-30 14:53:50 -0600810 object_types_header += '};\n'
811
Mark Young6ba8abe2017-11-09 10:37:04 -0700812 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
813 object_types_header += '\n'
814 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
815 object_types_header += 'static VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
816 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
817 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
818 for core_object_type in self.core_object_types:
819 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
820 core_target_type = core_target_type.replace("_", "")
821 for dr_object_type in self.debug_report_object_types:
822 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
823 dr_target_type = dr_target_type[:-4]
824 dr_target_type = dr_target_type.replace("_", "")
825 if core_target_type == dr_target_type:
826 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
827 object_types_header += ' return %s;\n' % core_object_type
828 break
829 object_types_header += ' }\n'
830 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
831 object_types_header += '}\n'
832
833 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
834 object_types_header += '\n'
835 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
836 object_types_header += 'static VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
837 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
838 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
839 for core_object_type in self.core_object_types:
840 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
841 core_target_type = core_target_type.replace("_", "")
842 for dr_object_type in self.debug_report_object_types:
843 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
844 dr_target_type = dr_target_type[:-4]
845 dr_target_type = dr_target_type.replace("_", "")
846 if core_target_type == dr_target_type:
847 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
848 object_types_header += ' return %s;\n' % dr_object_type
849 break
850 object_types_header += ' }\n'
851 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
852 object_types_header += '}\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600853 return object_types_header
854 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700855 # Determine if a structure needs a safe_struct helper function
856 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700857 def NeedSafeStruct(self, structure):
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700858 if 'sType' == structure.name:
859 return True
860 for member in structure.members:
861 if member.ispointer == True:
862 return True
863 return False
864 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700865 # Combine safe struct helper source file preamble with body text and return
866 def GenerateSafeStructHelperSource(self):
867 safe_struct_helper_source = '\n'
868 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
869 safe_struct_helper_source += '#include <string.h>\n'
870 safe_struct_helper_source += '\n'
871 safe_struct_helper_source += self.GenerateSafeStructSource()
872 return safe_struct_helper_source
873 #
874 # safe_struct source -- create bodies of safe struct helper functions
875 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700876 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700877 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
878 'VkXcbSurfaceCreateInfoKHR',
879 'VkWaylandSurfaceCreateInfoKHR',
880 'VkMirSurfaceCreateInfoKHR',
881 'VkAndroidSurfaceCreateInfoKHR',
882 'VkWin32SurfaceCreateInfoKHR'
883 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700884 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700885 if self.NeedSafeStruct(item) == False:
886 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700887 if item.name in wsi_structs:
888 continue
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700889 if item.ifdef_protect != None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700890 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
891 ss_name = "safe_%s" % item.name
892 init_list = '' # list of members in struct constructor initializer
893 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
894 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
895 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
896 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +0100897
898 custom_construct_txt = {
899 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
900 'VkWriteDescriptorSet' :
901 ' switch (descriptorType) {\n'
902 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
903 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
904 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
905 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
906 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
907 ' if (descriptorCount && in_struct->pImageInfo) {\n'
908 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
909 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
910 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
911 ' }\n'
912 ' }\n'
913 ' break;\n'
914 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
915 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
916 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
917 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
918 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
919 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
920 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
921 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
922 ' }\n'
923 ' }\n'
924 ' break;\n'
925 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
926 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
927 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
928 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
929 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
930 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
931 ' }\n'
932 ' }\n'
933 ' break;\n'
934 ' default:\n'
935 ' break;\n'
936 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100937 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +0100938 ' if (in_struct->pCode) {\n'
939 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
940 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
941 ' }\n',
942 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
943 'VkGraphicsPipelineCreateInfo' :
944 ' if (stageCount && in_struct->pStages) {\n'
945 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
946 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
947 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
948 ' }\n'
949 ' }\n'
950 ' if (in_struct->pVertexInputState)\n'
951 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
952 ' else\n'
953 ' pVertexInputState = NULL;\n'
954 ' if (in_struct->pInputAssemblyState)\n'
955 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
956 ' else\n'
957 ' pInputAssemblyState = NULL;\n'
958 ' bool has_tessellation_stage = false;\n'
959 ' if (stageCount && pStages)\n'
960 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
961 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
962 ' has_tessellation_stage = true;\n'
963 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
964 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
965 ' else\n'
966 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
967 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
968 ' if (in_struct->pViewportState && has_rasterization) {\n'
969 ' bool is_dynamic_viewports = false;\n'
970 ' bool is_dynamic_scissors = false;\n'
971 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
972 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
973 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
974 ' is_dynamic_viewports = true;\n'
975 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
976 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
977 ' is_dynamic_scissors = true;\n'
978 ' }\n'
979 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
980 ' } else\n'
981 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
982 ' if (in_struct->pRasterizationState)\n'
983 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
984 ' else\n'
985 ' pRasterizationState = NULL;\n'
986 ' if (in_struct->pMultisampleState && has_rasterization)\n'
987 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
988 ' else\n'
989 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
990 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
991 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
992 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
993 ' else\n'
994 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
995 ' // needs a tracked subpass state usesColorAttachment\n'
996 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
997 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
998 ' else\n'
999 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1000 ' if (in_struct->pDynamicState)\n'
1001 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
1002 ' else\n'
1003 ' pDynamicState = NULL;\n',
1004 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
1005 'VkPipelineViewportStateCreateInfo' :
1006 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
1007 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
1008 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
1009 ' }\n'
1010 ' else\n'
1011 ' pViewports = NULL;\n'
1012 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
1013 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
1014 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
1015 ' }\n'
1016 ' else\n'
1017 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001018 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
1019 'VkDescriptorSetLayoutBinding' :
1020 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
1021 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
1022 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
1023 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1024 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
1025 ' }\n'
1026 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +01001027 }
1028
1029 custom_copy_txt = {
1030 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
1031 'VkGraphicsPipelineCreateInfo' :
1032 ' if (stageCount && src.pStages) {\n'
1033 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1034 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1035 ' pStages[i].initialize(&src.pStages[i]);\n'
1036 ' }\n'
1037 ' }\n'
1038 ' if (src.pVertexInputState)\n'
1039 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
1040 ' else\n'
1041 ' pVertexInputState = NULL;\n'
1042 ' if (src.pInputAssemblyState)\n'
1043 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
1044 ' else\n'
1045 ' pInputAssemblyState = NULL;\n'
1046 ' bool has_tessellation_stage = false;\n'
1047 ' if (stageCount && pStages)\n'
1048 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1049 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1050 ' has_tessellation_stage = true;\n'
1051 ' if (src.pTessellationState && has_tessellation_stage)\n'
1052 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
1053 ' else\n'
1054 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1055 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
1056 ' if (src.pViewportState && has_rasterization) {\n'
1057 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
1058 ' } else\n'
1059 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1060 ' if (src.pRasterizationState)\n'
1061 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
1062 ' else\n'
1063 ' pRasterizationState = NULL;\n'
1064 ' if (src.pMultisampleState && has_rasterization)\n'
1065 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
1066 ' else\n'
1067 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1068 ' if (src.pDepthStencilState && has_rasterization)\n'
1069 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
1070 ' else\n'
1071 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1072 ' if (src.pColorBlendState && has_rasterization)\n'
1073 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1074 ' else\n'
1075 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1076 ' if (src.pDynamicState)\n'
1077 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1078 ' else\n'
1079 ' pDynamicState = NULL;\n',
1080 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1081 'VkPipelineViewportStateCreateInfo' :
1082 ' if (src.pViewports) {\n'
1083 ' pViewports = new VkViewport[src.viewportCount];\n'
1084 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1085 ' }\n'
1086 ' else\n'
1087 ' pViewports = NULL;\n'
1088 ' if (src.pScissors) {\n'
1089 ' pScissors = new VkRect2D[src.scissorCount];\n'
1090 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1091 ' }\n'
1092 ' else\n'
1093 ' pScissors = NULL;\n',
1094 }
1095
Mike Schuchardt81485762017-09-04 11:38:42 -06001096 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1097 ' if (pCode)\n'
1098 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001099
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001100 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001101 m_type = member.type
1102 if member.type in self.structNames:
1103 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1104 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1105 m_type = 'safe_%s' % member.type
1106 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1107 # 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 -07001108 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001109 # For these exceptions just copy initial value over for now
1110 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1111 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001112 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001113 default_init_list += '\n %s(nullptr),' % (member.name)
1114 init_list += '\n %s(nullptr),' % (member.name)
1115 init_func_txt += ' %s = nullptr;\n' % (member.name)
1116 if 'pNext' != member.name and 'void' not in m_type:
Mark Lobodzinski51160a12017-01-18 11:05:48 -07001117 if not member.isstaticarray and (member.len is None or '/' in member.len):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001118 construct_txt += ' if (in_struct->%s) {\n' % member.name
1119 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1120 construct_txt += ' }\n'
1121 destruct_txt += ' if (%s)\n' % member.name
1122 destruct_txt += ' delete %s;\n' % member.name
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001123 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001124 construct_txt += ' if (in_struct->%s) {\n' % member.name
1125 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1126 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1127 construct_txt += ' }\n'
1128 destruct_txt += ' if (%s)\n' % member.name
1129 destruct_txt += ' delete[] %s;\n' % member.name
1130 elif member.isstaticarray or member.len is not None:
1131 if member.len is None:
1132 # Extract length of static array by grabbing val between []
1133 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1134 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1135 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1136 construct_txt += ' }\n'
1137 else:
1138 # Init array ptr to NULL
1139 default_init_list += '\n %s(nullptr),' % member.name
1140 init_list += '\n %s(nullptr),' % member.name
1141 init_func_txt += ' %s = nullptr;\n' % member.name
1142 array_element = 'in_struct->%s[i]' % member.name
1143 if member.type in self.structNames:
1144 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1145 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1146 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1147 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1148 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1149 destruct_txt += ' if (%s)\n' % member.name
1150 destruct_txt += ' delete[] %s;\n' % member.name
1151 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1152 if 'safe_' in m_type:
1153 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001154 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001155 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1156 construct_txt += ' }\n'
1157 construct_txt += ' }\n'
1158 elif member.ispointer == True:
1159 construct_txt += ' if (in_struct->%s)\n' % member.name
1160 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1161 construct_txt += ' else\n'
1162 construct_txt += ' %s = NULL;\n' % member.name
1163 destruct_txt += ' if (%s)\n' % member.name
1164 destruct_txt += ' delete %s;\n' % member.name
1165 elif 'safe_' in m_type:
1166 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1167 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1168 else:
1169 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1170 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1171 if '' != init_list:
1172 init_list = init_list[:-1] # hack off final comma
1173 if item.name in custom_construct_txt:
1174 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001175 if item.name in custom_destruct_txt:
1176 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001177 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 -07001178 if '' != default_init_list:
1179 default_init_list = " :%s" % (default_init_list[:-1])
1180 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1181 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1182 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1183 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1184 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1185 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001186 if item.name in custom_copy_txt:
1187 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001188 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 -06001189 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 -07001190 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 -07001191 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001192 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 -07001193 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1194 init_copy = copy_construct_init.replace('src.', 'src->')
1195 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001196 safe_struct_body.append("\nvoid %s::initialize(const %s* src)\n{\n%s%s}" % (ss_name, ss_name, init_copy, init_construct))
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001197 if item.ifdef_protect != None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001198 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1199 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001200 #
John Zulaufde972ac2017-10-26 12:07:05 -06001201 # Generate the type map
1202 def GenerateTypeMapHelperHeader(self):
1203 prefix = 'Lvl'
1204 fprefix = 'lvl_'
1205 typemap = prefix + 'TypeMap'
1206 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001207 type_member = 'Type'
1208 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001209 id_decl = 'static const VkStructureType '
John Zulaufde972ac2017-10-26 12:07:05 -06001210 generic_header = prefix + 'GenericHeader'
1211 typename_func = fprefix + 'typename'
1212 idname_func = fprefix + 'stype_name'
1213 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001214 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001215
1216 explanatory_comment = '\n'.join((
1217 '// These empty generic templates are specialized for each type with sType',
1218 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001219 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001220
1221 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1222 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001223 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1224 typemap_format += '}};\n'
1225
1226 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1227 idmap_format = ''.join((
1228 'template <> struct {template}<{id_value}> {{\n',
1229 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001230 '}};\n'))
1231
1232 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1233 utilities_format = '\n'.join((
1234 '// Header "base class" for pNext chain traversal',
1235 'struct {header} {{',
1236 ' VkStructureType sType;',
1237 ' const {header} *pNext;',
1238 '}};',
1239 '',
1240 '// Find an entry of the given type in the pNext chain',
1241 'template <typename T> const T *{find_func}(const void *next) {{',
1242 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1243 ' const T *found = nullptr;',
1244 ' while (current) {{',
1245 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1246 ' found = reinterpret_cast<const T*>(current);',
1247 ' current = nullptr;',
1248 ' }} else {{',
1249 ' current = current->pNext;',
1250 ' }}',
1251 ' }}',
1252 ' return found;',
1253 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001254 '',
1255 '// Init the header of an sType struct with pNext',
1256 'template <typename T> T {init_func}(void *p_next) {{',
1257 ' T out = {{}};',
1258 ' out.sType = {type_map}<T>::kSType;',
1259 ' out.pNext = p_next;',
1260 ' return out;',
1261 '}}',
1262 '',
1263 '// Init the header of an sType struct',
1264 'template <typename T> T {init_func}() {{',
1265 ' T out = {{}};',
1266 ' out.sType = {type_map}<T>::kSType;',
1267 ' return out;',
1268 '}}',
1269
Mike Schuchardt97662b02017-12-06 13:31:29 -07001270 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001271
1272 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001273
1274 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001275 code.append('\n'.join((
1276 '#pragma once',
1277 '#include <vulkan/vulkan.h>\n',
1278 explanatory_comment, '',
1279 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001280 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001281
1282 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001283 for item in self.structMembers:
1284 typename = item.name
1285 info = self.structTypes.get(typename)
1286 if not info:
1287 continue
1288
1289 if item.ifdef_protect != None:
1290 code.append('#ifdef %s' % item.ifdef_protect)
1291
1292 code.append('// Map type {} to id {}'.format(typename, info.value))
1293 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001294 id_decl=id_decl, id_member=id_member))
1295 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001296
1297 if item.ifdef_protect != None:
1298 code.append('#endif // %s' % item.ifdef_protect)
1299
John Zulauf65ac9d52018-01-23 11:20:50 -07001300 # Generate utilities for all types
1301 code.append('\n'.join((
1302 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1303 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1304 find_func=find_func, init_func=init_func), ''
1305 )))
1306
John Zulaufde972ac2017-10-26 12:07:05 -06001307 return "\n".join(code)
1308
1309 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001310 # Create a helper file and return it as a string
1311 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001312 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001313 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001314 elif self.helper_file_type == 'struct_size_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001315 return self.GenerateStructSizeHelperHeader()
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001316 elif self.helper_file_type == 'struct_size_source':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001317 return self.GenerateStructSizeHelperSource()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001318 elif self.helper_file_type == 'safe_struct_header':
1319 return self.GenerateSafeStructHelperHeader()
1320 elif self.helper_file_type == 'safe_struct_source':
1321 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001322 elif self.helper_file_type == 'object_types_header':
1323 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001324 elif self.helper_file_type == 'extension_helper_header':
1325 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001326 elif self.helper_file_type == 'typemap_helper_header':
1327 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001328 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001329 return 'Bad Helper File Generator Option %s' % self.helper_file_type
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -07001330