-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1583 lines (1336 loc) · 59.8 KB
/
main.py
File metadata and controls
1583 lines (1336 loc) · 59.8 KB
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
from re import sub
from cpp_utils.main import *
from fs_utils.main import *
from enum import Enum, auto
from dataclasses import dataclass
from typing import List, Dict
from shader_summary import *
import argparse
import sys
# NOTE: this entire thing should be entirely be done in cpp one day, a long time away
constructor_body_template = """
glGenVertexArrays(1, &vertex_attribute_object);
glBindVertexArray(vertex_attribute_object);
REPLACE_ME
glBindVertexArray(0);
"""
destructor_body_template = """
glGenVertexArrays(1, &vertex_attribute_object);
glBindVertexArray(vertex_attribute_object);
REPLACE_ME
glBindVertexArray(0);
"""
TAB = " "
# TODO: use the ones from text utils in the future.
def snake_to_abbr(snake_str: str) -> str:
"""
Converts a snake_case string to its abbreviation.
Example: "convert_to_abbreviation" -> "cta"
"""
return "".join(word[0] for word in snake_str.split("_") if word).lower()
def snake_to_camel_case(snake_str):
components = snake_str.lower().split("_")
return "".join(x.title() for x in components)
def get_draw_data_struct_name(shader_type: ShaderType):
return snake_to_camel_case(shader_type.name) + "DrawData"
class DrawInfo(Enum):
INDEXED_VERTEX_POSITIONS = "draw_info::IndexedVertexPositions"
IVPTEXTURED = "draw_info::IVPTextured"
IVPCOLOR = "draw_info::IVPColor"
IVPNORMALS = "draw_info::IVPNormals"
IVPNCOLOR = "draw_info::IVPNColor"
IVPNTEXTURED = "draw_info::IVPNTextured"
# NOTE not all of them are here
draw_info_struct_hierarchy = {
DrawInfo.INDEXED_VERTEX_POSITIONS: {
DrawInfo.IVPNORMALS: {DrawInfo.IVPNCOLOR: {}, DrawInfo.IVPNTEXTURED: {}},
DrawInfo.IVPTEXTURED: {},
DrawInfo.IVPCOLOR: {},
}
}
shader_vertex_attribute_variables_to_valid_draw_info_structs: Dict[
"frozenset[ShaderVertexAttributeVariable]", DrawInfo
] = {
frozenset(
{ShaderVertexAttributeVariable.XYZ_POSITION}
): DrawInfo.INDEXED_VERTEX_POSITIONS,
frozenset(
{
ShaderVertexAttributeVariable.XYZ_POSITION,
ShaderVertexAttributeVariable.PASSTHROUGH_NORMAL,
}
): DrawInfo.IVPNORMALS,
frozenset(
{
ShaderVertexAttributeVariable.XYZ_POSITION,
ShaderVertexAttributeVariable.PASSTHROUGH_RGB_COLOR,
}
): DrawInfo.IVPCOLOR,
frozenset(
{
ShaderVertexAttributeVariable.XYZ_POSITION,
ShaderVertexAttributeVariable.PASSTHROUGH_RGB_COLOR,
ShaderVertexAttributeVariable.PASSTHROUGH_NORMAL,
}
): DrawInfo.IVPNCOLOR,
}
ivp_param: CppParameter = CppParameter(
"ivp",
DrawInfo.INDEXED_VERTEX_POSITIONS.value,
"",
)
ivp_param_ref: CppParameter = CppParameter(
"ivp", DrawInfo.INDEXED_VERTEX_POSITIONS.value, "", True
)
ivpn_param: CppParameter = CppParameter(
"ivpn",
DrawInfo.IVPNORMALS.value,
"",
)
ivpn_param_ref: CppParameter = CppParameter("ivpn", DrawInfo.IVPNORMALS.value, "", True)
ivpc_param: CppParameter = CppParameter(
"ivpc",
DrawInfo.IVPCOLOR.value,
"",
)
ivpc_param_ref: CppParameter = CppParameter("ivpc", DrawInfo.IVPCOLOR.value, "", True)
ivpnc_param: CppParameter = CppParameter(
"ivpnc",
DrawInfo.IVPNCOLOR.value,
"",
)
ivpnc_param_ref: CppParameter = CppParameter(
"ivpnc", DrawInfo.IVPNCOLOR.value, "", True
)
ivpX_struct_to_param_ref: Dict[DrawInfo, CppParameter] = {
DrawInfo.INDEXED_VERTEX_POSITIONS: ivp_param_ref,
DrawInfo.IVPNORMALS: ivpn_param_ref,
DrawInfo.IVPCOLOR: ivpc_param_ref,
DrawInfo.IVPNCOLOR: ivpnc_param_ref,
}
# NOTE: in the future these should not exist, there should be a generic hierarchy and then a way to produce a parameter of that type easily.
ivpX_param_to_superclass_params: Dict[CppParameter, List[CppParameter]] = {
ivp_param: [ivp_param, ivpn_param, ivpc_param, ivpnc_param],
ivpn_param: [ivpn_param, ivpnc_param],
ivpc_param: [ivpc_param, ivpnc_param],
ivpnc_param: [ivpnc_param],
}
ivpX_param_ref_to_superclass_param_refs: Dict[CppParameter, List[CppParameter]] = {
ivp_param_ref: [ivp_param_ref, ivpn_param_ref, ivpc_param_ref, ivpnc_param_ref],
ivpn_param_ref: [ivpn_param_ref, ivpnc_param_ref],
ivpc_param_ref: [ivpc_param_ref, ivpnc_param_ref],
ivpnc_param_ref: [ivpnc_param_ref],
}
class ShaderBatcherCppStruct:
def __init__(
self,
shader_type: ShaderType,
vertex_attributes: List[ShaderVertexAttributeVariable],
):
self.shader_type = shader_type
self.vertex_attributes = vertex_attributes
def generate_cpp_struct(self) -> CppStruct:
struct_name = get_draw_data_struct_name(self.shader_type)
cpp_struct = CppStruct(struct_name)
cpp_struct.add_member(CppMember("indices", "std::vector<unsigned int>"))
equals_body_comparisons = ["indices == other.indices"]
for vertex_attribute in self.vertex_attributes:
va_data = shader_vertex_attribute_to_data[vertex_attribute]
cpp_struct.add_member(
CppMember(
f"{va_data.plural_name}", f"std::vector<{va_data.attrib_type}>"
)
)
equals_body_comparisons.append(
f"{va_data.plural_name} == other.{va_data.plural_name}"
)
equals_body = "return " + " && ".join(equals_body_comparisons) + ";"
cpp_struct.add_method(
CppMethod(
"operator==",
"bool",
[CppParameter("other", struct_name, "const", True)],
equals_body,
define_in_header=True,
qualifiers=["const"],
)
)
return cpp_struct
class ShaderBatcherCppClass:
is_ubo_shader: bool
num_elements_in_buffer: int
def __init__(
self,
shader_type: ShaderType,
num_elements_in_buffer: int,
vertex_attributes: List[ShaderVertexAttributeVariable],
):
self.shader_type: ShaderType = shader_type
self.vertex_attributes: List[ShaderVertexAttributeVariable] = vertex_attributes
self.is_ubo_shader = (
ShaderVertexAttributeVariable.LOCAL_TO_WORLD_INDEX in self.vertex_attributes
)
self.num_elements_in_buffer = num_elements_in_buffer
def get_class_name(self) -> str:
return f"{snake_to_camel_case(self.shader_type.name)}ShaderBatcher"
def get_associated_draw_info_struct(self) -> Optional[DrawInfo]:
all_shader_vertex_attributes: frozenset[ShaderVertexAttributeVariable] = (
frozenset(
[
va
for va in self.vertex_attributes
if va != ShaderVertexAttributeVariable.LOCAL_TO_WORLD_INDEX
]
)
)
if (
all_shader_vertex_attributes
in shader_vertex_attribute_variables_to_valid_draw_info_structs
):
associated_draw_info_struct: DrawInfo = (
shader_vertex_attribute_variables_to_valid_draw_info_structs[
all_shader_vertex_attributes
]
)
return associated_draw_info_struct
else:
return None
def generate_queue_draw_parameter_list(self) -> List[CppParameter]:
# parameter_list = "const unsigned int object_id, const std::vector<unsigned int> &indices, "
parameter_list = [
CppParameter("object_id", "unsigned int", "const"),
CppParameter("indices", "std::vector<unsigned int>", "const", True),
]
for vertex_attribute in self.vertex_attributes:
data = shader_vertex_attribute_to_data[vertex_attribute]
parameter_list.append(
CppParameter(
data.plural_name, f"std::vector<{data.attrib_type}>", "const", True
)
)
# parameter_list += f"const std::vector<{data.attrib_type}> &{data.plural_name}, "
parameter_list.append(CppParameter("replace", "bool", "", False, "false"))
return parameter_list
def generate_cache_parameter_list(self) -> List[CppParameter]:
# parameter_list = "const unsigned int object_id, const std::vector<unsigned int> &indices, "
parameter_list = [
CppParameter("object_id", "unsigned int", "const"),
CppParameter("indices", "std::vector<unsigned int>", "const", True),
]
for vertex_attribute in self.vertex_attributes:
data = shader_vertex_attribute_to_data[vertex_attribute]
parameter_list.append(
CppParameter(
data.plural_name, f"std::vector<{data.attrib_type}>", "const", True
)
)
# parameter_list += f"const std::vector<{data.attrib_type}> &{data.plural_name}, "
parameter_list.append(CppParameter("replace", "bool", "", False, "false"))
return parameter_list
def generate_constructor_body(self) -> str:
body = ""
for vertex_attribute in self.vertex_attributes:
data = shader_vertex_attribute_to_data[vertex_attribute]
buffer_object_var_name = f"{data.plural_name}_buffer_object"
body += f"""
glGenBuffers(1, &{buffer_object_var_name});
// allocate space but don't actually buffer any data (nullptr) note that size is measured in bytes
glBindBuffer(GL_ARRAY_BUFFER, {buffer_object_var_name});
glBufferData(GL_ARRAY_BUFFER, initial_buffer_size * sizeof({data.attrib_type}), nullptr, GL_DYNAMIC_DRAW);
shader_cache.configure_vertex_attributes_for_drawables_vao(vertex_attribute_object, {buffer_object_var_name}, ShaderType::{self.shader_type.name}, ShaderVertexAttributeVariable::{vertex_attribute.name});
"""
body += f"""
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_buffer_object);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, initial_buffer_size * sizeof(unsigned int), nullptr, GL_DYNAMIC_DRAW);
"""
return body
def generate_deconstructor(self) -> str:
body = f"""
glDeleteVertexArrays(1, &vertex_attribute_object);
glDeleteBuffers(1, &indices_buffer_object);
"""
for vertex_attribute in self.vertex_attributes:
data = shader_vertex_attribute_to_data[vertex_attribute]
buffer_object_var_name = f"{data.plural_name}_buffer_object"
body += f"""
glDeleteBuffers(1, &{buffer_object_var_name});"""
return body
def get_delete_object_methods_for_draw_info_struct(self) -> List[CppMethod]:
associated_draw_info_struct: Optional[DrawInfo] = (
self.get_associated_draw_info_struct()
)
delete_object_methods = []
if associated_draw_info_struct:
associated_ivpX_param_ref = ivpX_struct_to_param_ref[
associated_draw_info_struct
]
ivpX_superclass_param_refs: List[CppParameter] = (
ivpX_param_ref_to_superclass_param_refs[associated_ivpX_param_ref]
)
for ivpX_param_ref in ivpX_superclass_param_refs:
delete_object_body = f"""
if ({ivpX_param_ref.name}.buffer_modification_tracker.has_data_in_buffer()) {{
delete_object({ivpX_param_ref.name}.id);
{ivpX_param_ref.name}.id = -1;
{ivpX_param_ref.name}.buffer_modification_tracker.free_buffered_data();
}}
"""
delete_object_methods.append(
CppMethod(
"delete_object",
"void",
[ivpX_param_ref],
delete_object_body,
"public",
initializer_list="",
define_in_header=False,
qualifiers=[],
docstring_comment="""
/**
* @brief Deletes an object from this shader batcher
*
* This frees up all resources for the given object id, and allows that id to be used again.
*/
""",
)
)
else:
print("there was no associated draw info struct")
return delete_object_methods
def generate_ivpX_tag_id_body(self, struct_var_name: str) -> str:
if self.is_ubo_shader:
return f"""
// NOTE: THIS IS WRONG when we use a tig the id's are not in sync, thus we need a separate id for both, fix later
{struct_var_name}.id = ltw_object_id_generator.get_id();"""
else:
return f"""
{struct_var_name}.id = object_id_generator.get_id();"""
def generate_ivpX_queue_draw_body(
self, ivpX_struct_parameter_name: str, attributes: List[str]
) -> str:
arg_list: str = ", ".join(
[ivpX_struct_parameter_name + "." + attr for attr in attributes]
)
optional_ubo_matrix_uploading_logic: str = f"""
// NOTE: for singular draw objects their ID represent their ltw matrix index
// but when working with tigs they don't (collection of draw_info structs all with same ltw idx)
ltw_matrices[{ivpX_struct_parameter_name}.id] = {ivpX_struct_parameter_name}.transform.get_full_transform_matrix();
"""
return f"""
// NOTE: if you try and queue something for drawing that isn't registered in the system we'll do that now
bool ivp_is_not_yet_registered = {ivpX_struct_parameter_name}.id == -1;
if (ivp_is_not_yet_registered) {{
tag_id({ivpX_struct_parameter_name});
}}
{optional_ubo_matrix_uploading_logic if self.is_ubo_shader else ""}
{f'std::vector<unsigned int> ltw_indices({ivpX_struct_parameter_name}.xyz_positions.size(), {ivpX_struct_parameter_name}.id);' if self.is_ubo_shader else ''}
bool replace = {ivpX_struct_parameter_name}.buffer_modification_tracker.has_been_modified_since_last_buffering();
queue_draw({ivpX_struct_parameter_name}.id, {ivpX_struct_parameter_name}.indices, {arg_list}{', ltw_indices' if self.is_ubo_shader else ''}, replace);
// NOTE: sometimes the queue draw doesn't buffer any data, so this method name might be bad, the inner logic makes sense though.
{ivpX_struct_parameter_name}.buffer_modification_tracker.just_buffered_data();
"""
def generate_ivpX_cache_body(
self, ivpX_struct_parameter_name: str, attributes: List[str]
) -> str:
arg_list: str = ", ".join(
[ivpX_struct_parameter_name + "." + attr for attr in attributes]
)
optional_ubo_matrix_uploading_logic: str = f"""
// NOTE: for singular draw objects their ID represent their ltw matrix index
// but when working with tigs they don't (collection of draw_info structs all with same ltw idx)
ltw_matrices[{ivpX_struct_parameter_name}.id] = {ivpX_struct_parameter_name}.transform.get_full_transform_matrix();
"""
return f"""
// NOTE: if you try and cache something for drawing that isn't registered in the system we'll do that now
bool ivp_is_not_yet_registered = {ivpX_struct_parameter_name}.id == -1;
if (ivp_is_not_yet_registered) {{
tag_id({ivpX_struct_parameter_name});
}}
{optional_ubo_matrix_uploading_logic if self.is_ubo_shader else ""}
{f'std::vector<unsigned int> ltw_indices({ivpX_struct_parameter_name}.xyz_positions.size(), {ivpX_struct_parameter_name}.id);' if self.is_ubo_shader else ''}
bool replace = {ivpX_struct_parameter_name}.buffer_modification_tracker.has_been_modified_since_last_buffering();
cache({ivpX_struct_parameter_name}.id, {ivpX_struct_parameter_name}.indices, {arg_list}{', ltw_indices' if self.is_ubo_shader else ''}, replace);
// NOTE: sometimes the queue draw doesn't buffer any data, so this method name might be bad, the inner logic makes sense though.
{ivpX_struct_parameter_name}.buffer_modification_tracker.just_buffered_data();
"""
def get_queue_draw_methods_for_draw_info_structs(self) -> List[CppMethod]:
# NOTE: we are generating a bunch of versions of the same function by allowing classes with at least the same attributes as the
# base param class to be passed in saving us time in the cpp code, guess eventually this could be templatized right? that would be we're generating templatized code which is pretty confusing... avoiding that for now.
def generate_ivpX_queue_draw_hierarchy_methods(
base_param: CppParameter, draw_info_attribute_names: List[str]
) -> List[CppMethod]:
return [
CppMethod(
"queue_draw",
"void",
[super_class_param],
self.generate_ivpX_queue_draw_body(
super_class_param.name, draw_info_attribute_names
),
"public",
)
for super_class_param in ivpX_param_ref_to_superclass_param_refs[
base_param
]
]
def generate_ivpX_cache_hierarchy_methods(
base_param: CppParameter, draw_info_attribute_names: List[str]
) -> List[CppMethod]:
return [
CppMethod(
"cache",
"void",
[super_class_param],
self.generate_ivpX_cache_body(
super_class_param.name, draw_info_attribute_names
),
"public",
)
for super_class_param in ivpX_param_ref_to_superclass_param_refs[
base_param
]
]
def generate_ivpX_tag_id_hierarchy_methods(
base_param_ref: CppParameter,
) -> List[CppMethod]:
return [
CppMethod(
"tag_id",
"void",
[super_class_param_ref],
self.generate_ivpX_tag_id_body(super_class_param_ref.name),
"public",
)
for super_class_param_ref in ivpX_param_ref_to_superclass_param_refs[
base_param_ref
]
]
# NOTE: doing this in a stupid way, building a bunch of data and then later on only selecting the stuff we need rather than just
# only generating the stuff we need in the first place
ivp_queue_draw_hierarchy_methods = generate_ivpX_queue_draw_hierarchy_methods(
ivp_param_ref, ["xyz_positions"]
)
ivpn_queue_draw_hierarchy_methods = generate_ivpX_queue_draw_hierarchy_methods(
ivpn_param_ref, ["xyz_positions", "normals"]
)
ivpc_queue_draw_hierarchy_methods = generate_ivpX_queue_draw_hierarchy_methods(
ivpc_param_ref, ["xyz_positions", "rgb_colors"]
)
ivpnc_queue_draw_hierarchy_methods = generate_ivpX_queue_draw_hierarchy_methods(
ivpnc_param_ref, ["xyz_positions", "normals", "rgb_colors"]
)
ivp_cache_hierarchy_methods = generate_ivpX_cache_hierarchy_methods(
ivp_param_ref, ["xyz_positions"]
)
ivpn_cache_hierarchy_methods = generate_ivpX_cache_hierarchy_methods(
ivpn_param_ref, ["xyz_positions", "normals"]
)
ivpc_cache_hierarchy_methods = generate_ivpX_cache_hierarchy_methods(
ivpc_param_ref, ["xyz_positions", "rgb_colors"]
)
ivpnc_cache_hierarchy_methods = generate_ivpX_cache_hierarchy_methods(
ivpnc_param_ref, ["xyz_positions", "normals", "rgb_colors"]
)
ivp_tag_id_hierarchy_methods = generate_ivpX_tag_id_hierarchy_methods(
ivp_param_ref
)
ivpn_tag_id_hierarchy_methods = generate_ivpX_tag_id_hierarchy_methods(
ivpn_param_ref
)
ivpc_tag_id_hierarchy_methods = generate_ivpX_tag_id_hierarchy_methods(
ivpc_param_ref
)
ivpnc_tag_id_hierarchy_methods = generate_ivpX_tag_id_hierarchy_methods(
ivpc_param_ref
)
draw_info_struct_to_queue_draw_cpp_methods: Dict[DrawInfo, List[CppMethod]] = {
DrawInfo.INDEXED_VERTEX_POSITIONS: ivp_queue_draw_hierarchy_methods,
DrawInfo.IVPNORMALS: ivpn_queue_draw_hierarchy_methods,
DrawInfo.IVPCOLOR: ivpc_queue_draw_hierarchy_methods,
DrawInfo.IVPNCOLOR: ivpnc_queue_draw_hierarchy_methods,
}
draw_info_struct_to_cache_cpp_methods: Dict[DrawInfo, List[CppMethod]] = {
DrawInfo.INDEXED_VERTEX_POSITIONS: ivp_cache_hierarchy_methods,
DrawInfo.IVPNORMALS: ivpn_cache_hierarchy_methods,
DrawInfo.IVPCOLOR: ivpc_cache_hierarchy_methods,
DrawInfo.IVPNCOLOR: ivpnc_cache_hierarchy_methods,
}
draw_info_struct_to_tag_id_cpp_method: Dict[DrawInfo, List[CppMethod]] = {
DrawInfo.INDEXED_VERTEX_POSITIONS: ivp_tag_id_hierarchy_methods,
DrawInfo.IVPNORMALS: ivpn_tag_id_hierarchy_methods,
DrawInfo.IVPCOLOR: ivpc_tag_id_hierarchy_methods,
DrawInfo.IVPNCOLOR: ivpnc_tag_id_hierarchy_methods,
}
# NOTE: we're using this for all of them, bad.
queue_draw_methods: List[CppMethod] = []
associated_draw_info_struct: Optional[DrawInfo] = (
self.get_associated_draw_info_struct()
)
if associated_draw_info_struct:
associated_queue_draw_methods: List[CppMethod] = (
draw_info_struct_to_queue_draw_cpp_methods[associated_draw_info_struct]
)
queue_draw_methods.extend(associated_queue_draw_methods)
associated_cache_methods: List[CppMethod] = (
draw_info_struct_to_cache_cpp_methods[associated_draw_info_struct]
)
queue_draw_methods.extend(associated_cache_methods)
associated_tag_id_methods: List[CppMethod] = (
draw_info_struct_to_tag_id_cpp_method[associated_draw_info_struct]
)
queue_draw_methods.extend(associated_tag_id_methods)
else:
print("cannot find an associated queue draw call")
return queue_draw_methods
def generate_queue_draw_body(self) -> str:
parameters_to_cache: List[str] = []
for vertex_attribute in self.vertex_attributes:
data = shader_vertex_attribute_to_data[vertex_attribute]
parameters_to_cache.append(data.plural_name)
unique_cache_params = ", ".join(parameters_to_cache)
body = f"""
object_ids_this_tick.push_back(object_id);
cache(object_id, indices, {unique_cache_params}, replace);
"""
return body
def generate_cache_body(self) -> str:
def generate_sub_buffering_calls() -> str:
lines = []
for v in self.vertex_attributes:
sva_data = shader_vertex_attribute_to_data[v]
lines.append(
f"glBindBuffer(GL_ARRAY_BUFFER, {sva_data.plural_name}_buffer_object);"
)
lines.append(
f"glBufferSubData(GL_ARRAY_BUFFER, *start_index * sizeof({sva_data.attrib_type}), {sva_data.plural_name}.size() * sizeof({sva_data.attrib_type}), {sva_data.plural_name}.data());"
)
lines.append("\n")
indentation = TAB
for i in range(len(lines)):
lines[i] = indentation + lines[i]
return "\n".join(lines)
body = f"""
bool logging = false;
bool incoming_data_is_already_cached =
cached_object_ids_to_indices.find(object_id) != cached_object_ids_to_indices.end();
if (incoming_data_is_already_cached and not replace) {{
return;
}}
// therefore the data is either not cached, or it needs to be replaced
// in both of those cases the data needs to be stored, so moving on:
// if the data already exists then we need to replace
auto metadata = fsat.get_metadata(object_id);
if (metadata) {{
// so mark that space as free, and it only needs to occur in the realm of metadata
// later on we'll just clobber the real contents of the VBO which is not a problem
fsat.remove_metadata(object_id);
}}
// note we use positions because that information is what gets stored into the vertex buffer objects
// note that any other vertex data could be used as they must all have the same size
size_t length = positions.size();
auto start_index = fsat.find_contiguous_space(length);
// if there's no space left we will compactify things, and try again.
if (!start_index) {{
fsat.compact();
// TODO implement later when running out of space is a real issue.
// storage.compact(tracker.get_all_metadata());
start_index = fsat.find_contiguous_space(length);
if (!start_index) {{
throw std::runtime_error("not enough space even after compacting.");
}}
}}
// at this point it's guarenteed that there is space for the object.
// therefore *start_index is competely valid from now on
std::vector<unsigned int> cached_indices_for_data;
for (unsigned int index : indices) {{
// note that it's guarenteed that cached_index is going to reside completely
// within the allocated space this is because if the size of the positions vector
// is given by N, then the indices are only allowed to be values of 0, ..., N - 1
// then we move it up by start_index, and thus we're always within start_index + N - 1
// which it the amount of space we found during our find_contiguous space call
unsigned int cached_index = index + *start_index;
cached_indices_for_data.push_back(cached_index);
}}
// using this one as it will replace the existing data, thus works for replacement or first time insertion.
cached_object_ids_to_indices.insert_or_assign(object_id, cached_indices_for_data);
// now we put that data into the graphics card
glBindVertexArray(vertex_attribute_object);
{generate_sub_buffering_calls()}
glBindVertexArray(0);
// ok now we're done, update the metadata so that we know this space is used up
fsat.add_metadata(object_id, *start_index, length);
replaced_data_for_an_object_this_tick = true;
if (logging) {{
std::cout << "^^^ QUEUE_DRAW ^^^" << std::endl;
}}
"""
return body
def generate_draw_everything_body(self) -> str:
body = f"""
bool logging = false;
if (logging) {{
std::cout << "VVV DRAW_EVERYTHING VVV" << std::endl;
}}
shader_cache.use_shader_program(ShaderType::{self.shader_type.name});
glBindVertexArray(vertex_attribute_object);
if (replaced_data_for_an_object_this_tick or object_ids_this_tick != object_ids_last_tick) {{
std::vector<unsigned int> all_indices;
for (const auto &draw_data : object_ids_this_tick) {{
auto it = cached_object_ids_to_indices.find(draw_data);
if (it != cached_object_ids_to_indices.end()) {{
const std::vector<unsigned int> &cached_indices = it->second;
all_indices.insert(all_indices.end(), cached_indices.begin(), cached_indices.end());
}} else {{
if (logging) {{
std::cerr << "draw data tried to be drawn but was not cached, look into this as it should not occur"
<< std::endl;
}}
}}
}}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_buffer_object);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, all_indices.size() * sizeof(unsigned int), all_indices.data());
glDrawElements(GL_TRIANGLES, all_indices.size(), GL_UNSIGNED_INT, 0);
object_ids_last_tick = object_ids_this_tick;
drawn_indices_last_tick = all_indices;
}} else {{
glDrawElements(GL_TRIANGLES, drawn_indices_last_tick.size(), GL_UNSIGNED_INT, 0);
}}
glBindVertexArray(0);
shader_cache.stop_using_shader_program();
object_ids_this_tick.clear();
replaced_data_for_an_object_this_tick = false;
if (logging) {{
std::cout << "^^^ DRAW_EVERYTHING ^^^" << std::endl;
}}
"""
return body
# TODO: in the future there will be a bass queue draw call and then the extension classes
# will extend the body of the function filling in empty data (eg bone transforms or something)
def generate_CWL_V_TRANSFORMATION_UBOS_1024_WITH_SOLID_COLOR_specific_class_data(
self, batcher_class: CppClass
):
tig = CppParameter("tig", "draw_info::TransformedIVPGroup", "", True)
replace = CppParameter("replace", "bool", "", False, "false")
transform_matrix_override = CppParameter(
"transform_matrix_override", "glm::mat4", "", False, "glm::mat4(0)"
)
body = """
GlobalLogSection("queue_draw(tig)", log_mode);
int ltw_object_id = tig.id;
// TODO: there will be a bug here if you try to override with the zero matrix, but you will probably never do that
bool requested_override = transform_matrix_override != glm::mat4(0);
if (requested_override) {
global_logger->info("setting matrix override");
ltw_matrices[ltw_object_id] = transform_matrix_override;
} else {
ltw_matrices[ltw_object_id] = tig.transform.get_full_transform_matrix();
}
for (auto &ivp : tig.ivps) {
std::vector<unsigned int> ltw_indices(ivp.xyz_positions.size(), ltw_object_id);
queue_draw(ivp.id, ivp.indices, ivp.xyz_positions, ltw_indices, replace);
}
"""
batcher_class.add_method(
CppMethod(
"queue_draw",
"void",
[tig, replace, transform_matrix_override],
body,
"public",
initializer_list="",
define_in_header=False,
qualifiers=[],
docstring_comment="""
/**
* @brief Deletes an object from this shader batcher
*
* This frees up all resources for the given object id, and allows that id to be used again.
*/
""",
)
)
def generate_TEXTURE_PACKER_CWL_V_TRANSFORMATION_UBOS_1024_specfic_class_data(
self, batcher_class: CppClass
):
indices = CppParameter("indices", "std::vector<unsigned int>")
xyz_positions = CppParameter("xyz_positions", "std::vector<glm::vec3>")
ivptps = CppParameter("ivptps", "std::vector<draw_info::IVPTexturePacked>")
# TODO: generic enough to be in any ltw batcher class
tig = CppParameter(
"tig_to_update", "draw_info::TransformedIVPTPGroup", "", True
)
body = """
GlobalLogSection("update_tig_ids", log_mode);
tig_to_update.id = ltw_object_id_generator.get_id();
for (auto &ivptp : tig_to_update.ivptps) {
// NOTE: note that we must regenerate the internal ivptp ids because we do not use instancing here and for each
// object we store its ltw matrices so we can't re-use the same geometry
ivptp.id = object_id_generator.get_id();
global_logger->info("set id to: {}", ivptp.id);
}
"""
batcher_class.add_method(
CppMethod(
"update_tig_ids",
"void",
[tig],
body,
"public",
initializer_list="",
define_in_header=False,
qualifiers=[],
docstring_comment="""
/**
* @brief Regenerates all associated ids for a tig
*
* The point of this function I believe is when you copy an object and then you want to regenerate all its ids
*/
""",
)
)
const_tig = CppParameter(
"tig", "draw_info::TransformedIVPTPGroup", "const", True
)
body = """
GlobalLogSection("delete_tig", log_mode);
for (const auto &ivptp : tig.ivptps) {
delete_object(ivptp.id);
}
ltw_object_id_generator.reclaim_id(tig.id);
"""
batcher_class.add_method(
CppMethod(
"delete_tig",
"void",
[const_tig],
body,
"public",
initializer_list="",
define_in_header=False,
qualifiers=[],
docstring_comment="""
/**
* @brief Deletes an object from this shader batcher
*
* This frees up all resources for the given object id, and allows that id to be used again.
*/
""",
)
)
tig = CppParameter("tig", "draw_info::TransformedIVPTPGroup")
replace = CppParameter("replace", "bool", "", False, "false")
transform_matrix_override = CppParameter(
"transform_matrix_override", "glm::mat4", "", False, "glm::mat4(0)"
)
body = """
GlobalLogSection("queue_draw(tig.ivptps)", log_mode);
int ltw_object_id = tig.id;
// TODO: there will be a bug here if you try to override with the zero matrix, but you will probably never do that
bool requested_override = transform_matrix_override != glm::mat4(0);
if (requested_override) {
ltw_matrices[ltw_object_id] = transform_matrix_override;
} else {
ltw_matrices[ltw_object_id] = tig.transform.get_full_transform_matrix();
}
for (const auto &ivptp : tig.ivptps) {
std::vector<unsigned int> ltw_indices(ivptp.xyz_positions.size(), ltw_object_id);
std::vector<int> ptis(ivptp.xyz_positions.size(), ivptp.packed_texture_index);
std::vector<int> ptbbi(ivptp.xyz_positions.size(), ivptp.packed_texture_bounding_box_index);
queue_draw(ivptp.id, ivptp.indices, ltw_indices, ptis, ivptp.packed_texture_coordinates, ptbbi,
ivptp.xyz_positions, replace);
}
"""
batcher_class.add_method(
CppMethod(
"queue_draw",
"void",
[tig, replace, transform_matrix_override],
body,
"public",
initializer_list="",
define_in_header=False,
qualifiers=[],
docstring_comment="""
/**
* @brief Queues up a tig to be drawn when draw_everything is called
*/
""",
)
)
def generate_TEXTURE_PACKER_RIGGED_AND_ANIMATED_CWL_V_TRANSFORMATION_UBOS_1024_WITH_TEXTURES_specfic_class_data(
self, batcher_class: CppClass
):
tig = CppParameter("tig", "draw_info::TransformedIVPNTPRGroup", "", True)
replace = CppParameter("replace", "bool", "", False, "false")
transform_matrix_override = CppParameter(
"transform_matrix_override", "glm::mat4", "", False, "glm::mat4(0)"
)
body = """
GlobalLogSection("queue_draw(tig.ivpntprs)", log_mode);
int ltw_object_id = tig.id;
// TODO: there will be a bug here if you try to override with the zero matrix, but you will probably never do that
bool requested_override = transform_matrix_override != glm::mat4(0);
if (requested_override) {
ltw_matrices[ltw_object_id] = transform_matrix_override;
} else {
ltw_matrices[ltw_object_id] = tig.transform.get_full_transform_matrix();
}
for (auto &ivpntpr : tig.ivpntprs) {
// Populate bone_indices and bone_weights
std::vector<glm::ivec4> bone_indices;
std::vector<glm::vec4> bone_weights;
for (const auto &vertex_bone_data : ivpntpr.bone_data) {
glm::ivec4 indices(static_cast<int>(vertex_bone_data.indices_of_bones_that_affect_this_vertex[0]),
static_cast<int>(vertex_bone_data.indices_of_bones_that_affect_this_vertex[1]),
static_cast<int>(vertex_bone_data.indices_of_bones_that_affect_this_vertex[2]),
static_cast<int>(vertex_bone_data.indices_of_bones_that_affect_this_vertex[3]));
glm::vec4 weights(vertex_bone_data.weight_value_of_this_vertex_wrt_bone[0],
vertex_bone_data.weight_value_of_this_vertex_wrt_bone[1],
vertex_bone_data.weight_value_of_this_vertex_wrt_bone[2],
vertex_bone_data.weight_value_of_this_vertex_wrt_bone[3]);
bone_indices.push_back(indices);
bone_weights.push_back(weights);
}
std::vector<int> packed_texture_indices(ivpntpr.xyz_positions.size(), ivpntpr.packed_texture_index);
std::vector<int> packed_texture_bounding_box_indices(ivpntpr.xyz_positions.size(), ivpntpr.packed_texture_bounding_box_index);
std::vector<unsigned int> ltw_indices(ivpntpr.xyz_positions.size(), tig.id);
queue_draw(ivpntpr.id, ivpntpr.indices, ltw_indices, bone_indices, bone_weights,
packed_texture_indices, ivpntpr.packed_texture_coordinates,
packed_texture_bounding_box_indices, ivpntpr.xyz_positions);
}
"""
batcher_class.add_method(
CppMethod(
"queue_draw",
"void",
[tig, replace, transform_matrix_override],
body,
"public",
initializer_list="",
define_in_header=False,
qualifiers=[],
docstring_comment="""
/**
* @brief Queues up a tig to be drawn when draw_everything is called
*/
""",
)
)
# NOTE: this is the main entry point to generating each batcher
# do a forward seach for add_method
def generate_cpp_class(self) -> CppClass:
batcher_class = CppClass(self.get_class_name())
is_ubo_1024_shader = (
ShaderVertexAttributeVariable.LOCAL_TO_WORLD_INDEX in self.vertex_attributes
)
# CLASS ATTRIBUTES START
if is_ubo_1024_shader:
batcher_class.add_member(
CppMember(
"ltw_object_id_generator",
"BoundedUniqueIDGenerator",
"BoundedUniqueIDGenerator(1024)",
)
)
batcher_class.add_member(CppMember("ltw_matrices_gl_name", "GLuint"))
batcher_class.add_member(CppMember("ltw_matrices[1024]", "glm::mat4"))
batcher_class.add_member(CppMember("object_id_generator", "UniqueIDGenerator"))
batcher_class.add_member(CppMember("shader_cache", "ShaderCache"))
batcher_class.add_member(CppMember("vertex_attribute_object", "GLuint"))
batcher_class.add_member(CppMember("indices_buffer_object", "GLuint"))
# add vector for each thing this shader type has
for vertex_attribute in self.vertex_attributes:
va_data = shader_vertex_attribute_to_data[vertex_attribute]
batcher_class.add_member(
CppMember(f"{va_data.plural_name}_buffer_object", "GLuint")
)
batcher_class.add_member(
CppMember("curr_index_buffer_offset", "unsigned int", "0")
)
batcher_class.add_member(