forked from LunarG/VulkanSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vk_helper.py
executable file
·2213 lines (2098 loc) · 129 KB
/
vk_helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright (c) 2015-2016 The Khronos Group Inc.
# Copyright (c) 2015-2016 Valve Corporation
# Copyright (c) 2015-2016 LunarG, Inc.
# Copyright (c) 2015-2016 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and/or associated documentation files (the "Materials"), to
# deal in the Materials without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Materials, and to permit persons to whom the Materials
# are furnished to do so, subject to the following conditions:
#
# The above copyright notice(s) and this permission notice shall be included
# in all copies or substantial portions of the Materials.
#
# THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
#
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE
# USE OR OTHER DEALINGS IN THE MATERIALS
#
# Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
# Author: Tobin Ehlis <tobin@lunarg.com>
import argparse
import os
import sys
import re
import vulkan
from source_line_info import sourcelineinfo
# vk_helper.py overview
# This script generates code based on vulkan input header
# It generate wrappers functions that can be used to display
# structs in a human-readable txt format, as well as utility functions
# to print enum values as strings
def handle_args():
parser = argparse.ArgumentParser(description='Perform analysis of vogl trace.')
parser.add_argument('input_file', help='The input header file from which code will be generated.')
parser.add_argument('--rel_out_dir', required=False, default='vktrace_gen', help='Path relative to exec path to write output files. Will be created if needed.')
parser.add_argument('--abs_out_dir', required=False, default=None, help='Absolute path to write output files. Will be created if needed.')
parser.add_argument('--gen_enum_string_helper', required=False, action='store_true', default=False, help='Enable generation of helper header file to print string versions of enums.')
parser.add_argument('--gen_struct_wrappers', required=False, action='store_true', default=False, help='Enable generation of struct wrapper classes.')
parser.add_argument('--gen_struct_sizes', required=False, action='store_true', default=False, help='Enable generation of struct sizes.')
parser.add_argument('--gen_cmake', required=False, action='store_true', default=False, help='Enable generation of cmake file for generated code.')
parser.add_argument('--gen_graphviz', required=False, action='store_true', default=False, help='Enable generation of graphviz dot file.')
#parser.add_argument('--test', action='store_true', default=False, help='Run simple test.')
return parser.parse_args()
# TODO : Ideally these data structs would be opaque to user and could be wrapped
# in their own class(es) to make them friendly for data look-up
# Dicts for Data storage
# enum_val_dict[value_name] = dict keys are the string enum value names for all enums
# |-------->['type'] = the type of enum class into which the value falls
# |-------->['val'] = the value assigned to this particular value_name
# '-------->['unique'] = bool designating if this enum 'val' is unique within this enum 'type'
enum_val_dict = {}
# enum_type_dict['type'] = the type or class of of enum
# '----->['val_name1', 'val_name2'...] = each type references a list of val_names within this type
enum_type_dict = {}
# struct_dict['struct_basename'] = the base (non-typedef'd) name of the struct
# |->[<member_num>] = members are stored via their integer placement in the struct
# | |->['name'] = string name of this struct member
# ... |->['full_type'] = complete type qualifier for this member
# |->['type'] = base type for this member
# |->['ptr'] = bool indicating if this member is ptr
# |->['const'] = bool indicating if this member is const
# |->['struct'] = bool indicating if this member is a struct type
# |->['array'] = bool indicating if this member is an array
# |->['dyn_array'] = bool indicating if member is a dynamically sized array
# '->['array_size'] = For dyn_array, member name used to size array, else int size for static array
struct_dict = {}
struct_order_list = [] # struct names in order they're declared
# Store struct names that require #ifdef guards
# dict stores struct and enum definitions that are guarded by ifdef as the key
# and the txt of the ifdef is the value
ifdef_dict = {}
# typedef_fwd_dict stores mapping from orig_type_name -> new_type_name
typedef_fwd_dict = {}
# typedef_rev_dict stores mapping from new_type_name -> orig_type_name
typedef_rev_dict = {} # store new_name -> orig_name mapping
# types_dict['id_name'] = identifier name will map to it's type
# '---->'type' = currently either 'struct' or 'enum'
types_dict = {} # store orig_name -> type mapping
# Class that parses header file and generates data structures that can
# Then be used for other tasks
class HeaderFileParser:
def __init__(self, header_file=None):
self.header_file = header_file
# store header data in various formats, see above for more info
self.enum_val_dict = {}
self.enum_type_dict = {}
self.struct_dict = {}
self.typedef_fwd_dict = {}
self.typedef_rev_dict = {}
self.types_dict = {}
self.last_struct_count_name = ''
def setHeaderFile(self, header_file):
self.header_file = header_file
def get_enum_val_dict(self):
return self.enum_val_dict
def get_enum_type_dict(self):
return self.enum_type_dict
def get_struct_dict(self):
return self.struct_dict
def get_typedef_fwd_dict(self):
return self.typedef_fwd_dict
def get_typedef_rev_dict(self):
return self.typedef_rev_dict
def get_types_dict(self):
return self.types_dict
# Parse header file into data structures
def parse(self):
# parse through the file, identifying different sections
parse_enum = False
parse_struct = False
member_num = 0
# TODO : Comment parsing is very fragile but handles 2 known files
block_comment = False
prev_count_name = ''
ifdef_txt = ''
ifdef_active = 0
exclude_struct_list = ['VkPlatformHandleXcbKHR', 'VkPlatformHandleX11KHR']
with open(self.header_file) as f:
for line in f:
if True in [ifd_txt in line for ifd_txt in ['#ifdef ', '#ifndef ']]:
ifdef_txt = line.split()[1]
ifdef_active = ifdef_active + 1
continue
if ifdef_active != 0 and '#endif' in line:
ifdef_active = ifdef_active - 1
if block_comment:
if '*/' in line:
block_comment = False
continue
if '/*' in line:
if '*/' in line: # single line block comment
continue
block_comment = True
elif 0 == len(line.split()):
#print("Skipping empty line")
continue
elif line.split()[0].strip().startswith("//"):
#print("Skipping commented line %s" % line)
continue
elif 'typedef enum' in line:
(ty_txt, en_txt, base_type) = line.strip().split(None, 2)
#print("Found ENUM type %s" % base_type)
if '{' == base_type:
base_type = 'tmp_enum'
parse_enum = True
default_enum_val = 0
self.types_dict[base_type] = 'enum'
elif 'typedef struct' in line or 'typedef union' in line:
if True in [ex_type in line for ex_type in exclude_struct_list]:
continue
(ty_txt, st_txt, base_type) = line.strip().split(None, 2)
if ' ' in base_type:
(ignored, base_type) = base_type.strip().split(None, 1)
#print("Found STRUCT type: %s" % base_type)
# Note: This really needs to be updated to handle one line struct definition, like
# typedef struct obj##_T { uint64_t handle; } obj;
if ('{' == base_type or not (' ' in base_type)):
base_type = 'tmp_struct'
parse_struct = True
self.types_dict[base_type] = 'struct'
# elif 'typedef union' in line:
# (ty_txt, st_txt, base_type) = line.strip().split(None, 2)
# print("Found UNION type: %s" % base_type)
# parse_struct = True
# self.types_dict[base_type] = 'struct'
elif '}' in line and (parse_enum or parse_struct):
if len(line.split()) > 1: # deals with embedded union in one struct
parse_enum = False
parse_struct = False
self.last_struct_count_name = ''
member_num = 0
(cur_char, targ_type) = line.strip().split(None, 1)
if 'tmp_struct' == base_type:
base_type = targ_type.strip(';')
if True in [ex_type in base_type for ex_type in exclude_struct_list]:
del self.struct_dict['tmp_struct']
continue
#print("Found Actual Struct type %s" % base_type)
self.struct_dict[base_type] = self.struct_dict['tmp_struct']
self.struct_dict.pop('tmp_struct', 0)
struct_order_list.append(base_type)
self.types_dict[base_type] = 'struct'
self.types_dict.pop('tmp_struct', 0)
elif 'tmp_enum' == base_type:
base_type = targ_type.strip(';')
#print("Found Actual ENUM type %s" % base_type)
for n in self.enum_val_dict:
if 'tmp_enum' == self.enum_val_dict[n]['type']:
self.enum_val_dict[n]['type'] = base_type
# self.enum_val_dict[base_type] = self.enum_val_dict['tmp_enum']
# self.enum_val_dict.pop('tmp_enum', 0)
self.enum_type_dict[base_type] = self.enum_type_dict['tmp_enum']
self.enum_type_dict.pop('tmp_enum', 0)
self.types_dict[base_type] = 'enum'
self.types_dict.pop('tmp_enum', 0)
if ifdef_active:
ifdef_dict[base_type] = ifdef_txt
self.typedef_fwd_dict[base_type] = targ_type.strip(';')
self.typedef_rev_dict[targ_type.strip(';')] = base_type
#print("fwd_dict: %s = %s" % (base_type, targ_type))
elif parse_enum:
#if 'VK_MAX_ENUM' not in line and '{' not in line:
if True not in [ens in line for ens in ['{', '_MAX_ENUM', '_BEGIN_RANGE', '_END_RANGE', '_NUM = ', '_ENUM_RANGE']]:
self._add_enum(line, base_type, default_enum_val)
default_enum_val += 1
elif parse_struct:
if ';' in line:
self._add_struct(line, base_type, member_num)
member_num = member_num + 1
# populate enum dicts based on enum lines
def _add_enum(self, line_txt, enum_type, def_enum_val):
#print("Parsing enum line %s" % line_txt)
if '=' in line_txt:
(enum_name, eq_char, enum_val) = line_txt.split(None, 2)
else:
enum_name = line_txt.split(',')[0]
enum_val = str(def_enum_val)
self.enum_val_dict[enum_name] = {}
self.enum_val_dict[enum_name]['type'] = enum_type
# strip comma and comment, then extra split in case of no comma w/ comments
enum_val = enum_val.strip().split(',', 1)[0]
self.enum_val_dict[enum_name]['val'] = enum_val.split()[0]
# Perform conversion of VK_BIT macro
if 'VK_BIT' in self.enum_val_dict[enum_name]['val']:
vk_bit_val = self.enum_val_dict[enum_name]['val']
bit_shift = int(vk_bit_val[vk_bit_val.find('(')+1:vk_bit_val.find(')')], 0)
self.enum_val_dict[enum_name]['val'] = str(1 << bit_shift)
else:
# account for negative values surrounded by parens
self.enum_val_dict[enum_name]['val'] = self.enum_val_dict[enum_name]['val'].strip(')').replace('-(', '-')
# Try to cast to int to determine if enum value is unique
try:
#print("ENUM val:", self.enum_val_dict[enum_name]['val'])
int(self.enum_val_dict[enum_name]['val'], 0)
self.enum_val_dict[enum_name]['unique'] = True
#print("ENUM has num value")
except ValueError:
self.enum_val_dict[enum_name]['unique'] = False
#print("ENUM is not a number value")
# Update enum_type_dict as well
if not enum_type in self.enum_type_dict:
self.enum_type_dict[enum_type] = []
self.enum_type_dict[enum_type].append(enum_name)
# Return True if struct member is a dynamic array
# RULES : This is a bit quirky based on the API
# NOTE : Changes in API spec may cause these rules to change
# 1. There must be a previous uint var w/ 'count' in the name in the struct
# 2. Dynam array must have 'const' and '*' qualifiers
# 3a. Name of dynam array must end in 's' char OR
# 3b. Name of count var minus 'count' must be contained in name of dynamic array
def _is_dynamic_array(self, full_type, name):
exceptions = ['pEnabledFeatures', 'pWaitDstStageMask', 'pSampleMask']
if name in exceptions:
return False
if '' != self.last_struct_count_name:
if 'const' in full_type and '*' in full_type:
if name.endswith('s') or self.last_struct_count_name.lower().replace('count', '') in name.lower():
return True
# VkWriteDescriptorSet
if self.last_struct_count_name == "descriptorCount":
return True
return False
# populate struct dicts based on struct lines
# TODO : Handle ":" bitfield, "**" ptr->ptr and "const type*const*"
def _add_struct(self, line_txt, struct_type, num):
#print("Parsing struct line %s" % line_txt)
if '{' == struct_type:
print("Parsing struct '{' w/ line %s" % line_txt)
if not struct_type in self.struct_dict:
self.struct_dict[struct_type] = {}
members = line_txt.strip().split(';', 1)[0] # first strip semicolon & comments
# TODO : Handle bitfields more correctly
members = members.strip().split(':', 1)[0] # strip bitfield element
(member_type, member_name) = members.rsplit(None, 1)
# Store counts to help recognize and size dynamic arrays
if 'count' in member_name.lower() and 'samplecount' != member_name.lower() and 'uint' in member_type:
self.last_struct_count_name = member_name
self.struct_dict[struct_type][num] = {}
self.struct_dict[struct_type][num]['full_type'] = member_type
self.struct_dict[struct_type][num]['dyn_array'] = False
if '*' in member_type:
self.struct_dict[struct_type][num]['ptr'] = True
# TODO : Need more general purpose way here to reduce down to basic type
member_type = member_type.replace(' const*', '')
member_type = member_type.strip('*')
else:
self.struct_dict[struct_type][num]['ptr'] = False
if 'const' in member_type:
self.struct_dict[struct_type][num]['const'] = True
member_type = member_type.replace('const', '').strip()
else:
self.struct_dict[struct_type][num]['const'] = False
# TODO : There is a bug here where it seems that at the time we do this check,
# the data is not in the types or typedef_rev_dict, so we never pass this if check
if is_type(member_type, 'struct'):
self.struct_dict[struct_type][num]['struct'] = True
else:
self.struct_dict[struct_type][num]['struct'] = False
self.struct_dict[struct_type][num]['type'] = member_type
if '[' in member_name:
(member_name, array_size) = member_name.split('[', 1)
#if 'char' in member_type:
# self.struct_dict[struct_type][num]['array'] = False
# self.struct_dict[struct_type][num]['array_size'] = 0
# self.struct_dict[struct_type][num]['ptr'] = True
#else:
self.struct_dict[struct_type][num]['array'] = True
self.struct_dict[struct_type][num]['array_size'] = array_size.strip(']')
elif self._is_dynamic_array(self.struct_dict[struct_type][num]['full_type'], member_name):
#print("Found dynamic array %s of size %s" % (member_name, self.last_struct_count_name))
self.struct_dict[struct_type][num]['array'] = True
self.struct_dict[struct_type][num]['dyn_array'] = True
self.struct_dict[struct_type][num]['array_size'] = self.last_struct_count_name
elif not 'array' in self.struct_dict[struct_type][num]:
self.struct_dict[struct_type][num]['array'] = False
self.struct_dict[struct_type][num]['array_size'] = 0
self.struct_dict[struct_type][num]['name'] = member_name
# check if given identifier is of specified type_to_check
def is_type(identifier, type_to_check):
if identifier in types_dict and type_to_check == types_dict[identifier]:
return True
if identifier in typedef_rev_dict:
new_id = typedef_rev_dict[identifier]
if new_id in types_dict and type_to_check == types_dict[new_id]:
return True
return False
# This is a validation function to verify that we can reproduce the original structs
def recreate_structs():
for struct_name in struct_dict:
sys.stdout.write("typedef struct %s\n{\n" % struct_name)
for mem_num in sorted(struct_dict[struct_name]):
sys.stdout.write(" ")
if struct_dict[struct_name][mem_num]['const']:
sys.stdout.write("const ")
#if struct_dict[struct_name][mem_num]['struct']:
# sys.stdout.write("struct ")
sys.stdout.write (struct_dict[struct_name][mem_num]['type'])
if struct_dict[struct_name][mem_num]['ptr']:
sys.stdout.write("*")
sys.stdout.write(" ")
sys.stdout.write(struct_dict[struct_name][mem_num]['name'])
if struct_dict[struct_name][mem_num]['array']:
sys.stdout.write("[")
sys.stdout.write(struct_dict[struct_name][mem_num]['array_size'])
sys.stdout.write("]")
sys.stdout.write(";\n")
sys.stdout.write("} ")
sys.stdout.write(typedef_fwd_dict[struct_name])
sys.stdout.write(";\n\n")
#
# TODO: Fix construction of struct name
def get_struct_name_from_struct_type(struct_type):
# Note: All struct types are now camel-case
# Debug Report has an inconsistency - so need special case.
if ("VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT" == struct_type):
return "VkDebugReportCallbackCreateInfoEXT"
caps_struct_name = struct_type.replace("_STRUCTURE_TYPE", "")
char_idx = 0
struct_name = ''
for char in caps_struct_name:
if (0 == char_idx) or (caps_struct_name[char_idx-1] == '_'):
struct_name += caps_struct_name[char_idx]
elif (caps_struct_name[char_idx] == '_'):
pass
else:
struct_name += caps_struct_name[char_idx].lower()
char_idx += 1
return struct_name
# class for writing common file elements
# Here's how this class lays out a file:
# COPYRIGHT
# HEADER
# BODY
# FOOTER
#
# For each of these sections, there's a "set*" function
# The class as a whole has a generate function which will write each section in order
class CommonFileGen:
def __init__(self, filename=None, copyright_txt="", header_txt="", body_txt="", footer_txt=""):
self.filename = filename
self.contents = {'copyright': copyright_txt, 'header': header_txt, 'body': body_txt, 'footer': footer_txt}
# TODO : Set a default copyright & footer at least
def setFilename(self, filename):
self.filename = filename
def setCopyright(self, c):
self.contents['copyright'] = c
def setHeader(self, h):
self.contents['header'] = h
def setBody(self, b):
self.contents['body'] = b
def setFooter(self, f):
self.contents['footer'] = f
def generate(self):
#print("Generate to file %s" % self.filename)
with open(self.filename, "w") as f:
f.write(self.contents['copyright'])
f.write(self.contents['header'])
f.write(self.contents['body'])
f.write(self.contents['footer'])
# class for writing a wrapper class for structures
# The wrapper class wraps the structs and includes utility functions for
# setting/getting member values and displaying the struct data in various formats
class StructWrapperGen:
def __init__(self, in_struct_dict, prefix, out_dir):
self.struct_dict = in_struct_dict
self.include_headers = []
self.lineinfo = sourcelineinfo()
self.api = prefix
if prefix.lower() == "vulkan":
self.api_prefix = "vk"
else:
self.api_prefix = prefix
self.header_filename = os.path.join(out_dir, self.api_prefix+"_struct_wrappers.h")
self.class_filename = os.path.join(out_dir, self.api_prefix+"_struct_wrappers.cpp")
self.safe_struct_header_filename = os.path.join(out_dir, self.api_prefix+"_safe_struct.h")
self.safe_struct_source_filename = os.path.join(out_dir, self.api_prefix+"_safe_struct.cpp")
self.string_helper_filename = os.path.join(out_dir, self.api_prefix+"_struct_string_helper.h")
self.string_helper_no_addr_filename = os.path.join(out_dir, self.api_prefix+"_struct_string_helper_no_addr.h")
self.string_helper_cpp_filename = os.path.join(out_dir, self.api_prefix+"_struct_string_helper_cpp.h")
self.string_helper_no_addr_cpp_filename = os.path.join(out_dir, self.api_prefix+"_struct_string_helper_no_addr_cpp.h")
self.validate_helper_filename = os.path.join(out_dir, self.api_prefix+"_struct_validate_helper.h")
self.no_addr = False
# Safe Struct (ss) header and source files
self.ssh = CommonFileGen(self.safe_struct_header_filename)
self.sss = CommonFileGen(self.safe_struct_source_filename)
self.hfg = CommonFileGen(self.header_filename)
self.cfg = CommonFileGen(self.class_filename)
self.shg = CommonFileGen(self.string_helper_filename)
self.shcppg = CommonFileGen(self.string_helper_cpp_filename)
self.vhg = CommonFileGen(self.validate_helper_filename)
self.size_helper_filename = os.path.join(out_dir, self.api_prefix+"_struct_size_helper.h")
self.size_helper_c_filename = os.path.join(out_dir, self.api_prefix+"_struct_size_helper.c")
self.size_helper_gen = CommonFileGen(self.size_helper_filename)
self.size_helper_c_gen = CommonFileGen(self.size_helper_c_filename)
#print(self.header_filename)
self.header_txt = ""
self.definition_txt = ""
def set_include_headers(self, include_headers):
self.include_headers = include_headers
def set_no_addr(self, no_addr):
self.no_addr = no_addr
if self.no_addr:
self.shg = CommonFileGen(self.string_helper_no_addr_filename)
self.shcppg = CommonFileGen(self.string_helper_no_addr_cpp_filename)
else:
self.shg = CommonFileGen(self.string_helper_filename)
self.shcppg = CommonFileGen(self.string_helper_cpp_filename)
# Return class name for given struct name
def get_class_name(self, struct_name):
class_name = struct_name.strip('_').lower() + "_struct_wrapper"
return class_name
def get_file_list(self):
return [os.path.basename(self.header_filename), os.path.basename(self.class_filename), os.path.basename(self.string_helper_filename)]
# Generate class header file
def generateHeader(self):
self.hfg.setCopyright(self._generateCopyright())
self.hfg.setHeader(self._generateHeader())
self.hfg.setBody(self._generateClassDeclaration())
self.hfg.setFooter(self._generateFooter())
self.hfg.generate()
# Generate class definition
def generateBody(self):
self.cfg.setCopyright(self._generateCopyright())
self.cfg.setHeader(self._generateCppHeader())
self.cfg.setBody(self._generateClassDefinition())
self.cfg.setFooter(self._generateFooter())
self.cfg.generate()
# Safe Structs are versions of vulkan structs with non-const safe ptrs
# that make shadowing structures and clean-up of shadowed structures very simple
def generateSafeStructHeader(self):
self.ssh.setCopyright(self._generateCopyright())
self.ssh.setHeader(self._generateSafeStructHeader())
self.ssh.setBody(self._generateSafeStructDecls())
self.ssh.generate()
def generateSafeStructs(self):
self.sss.setCopyright(self._generateCopyright())
self.sss.setHeader(self._generateSafeStructSourceHeader())
self.sss.setBody(self._generateSafeStructSource())
self.sss.generate()
# Generate c-style .h file that contains functions for printing structs
def generateStringHelper(self):
print("Generating struct string helper")
self.shg.setCopyright(self._generateCopyright())
self.shg.setHeader(self._generateStringHelperHeader())
self.shg.setBody(self._generateStringHelperFunctions())
self.shg.generate()
# Generate cpp-style .h file that contains functions for printing structs
def generateStringHelperCpp(self):
print("Generating struct string helper cpp")
self.shcppg.setCopyright(self._generateCopyright())
self.shcppg.setHeader(self._generateStringHelperHeaderCpp())
self.shcppg.setBody(self._generateStringHelperFunctionsCpp())
self.shcppg.generate()
# Generate c-style .h file that contains functions for printing structs
def generateValidateHelper(self):
print("Generating struct validate helper")
self.vhg.setCopyright(self._generateCopyright())
self.vhg.setHeader(self._generateValidateHelperHeader())
self.vhg.setBody(self._generateValidateHelperFunctions())
self.vhg.generate()
def generateSizeHelper(self):
print("Generating struct size helper")
self.size_helper_gen.setCopyright(self._generateCopyright())
self.size_helper_gen.setHeader(self._generateSizeHelperHeader())
self.size_helper_gen.setBody(self._generateSizeHelperFunctions())
self.size_helper_gen.generate()
def generateSizeHelperC(self):
print("Generating struct size helper c")
self.size_helper_c_gen.setCopyright(self._generateCopyright())
self.size_helper_c_gen.setHeader(self._generateSizeHelperHeaderC())
self.size_helper_c_gen.setBody(self._generateSizeHelperFunctionsC())
self.size_helper_c_gen.generate()
def _generateCopyright(self):
copyright = []
copyright.append('/* THIS FILE IS GENERATED. DO NOT EDIT. */');
copyright.append('');
copyright.append('/*');
copyright.append(' * Vulkan');
copyright.append(' *');
copyright.append(' * Copyright (c) 2015-2016 The Khronos Group Inc.');
copyright.append(' * Copyright (c) 2015-2016 Valve Corporation.');
copyright.append(' * Copyright (c) 2015-2016 LunarG, Inc.');
copyright.append(' * Copyright (c) 2015-2016 Google Inc.');
copyright.append(' *');
copyright.append(' * Permission is hereby granted, free of charge, to any person obtaining a');
copyright.append(' * copy of this software and associated documentation files (the "Materials"),');
copyright.append(' * to deal in the Materials without restriction, including without limitation');
copyright.append(' * the rights to use, copy, modify, merge, publish, distribute, sublicense,');
copyright.append(' * and/or sell copies of the Materials, and to permit persons to whom the');
copyright.append(' * Materials is furnished to do so, subject to the following conditions:');
copyright.append(' *');
copyright.append(' * The above copyright notice and this permission notice shall be included');
copyright.append(' * in all copies or substantial portions of the Materials.');
copyright.append(' *');
copyright.append(' * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR');
copyright.append(' * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,');
copyright.append(' * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.');
copyright.append(' *');
copyright.append(' * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,');
copyright.append(' * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR');
copyright.append(' * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE');
copyright.append(' * USE OR OTHER DEALINGS IN THE MATERIALS');
copyright.append(' *');
copyright.append(' * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>');
copyright.append(' * Author: Tobin Ehlis <tobin@lunarg.com>');
copyright.append(' */');
copyright.append('');
return "\n".join(copyright)
def _generateCppHeader(self):
header = []
header.append("//#includes, #defines, globals and such...\n")
header.append("#include <stdio.h>\n#include <%s>\n#include <%s_enum_string_helper.h>\n" % (os.path.basename(self.header_filename), self.api_prefix))
return "".join(header)
def _generateClassDefinition(self):
class_def = []
if 'vk' == self.api:
class_def.append(self._generateDynamicPrintFunctions())
for s in sorted(self.struct_dict):
class_def.append("\n// %s class definition" % self.get_class_name(s))
class_def.append(self._generateConstructorDefinitions(s))
class_def.append(self._generateDestructorDefinitions(s))
class_def.append(self._generateDisplayDefinitions(s))
return "\n".join(class_def)
def _generateConstructorDefinitions(self, s):
con_defs = []
con_defs.append("%s::%s() : m_struct(), m_indent(0), m_dummy_prefix('\\0'), m_origStructAddr(NULL) {}" % (self.get_class_name(s), self.get_class_name(s)))
# TODO : This is a shallow copy of ptrs
con_defs.append("%s::%s(%s* pInStruct) : m_indent(0), m_dummy_prefix('\\0')\n{\n m_struct = *pInStruct;\n m_origStructAddr = pInStruct;\n}" % (self.get_class_name(s), self.get_class_name(s), typedef_fwd_dict[s]))
con_defs.append("%s::%s(const %s* pInStruct) : m_indent(0), m_dummy_prefix('\\0')\n{\n m_struct = *pInStruct;\n m_origStructAddr = pInStruct;\n}" % (self.get_class_name(s), self.get_class_name(s), typedef_fwd_dict[s]))
return "\n".join(con_defs)
def _generateDestructorDefinitions(self, s):
return "%s::~%s() {}" % (self.get_class_name(s), self.get_class_name(s))
def _generateDynamicPrintFunctions(self):
dp_funcs = []
dp_funcs.append("\nvoid dynamic_display_full_txt(const void* pStruct, uint32_t indent)\n{\n // Cast to APP_INFO ptr initially just to pull sType off struct")
dp_funcs.append(" VkStructureType sType = ((VkApplicationInfo*)pStruct)->sType;\n")
dp_funcs.append(" switch (sType)\n {")
for e in enum_type_dict:
class_num = 0
if "StructureType" in e:
for v in sorted(enum_type_dict[e]):
struct_name = get_struct_name_from_struct_type(v)
if struct_name not in self.struct_dict:
continue
class_name = self.get_class_name(struct_name)
instance_name = "swc%i" % class_num
dp_funcs.append(" case %s:\n {" % (v))
dp_funcs.append(" %s %s((%s*)pStruct);" % (class_name, instance_name, struct_name))
dp_funcs.append(" %s.set_indent(indent);" % (instance_name))
dp_funcs.append(" %s.display_full_txt();" % (instance_name))
dp_funcs.append(" }")
dp_funcs.append(" break;")
class_num += 1
dp_funcs.append(" }")
dp_funcs.append("}\n")
return "\n".join(dp_funcs)
def _get_func_name(self, struct, mid_str):
return "%s_%s_%s" % (self.api_prefix, mid_str, struct.lower().strip("_"))
def _get_sh_func_name(self, struct):
return self._get_func_name(struct, 'print')
def _get_vh_func_name(self, struct):
return self._get_func_name(struct, 'validate')
def _get_size_helper_func_name(self, struct):
return self._get_func_name(struct, 'size')
# Return elements to create formatted string for given struct member
def _get_struct_print_formatted(self, struct_member, pre_var_name="prefix", postfix = "\\n", struct_var_name="pStruct", struct_ptr=True, print_array=False):
struct_op = "->"
if not struct_ptr:
struct_op = "."
member_name = struct_member['name']
print_type = "p"
cast_type = ""
member_post = ""
array_index = ""
member_print_post = ""
print_delimiter = "%"
if struct_member['array'] and 'char' in struct_member['type'].lower(): # just print char array as string
if member_name.startswith('pp'): # TODO : Only printing first element of dynam array of char* for now
member_post = "[0]"
print_type = "s"
print_array = False
elif struct_member['array'] and not print_array:
# Just print base address of array when not full print_array
cast_type = "(void*)"
elif is_type(struct_member['type'], 'enum'):
cast_type = "string_%s" % struct_member['type']
if struct_member['ptr']:
struct_var_name = "*" + struct_var_name
print_type = "s"
elif is_type(struct_member['type'], 'struct'): # print struct address for now
cast_type = "(void*)"
if not struct_member['ptr']:
cast_type = "(void*)&"
elif 'bool' in struct_member['type'].lower():
print_type = "s"
member_post = ' ? "TRUE" : "FALSE"'
elif 'float' in struct_member['type']:
print_type = "f"
elif 'uint64' in struct_member['type'] or 'gpusize' in struct_member['type'].lower():
print_type = '" PRId64 "'
elif 'uint8' in struct_member['type']:
print_type = "hu"
elif 'size' in struct_member['type'].lower():
print_type = '" PRINTF_SIZE_T_SPECIFIER "'
print_delimiter = ""
elif True in [ui_str.lower() in struct_member['type'].lower() for ui_str in ['uint', 'flags', 'samplemask']]:
print_type = "u"
elif 'int' in struct_member['type']:
print_type = "i"
elif struct_member['ptr']:
pass
else:
#print("Unhandled struct type: %s" % struct_member['type'])
cast_type = "(void*)"
if print_array and struct_member['array']:
member_print_post = "[%u]"
array_index = " i,"
member_post = "[i]"
print_out = "%%s%s%s = %s%s%s" % (member_name, member_print_post, print_delimiter, print_type, postfix) # section of print that goes inside of quotes
print_arg = ", %s,%s %s(%s%s%s)%s" % (pre_var_name, array_index, cast_type, struct_var_name, struct_op, member_name, member_post) # section of print passed to portion in quotes
if self.no_addr and "p" == print_type:
print_out = "%%s%s%s = addr\\n" % (member_name, member_print_post) # section of print that goes inside of quotes
print_arg = ", %s" % (pre_var_name)
return (print_out, print_arg)
def _generateStringHelperFunctions(self):
sh_funcs = []
# We do two passes, first pass just generates prototypes for all the functsions
for s in sorted(self.struct_dict):
sh_funcs.append('char* %s(const %s* pStruct, const char* prefix);' % (self._get_sh_func_name(s), typedef_fwd_dict[s]))
sh_funcs.append('')
sh_funcs.append('#if defined(_WIN32)')
sh_funcs.append('// Microsoft did not implement C99 in Visual Studio; but started adding it with')
sh_funcs.append('// VS2013. However, VS2013 still did not have snprintf(). The following is a')
sh_funcs.append('// work-around.')
sh_funcs.append('#define snprintf _snprintf')
sh_funcs.append('#endif // _WIN32\n')
for s in sorted(self.struct_dict):
p_out = ""
p_args = ""
stp_list = [] # stp == "struct to print" a list of structs for this API call that should be printed as structs
# This pre-pass flags embedded structs and pNext
for m in sorted(self.struct_dict[s]):
if 'pNext' == self.struct_dict[s][m]['name'] or is_type(self.struct_dict[s][m]['type'], 'struct'):
stp_list.append(self.struct_dict[s][m])
sh_funcs.append('char* %s(const %s* pStruct, const char* prefix)\n{\n char* str;' % (self._get_sh_func_name(s), typedef_fwd_dict[s]))
sh_funcs.append(" size_t len;")
num_stps = len(stp_list);
total_strlen_str = ''
if 0 != num_stps:
sh_funcs.append(" char* tmpStr;")
sh_funcs.append(' char* extra_indent = (char*)malloc(strlen(prefix) + 3);')
sh_funcs.append(' strcpy(extra_indent, " ");')
sh_funcs.append(' strncat(extra_indent, prefix, strlen(prefix));')
sh_funcs.append(' char* stp_strs[%i];' % num_stps)
for index in range(num_stps):
# If it's an array, print all of the elements
# If it's a ptr, print thing it's pointing to
# Non-ptr struct case. Print the struct using its address
struct_deref = '&'
if 1 < stp_list[index]['full_type'].count('*'):
struct_deref = ''
if (stp_list[index]['ptr']):
sh_funcs.append(' if (pStruct->%s) {' % stp_list[index]['name'])
if 'pNext' == stp_list[index]['name']:
sh_funcs.append(' tmpStr = dynamic_display((void*)pStruct->pNext, prefix);')
sh_funcs.append(' len = 256+strlen(tmpStr);')
sh_funcs.append(' stp_strs[%i] = (char*)malloc(len);' % index)
if self.no_addr:
sh_funcs.append(' snprintf(stp_strs[%i], len, " %%spNext (addr)\\n%%s", prefix, tmpStr);' % index)
else:
sh_funcs.append(' snprintf(stp_strs[%i], len, " %%spNext (%%p)\\n%%s", prefix, (void*)pStruct->pNext, tmpStr);' % index)
sh_funcs.append(' free(tmpStr);')
else:
if stp_list[index]['name'] in ['pImageViews', 'pBufferViews']:
# TODO : This is a quick hack to handle these arrays of ptrs
sh_funcs.append(' tmpStr = %s(&pStruct->%s[0], extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
else:
sh_funcs.append(' tmpStr = %s(pStruct->%s, extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
sh_funcs.append(' len = 256+strlen(tmpStr)+strlen(prefix);')
sh_funcs.append(' stp_strs[%i] = (char*)malloc(len);' % (index))
if self.no_addr:
sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s (addr)\\n%%s", prefix, tmpStr);' % (index, stp_list[index]['name']))
else:
sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s (%%p)\\n%%s", prefix, (void*)pStruct->%s, tmpStr);' % (index, stp_list[index]['name'], stp_list[index]['name']))
sh_funcs.append(' }')
sh_funcs.append(" else\n stp_strs[%i] = \"\";" % (index))
elif stp_list[index]['array']:
sh_funcs.append(' tmpStr = %s(&pStruct->%s[0], extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
sh_funcs.append(' len = 256+strlen(tmpStr);')
sh_funcs.append(' stp_strs[%i] = (char*)malloc(len);' % (index))
if self.no_addr:
sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s[0] (addr)\\n%%s", prefix, tmpStr);' % (index, stp_list[index]['name']))
else:
sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s[0] (%%p)\\n%%s", prefix, (void*)&pStruct->%s[0], tmpStr);' % (index, stp_list[index]['name'], stp_list[index]['name']))
else:
sh_funcs.append(' tmpStr = %s(&pStruct->%s, extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
sh_funcs.append(' len = 256+strlen(tmpStr);')
sh_funcs.append(' stp_strs[%i] = (char*)malloc(len);' % (index))
if self.no_addr:
sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s (addr)\\n%%s", prefix, tmpStr);' % (index, stp_list[index]['name']))
else:
sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s (%%p)\\n%%s", prefix, (void*)&pStruct->%s, tmpStr);' % (index, stp_list[index]['name'], stp_list[index]['name']))
total_strlen_str += 'strlen(stp_strs[%i]) + ' % index
sh_funcs.append(' len = %ssizeof(char)*1024;' % (total_strlen_str))
sh_funcs.append(' str = (char*)malloc(len);')
sh_funcs.append(' snprintf(str, len, "')
for m in sorted(self.struct_dict[s]):
(p_out1, p_args1) = self._get_struct_print_formatted(self.struct_dict[s][m])
p_out += p_out1
p_args += p_args1
p_out += '"'
p_args += ");"
sh_funcs[-1] = '%s%s%s' % (sh_funcs[-1], p_out, p_args)
if 0 != num_stps:
sh_funcs.append(' for (int32_t stp_index = %i; stp_index >= 0; stp_index--) {' % (num_stps-1))
sh_funcs.append(' if (0 < strlen(stp_strs[stp_index])) {')
sh_funcs.append(' strncat(str, stp_strs[stp_index], strlen(stp_strs[stp_index]));')
sh_funcs.append(' free(stp_strs[stp_index]);')
sh_funcs.append(' }')
sh_funcs.append(' }')
sh_funcs.append(' free(extra_indent);')
sh_funcs.append(" return str;\n}")
# Add function to dynamically print out unknown struct
sh_funcs.append("char* dynamic_display(const void* pStruct, const char* prefix)\n{")
sh_funcs.append(" // Cast to APP_INFO ptr initially just to pull sType off struct")
sh_funcs.append(" if (pStruct == NULL) {")
sh_funcs.append(" return NULL;")
sh_funcs.append(" }")
sh_funcs.append(" VkStructureType sType = ((VkApplicationInfo*)pStruct)->sType;")
sh_funcs.append(' char indent[100];\n strcpy(indent, " ");\n strcat(indent, prefix);')
sh_funcs.append(" switch (sType)\n {")
for e in enum_type_dict:
if "StructureType" in e:
for v in sorted(enum_type_dict[e]):
struct_name = get_struct_name_from_struct_type(v)
if struct_name not in self.struct_dict:
continue
print_func_name = self._get_sh_func_name(struct_name)
sh_funcs.append(' case %s:\n {' % (v))
sh_funcs.append(' return %s((%s*)pStruct, indent);' % (print_func_name, struct_name))
sh_funcs.append(' }')
sh_funcs.append(' break;')
sh_funcs.append(" default:")
sh_funcs.append(" return NULL;")
sh_funcs.append(" }")
sh_funcs.append("}")
return "\n".join(sh_funcs)
def _generateStringHelperFunctionsCpp(self):
# declare str & tmp str
# declare array of stringstreams for every struct ptr in current struct
# declare array of stringstreams for every non-string element in current struct
# For every struct ptr, if non-Null, then set its string, else set to NULL str
# For every non-string element, set its string stream
# create and return final string
sh_funcs = []
# First generate prototypes for every struct
# XXX - REMOVE this comment
lineinfo = sourcelineinfo()
sh_funcs.append('%s' % lineinfo.get())
exclude_struct_list = ['VkAndroidSurfaceCreateInfoKHR',
'VkMirSurfaceCreateInfoKHR',
'VkWaylandSurfaceCreateInfoKHR',
'VkXlibSurfaceCreateInfoKHR']
if sys.platform == 'win32':
exclude_struct_list.append('VkXcbSurfaceCreateInfoKHR')
else:
exclude_struct_list.append('VkWin32SurfaceCreateInfoKHR')
for s in sorted(self.struct_dict):
if (typedef_fwd_dict[s] not in exclude_struct_list):
if (re.match(r'.*Xcb.*', typedef_fwd_dict[s])):
sh_funcs.append("#ifdef VK_USE_PLATFORM_XCB_KHR")
if (re.match(r'.*Win32.*', typedef_fwd_dict[s])):
sh_funcs.append("#ifdef VK_USE_PLATFORM_WIN32_KHR")
sh_funcs.append('string %s(const %s* pStruct, const string prefix);' % (self._get_sh_func_name(s), typedef_fwd_dict[s]))
if (re.match(r'.*Win32.*', typedef_fwd_dict[s])):
sh_funcs.append("#endif //VK_USE_PLATFORM_WIN32_KHR")
if (re.match(r'.*Xcb.*', typedef_fwd_dict[s])):
sh_funcs.append("#endif //VK_USE_PLATFORM_XCB_KHR")
sh_funcs.append('\n')
sh_funcs.append('%s' % lineinfo.get())
for s in sorted(self.struct_dict):
num_non_enum_elems = [(is_type(self.struct_dict[s][elem]['type'], 'enum') and not self.struct_dict[s][elem]['ptr']) for elem in self.struct_dict[s]].count(False)
stp_list = [] # stp == "struct to print" a list of structs for this API call that should be printed as structs
# This pre-pass flags embedded structs and pNext
for m in sorted(self.struct_dict[s]):
if 'pNext' == self.struct_dict[s][m]['name'] or is_type(self.struct_dict[s][m]['type'], 'struct') or self.struct_dict[s][m]['array']:
# TODO: This is a tmp workaround
if 'ppActiveLayerNames' not in self.struct_dict[s][m]['name']:
stp_list.append(self.struct_dict[s][m])
if (typedef_fwd_dict[s] in exclude_struct_list):
continue
sh_funcs.append('%s' % lineinfo.get())
if (re.match(r'.*Xcb.*', typedef_fwd_dict[s])):
sh_funcs.append("#ifdef VK_USE_PLATFORM_XCB_KHR")
if (re.match(r'.*Win32.*', typedef_fwd_dict[s])):
sh_funcs.append("#ifdef VK_USE_PLATFORM_WIN32_KHR")
sh_funcs.append('string %s(const %s* pStruct, const string prefix)\n{' % (self._get_sh_func_name(s), typedef_fwd_dict[s]))
sh_funcs.append('%s' % lineinfo.get())
indent = ' '
sh_funcs.append('%susing namespace StreamControl;' % (indent))
sh_funcs.append('%sstring final_str;' % (indent))
sh_funcs.append('%sstring tmp_str;' % (indent))
sh_funcs.append('%sstring extra_indent = " " + prefix;' % (indent))
if (0 != num_non_enum_elems):
sh_funcs.append('%sstringstream ss[%u];' % (indent, num_non_enum_elems))
num_stps = len(stp_list)
# First generate code for any embedded structs or arrays
if 0 < num_stps:
sh_funcs.append('%sstring stp_strs[%u];' % (indent, num_stps))
idx_ss_decl = False # Make sure to only decl this once
for index in range(num_stps):
addr_char = '&'
if 1 < stp_list[index]['full_type'].count('*'):
addr_char = ''
if stp_list[index]['array']:
sh_funcs.append('%s' % lineinfo.get())
if stp_list[index]['dyn_array']:
sh_funcs.append('%s' % lineinfo.get())
array_count = 'pStruct->%s' % (stp_list[index]['array_size'])
else:
sh_funcs.append('%s' % lineinfo.get())
array_count = '%s' % (stp_list[index]['array_size'])
sh_funcs.append('%s' % lineinfo.get())
sh_funcs.append('%sstp_strs[%u] = "";' % (indent, index))
if not idx_ss_decl:
sh_funcs.append('%sstringstream index_ss;' % (indent))
idx_ss_decl = True
if (stp_list[index]['name'] == 'pQueueFamilyIndices'):
if (typedef_fwd_dict[s] == 'VkSwapchainCreateInfoKHR'):
sh_funcs.append('%sif (pStruct->imageSharingMode == VK_SHARING_MODE_CONCURRENT) {' % (indent))
else:
sh_funcs.append('%sif (pStruct->sharingMode == VK_SHARING_MODE_CONCURRENT) {' % (indent))
indent += ' '
if (stp_list[index]['name'] == 'pImageInfo'):
sh_funcs.append('%sif ((pStruct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) ||' % (indent))
sh_funcs.append('%s (pStruct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) ||' % (indent))
sh_funcs.append('%s (pStruct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) ||' % (indent))
sh_funcs.append('%s (pStruct->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE)) {' % (indent))
indent += ' '
elif (stp_list[index]['name'] == 'pBufferInfo'):
sh_funcs.append('%sif ((pStruct->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) ||' % (indent))
sh_funcs.append('%s (pStruct->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) ||' % (indent))
sh_funcs.append('%s (pStruct->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) ||' % (indent))
sh_funcs.append('%s (pStruct->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) {' % (indent))
indent += ' '
elif (stp_list[index]['name'] == 'pTexelBufferView'):
sh_funcs.append('%sif ((pStruct->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER) ||' % (indent))
sh_funcs.append('%s (pStruct->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER)) {' % (indent))
indent += ' '
if stp_list[index]['dyn_array']:
sh_funcs.append('%sif (pStruct->%s) {' % (indent, stp_list[index]['name']))
indent += ' '
sh_funcs.append('%sfor (uint32_t i = 0; i < %s; i++) {' % (indent, array_count))
indent += ' '
sh_funcs.append('%sindex_ss.str("");' % (indent))
sh_funcs.append('%sindex_ss << i;' % (indent))
if is_type(stp_list[index]['type'], 'enum'):
sh_funcs.append('%s' % lineinfo.get())
addr_char = ''
#value_print = 'string_%s(%spStruct->%s)' % (self.struct_dict[s][m]['type'], deref, self.struct_dict[s][m]['name'])
sh_funcs.append('%sss[%u] << string_%s(pStruct->%s[i]);' % (indent, index, stp_list[index]['type'], stp_list[index]['name']))
sh_funcs.append('%sstp_strs[%u] += " " + prefix + "%s[" + index_ss.str() + "] = " + ss[%u].str() + "\\n";' % (indent, index, stp_list[index]['name'], index))
elif is_type(stp_list[index]['type'], 'struct'):
sh_funcs.append('%s' % lineinfo.get())
sh_funcs.append('%sss[%u] << %spStruct->%s[i];' % (indent, index, addr_char, stp_list[index]['name']))
sh_funcs.append('%stmp_str = %s(%spStruct->%s[i], extra_indent);' % (indent, self._get_sh_func_name(stp_list[index]['type']), addr_char, stp_list[index]['name']))
if self.no_addr:
sh_funcs.append('%s' % lineinfo.get())
sh_funcs.append('%sstp_strs[%u] += " " + prefix + "%s[" + index_ss.str() + "] (addr)\\n" + tmp_str;' % (indent, index, stp_list[index]['name']))
else:
sh_funcs.append('%s' % lineinfo.get())
sh_funcs.append('%sstp_strs[%u] += " " + prefix + "%s[" + index_ss.str() + "] (" + ss[%u].str() + ")\\n" + tmp_str;' % (indent, index, stp_list[index]['name'], index))
else:
sh_funcs.append('%s' % lineinfo.get())
addr_char = ''
sh_funcs.append('%sss[%u] << %spStruct->%s[i];' % (indent, index, addr_char, stp_list[index]['name']))
if stp_list[index]['type'] in vulkan.core.objects:
sh_funcs.append('%sstp_strs[%u] += " " + prefix + "%s[" + index_ss.str() + "].handle = " + ss[%u].str() + "\\n";' % (indent, index, stp_list[index]['name'], index))
else:
sh_funcs.append('%sstp_strs[%u] += " " + prefix + "%s[" + index_ss.str() + "] = " + ss[%u].str() + "\\n";' % (indent, index, stp_list[index]['name'], index))
sh_funcs.append('%s' % lineinfo.get())
sh_funcs.append('%sss[%u].str("");' % (indent, index))
indent = indent[4:]
sh_funcs.append('%s}' % (indent))
if stp_list[index]['dyn_array']:
indent = indent[4:]
sh_funcs.append('%s}' % (indent))
#endif
if (stp_list[index]['name'] == 'pQueueFamilyIndices') or (stp_list[index]['name'] == 'pImageInfo') or (stp_list[index]['name'] == 'pBufferInfo') or (stp_list[index]['name'] == 'pTexelBufferView'):
indent = indent[4:]
sh_funcs.append('%s}' % (indent))
elif (stp_list[index]['ptr']):