blob: 6f2ea4b6940e251c2b109d6a74e331d6cf2db9f7 [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
27
28#
29# HelperFileOutputGeneratorOptions - subclass of GeneratorOptions.
30class HelperFileOutputGeneratorOptions(GeneratorOptions):
31 def __init__(self,
32 filename = None,
33 directory = '.',
34 apiname = None,
35 profile = None,
36 versions = '.*',
37 emitversions = '.*',
38 defaultExtensions = None,
39 addExtensions = None,
40 removeExtensions = None,
41 sortProcedure = regSortFeatures,
42 prefixText = "",
43 genFuncPointers = True,
44 protectFile = True,
45 protectFeature = True,
46 protectProto = None,
47 protectProtoStr = None,
48 apicall = '',
49 apientry = '',
50 apientryp = '',
51 alignFuncParam = 0,
52 library_name = '',
53 helper_file_type = ''):
54 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
55 versions, emitversions, defaultExtensions,
56 addExtensions, removeExtensions, sortProcedure)
57 self.prefixText = prefixText
58 self.genFuncPointers = genFuncPointers
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070059 self.protectFile = protectFile
60 self.protectFeature = protectFeature
61 self.protectProto = protectProto
62 self.protectProtoStr = protectProtoStr
63 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
80 self.struct_size_h_output = '' # string built up of struct size header output
81 self.struct_size_c_output = '' # string built up of struct size source output
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070082 # Internal state - accumulators for different inner block text
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070083 self.structNames = [] # List of Vulkan struct typenames
84 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070085 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -060086 self.object_types = [] # List of all handle types
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060087 self.debug_report_object_types = [] # Handy copy of debug_report_object_type enum data
Mark Young1ded24b2017-05-30 14:53:50 -060088 self.core_object_types = [] # Handy copy of core_object_type enum data
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -060089 self.device_extension_info = dict() # Dict of device extension name defines and ifdef values
90 self.instance_extension_info = dict() # Dict of instance extension name defines and ifdef values
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060091
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070092 # Named tuples to store struct and command data
93 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070094 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl'])
Mark Lobodzinski5380d132016-12-28 14:45:34 -070095 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members', 'ifdef_protect'])
Petr Krause91f7a12017-12-14 20:57:36 +010096
97 self.custom_construct_params = {
98 # safe_VkGraphicsPipelineCreateInfo needs to know if subpass has color and\or depth\stencil attachments to use its pointers
99 'VkGraphicsPipelineCreateInfo' :
100 ', const bool uses_color_attachment, const bool uses_depthstencil_attachment',
101 # safe_VkPipelineViewportStateCreateInfo needs to know if viewport and scissor is dynamic to use its pointers
102 'VkPipelineViewportStateCreateInfo' :
103 ', const bool is_dynamic_viewports, const bool is_dynamic_scissors',
104 }
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700105 #
106 # Called once at the beginning of each run
107 def beginFile(self, genOpts):
108 OutputGenerator.beginFile(self, genOpts)
109 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700110 self.helper_file_type = genOpts.helper_file_type
111 self.library_name = genOpts.library_name
112 # File Comment
113 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
114 file_comment += '// See helper_file_generator.py for modifications\n'
115 write(file_comment, file=self.outFile)
116 # Copyright Notice
117 copyright = ''
118 copyright += '\n'
119 copyright += '/***************************************************************************\n'
120 copyright += ' *\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700121 copyright += ' * Copyright (c) 2015-2017 The Khronos Group Inc.\n'
122 copyright += ' * Copyright (c) 2015-2017 Valve Corporation\n'
123 copyright += ' * Copyright (c) 2015-2017 LunarG, Inc.\n'
124 copyright += ' * Copyright (c) 2015-2017 Google Inc.\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700125 copyright += ' *\n'
126 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
127 copyright += ' * you may not use this file except in compliance with the License.\n'
128 copyright += ' * You may obtain a copy of the License at\n'
129 copyright += ' *\n'
130 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
131 copyright += ' *\n'
132 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
133 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
134 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
135 copyright += ' * See the License for the specific language governing permissions and\n'
136 copyright += ' * limitations under the License.\n'
137 copyright += ' *\n'
138 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Mark Lobodzinskia9c963d2016-12-28 07:45:35 -0700139 copyright += ' * Author: Courtney Goeltzenleuchter <courtneygo@google.com>\n'
140 copyright += ' * Author: Tobin Ehlis <tobine@google.com>\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600141 copyright += ' * Author: Chris Forbes <chrisforbes@google.com>\n'
John Zulaufde972ac2017-10-26 12:07:05 -0600142 copyright += ' * Author: John Zulauf<jzulauf@lunarg.com>\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700143 copyright += ' *\n'
144 copyright += ' ****************************************************************************/\n'
145 write(copyright, file=self.outFile)
146 #
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -0700147 # Write generated file content to output file
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700148 def endFile(self):
149 dest_file = ''
150 dest_file += self.OutputDestFile()
Mark Lobodzinskiafe10542017-01-03 13:22:44 -0700151 # Remove blank lines at EOF
152 if dest_file.endswith('\n'):
153 dest_file = dest_file[:-1]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700154 write(dest_file, file=self.outFile);
155 # Finish processing in superclass
156 OutputGenerator.endFile(self)
157 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600158 # Override parent class to be notified of the beginning of an extension
159 def beginFeature(self, interface, emit):
160 # Start processing in superclass
161 OutputGenerator.beginFeature(self, interface, emit)
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600162 if self.featureName == 'VK_VERSION_1_0' or self.featureName == 'VK_VERSION_1_1':
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600163 return
164 nameElem = interface[0][1]
165 name = nameElem.get('name')
166 if 'EXTENSION_NAME' not in name:
167 print("Error in vk.xml file -- extension name is not available")
168 if interface.get('type') == 'instance':
169 self.instance_extension_info[name] = self.featureExtraProtect
170 else:
171 self.device_extension_info[name] = self.featureExtraProtect
172 #
173 # Override parent class to be notified of the end of an extension
174 def endFeature(self):
175 # Finish processing in superclass
176 OutputGenerator.endFeature(self)
177 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700178 # Grab group (e.g. C "enum" type) info to output for enum-string conversion helper
179 def genGroup(self, groupinfo, groupName):
180 OutputGenerator.genGroup(self, groupinfo, groupName)
181 groupElem = groupinfo.elem
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700182 # For enum_string_header
183 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700184 value_list = []
185 for elem in groupElem.findall('enum'):
186 if elem.get('supported') != 'disabled':
187 item_name = elem.get('name')
Mark Lobodzinskic8d02242017-09-28 15:12:02 -0600188 # Avoid duplicates
189 if item_name not in value_list:
190 value_list.append(item_name)
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700191 if value_list is not None:
192 self.enum_output += self.GenerateEnumStringConversion(groupName, value_list)
Mark Young1ded24b2017-05-30 14:53:50 -0600193 elif self.helper_file_type == 'object_types_header':
194 if groupName == 'VkDebugReportObjectTypeEXT':
195 for elem in groupElem.findall('enum'):
196 if elem.get('supported') != 'disabled':
197 item_name = elem.get('name')
198 self.debug_report_object_types.append(item_name)
199 elif groupName == 'VkObjectType':
200 for elem in groupElem.findall('enum'):
201 if elem.get('supported') != 'disabled':
202 item_name = elem.get('name')
203 self.core_object_types.append(item_name)
204
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700205 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700206 # Called for each type -- if the type is a struct/union, grab the metadata
207 def genType(self, typeinfo, name):
208 OutputGenerator.genType(self, typeinfo, name)
209 typeElem = typeinfo.elem
210 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
211 # Otherwise, emit the tag text.
212 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600213 if category == 'handle':
214 self.object_types.append(name)
215 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700216 self.structNames.append(name)
217 self.genStruct(typeinfo, name)
218 #
219 # Generate a VkStructureType based on a structure typename
220 def genVkStructureType(self, typename):
221 # Add underscore between lowercase then uppercase
222 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
223 # Change to uppercase
224 value = value.upper()
225 # Add STRUCTURE_TYPE_
226 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
227 #
228 # Check if the parameter passed in is a pointer
229 def paramIsPointer(self, param):
230 ispointer = False
231 for elem in param:
232 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
233 ispointer = True
234 return ispointer
235 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700236 # Check if the parameter passed in is a static array
237 def paramIsStaticArray(self, param):
238 isstaticarray = 0
239 paramname = param.find('name')
240 if (paramname.tail is not None) and ('[' in paramname.tail):
241 isstaticarray = paramname.tail.count('[')
242 return isstaticarray
243 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700244 # Retrieve the type and name for a parameter
245 def getTypeNameTuple(self, param):
246 type = ''
247 name = ''
248 for elem in param:
249 if elem.tag == 'type':
250 type = noneStr(elem.text)
251 elif elem.tag == 'name':
252 name = noneStr(elem.text)
253 return (type, name)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700254 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
255 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
256 def parseLateXMath(self, source):
257 name = 'ERROR'
258 decoratedName = 'ERROR'
259 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700260 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
261 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 -0700262 if not match or match.group(1) != match.group(4):
263 raise 'Unrecognized latexmath expression'
264 name = match.group(2)
mizhenc27f6c72017-03-31 09:08:16 -0600265 # Need to add 1 for ceiling function; otherwise, the allocated packet
266 # size will be less than needed during capture for some title which use
267 # this in VkPipelineMultisampleStateCreateInfo. based on ceiling function
268 # definition,it is '{0}%{1}?{0}/{1} + 1:{0}/{1}'.format(*match.group(2, 3)),
269 # its value <= '{}/{} + 1'.
270 if match.group(1) == 'ceil':
271 decoratedName = '{}/{} + 1'.format(*match.group(2, 3))
272 else:
273 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700274 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700275 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Mark Young0f183a82017-02-28 09:58:04 -0700276 match = re.match(r'latexmath\s*\:\s*\[\s*(\w+)\s*\\over\s*(\d+)\s*\]', source)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700277 name = match.group(1)
278 decoratedName = '{}/{}'.format(*match.group(1, 2))
279 return name, decoratedName
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700280 #
281 # Retrieve the value of the len tag
282 def getLen(self, param):
283 result = None
284 len = param.attrib.get('len')
285 if len and len != 'null-terminated':
286 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
287 # have a null terminated array of strings. We strip the null-terminated from the
288 # 'len' field and only return the parameter specifying the string count
289 if 'null-terminated' in len:
290 result = len.split(',')[0]
291 else:
292 result = len
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700293 if 'latexmath' in len:
294 param_type, param_name = self.getTypeNameTuple(param)
295 len_name, result = self.parseLateXMath(len)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700296 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
297 result = str(result).replace('::', '->')
298 return result
299 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700300 # Check if a structure is or contains a dispatchable (dispatchable = True) or
301 # non-dispatchable (dispatchable = False) handle
302 def TypeContainsObjectHandle(self, handle_type, dispatchable):
303 if dispatchable:
304 type_key = 'VK_DEFINE_HANDLE'
305 else:
306 type_key = 'VK_DEFINE_NON_DISPATCHABLE_HANDLE'
307 handle = self.registry.tree.find("types/type/[name='" + handle_type + "'][@category='handle']")
308 if handle is not None and handle.find('type').text == type_key:
309 return True
310 # if handle_type is a struct, search its members
311 if handle_type in self.structNames:
312 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == handle_type), None)
313 if member_index is not None:
314 for item in self.structMembers[member_index].members:
315 handle = self.registry.tree.find("types/type/[name='" + item.type + "'][@category='handle']")
316 if handle is not None and handle.find('type').text == type_key:
317 return True
318 return False
319 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700320 # Generate local ready-access data describing Vulkan structures and unions from the XML metadata
321 def genStruct(self, typeinfo, typeName):
322 OutputGenerator.genStruct(self, typeinfo, typeName)
323 members = typeinfo.elem.findall('.//member')
324 # Iterate over members once to get length parameters for arrays
325 lens = set()
326 for member in members:
327 len = self.getLen(member)
328 if len:
329 lens.add(len)
330 # Generate member info
331 membersInfo = []
332 for member in members:
333 # Get the member's type and name
334 info = self.getTypeNameTuple(member)
335 type = info[0]
336 name = info[1]
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700337 cdecl = self.makeCParamDecl(member, 1)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700338 # Process VkStructureType
339 if type == 'VkStructureType':
340 # Extract the required struct type value from the comments
341 # embedded in the original text defining the 'typeinfo' element
342 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
343 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
344 if result:
345 value = result.group(0)
346 else:
347 value = self.genVkStructureType(typeName)
348 # Store the required type value
349 self.structTypes[typeName] = self.StructType(name=name, value=value)
350 # Store pointer/array/string info
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700351 isstaticarray = self.paramIsStaticArray(member)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700352 membersInfo.append(self.CommandParam(type=type,
353 name=name,
354 ispointer=self.paramIsPointer(member),
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700355 isstaticarray=isstaticarray,
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700356 isconst=True if 'const' in cdecl else False,
357 iscount=True if name in lens else False,
358 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600359 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700360 cdecl=cdecl))
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700361 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo, ifdef_protect=self.featureExtraProtect))
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700362 #
363 # Enum_string_header: Create a routine to convert an enumerated value into a string
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700364 def GenerateEnumStringConversion(self, groupName, value_list):
365 outstring = '\n'
366 outstring += 'static inline const char* string_%s(%s input_value)\n' % (groupName, groupName)
367 outstring += '{\n'
368 outstring += ' switch ((%s)input_value)\n' % groupName
369 outstring += ' {\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700370 for item in value_list:
371 outstring += ' case %s:\n' % item
372 outstring += ' return "%s";\n' % item
373 outstring += ' default:\n'
374 outstring += ' return "Unhandled %s";\n' % groupName
375 outstring += ' }\n'
376 outstring += '}\n'
377 return outstring
378 #
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600379 # Tack on a helper which, given an index into a VkPhysicalDeviceFeatures structure, will print the corresponding feature name
380 def DeIndexPhysDevFeatures(self):
381 pdev_members = None
382 for name, members, ifdef in self.structMembers:
383 if name == 'VkPhysicalDeviceFeatures':
384 pdev_members = members
385 break
386 deindex = '\n'
387 deindex += 'static const char * GetPhysDevFeatureString(uint32_t index) {\n'
388 deindex += ' const char * IndexToPhysDevFeatureString[] = {\n'
389 for feature in pdev_members:
390 deindex += ' "%s",\n' % feature.name
391 deindex += ' };\n\n'
392 deindex += ' return IndexToPhysDevFeatureString[index];\n'
393 deindex += '}\n'
394 return deindex
395 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700396 # Combine enum string helper header file preamble with body text and return
397 def GenerateEnumStringHelperHeader(self):
398 enum_string_helper_header = '\n'
399 enum_string_helper_header += '#pragma once\n'
400 enum_string_helper_header += '#ifdef _WIN32\n'
401 enum_string_helper_header += '#pragma warning( disable : 4065 )\n'
402 enum_string_helper_header += '#endif\n'
403 enum_string_helper_header += '\n'
404 enum_string_helper_header += '#include <vulkan/vulkan.h>\n'
405 enum_string_helper_header += '\n'
406 enum_string_helper_header += self.enum_output
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600407 enum_string_helper_header += self.DeIndexPhysDevFeatures()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700408 return enum_string_helper_header
409 #
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700410 # struct_size_header: build function prototypes for header file
411 def GenerateStructSizeHeader(self):
412 outstring = ''
413 outstring += 'size_t get_struct_chain_size(const void* struct_ptr);\n'
David Pinedob95caa02017-10-05 10:30:02 -0600414 outstring += 'size_t get_struct_size(const void* struct_ptr);\n'
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700415 for item in self.structMembers:
416 lower_case_name = item.name.lower()
417 if item.ifdef_protect != None:
418 outstring += '#ifdef %s\n' % item.ifdef_protect
419 outstring += 'size_t vk_size_%s(const %s* struct_ptr);\n' % (item.name.lower(), item.name)
420 if item.ifdef_protect != None:
421 outstring += '#endif // %s\n' % item.ifdef_protect
422 outstring += '#ifdef __cplusplus\n'
423 outstring += '}\n'
424 outstring += '#endif'
425 return outstring
426 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700427 # Combine struct size helper header file preamble with body text and return
428 def GenerateStructSizeHelperHeader(self):
429 struct_size_helper_header = '\n'
430 struct_size_helper_header += '#ifdef __cplusplus\n'
431 struct_size_helper_header += 'extern "C" {\n'
432 struct_size_helper_header += '#endif\n'
433 struct_size_helper_header += '\n'
434 struct_size_helper_header += '#include <stdio.h>\n'
435 struct_size_helper_header += '#include <stdlib.h>\n'
436 struct_size_helper_header += '#include <vulkan/vulkan.h>\n'
437 struct_size_helper_header += '\n'
438 struct_size_helper_header += '// Function Prototypes\n'
439 struct_size_helper_header += self.GenerateStructSizeHeader()
440 return struct_size_helper_header
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700441 #
442 # Helper function for declaring a counter variable only once
443 def DeclareCounter(self, string_var, declare_flag):
444 if declare_flag == False:
445 string_var += ' uint32_t i = 0;\n'
446 declare_flag = True
447 return string_var, declare_flag
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700448 #
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700449 # Build the header of the get_struct_chain_size function
450 def GenerateChainSizePreamble(self):
David Pinedob95caa02017-10-05 10:30:02 -0600451 preamble = '\nsize_t get_struct_chain_size(const void* struct_ptr) {\n'
452 preamble += ' // Use VkApplicationInfo as struct until actual type is resolved\n'
453 preamble += ' VkApplicationInfo* pNext = (VkApplicationInfo*)struct_ptr;\n'
454 preamble += ' size_t struct_size = 0;\n'
455 preamble += ' while (pNext) {\n'
456 preamble += ' switch (pNext->sType) {\n'
457 return preamble
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700458 #
459 # Build the footer of the get_struct_chain_size function
460 def GenerateChainSizePostamble(self):
461 postamble = ' default:\n'
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700462 postamble += ' struct_size += 0;\n'
Joey Bzdekb6875332017-10-19 14:24:05 -0600463 postamble += ' break;'
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700464 postamble += ' }\n'
465 postamble += ' pNext = (VkApplicationInfo*)pNext->pNext;\n'
466 postamble += ' }\n'
467 postamble += ' return struct_size;\n'
David Pinedob95caa02017-10-05 10:30:02 -0600468 postamble += '}\n'
469 return postamble
470 #
471 # Build the header of the get_struct_size function
472 def GenerateStructSizePreamble(self):
473 preamble = '\nsize_t get_struct_size(const void* struct_ptr) {\n'
474 preamble += ' switch (((VkApplicationInfo*)struct_ptr)->sType) {\n'
475 return preamble
476 #
477 # Build the footer of the get_struct_size function
478 def GenerateStructSizePostamble(self):
479 postamble = ' default:\n'
David Pinedob95caa02017-10-05 10:30:02 -0600480 postamble += ' return(0);\n'
481 postamble += ' }\n'
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700482 postamble += '}'
483 return postamble
484 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700485 # struct_size_helper source -- create bodies of struct size helper functions
486 def GenerateStructSizeSource(self):
David Pinedob95caa02017-10-05 10:30:02 -0600487 # Construct the bodies of the struct size functions, get_struct_chain_size(),
488 # and get_struct_size() simultaneously
489 struct_size_funcs = ''
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700490 chain_size = self.GenerateChainSizePreamble()
David Pinedob95caa02017-10-05 10:30:02 -0600491 struct_size = self.GenerateStructSizePreamble()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700492 for item in self.structMembers:
David Pinedob95caa02017-10-05 10:30:02 -0600493 struct_size_funcs += '\n'
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700494 lower_case_name = item.name.lower()
495 if item.ifdef_protect != None:
David Pinedob95caa02017-10-05 10:30:02 -0600496 struct_size_funcs += '#ifdef %s\n' % item.ifdef_protect
497 struct_size += '#ifdef %s\n' % item.ifdef_protect
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700498 chain_size += '#ifdef %s\n' % item.ifdef_protect
499 if item.name in self.structTypes:
500 chain_size += ' case %s: {\n' % self.structTypes[item.name].value
501 chain_size += ' struct_size += vk_size_%s((%s*)pNext);\n' % (item.name.lower(), item.name)
502 chain_size += ' break;\n'
503 chain_size += ' }\n'
David Pinedob95caa02017-10-05 10:30:02 -0600504 struct_size += ' case %s: \n' % self.structTypes[item.name].value
505 struct_size += ' return vk_size_%s((%s*)struct_ptr);\n' % (item.name.lower(), item.name)
506 struct_size_funcs += 'size_t vk_size_%s(const %s* struct_ptr) { \n' % (item.name.lower(), item.name)
507 struct_size_funcs += ' size_t struct_size = 0;\n'
508 struct_size_funcs += ' if (struct_ptr) {\n'
509 struct_size_funcs += ' struct_size = sizeof(%s);\n' % item.name
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700510 counter_declared = False
511 for member in item.members:
512 vulkan_type = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
513 if member.ispointer == True:
514 if vulkan_type is not None:
515 # If this is another Vulkan structure call generated size function
516 if member.len is not None:
David Pinedob95caa02017-10-05 10:30:02 -0600517 struct_size_funcs, counter_declared = self.DeclareCounter(struct_size_funcs, counter_declared)
518 struct_size_funcs += ' for (i = 0; i < struct_ptr->%s; i++) {\n' % member.len
519 struct_size_funcs += ' struct_size += vk_size_%s(&struct_ptr->%s[i]);\n' % (member.type.lower(), member.name)
520 struct_size_funcs += ' }\n'
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700521 else:
David Pinedob95caa02017-10-05 10:30:02 -0600522 struct_size_funcs += ' struct_size += vk_size_%s(struct_ptr->%s);\n' % (member.type.lower(), member.name)
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700523 else:
524 if member.type == 'char':
525 # Deal with sizes of character strings
526 if member.len is not None:
David Pinedob95caa02017-10-05 10:30:02 -0600527 struct_size_funcs, counter_declared = self.DeclareCounter(struct_size_funcs, counter_declared)
528 struct_size_funcs += ' for (i = 0; i < struct_ptr->%s; i++) {\n' % member.len
529 struct_size_funcs += ' struct_size += (sizeof(char*) + (sizeof(char) * (1 + strlen(struct_ptr->%s[i]))));\n' % (member.name)
530 struct_size_funcs += ' }\n'
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700531 else:
David Pinedob95caa02017-10-05 10:30:02 -0600532 struct_size_funcs += ' struct_size += (struct_ptr->%s != NULL) ? sizeof(char)*(1+strlen(struct_ptr->%s)) : 0;\n' % (member.name, member.name)
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700533 else:
534 if member.len is not None:
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700535 # Avoid using 'sizeof(void)', which generates compile-time warnings/errors
536 checked_type = member.type
537 if checked_type == 'void':
538 checked_type = 'void*'
David Pinedob95caa02017-10-05 10:30:02 -0600539 struct_size_funcs += ' struct_size += (struct_ptr->%s ) * sizeof(%s);\n' % (member.len, checked_type)
540 struct_size_funcs += ' }\n'
541 struct_size_funcs += ' return struct_size;\n'
542 struct_size_funcs += '}\n'
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700543 if item.ifdef_protect != None:
David Pinedob95caa02017-10-05 10:30:02 -0600544 struct_size_funcs += '#endif // %s\n' % item.ifdef_protect
545 struct_size += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700546 chain_size += '#endif // %s\n' % item.ifdef_protect
547 chain_size += self.GenerateChainSizePostamble()
David Pinedob95caa02017-10-05 10:30:02 -0600548 struct_size += self.GenerateStructSizePostamble()
549 return_value = struct_size_funcs + chain_size + struct_size;
550 return return_value
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700551 #
552 # Combine struct size helper source file preamble with body text and return
553 def GenerateStructSizeHelperSource(self):
554 struct_size_helper_source = '\n'
555 struct_size_helper_source += '#include "vk_struct_size_helper.h"\n'
556 struct_size_helper_source += '#include <string.h>\n'
557 struct_size_helper_source += '#include <assert.h>\n'
558 struct_size_helper_source += '\n'
559 struct_size_helper_source += '// Function Definitions\n'
560 struct_size_helper_source += self.GenerateStructSizeSource()
561 return struct_size_helper_source
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700562 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700563 # Combine safe struct helper header file preamble with body text and return
564 def GenerateSafeStructHelperHeader(self):
565 safe_struct_helper_header = '\n'
566 safe_struct_helper_header += '#pragma once\n'
567 safe_struct_helper_header += '#include <vulkan/vulkan.h>\n'
568 safe_struct_helper_header += '\n'
569 safe_struct_helper_header += self.GenerateSafeStructHeader()
570 return safe_struct_helper_header
571 #
572 # safe_struct header: build function prototypes for header file
573 def GenerateSafeStructHeader(self):
574 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700575 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700576 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700577 safe_struct_header += '\n'
578 if item.ifdef_protect != None:
579 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
580 safe_struct_header += 'struct safe_%s {\n' % (item.name)
581 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700582 if member.type in self.structNames:
583 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
584 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
585 if member.ispointer:
586 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
587 else:
588 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
589 continue
590 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
591 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
592 else:
593 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100594 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 -0600595 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700596 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700597 safe_struct_header += ' safe_%s();\n' % item.name
598 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100599 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
600 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700601 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
602 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
603 safe_struct_header += '};\n'
604 if item.ifdef_protect != None:
605 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700606 return safe_struct_header
607 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600608 # Generate extension helper header file
609 def GenerateExtensionHelperHeader(self):
610 extension_helper_header = '\n'
611 extension_helper_header += '#ifndef VK_EXTENSION_HELPER_H_\n'
612 extension_helper_header += '#define VK_EXTENSION_HELPER_H_\n'
613 struct = '\n'
Tobin Ehlis84154d32017-06-09 15:46:14 -0600614 extension_helper_header += '#include <vulkan/vulkan.h>\n'
Tobin Ehlisd922d4c2017-06-14 09:43:04 -0600615 extension_helper_header += '#include <string.h>\n'
Tobin Ehlis84154d32017-06-09 15:46:14 -0600616 extension_helper_header += '#include <utility>\n'
617 extension_helper_header += '\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600618 extension_dict = dict()
619 for type in ['Instance', 'Device']:
620 if type == 'Instance':
621 extension_dict = self.instance_extension_info
622 struct += 'struct InstanceExtensions { \n'
623 else:
624 extension_dict = self.device_extension_info
625 struct += 'struct DeviceExtensions : public InstanceExtensions { \n'
626 for ext_name, ifdef in extension_dict.items():
627 bool_name = ext_name.lower()
628 bool_name = re.sub('_extension_name', '', bool_name)
629 struct += ' bool %s{false};\n' % bool_name
630 struct += '\n'
631 if type == 'Instance':
632 struct += ' void InitFromInstanceCreateInfo(const VkInstanceCreateInfo *pCreateInfo) {\n'
633 else:
634 struct += ' void InitFromDeviceCreateInfo(const InstanceExtensions *instance_extensions, const VkDeviceCreateInfo *pCreateInfo) {\n'
635 struct += '\n'
636 struct += ' static const std::pair<char const *, bool %sExtensions::*> known_extensions[]{\n' % type
637 for ext_name, ifdef in extension_dict.items():
638 if ifdef is not None:
639 struct += '#ifdef %s\n' % ifdef
640 bool_name = ext_name.lower()
641 bool_name = re.sub('_extension_name', '', bool_name)
642 struct += ' {%s, &%sExtensions::%s},\n' % (ext_name, type, bool_name)
643 if ifdef is not None:
644 struct += '#endif\n'
645 struct += ' };\n'
646 struct += '\n'
647 struct += ' // Initialize struct data\n'
648 for ext_name, ifdef in self.instance_extension_info.items():
649 bool_name = ext_name.lower()
650 bool_name = re.sub('_extension_name', '', bool_name)
651 if type == 'Device':
652 struct += ' %s = instance_extensions->%s;\n' % (bool_name, bool_name)
653 struct += '\n'
654 struct += ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {\n'
655 struct += ' for (auto ext : known_extensions) {\n'
656 struct += ' if (!strcmp(ext.first, pCreateInfo->ppEnabledExtensionNames[i])) {\n'
657 struct += ' this->*(ext.second) = true;\n'
658 struct += ' break;\n'
659 struct += ' }\n'
660 struct += ' }\n'
661 struct += ' }\n'
662 struct += ' }\n'
663 struct += '};\n'
664 struct += '\n'
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700665 # Output reference lists of instance/device extension names
666 struct += 'static const char * const k%sExtensionNames = \n' % type
667 for ext_name, ifdef in extension_dict.items():
668 if ifdef is not None:
669 struct += '#ifdef %s\n' % ifdef
670 struct += ' %s\n' % ext_name
671 if ifdef is not None:
672 struct += '#endif\n'
673 struct += ';\n\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600674 extension_helper_header += struct
675 extension_helper_header += '\n'
676 extension_helper_header += '#endif // VK_EXTENSION_HELPER_H_\n'
677 return extension_helper_header
678 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600679 # Combine object types helper header file preamble with body text and return
680 def GenerateObjectTypesHelperHeader(self):
681 object_types_helper_header = '\n'
682 object_types_helper_header += '#pragma once\n'
683 object_types_helper_header += '\n'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600684 object_types_helper_header += '#include <vulkan/vulkan.h>\n\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600685 object_types_helper_header += self.GenerateObjectTypesHeader()
686 return object_types_helper_header
687 #
688 # Object types header: create object enum type header file
689 def GenerateObjectTypesHeader(self):
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600690 object_types_header = '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600691 object_types_header += 'typedef enum VulkanObjectType {\n'
692 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
693 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600694 type_list = [];
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600695
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600696 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600697 for item in self.object_types:
698 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600699 enum_entry = 'kVulkanObjectType%s' % fixup_name
700 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600701 object_types_header += ' = %d,\n' % enum_num
702 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600703 type_list.append(enum_entry)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600704 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600705 object_types_header += '} VulkanObjectType;\n\n'
706
707 # Output name string helper
708 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600709 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600710 object_types_header += ' "Unknown",\n'
711 for item in self.object_types:
712 fixup_name = item[2:]
713 object_types_header += ' "%s",\n' % fixup_name
714 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600715
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600716 # Output a conversion routine from the layer object definitions to the debug report definitions
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600717 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600718 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 -0600719 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Lobodzinski34ad5f62017-11-14 10:19:40 -0700720 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // No Match\n'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600721 for object_type in type_list:
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600722 search_type = object_type.replace("kVulkanObjectType", "").lower()
723 for vk_object_type in self.debug_report_object_types:
724 target_type = vk_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
725 target_type = target_type[:-4]
726 target_type = target_type.replace("_", "")
727 if search_type == target_type:
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600728 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600729 break
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600730 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600731
732 # Output a conversion routine from the layer object definitions to the core object type definitions
733 object_types_header += '\n'
734 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
735 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Lobodzinski34ad5f62017-11-14 10:19:40 -0700736 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // No Match\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600737 for object_type in type_list:
Mark Young1ded24b2017-05-30 14:53:50 -0600738 search_type = object_type.replace("kVulkanObjectType", "").lower()
739 for vk_object_type in self.core_object_types:
740 target_type = vk_object_type.replace("VK_OBJECT_TYPE_", "").lower()
741 target_type = target_type.replace("_", "")
742 if search_type == target_type:
743 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Young1ded24b2017-05-30 14:53:50 -0600744 break
Mark Young1ded24b2017-05-30 14:53:50 -0600745 object_types_header += '};\n'
746
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600747 return object_types_header
748 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700749 # Determine if a structure needs a safe_struct helper function
750 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700751 def NeedSafeStruct(self, structure):
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700752 if 'sType' == structure.name:
753 return True
754 for member in structure.members:
755 if member.ispointer == True:
756 return True
757 return False
758 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700759 # Combine safe struct helper source file preamble with body text and return
760 def GenerateSafeStructHelperSource(self):
761 safe_struct_helper_source = '\n'
762 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
763 safe_struct_helper_source += '#include <string.h>\n'
764 safe_struct_helper_source += '\n'
765 safe_struct_helper_source += self.GenerateSafeStructSource()
766 return safe_struct_helper_source
767 #
768 # safe_struct source -- create bodies of safe struct helper functions
769 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700770 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700771 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
772 'VkXcbSurfaceCreateInfoKHR',
773 'VkWaylandSurfaceCreateInfoKHR',
774 'VkMirSurfaceCreateInfoKHR',
775 'VkAndroidSurfaceCreateInfoKHR',
776 'VkWin32SurfaceCreateInfoKHR'
777 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700778 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700779 if self.NeedSafeStruct(item) == False:
780 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700781 if item.name in wsi_structs:
782 continue
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700783 if item.ifdef_protect != None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700784 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
785 ss_name = "safe_%s" % item.name
786 init_list = '' # list of members in struct constructor initializer
787 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
788 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
789 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
790 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +0100791
792 custom_construct_txt = {
793 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
794 'VkWriteDescriptorSet' :
795 ' switch (descriptorType) {\n'
796 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
797 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
798 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
799 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
800 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
801 ' if (descriptorCount && in_struct->pImageInfo) {\n'
802 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
803 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
804 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
805 ' }\n'
806 ' }\n'
807 ' break;\n'
808 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
809 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
810 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
811 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
812 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
813 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
814 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
815 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
816 ' }\n'
817 ' }\n'
818 ' break;\n'
819 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
820 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
821 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
822 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
823 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
824 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
825 ' }\n'
826 ' }\n'
827 ' break;\n'
828 ' default:\n'
829 ' break;\n'
830 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100831 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +0100832 ' if (in_struct->pCode) {\n'
833 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
834 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
835 ' }\n',
836 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
837 'VkGraphicsPipelineCreateInfo' :
838 ' if (stageCount && in_struct->pStages) {\n'
839 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
840 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
841 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
842 ' }\n'
843 ' }\n'
844 ' if (in_struct->pVertexInputState)\n'
845 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
846 ' else\n'
847 ' pVertexInputState = NULL;\n'
848 ' if (in_struct->pInputAssemblyState)\n'
849 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
850 ' else\n'
851 ' pInputAssemblyState = NULL;\n'
852 ' bool has_tessellation_stage = false;\n'
853 ' if (stageCount && pStages)\n'
854 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
855 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
856 ' has_tessellation_stage = true;\n'
857 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
858 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
859 ' else\n'
860 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
861 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
862 ' if (in_struct->pViewportState && has_rasterization) {\n'
863 ' bool is_dynamic_viewports = false;\n'
864 ' bool is_dynamic_scissors = false;\n'
865 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
866 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
867 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
868 ' is_dynamic_viewports = true;\n'
869 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
870 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
871 ' is_dynamic_scissors = true;\n'
872 ' }\n'
873 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
874 ' } else\n'
875 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
876 ' if (in_struct->pRasterizationState)\n'
877 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
878 ' else\n'
879 ' pRasterizationState = NULL;\n'
880 ' if (in_struct->pMultisampleState && has_rasterization)\n'
881 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
882 ' else\n'
883 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
884 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
885 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
886 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
887 ' else\n'
888 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
889 ' // needs a tracked subpass state usesColorAttachment\n'
890 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
891 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
892 ' else\n'
893 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
894 ' if (in_struct->pDynamicState)\n'
895 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
896 ' else\n'
897 ' pDynamicState = NULL;\n',
898 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
899 'VkPipelineViewportStateCreateInfo' :
900 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
901 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
902 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
903 ' }\n'
904 ' else\n'
905 ' pViewports = NULL;\n'
906 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
907 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
908 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
909 ' }\n'
910 ' else\n'
911 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100912 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
913 'VkDescriptorSetLayoutBinding' :
914 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
915 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
916 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
917 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
918 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
919 ' }\n'
920 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +0100921 }
922
923 custom_copy_txt = {
924 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
925 'VkGraphicsPipelineCreateInfo' :
926 ' if (stageCount && src.pStages) {\n'
927 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
928 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
929 ' pStages[i].initialize(&src.pStages[i]);\n'
930 ' }\n'
931 ' }\n'
932 ' if (src.pVertexInputState)\n'
933 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
934 ' else\n'
935 ' pVertexInputState = NULL;\n'
936 ' if (src.pInputAssemblyState)\n'
937 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
938 ' else\n'
939 ' pInputAssemblyState = NULL;\n'
940 ' bool has_tessellation_stage = false;\n'
941 ' if (stageCount && pStages)\n'
942 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
943 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
944 ' has_tessellation_stage = true;\n'
945 ' if (src.pTessellationState && has_tessellation_stage)\n'
946 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
947 ' else\n'
948 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
949 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
950 ' if (src.pViewportState && has_rasterization) {\n'
951 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
952 ' } else\n'
953 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
954 ' if (src.pRasterizationState)\n'
955 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
956 ' else\n'
957 ' pRasterizationState = NULL;\n'
958 ' if (src.pMultisampleState && has_rasterization)\n'
959 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
960 ' else\n'
961 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
962 ' if (src.pDepthStencilState && has_rasterization)\n'
963 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
964 ' else\n'
965 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
966 ' if (src.pColorBlendState && has_rasterization)\n'
967 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
968 ' else\n'
969 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
970 ' if (src.pDynamicState)\n'
971 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
972 ' else\n'
973 ' pDynamicState = NULL;\n',
974 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
975 'VkPipelineViewportStateCreateInfo' :
976 ' if (src.pViewports) {\n'
977 ' pViewports = new VkViewport[src.viewportCount];\n'
978 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
979 ' }\n'
980 ' else\n'
981 ' pViewports = NULL;\n'
982 ' if (src.pScissors) {\n'
983 ' pScissors = new VkRect2D[src.scissorCount];\n'
984 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
985 ' }\n'
986 ' else\n'
987 ' pScissors = NULL;\n',
988 }
989
Mike Schuchardt81485762017-09-04 11:38:42 -0600990 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
991 ' if (pCode)\n'
992 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700993
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700994 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700995 m_type = member.type
996 if member.type in self.structNames:
997 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
998 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
999 m_type = 'safe_%s' % member.type
1000 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1001 # 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 -07001002 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001003 # For these exceptions just copy initial value over for now
1004 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1005 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001006 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001007 default_init_list += '\n %s(nullptr),' % (member.name)
1008 init_list += '\n %s(nullptr),' % (member.name)
1009 init_func_txt += ' %s = nullptr;\n' % (member.name)
1010 if 'pNext' != member.name and 'void' not in m_type:
Mark Lobodzinski51160a12017-01-18 11:05:48 -07001011 if not member.isstaticarray and (member.len is None or '/' in member.len):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001012 construct_txt += ' if (in_struct->%s) {\n' % member.name
1013 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1014 construct_txt += ' }\n'
1015 destruct_txt += ' if (%s)\n' % member.name
1016 destruct_txt += ' delete %s;\n' % member.name
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001017 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001018 construct_txt += ' if (in_struct->%s) {\n' % member.name
1019 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1020 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1021 construct_txt += ' }\n'
1022 destruct_txt += ' if (%s)\n' % member.name
1023 destruct_txt += ' delete[] %s;\n' % member.name
1024 elif member.isstaticarray or member.len is not None:
1025 if member.len is None:
1026 # Extract length of static array by grabbing val between []
1027 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1028 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1029 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1030 construct_txt += ' }\n'
1031 else:
1032 # Init array ptr to NULL
1033 default_init_list += '\n %s(nullptr),' % member.name
1034 init_list += '\n %s(nullptr),' % member.name
1035 init_func_txt += ' %s = nullptr;\n' % member.name
1036 array_element = 'in_struct->%s[i]' % member.name
1037 if member.type in self.structNames:
1038 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1039 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1040 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1041 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1042 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1043 destruct_txt += ' if (%s)\n' % member.name
1044 destruct_txt += ' delete[] %s;\n' % member.name
1045 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1046 if 'safe_' in m_type:
1047 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001048 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001049 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1050 construct_txt += ' }\n'
1051 construct_txt += ' }\n'
1052 elif member.ispointer == True:
1053 construct_txt += ' if (in_struct->%s)\n' % member.name
1054 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1055 construct_txt += ' else\n'
1056 construct_txt += ' %s = NULL;\n' % member.name
1057 destruct_txt += ' if (%s)\n' % member.name
1058 destruct_txt += ' delete %s;\n' % member.name
1059 elif 'safe_' in m_type:
1060 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1061 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1062 else:
1063 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1064 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1065 if '' != init_list:
1066 init_list = init_list[:-1] # hack off final comma
1067 if item.name in custom_construct_txt:
1068 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001069 if item.name in custom_destruct_txt:
1070 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001071 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 -07001072 if '' != default_init_list:
1073 default_init_list = " :%s" % (default_init_list[:-1])
1074 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1075 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1076 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1077 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1078 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1079 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001080 if item.name in custom_copy_txt:
1081 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001082 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 -06001083 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 -07001084 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 -07001085 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001086 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 -07001087 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1088 init_copy = copy_construct_init.replace('src.', 'src->')
1089 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001090 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 -07001091 if item.ifdef_protect != None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001092 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1093 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001094 #
John Zulaufde972ac2017-10-26 12:07:05 -06001095 # Generate the type map
1096 def GenerateTypeMapHelperHeader(self):
1097 prefix = 'Lvl'
1098 fprefix = 'lvl_'
1099 typemap = prefix + 'TypeMap'
1100 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001101 type_member = 'Type'
1102 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001103 id_decl = 'static const VkStructureType '
John Zulaufde972ac2017-10-26 12:07:05 -06001104 generic_header = prefix + 'GenericHeader'
1105 typename_func = fprefix + 'typename'
1106 idname_func = fprefix + 'stype_name'
1107 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001108 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001109
1110 explanatory_comment = '\n'.join((
1111 '// These empty generic templates are specialized for each type with sType',
1112 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001113 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001114
1115 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1116 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001117 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1118 typemap_format += '}};\n'
1119
1120 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1121 idmap_format = ''.join((
1122 'template <> struct {template}<{id_value}> {{\n',
1123 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001124 '}};\n'))
1125
1126 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1127 utilities_format = '\n'.join((
1128 '// Header "base class" for pNext chain traversal',
1129 'struct {header} {{',
1130 ' VkStructureType sType;',
1131 ' const {header} *pNext;',
1132 '}};',
1133 '',
1134 '// Find an entry of the given type in the pNext chain',
1135 'template <typename T> const T *{find_func}(const void *next) {{',
1136 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1137 ' const T *found = nullptr;',
1138 ' while (current) {{',
1139 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1140 ' found = reinterpret_cast<const T*>(current);',
1141 ' current = nullptr;',
1142 ' }} else {{',
1143 ' current = current->pNext;',
1144 ' }}',
1145 ' }}',
1146 ' return found;',
1147 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001148 '',
1149 '// Init the header of an sType struct with pNext',
1150 'template <typename T> T {init_func}(void *p_next) {{',
1151 ' T out = {{}};',
1152 ' out.sType = {type_map}<T>::kSType;',
1153 ' out.pNext = p_next;',
1154 ' return out;',
1155 '}}',
1156 '',
1157 '// Init the header of an sType struct',
1158 'template <typename T> T {init_func}() {{',
1159 ' T out = {{}};',
1160 ' out.sType = {type_map}<T>::kSType;',
1161 ' return out;',
1162 '}}',
1163
Mike Schuchardt97662b02017-12-06 13:31:29 -07001164 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001165
1166 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001167
1168 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001169 code.append('\n'.join((
1170 '#pragma once',
1171 '#include <vulkan/vulkan.h>\n',
1172 explanatory_comment, '',
1173 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001174 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001175
1176 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001177 for item in self.structMembers:
1178 typename = item.name
1179 info = self.structTypes.get(typename)
1180 if not info:
1181 continue
1182
1183 if item.ifdef_protect != None:
1184 code.append('#ifdef %s' % item.ifdef_protect)
1185
1186 code.append('// Map type {} to id {}'.format(typename, info.value))
1187 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001188 id_decl=id_decl, id_member=id_member))
1189 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001190
1191 if item.ifdef_protect != None:
1192 code.append('#endif // %s' % item.ifdef_protect)
1193
John Zulauf65ac9d52018-01-23 11:20:50 -07001194 # Generate utilities for all types
1195 code.append('\n'.join((
1196 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1197 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1198 find_func=find_func, init_func=init_func), ''
1199 )))
1200
John Zulaufde972ac2017-10-26 12:07:05 -06001201 return "\n".join(code)
1202
1203 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001204 # Create a helper file and return it as a string
1205 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001206 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001207 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001208 elif self.helper_file_type == 'struct_size_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001209 return self.GenerateStructSizeHelperHeader()
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001210 elif self.helper_file_type == 'struct_size_source':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001211 return self.GenerateStructSizeHelperSource()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001212 elif self.helper_file_type == 'safe_struct_header':
1213 return self.GenerateSafeStructHelperHeader()
1214 elif self.helper_file_type == 'safe_struct_source':
1215 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001216 elif self.helper_file_type == 'object_types_header':
1217 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001218 elif self.helper_file_type == 'extension_helper_header':
1219 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001220 elif self.helper_file_type == 'typemap_helper_header':
1221 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001222 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001223 return 'Bad Helper File Generator Option %s' % self.helper_file_type
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -07001224