1 // Testbench for HLSL resource binding APIs.
2 // It does not validate output at the moment, but it's useful for ad-hoc testing.
3
4 #include <spirv_cross_c.h>
5 #include <vector>
6 #include <stdio.h>
7 #include <stdlib.h>
8
9 #define SPVC_CHECKED_CALL(x) do { \
10 if ((x) != SPVC_SUCCESS) { \
11 fprintf(stderr, "Failed at line %d.\n", __LINE__); \
12 exit(1); \
13 } \
14 } while(0)
15
read_file(const char * path)16 static std::vector<SpvId> read_file(const char *path)
17 {
18 long len;
19 FILE *file = fopen(path, "rb");
20
21 if (!file)
22 return {};
23
24 fseek(file, 0, SEEK_END);
25 len = ftell(file);
26 rewind(file);
27
28 std::vector<SpvId> buffer(len / sizeof(SpvId));
29 if (fread(buffer.data(), 1, len, file) != (size_t)len)
30 {
31 fclose(file);
32 return {};
33 }
34
35 fclose(file);
36 return buffer;
37 }
38
main(int argc,char ** argv)39 int main(int argc, char **argv)
40 {
41 if (argc != 2)
42 return EXIT_FAILURE;
43
44 auto buffer = read_file(argv[1]);
45 if (buffer.empty())
46 return EXIT_FAILURE;
47
48 spvc_context ctx;
49 spvc_parsed_ir parsed_ir;
50 spvc_compiler compiler;
51
52 SPVC_CHECKED_CALL(spvc_context_create(&ctx));
53 SPVC_CHECKED_CALL(spvc_context_parse_spirv(ctx, buffer.data(), buffer.size(), &parsed_ir));
54 SPVC_CHECKED_CALL(spvc_context_create_compiler(ctx, SPVC_BACKEND_HLSL, parsed_ir, SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, &compiler));
55
56 spvc_compiler_options opts;
57 SPVC_CHECKED_CALL(spvc_compiler_create_compiler_options(compiler, &opts));
58 SPVC_CHECKED_CALL(spvc_compiler_options_set_uint(opts, SPVC_COMPILER_OPTION_HLSL_SHADER_MODEL, 51));
59 SPVC_CHECKED_CALL(spvc_compiler_install_compiler_options(compiler, opts));
60
61 spvc_hlsl_resource_binding binding;
62 spvc_hlsl_resource_binding_init(&binding);
63 binding.stage = SpvExecutionModelFragment;
64 binding.desc_set = 1;
65 binding.binding = 4;
66 binding.srv.register_space = 2;
67 binding.srv.register_binding = 3;
68 binding.sampler.register_space = 4;
69 binding.sampler.register_binding = 5;
70 SPVC_CHECKED_CALL(spvc_compiler_hlsl_add_resource_binding(compiler, &binding));
71
72 binding.desc_set = SPVC_HLSL_PUSH_CONSTANT_DESC_SET;
73 binding.binding = SPVC_HLSL_PUSH_CONSTANT_BINDING;
74 binding.cbv.register_space = 0;
75 binding.cbv.register_binding = 4;
76 SPVC_CHECKED_CALL(spvc_compiler_hlsl_add_resource_binding(compiler, &binding));
77
78 const char *str;
79 SPVC_CHECKED_CALL(spvc_compiler_compile(compiler, &str));
80
81 fprintf(stderr, "Output:\n%s\n", str);
82
83 if (!spvc_compiler_hlsl_is_resource_used(compiler, SpvExecutionModelFragment, 1, 4))
84 return EXIT_FAILURE;
85
86 if (!spvc_compiler_hlsl_is_resource_used(compiler, SpvExecutionModelFragment, SPVC_HLSL_PUSH_CONSTANT_DESC_SET, SPVC_HLSL_PUSH_CONSTANT_BINDING))
87 return EXIT_FAILURE;
88 }
89
90