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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
|
/*!
Helpers for the hlsl backend
Important note about `Expression::ImageQuery`/`Expression::ArrayLength` and hlsl backend:
Due to implementation of `GetDimensions` function in hlsl (<https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions>)
backend can't work with it as an expression.
Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texture info and query function.
See `WrappedImageQuery` struct that represents a unique function and will be generated before writing all statements and expressions.
This allowed to works with `Expression::ImageQuery` as expression and write wrapped function.
For example:
```wgsl
let dim_1d = textureDimensions(image_1d);
```
```hlsl
int NagaDimensions1D(Texture1D<float4>)
{
uint4 ret;
image_1d.GetDimensions(ret.x);
return ret.x;
}
int dim_1d = NagaDimensions1D(image_1d);
```
*/
use super::{super::FunctionCtx, BackendResult};
use crate::{arena::Handle, proc::NameKey};
use std::fmt::Write;
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
pub(super) struct WrappedArrayLength {
pub(super) writable: bool,
}
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
pub(super) struct WrappedImageQuery {
pub(super) dim: crate::ImageDimension,
pub(super) arrayed: bool,
pub(super) class: crate::ImageClass,
pub(super) query: ImageQuery,
}
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
pub(super) struct WrappedConstructor {
pub(super) ty: Handle<crate::Type>,
}
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
pub(super) struct WrappedStructMatrixAccess {
pub(super) ty: Handle<crate::Type>,
pub(super) index: u32,
}
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
pub(super) struct WrappedMatCx2 {
pub(super) columns: crate::VectorSize,
}
/// HLSL backend requires its own `ImageQuery` enum.
///
/// It is used inside `WrappedImageQuery` and should be unique per ImageQuery function.
/// IR version can't be unique per function, because it's store mipmap level as an expression.
///
/// For example:
/// ```wgsl
/// let dim_cube_array_lod = textureDimensions(image_cube_array, 1);
/// let dim_cube_array_lod2 = textureDimensions(image_cube_array, 1);
/// ```
///
/// ```ir
/// ImageQuery {
/// image: [1],
/// query: Size {
/// level: Some(
/// [1],
/// ),
/// },
/// },
/// ImageQuery {
/// image: [1],
/// query: Size {
/// level: Some(
/// [2],
/// ),
/// },
/// },
/// ```
///
/// HLSL should generate only 1 function for this case.
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
pub(super) enum ImageQuery {
Size,
SizeLevel,
NumLevels,
NumLayers,
NumSamples,
}
impl From<crate::ImageQuery> for ImageQuery {
fn from(q: crate::ImageQuery) -> Self {
use crate::ImageQuery as Iq;
match q {
Iq::Size { level: Some(_) } => ImageQuery::SizeLevel,
Iq::Size { level: None } => ImageQuery::Size,
Iq::NumLevels => ImageQuery::NumLevels,
Iq::NumLayers => ImageQuery::NumLayers,
Iq::NumSamples => ImageQuery::NumSamples,
}
}
}
impl<'a, W: Write> super::Writer<'a, W> {
pub(super) fn write_image_type(
&mut self,
dim: crate::ImageDimension,
arrayed: bool,
class: crate::ImageClass,
) -> BackendResult {
let access_str = match class {
crate::ImageClass::Storage { .. } => "RW",
_ => "",
};
let dim_str = dim.to_hlsl_str();
let arrayed_str = if arrayed { "Array" } else { "" };
write!(self.out, "{}Texture{}{}", access_str, dim_str, arrayed_str)?;
match class {
crate::ImageClass::Depth { multi } => {
let multi_str = if multi { "MS" } else { "" };
write!(self.out, "{}<float>", multi_str)?
}
crate::ImageClass::Sampled { kind, multi } => {
let multi_str = if multi { "MS" } else { "" };
let scalar_kind_str = kind.to_hlsl_str(4)?;
write!(self.out, "{}<{}4>", multi_str, scalar_kind_str)?
}
crate::ImageClass::Storage { format, .. } => {
let storage_format_str = format.to_hlsl_str();
write!(self.out, "<{}>", storage_format_str)?
}
}
Ok(())
}
pub(super) fn write_wrapped_array_length_function_name(
&mut self,
query: WrappedArrayLength,
) -> BackendResult {
let access_str = if query.writable { "RW" } else { "" };
write!(self.out, "NagaBufferLength{}", access_str,)?;
Ok(())
}
/// Helper function that write wrapped function for `Expression::ArrayLength`
///
/// <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-rwbyteaddressbuffer-getdimensions>
pub(super) fn write_wrapped_array_length_function(
&mut self,
module: &crate::Module,
wal: WrappedArrayLength,
expr_handle: Handle<crate::Expression>,
func_ctx: &FunctionCtx,
) -> BackendResult {
use crate::back::INDENT;
const ARGUMENT_VARIABLE_NAME: &str = "buffer";
const RETURN_VARIABLE_NAME: &str = "ret";
// Write function return type and name
let ret_ty = func_ctx.info[expr_handle].ty.inner_with(&module.types);
self.write_value_type(module, ret_ty)?;
write!(self.out, " ")?;
self.write_wrapped_array_length_function_name(wal)?;
// Write function parameters
write!(self.out, "(")?;
let access_str = if wal.writable { "RW" } else { "" };
writeln!(
self.out,
"{}ByteAddressBuffer {})",
access_str, ARGUMENT_VARIABLE_NAME
)?;
// Write function body
writeln!(self.out, "{{")?;
// Write `GetDimensions` function.
writeln!(self.out, "{}uint {};", INDENT, RETURN_VARIABLE_NAME)?;
writeln!(
self.out,
"{}{}.GetDimensions({});",
INDENT, ARGUMENT_VARIABLE_NAME, RETURN_VARIABLE_NAME
)?;
// Write return value
writeln!(self.out, "{}return {};", INDENT, RETURN_VARIABLE_NAME)?;
// End of function body
writeln!(self.out, "}}")?;
// Write extra new line
writeln!(self.out)?;
Ok(())
}
pub(super) fn write_wrapped_image_query_function_name(
&mut self,
query: WrappedImageQuery,
) -> BackendResult {
let dim_str = query.dim.to_hlsl_str();
let class_str = match query.class {
crate::ImageClass::Sampled { multi: true, .. } => "MS",
crate::ImageClass::Depth { multi: true } => "DepthMS",
crate::ImageClass::Depth { multi: false } => "Depth",
crate::ImageClass::Sampled { multi: false, .. } => "",
crate::ImageClass::Storage { .. } => "RW",
};
let arrayed_str = if query.arrayed { "Array" } else { "" };
let query_str = match query.query {
ImageQuery::Size => "Dimensions",
ImageQuery::SizeLevel => "MipDimensions",
ImageQuery::NumLevels => "NumLevels",
ImageQuery::NumLayers => "NumLayers",
ImageQuery::NumSamples => "NumSamples",
};
write!(
self.out,
"Naga{}{}{}{}",
class_str, query_str, dim_str, arrayed_str
)?;
Ok(())
}
/// Helper function that write wrapped function for `Expression::ImageQuery`
///
/// <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions>
pub(super) fn write_wrapped_image_query_function(
&mut self,
module: &crate::Module,
wiq: WrappedImageQuery,
expr_handle: Handle<crate::Expression>,
func_ctx: &FunctionCtx,
) -> BackendResult {
use crate::{
back::{COMPONENTS, INDENT},
ImageDimension as IDim,
};
const ARGUMENT_VARIABLE_NAME: &str = "tex";
const RETURN_VARIABLE_NAME: &str = "ret";
const MIP_LEVEL_PARAM: &str = "mip_level";
// Write function return type and name
let ret_ty = func_ctx.info[expr_handle].ty.inner_with(&module.types);
self.write_value_type(module, ret_ty)?;
write!(self.out, " ")?;
self.write_wrapped_image_query_function_name(wiq)?;
// Write function parameters
write!(self.out, "(")?;
// Texture always first parameter
self.write_image_type(wiq.dim, wiq.arrayed, wiq.class)?;
write!(self.out, " {}", ARGUMENT_VARIABLE_NAME)?;
// Mipmap is a second parameter if exists
if let ImageQuery::SizeLevel = wiq.query {
write!(self.out, ", uint {}", MIP_LEVEL_PARAM)?;
}
writeln!(self.out, ")")?;
// Write function body
writeln!(self.out, "{{")?;
let array_coords = if wiq.arrayed { 1 } else { 0 };
// extra parameter is the mip level count or the sample count
let extra_coords = match wiq.class {
crate::ImageClass::Storage { .. } => 0,
crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth { .. } => 1,
};
// GetDimensions Overloaded Methods
// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions#overloaded-methods
let (ret_swizzle, number_of_params) = match wiq.query {
ImageQuery::Size | ImageQuery::SizeLevel => {
let ret = match wiq.dim {
IDim::D1 => "x",
IDim::D2 => "xy",
IDim::D3 => "xyz",
IDim::Cube => "xy",
};
(ret, ret.len() + array_coords + extra_coords)
}
ImageQuery::NumLevels | ImageQuery::NumSamples | ImageQuery::NumLayers => {
if wiq.arrayed || wiq.dim == IDim::D3 {
("w", 4)
} else {
("z", 3)
}
}
};
// Write `GetDimensions` function.
writeln!(self.out, "{}uint4 {};", INDENT, RETURN_VARIABLE_NAME)?;
write!(
self.out,
"{}{}.GetDimensions(",
INDENT, ARGUMENT_VARIABLE_NAME
)?;
match wiq.query {
ImageQuery::SizeLevel => {
write!(self.out, "{}, ", MIP_LEVEL_PARAM)?;
}
_ => match wiq.class {
crate::ImageClass::Sampled { multi: true, .. }
| crate::ImageClass::Depth { multi: true }
| crate::ImageClass::Storage { .. } => {}
_ => {
// Write zero mipmap level for supported types
write!(self.out, "0, ")?;
}
},
}
for component in COMPONENTS[..number_of_params - 1].iter() {
write!(self.out, "{}.{}, ", RETURN_VARIABLE_NAME, component)?;
}
// write last parameter without comma and space for last parameter
write!(
self.out,
"{}.{}",
RETURN_VARIABLE_NAME,
COMPONENTS[number_of_params - 1]
)?;
writeln!(self.out, ");")?;
// Write return value
writeln!(
self.out,
"{}return {}.{};",
INDENT, RETURN_VARIABLE_NAME, ret_swizzle
)?;
// End of function body
writeln!(self.out, "}}")?;
// Write extra new line
writeln!(self.out)?;
Ok(())
}
pub(super) fn write_wrapped_constructor_function_name(
&mut self,
module: &crate::Module,
constructor: WrappedConstructor,
) -> BackendResult {
let name = module.types[constructor.ty].inner.hlsl_type_id(
constructor.ty,
&module.types,
&module.constants,
&self.names,
)?;
write!(self.out, "Construct{}", name)?;
Ok(())
}
/// Helper function that write wrapped function for `Expression::Compose` for structures.
pub(super) fn write_wrapped_constructor_function(
&mut self,
module: &crate::Module,
constructor: WrappedConstructor,
) -> BackendResult {
use crate::back::INDENT;
const ARGUMENT_VARIABLE_NAME: &str = "arg";
const RETURN_VARIABLE_NAME: &str = "ret";
// Write function return type and name
if let crate::TypeInner::Array { base, size, .. } = module.types[constructor.ty].inner {
write!(self.out, "typedef ")?;
self.write_type(module, constructor.ty)?;
write!(self.out, " ret_")?;
self.write_wrapped_constructor_function_name(module, constructor)?;
self.write_array_size(module, base, size)?;
writeln!(self.out, ";")?;
write!(self.out, "ret_")?;
self.write_wrapped_constructor_function_name(module, constructor)?;
} else {
self.write_type(module, constructor.ty)?;
}
write!(self.out, " ")?;
self.write_wrapped_constructor_function_name(module, constructor)?;
// Write function parameters
write!(self.out, "(")?;
let mut write_arg = |i, ty| -> BackendResult {
if i != 0 {
write!(self.out, ", ")?;
}
self.write_type(module, ty)?;
write!(self.out, " {}{}", ARGUMENT_VARIABLE_NAME, i)?;
if let crate::TypeInner::Array { base, size, .. } = module.types[ty].inner {
self.write_array_size(module, base, size)?;
}
Ok(())
};
match module.types[constructor.ty].inner {
crate::TypeInner::Struct { ref members, .. } => {
for (i, member) in members.iter().enumerate() {
write_arg(i, member.ty)?;
}
}
crate::TypeInner::Array {
base,
size: crate::ArraySize::Constant(size),
..
} => {
let count = module.constants[size].to_array_length().unwrap();
for i in 0..count as usize {
write_arg(i, base)?;
}
}
_ => unreachable!(),
};
write!(self.out, ")")?;
// Write function body
writeln!(self.out, " {{")?;
match module.types[constructor.ty].inner {
crate::TypeInner::Struct { ref members, .. } => {
let struct_name = &self.names[&NameKey::Type(constructor.ty)];
writeln!(
self.out,
"{}{} {} = ({})0;",
INDENT, struct_name, RETURN_VARIABLE_NAME, struct_name
)?;
for (i, member) in members.iter().enumerate() {
let field_name = &self.names[&NameKey::StructMember(constructor.ty, i as u32)];
match module.types[member.ty].inner {
crate::TypeInner::Matrix {
columns,
rows: crate::VectorSize::Bi,
..
} if member.binding.is_none() => {
for j in 0..columns as u8 {
writeln!(
self.out,
"{}{}.{}_{} = {}{}[{}];",
INDENT,
RETURN_VARIABLE_NAME,
field_name,
j,
ARGUMENT_VARIABLE_NAME,
i,
j
)?;
}
}
ref other => {
// We cast arrays of native HLSL `floatCx2`s to arrays of `matCx2`s
// (where the inner matrix is represented by a struct with C `float2` members).
// See the module-level block comment in mod.rs for details.
if let Some(super::writer::MatrixType {
columns,
rows: crate::VectorSize::Bi,
width: 4,
}) = super::writer::get_inner_matrix_data(module, member.ty)
{
write!(
self.out,
"{}{}.{} = (__mat{}x2",
INDENT, RETURN_VARIABLE_NAME, field_name, columns as u8
)?;
if let crate::TypeInner::Array { base, size, .. } = *other {
self.write_array_size(module, base, size)?;
}
writeln!(self.out, "){}{};", ARGUMENT_VARIABLE_NAME, i,)?;
} else {
writeln!(
self.out,
"{}{}.{} = {}{};",
INDENT,
RETURN_VARIABLE_NAME,
field_name,
ARGUMENT_VARIABLE_NAME,
i,
)?;
}
}
}
}
}
crate::TypeInner::Array {
base,
size: crate::ArraySize::Constant(size),
..
} => {
write!(self.out, "{}", INDENT)?;
self.write_type(module, base)?;
write!(self.out, " {}", RETURN_VARIABLE_NAME)?;
self.write_array_size(module, base, crate::ArraySize::Constant(size))?;
write!(self.out, " = {{ ")?;
let count = module.constants[size].to_array_length().unwrap();
for i in 0..count {
if i != 0 {
write!(self.out, ", ")?;
}
write!(self.out, "{}{}", ARGUMENT_VARIABLE_NAME, i)?;
}
writeln!(self.out, " }};",)?;
}
_ => unreachable!(),
}
// Write return value
writeln!(self.out, "{}return {};", INDENT, RETURN_VARIABLE_NAME)?;
// End of function body
writeln!(self.out, "}}")?;
// Write extra new line
writeln!(self.out)?;
Ok(())
}
pub(super) fn write_wrapped_struct_matrix_get_function_name(
&mut self,
access: WrappedStructMatrixAccess,
) -> BackendResult {
let name = &self.names[&NameKey::Type(access.ty)];
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)];
write!(self.out, "GetMat{}On{}", field_name, name)?;
Ok(())
}
/// Writes a function used to get a matCx2 from within a structure.
pub(super) fn write_wrapped_struct_matrix_get_function(
&mut self,
module: &crate::Module,
access: WrappedStructMatrixAccess,
) -> BackendResult {
use crate::back::INDENT;
const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj";
// Write function return type and name
let member = match module.types[access.ty].inner {
crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize],
_ => unreachable!(),
};
let ret_ty = &module.types[member.ty].inner;
self.write_value_type(module, ret_ty)?;
write!(self.out, " ")?;
self.write_wrapped_struct_matrix_get_function_name(access)?;
// Write function parameters
write!(self.out, "(")?;
let struct_name = &self.names[&NameKey::Type(access.ty)];
write!(
self.out,
"{} {}",
struct_name, STRUCT_ARGUMENT_VARIABLE_NAME
)?;
// Write function body
writeln!(self.out, ") {{")?;
// Write return value
write!(self.out, "{}return ", INDENT)?;
self.write_value_type(module, ret_ty)?;
write!(self.out, "(")?;
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)];
match module.types[member.ty].inner {
crate::TypeInner::Matrix { columns, .. } => {
for i in 0..columns as u8 {
if i != 0 {
write!(self.out, ", ")?;
}
write!(
self.out,
"{}.{}_{}",
STRUCT_ARGUMENT_VARIABLE_NAME, field_name, i
)?;
}
}
_ => unreachable!(),
}
writeln!(self.out, ");")?;
// End of function body
writeln!(self.out, "}}")?;
// Write extra new line
writeln!(self.out)?;
Ok(())
}
pub(super) fn write_wrapped_struct_matrix_set_function_name(
&mut self,
access: WrappedStructMatrixAccess,
) -> BackendResult {
let name = &self.names[&NameKey::Type(access.ty)];
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)];
write!(self.out, "SetMat{}On{}", field_name, name)?;
Ok(())
}
/// Writes a function used to set a matCx2 from within a structure.
pub(super) fn write_wrapped_struct_matrix_set_function(
&mut self,
module: &crate::Module,
access: WrappedStructMatrixAccess,
) -> BackendResult {
use crate::back::INDENT;
const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj";
const MATRIX_ARGUMENT_VARIABLE_NAME: &str = "mat";
// Write function return type and name
write!(self.out, "void ")?;
self.write_wrapped_struct_matrix_set_function_name(access)?;
// Write function parameters
write!(self.out, "(")?;
let struct_name = &self.names[&NameKey::Type(access.ty)];
write!(
self.out,
"{} {}, ",
struct_name, STRUCT_ARGUMENT_VARIABLE_NAME
)?;
let member = match module.types[access.ty].inner {
crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize],
_ => unreachable!(),
};
self.write_type(module, member.ty)?;
write!(self.out, " {}", MATRIX_ARGUMENT_VARIABLE_NAME)?;
// Write function body
writeln!(self.out, ") {{")?;
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)];
match module.types[member.ty].inner {
crate::TypeInner::Matrix { columns, .. } => {
for i in 0..columns as u8 {
writeln!(
self.out,
"{}{}.{}_{} = {}[{}];",
INDENT,
STRUCT_ARGUMENT_VARIABLE_NAME,
field_name,
i,
MATRIX_ARGUMENT_VARIABLE_NAME,
i
)?;
}
}
_ => unreachable!(),
}
// End of function body
writeln!(self.out, "}}")?;
// Write extra new line
writeln!(self.out)?;
Ok(())
}
pub(super) fn write_wrapped_struct_matrix_set_vec_function_name(
&mut self,
access: WrappedStructMatrixAccess,
) -> BackendResult {
let name = &self.names[&NameKey::Type(access.ty)];
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)];
write!(self.out, "SetMatVec{}On{}", field_name, name)?;
Ok(())
}
/// Writes a function used to set a vec2 on a matCx2 from within a structure.
pub(super) fn write_wrapped_struct_matrix_set_vec_function(
&mut self,
module: &crate::Module,
access: WrappedStructMatrixAccess,
) -> BackendResult {
use crate::back::INDENT;
const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj";
const VECTOR_ARGUMENT_VARIABLE_NAME: &str = "vec";
const MATRIX_INDEX_ARGUMENT_VARIABLE_NAME: &str = "mat_idx";
// Write function return type and name
write!(self.out, "void ")?;
self.write_wrapped_struct_matrix_set_vec_function_name(access)?;
// Write function parameters
write!(self.out, "(")?;
let struct_name = &self.names[&NameKey::Type(access.ty)];
write!(
self.out,
"{} {}, ",
struct_name, STRUCT_ARGUMENT_VARIABLE_NAME
)?;
let member = match module.types[access.ty].inner {
crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize],
_ => unreachable!(),
};
let vec_ty = match module.types[member.ty].inner {
crate::TypeInner::Matrix { rows, width, .. } => crate::TypeInner::Vector {
size: rows,
kind: crate::ScalarKind::Float,
width,
},
_ => unreachable!(),
};
self.write_value_type(module, &vec_ty)?;
write!(
self.out,
" {}, uint {}",
VECTOR_ARGUMENT_VARIABLE_NAME, MATRIX_INDEX_ARGUMENT_VARIABLE_NAME
)?;
// Write function body
writeln!(self.out, ") {{")?;
writeln!(
self.out,
"{}switch({}) {{",
INDENT, MATRIX_INDEX_ARGUMENT_VARIABLE_NAME
)?;
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)];
match module.types[member.ty].inner {
crate::TypeInner::Matrix { columns, .. } => {
for i in 0..columns as u8 {
writeln!(
self.out,
"{}case {}: {{ {}.{}_{} = {}; break; }}",
INDENT,
i,
STRUCT_ARGUMENT_VARIABLE_NAME,
field_name,
i,
VECTOR_ARGUMENT_VARIABLE_NAME
)?;
}
}
_ => unreachable!(),
}
writeln!(self.out, "{}}}", INDENT)?;
// End of function body
writeln!(self.out, "}}")?;
// Write extra new line
writeln!(self.out)?;
Ok(())
}
pub(super) fn write_wrapped_struct_matrix_set_scalar_function_name(
&mut self,
access: WrappedStructMatrixAccess,
) -> BackendResult {
let name = &self.names[&NameKey::Type(access.ty)];
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)];
write!(self.out, "SetMatScalar{}On{}", field_name, name)?;
Ok(())
}
/// Writes a function used to set a float on a matCx2 from within a structure.
pub(super) fn write_wrapped_struct_matrix_set_scalar_function(
&mut self,
module: &crate::Module,
access: WrappedStructMatrixAccess,
) -> BackendResult {
use crate::back::INDENT;
const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj";
const SCALAR_ARGUMENT_VARIABLE_NAME: &str = "scalar";
const MATRIX_INDEX_ARGUMENT_VARIABLE_NAME: &str = "mat_idx";
const VECTOR_INDEX_ARGUMENT_VARIABLE_NAME: &str = "vec_idx";
// Write function return type and name
write!(self.out, "void ")?;
self.write_wrapped_struct_matrix_set_scalar_function_name(access)?;
// Write function parameters
write!(self.out, "(")?;
let struct_name = &self.names[&NameKey::Type(access.ty)];
write!(
self.out,
"{} {}, ",
struct_name, STRUCT_ARGUMENT_VARIABLE_NAME
)?;
let member = match module.types[access.ty].inner {
crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize],
_ => unreachable!(),
};
let scalar_ty = match module.types[member.ty].inner {
crate::TypeInner::Matrix { width, .. } => crate::TypeInner::Scalar {
kind: crate::ScalarKind::Float,
width,
},
_ => unreachable!(),
};
self.write_value_type(module, &scalar_ty)?;
write!(
self.out,
" {}, uint {}, uint {}",
SCALAR_ARGUMENT_VARIABLE_NAME,
MATRIX_INDEX_ARGUMENT_VARIABLE_NAME,
VECTOR_INDEX_ARGUMENT_VARIABLE_NAME
)?;
// Write function body
writeln!(self.out, ") {{")?;
writeln!(
self.out,
"{}switch({}) {{",
INDENT, MATRIX_INDEX_ARGUMENT_VARIABLE_NAME
)?;
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)];
match module.types[member.ty].inner {
crate::TypeInner::Matrix { columns, .. } => {
for i in 0..columns as u8 {
writeln!(
self.out,
"{}case {}: {{ {}.{}_{}[{}] = {}; break; }}",
INDENT,
i,
STRUCT_ARGUMENT_VARIABLE_NAME,
field_name,
i,
VECTOR_INDEX_ARGUMENT_VARIABLE_NAME,
SCALAR_ARGUMENT_VARIABLE_NAME
)?;
}
}
_ => unreachable!(),
}
writeln!(self.out, "{}}}", INDENT)?;
// End of function body
writeln!(self.out, "}}")?;
// Write extra new line
writeln!(self.out)?;
Ok(())
}
/// Helper function that write wrapped function for `Expression::ImageQuery` and `Expression::ArrayLength`
///
/// <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions>
pub(super) fn write_wrapped_functions(
&mut self,
module: &crate::Module,
func_ctx: &FunctionCtx,
) -> BackendResult {
for (handle, _) in func_ctx.expressions.iter() {
match func_ctx.expressions[handle] {
crate::Expression::ArrayLength(expr) => {
let global_expr = match func_ctx.expressions[expr] {
crate::Expression::GlobalVariable(_) => expr,
crate::Expression::AccessIndex { base, index: _ } => base,
ref other => unreachable!("Array length of {:?}", other),
};
let global_var = match func_ctx.expressions[global_expr] {
crate::Expression::GlobalVariable(var_handle) => {
&module.global_variables[var_handle]
}
ref other => unreachable!("Array length of base {:?}", other),
};
let storage_access = match global_var.space {
crate::AddressSpace::Storage { access } => access,
_ => crate::StorageAccess::default(),
};
let wal = WrappedArrayLength {
writable: storage_access.contains(crate::StorageAccess::STORE),
};
if !self.wrapped.array_lengths.contains(&wal) {
self.write_wrapped_array_length_function(module, wal, handle, func_ctx)?;
self.wrapped.array_lengths.insert(wal);
}
}
crate::Expression::ImageQuery { image, query } => {
let wiq = match *func_ctx.info[image].ty.inner_with(&module.types) {
crate::TypeInner::Image {
dim,
arrayed,
class,
} => WrappedImageQuery {
dim,
arrayed,
class,
query: query.into(),
},
_ => unreachable!("we only query images"),
};
if !self.wrapped.image_queries.contains(&wiq) {
self.write_wrapped_image_query_function(module, wiq, handle, func_ctx)?;
self.wrapped.image_queries.insert(wiq);
}
}
// Write `WrappedConstructor` for structs that are loaded from `AddressSpace::Storage`
// since they will later be used by the fn `write_storage_load`
crate::Expression::Load { pointer } => {
let pointer_space = func_ctx.info[pointer]
.ty
.inner_with(&module.types)
.pointer_space();
if let Some(crate::AddressSpace::Storage { .. }) = pointer_space {
if let Some(ty) = func_ctx.info[handle].ty.handle() {
write_wrapped_constructor(self, ty, module, func_ctx)?;
}
}
fn write_wrapped_constructor<W: Write>(
writer: &mut super::Writer<'_, W>,
ty: Handle<crate::Type>,
module: &crate::Module,
func_ctx: &FunctionCtx,
) -> BackendResult {
match module.types[ty].inner {
crate::TypeInner::Struct { ref members, .. } => {
for member in members {
write_wrapped_constructor(writer, member.ty, module, func_ctx)?;
}
let constructor = WrappedConstructor { ty };
if !writer.wrapped.constructors.contains(&constructor) {
writer
.write_wrapped_constructor_function(module, constructor)?;
writer.wrapped.constructors.insert(constructor);
}
}
crate::TypeInner::Array { base, .. } => {
write_wrapped_constructor(writer, base, module, func_ctx)?;
}
_ => {}
};
Ok(())
}
}
crate::Expression::Compose { ty, components: _ } => {
let constructor = match module.types[ty].inner {
crate::TypeInner::Struct { .. } | crate::TypeInner::Array { .. } => {
WrappedConstructor { ty }
}
_ => continue,
};
if !self.wrapped.constructors.contains(&constructor) {
self.write_wrapped_constructor_function(module, constructor)?;
self.wrapped.constructors.insert(constructor);
}
}
// We treat matrices of the form `matCx2` as a sequence of C `vec2`s
// (see top level module docs for details).
//
// The functions injected here are required to get the matrix accesses working.
crate::Expression::AccessIndex { base, index } => {
let base_ty_res = &func_ctx.info[base].ty;
let mut resolved = base_ty_res.inner_with(&module.types);
let base_ty_handle = match *resolved {
crate::TypeInner::Pointer { base, .. } => {
resolved = &module.types[base].inner;
Some(base)
}
_ => base_ty_res.handle(),
};
if let crate::TypeInner::Struct { ref members, .. } = *resolved {
let member = &members[index as usize];
match module.types[member.ty].inner {
crate::TypeInner::Matrix {
rows: crate::VectorSize::Bi,
..
} if member.binding.is_none() => {
let ty = base_ty_handle.unwrap();
let access = WrappedStructMatrixAccess { ty, index };
if !self.wrapped.struct_matrix_access.contains(&access) {
self.write_wrapped_struct_matrix_get_function(module, access)?;
self.write_wrapped_struct_matrix_set_function(module, access)?;
self.write_wrapped_struct_matrix_set_vec_function(
module, access,
)?;
self.write_wrapped_struct_matrix_set_scalar_function(
module, access,
)?;
self.wrapped.struct_matrix_access.insert(access);
}
}
_ => {}
}
}
}
_ => {}
};
}
Ok(())
}
pub(super) fn write_wrapped_constructor_function_for_constant(
&mut self,
module: &crate::Module,
constant: &crate::Constant,
) -> BackendResult {
if let crate::ConstantInner::Composite { ty, ref components } = constant.inner {
match module.types[ty].inner {
crate::TypeInner::Struct { .. } | crate::TypeInner::Array { .. } => {
let constructor = WrappedConstructor { ty };
if !self.wrapped.constructors.contains(&constructor) {
self.write_wrapped_constructor_function(module, constructor)?;
self.wrapped.constructors.insert(constructor);
}
}
_ => {}
}
for constant in components {
self.write_wrapped_constructor_function_for_constant(
module,
&module.constants[*constant],
)?;
}
}
Ok(())
}
pub(super) fn write_texture_coordinates(
&mut self,
kind: &str,
coordinate: Handle<crate::Expression>,
array_index: Option<Handle<crate::Expression>>,
mip_level: Option<Handle<crate::Expression>>,
module: &crate::Module,
func_ctx: &FunctionCtx,
) -> BackendResult {
// HLSL expects the array index to be merged with the coordinate
let extra = array_index.is_some() as usize + (mip_level.is_some()) as usize;
if extra == 0 {
self.write_expr(module, coordinate, func_ctx)?;
} else {
let num_coords = match *func_ctx.info[coordinate].ty.inner_with(&module.types) {
crate::TypeInner::Scalar { .. } => 1,
crate::TypeInner::Vector { size, .. } => size as usize,
_ => unreachable!(),
};
write!(self.out, "{}{}(", kind, num_coords + extra)?;
self.write_expr(module, coordinate, func_ctx)?;
if let Some(expr) = array_index {
write!(self.out, ", ")?;
self.write_expr(module, expr, func_ctx)?;
}
if let Some(expr) = mip_level {
write!(self.out, ", ")?;
self.write_expr(module, expr, func_ctx)?;
}
write!(self.out, ")")?;
}
Ok(())
}
pub(super) fn write_mat_cx2_typedef_and_functions(
&mut self,
WrappedMatCx2 { columns }: WrappedMatCx2,
) -> BackendResult {
use crate::back::INDENT;
// typedef
write!(self.out, "typedef struct {{ ")?;
for i in 0..columns as u8 {
write!(self.out, "float2 _{}; ", i)?;
}
writeln!(self.out, "}} __mat{}x2;", columns as u8)?;
// __get_col_of_mat
writeln!(
self.out,
"float2 __get_col_of_mat{}x2(__mat{}x2 mat, uint idx) {{",
columns as u8, columns as u8
)?;
writeln!(self.out, "{}switch(idx) {{", INDENT)?;
for i in 0..columns as u8 {
writeln!(self.out, "{}case {}: {{ return mat._{}; }}", INDENT, i, i)?;
}
writeln!(self.out, "{}default: {{ return (float2)0; }}", INDENT)?;
writeln!(self.out, "{}}}", INDENT)?;
writeln!(self.out, "}}")?;
// __set_col_of_mat
writeln!(
self.out,
"void __set_col_of_mat{}x2(__mat{}x2 mat, uint idx, float2 value) {{",
columns as u8, columns as u8
)?;
writeln!(self.out, "{}switch(idx) {{", INDENT)?;
for i in 0..columns as u8 {
writeln!(
self.out,
"{}case {}: {{ mat._{} = value; break; }}",
INDENT, i, i
)?;
}
writeln!(self.out, "{}}}", INDENT)?;
writeln!(self.out, "}}")?;
// __set_el_of_mat
writeln!(
self.out,
"void __set_el_of_mat{}x2(__mat{}x2 mat, uint idx, uint vec_idx, float value) {{",
columns as u8, columns as u8
)?;
writeln!(self.out, "{}switch(idx) {{", INDENT)?;
for i in 0..columns as u8 {
writeln!(
self.out,
"{}case {}: {{ mat._{}[vec_idx] = value; break; }}",
INDENT, i, i
)?;
}
writeln!(self.out, "{}}}", INDENT)?;
writeln!(self.out, "}}")?;
writeln!(self.out)?;
Ok(())
}
pub(super) fn write_all_mat_cx2_typedefs_and_functions(
&mut self,
module: &crate::Module,
) -> BackendResult {
for (handle, _) in module.global_variables.iter() {
let global = &module.global_variables[handle];
if global.space == crate::AddressSpace::Uniform {
if let Some(super::writer::MatrixType {
columns,
rows: crate::VectorSize::Bi,
width: 4,
}) = super::writer::get_inner_matrix_data(module, global.ty)
{
let entry = WrappedMatCx2 { columns };
if !self.wrapped.mat_cx2s.contains(&entry) {
self.write_mat_cx2_typedef_and_functions(entry)?;
self.wrapped.mat_cx2s.insert(entry);
}
}
}
}
for (_, ty) in module.types.iter() {
if let crate::TypeInner::Struct { ref members, .. } = ty.inner {
for member in members.iter() {
if let crate::TypeInner::Array { .. } = module.types[member.ty].inner {
if let Some(super::writer::MatrixType {
columns,
rows: crate::VectorSize::Bi,
width: 4,
}) = super::writer::get_inner_matrix_data(module, member.ty)
{
let entry = WrappedMatCx2 { columns };
if !self.wrapped.mat_cx2s.contains(&entry) {
self.write_mat_cx2_typedef_and_functions(entry)?;
self.wrapped.mat_cx2s.insert(entry);
}
}
}
}
}
}
Ok(())
}
}
|