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
use crate::error::{ContextRooted, SpirvCrossError, ToContextError};
use crate::handle::{Handle, TypeId, VariableId};
use crate::sealed::Sealed;
use crate::string::ContextStr;
use crate::{error, spirv, Compiler, PhantomCompiler, ToStatic};
use spirv_cross_sys as sys;
use spirv_cross_sys::{
    spvc_context_s, spvc_reflected_builtin_resource, spvc_reflected_resource, spvc_resources_s,
    spvc_set,
};
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::slice;

pub use spirv_cross_sys::{BuiltinResourceType, ResourceType};

/// A handle to shader resources.
pub struct ShaderResources<'a>(NonNull<spvc_resources_s>, PhantomCompiler<'a>);

impl ContextRooted for &ShaderResources<'_> {
    #[inline(always)]
    fn context(&self) -> NonNull<spvc_context_s> {
        self.1.context()
    }
}

impl<'ctx, T> Compiler<'ctx, T> {
    /// Query shader resources, use ids with reflection interface to modify or query binding points, etc.
    pub fn shader_resources(&self) -> crate::error::Result<ShaderResources<'ctx>> {
        // SAFETY: 'ctx is Ok
        // since this gets allocated forever
        // https://github.com/KhronosGroup/SPIRV-Cross/blob/6a1fb66eef1bdca14acf7d0a51a3f883499d79f0/spirv_cross_c.cpp#L1925
        unsafe {
            let mut resources = std::ptr::null_mut();
            sys::spvc_compiler_create_shader_resources(self.ptr.as_ptr(), &mut resources)
                .ok(self)?;

            let Some(resources) = NonNull::new(resources) else {
                return Err(SpirvCrossError::OutOfMemory(String::from("Out of memory")));
            };

            Ok(ShaderResources(resources, self.phantom()))
        }
    }

    /// Query shader resources, but only return the variables which are part of active_variables.
    /// E.g.: get_shader_resources(get_active_variables()) to only return the variables which are statically
    /// accessed.
    pub fn shader_resources_for_active_variables(
        &self,
        set: InterfaceVariableSet,
    ) -> error::Result<ShaderResources<'ctx>> {
        // SAFETY: 'ctx is Ok
        // since this gets allocated forever
        // https://github.com/KhronosGroup/SPIRV-Cross/blob/6a1fb66eef1bdca14acf7d0a51a3f883499d79f0/spirv_cross_c.cpp#L1925
        unsafe {
            let mut resources = std::ptr::null_mut();
            sys::spvc_compiler_create_shader_resources_for_active_variables(
                self.ptr.as_ptr(),
                &mut resources,
                set.0,
            )
            .ok(self)?;

            let Some(resources) = NonNull::new(resources) else {
                return Err(SpirvCrossError::OutOfMemory(String::from("Out of memory")));
            };

            Ok(ShaderResources(resources, self.phantom()))
        }
    }
}

/// A handle to a set of interface variables.
pub struct InterfaceVariableSet<'a>(spvc_set, Handle<PhantomData<&'a ()>>, PhantomCompiler<'a>);

impl<'a> InterfaceVariableSet<'a> {
    /// Get the SPIR-V IDs for the active interface variables.
    ///
    /// This is only meant to be used for reflection. It is not possible
    /// to modify the contents of an [`InterfaceVariableSet`].
    pub fn to_handles(&self) -> Vec<Handle<VariableId>> {
        unsafe {
            // Get the length of allocation
            let mut length = 0;
            spirv_cross_sys::spvc_rs_expose_set(self.0, std::ptr::null_mut(), &mut length);

            // write into the vec
            let mut vec = vec![0; length];
            spirv_cross_sys::spvc_rs_expose_set(self.0, vec.as_mut_ptr(), &mut length);

            let mut handles: Vec<Handle<VariableId>> = vec
                .into_iter()
                .map(|id| self.2.create_handle(VariableId::from(id)))
                .collect();

            handles.sort_by_key(|h| h.id());

            handles
        }
    }
}

// reflection
impl<'a, T> Compiler<'a, T> {
    /// Returns a set of all global variables which are statically accessed
    /// by the control flow graph from the current entry point.
    /// Only variables which change the interface for a shader are returned, that is,
    /// variables with storage class of Input, Output, Uniform, UniformConstant, PushConstant and AtomicCounter
    /// storage classes are returned.
    ///
    /// To use the returned set as the filter for which variables are used during compilation,
    /// this set can be moved to set_enabled_interface_variables().
    ///
    /// The return object is opaque to Rust, but its contents inspected by using [`InterfaceVariableSet::to_handles`].
    /// There is no way to modify the contents or use your own `InterfaceVariableSet`.
    pub fn active_interface_variables(&self) -> error::Result<InterfaceVariableSet<'a>> {
        unsafe {
            let mut set = std::ptr::null();
            sys::spvc_compiler_get_active_interface_variables(self.ptr.as_ptr(), &mut set)
                .ok(self)?;

            Ok(InterfaceVariableSet(
                set,
                self.create_handle(PhantomData),
                self.phantom(),
            ))
        }
    }

    /// Sets the interface variables which are used during compilation.
    /// By default, all variables are used.
    /// Once set, [`Compiler::compile`] will only consider the set in active_variables.
    pub fn set_enabled_interface_variables(
        &mut self,
        set: InterfaceVariableSet,
    ) -> error::Result<()> {
        if !self.handle_is_valid(&set.1) {
            return Err(SpirvCrossError::InvalidOperation(String::from(
                "The interface variable set is invalid for this compiler instance.",
            )));
        }
        unsafe {
            sys::spvc_compiler_set_enabled_interface_variables(self.ptr.as_ptr(), set.0)
                .ok(self)?;
            Ok(())
        }
    }
}

/// Iterator over reflected resources, created by [`ShaderResources::resources_for_type`].
pub struct ResourceIter<'a>(
    PhantomCompiler<'a>,
    slice::Iter<'a, spvc_reflected_resource>,
);

impl<'a> Iterator for ResourceIter<'a> {
    type Item = Resource<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        self.1.next().map(|o| Resource::from_raw(self.0.clone(), o))
    }
}

/// Iterator over reflected builtin resources, created by [`ShaderResources::builtin_resources_for_type`].
pub struct BuiltinResourceIter<'a>(
    PhantomCompiler<'a>,
    slice::Iter<'a, spvc_reflected_builtin_resource>,
);

impl<'a> Iterator for BuiltinResourceIter<'a> {
    type Item = BuiltinResource<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        self.1
            .next()
            .map(|o| BuiltinResource::from_raw(self.0.clone(), o))
    }
}

/// Description of a shader resource.
#[derive(Debug)]
pub struct Resource<'a> {
    /// A handle to the variable this resource points to.
    pub id: Handle<VariableId>,
    /// A handle to the base type of this resource.
    pub base_type_id: Handle<TypeId>,
    /// A handle to the type of this resource, often a pointer
    /// or array.
    pub type_id: Handle<TypeId>,
    /// The name of this resource.
    pub name: ContextStr<'a>,
}

impl<'a> Resource<'a> {
    fn from_raw(comp: PhantomCompiler<'a>, value: &'a spvc_reflected_resource) -> Self {
        Self {
            id: comp.create_handle(value.id),
            base_type_id: comp.create_handle(value.base_type_id),
            type_id: comp.create_handle(value.type_id),
            // There should never be invalid UTF-8 in a shader.
            // as per SPIR-V spec: The character set is Unicode in the UTF-8 encoding scheme.
            // so this will be free 100% of the time.
            name: unsafe { ContextStr::from_ptr(value.name, comp.ctx.clone()) },
        }
    }
}

impl<'a, 'b> From<&'a Resource<'b>> for Handle<VariableId> {
    fn from(value: &'a Resource<'b>) -> Self {
        value.id
    }
}

impl From<Resource<'_>> for Handle<VariableId> {
    fn from(value: Resource<'_>) -> Self {
        value.id
    }
}

impl Sealed for Resource<'_> {}
impl ToStatic for Resource<'_> {
    type Static<'a>

    = Resource<'static>
    where
        'a: 'static;

    fn to_static(&self) -> Self::Static<'static> {
        Resource {
            id: self.id,
            base_type_id: self.base_type_id,
            type_id: self.type_id,
            name: ContextStr::from_string(self.name.to_string()),
        }
    }
}

/// Cloning a [`Resource`] will detach its lifetime from the [`crate::SpirvCrossContext`] context
/// from which it originated.
impl Clone for Resource<'_> {
    fn clone(&self) -> Resource<'static> {
        self.to_static()
    }
}

/// Description of a built-in shader resource.
#[derive(Debug)]
pub struct BuiltinResource<'a> {
    /// The SPIR-V built-in for this resource.
    pub builtin: spirv::BuiltIn,
    /// A handle to the type ID of the value.
    pub value_type_id: Handle<TypeId>,
    /// The resource data for this built-in resource.
    pub resource: Resource<'a>,
}

impl<'a, 'b> From<&'a BuiltinResource<'b>> for Handle<VariableId> {
    fn from(value: &'a BuiltinResource<'b>) -> Self {
        value.resource.id
    }
}

impl From<BuiltinResource<'_>> for Handle<VariableId> {
    fn from(value: BuiltinResource<'_>) -> Self {
        value.resource.id
    }
}

impl<'a> BuiltinResource<'a> {
    fn from_raw(comp: PhantomCompiler<'a>, value: &'a spvc_reflected_builtin_resource) -> Self {
        Self {
            builtin: value.builtin,
            value_type_id: comp.create_handle(value.value_type_id),
            resource: Resource::from_raw(comp, &value.resource),
        }
    }
}

impl Sealed for BuiltinResource<'_> {}
impl ToStatic for BuiltinResource<'_> {
    type Static<'a>

    = BuiltinResource<'static>
    where
        'a: 'static;

    fn to_static(&self) -> Self::Static<'static> {
        let resource: BuiltinResource<'static> = BuiltinResource {
            builtin: self.builtin,
            value_type_id: self.value_type_id,
            resource: self.resource.to_static(),
        };
        resource
    }
}

/// Cloning a [`BuiltinResource`] will detach its lifetime from the [`crate::SpirvCrossContext`] context
/// from which it originated.
impl Clone for BuiltinResource<'_> {
    fn clone(&self) -> BuiltinResource<'static> {
        self.to_static()
    }
}

/// All SPIR-V resources declared in the module.
#[derive(Debug)]
pub struct AllResources<'a> {
    /// Uniform buffer (UBOs) resources.
    pub uniform_buffers: Vec<Resource<'a>>,
    /// Storage buffer (SSBO) resources.
    pub storage_buffers: Vec<Resource<'a>>,
    /// Shader stage inputs.
    pub stage_inputs: Vec<Resource<'a>>,
    /// Shader stage outputs.
    pub stage_outputs: Vec<Resource<'a>>,
    /// Shader subpass inputs.
    pub subpass_inputs: Vec<Resource<'a>>,
    /// Storage images (i.e. `imageND`).
    pub storage_images: Vec<Resource<'a>>,
    /// Sampled images (i.e. `samplerND`).
    pub sampled_images: Vec<Resource<'a>>,
    /// Atomic counters.
    pub atomic_counters: Vec<Resource<'a>>,
    /// Acceleration structures.
    pub acceleration_structures: Vec<Resource<'a>>,
    /// Legacy OpenGL plain uniforms.
    pub gl_plain_uniforms: Vec<Resource<'a>>,

    /// Push constant buffers.
    ///
    /// There is only ever at most one push constant buffer,
    /// but this is multiplicit in case this restriction is lifted.
    pub push_constant_buffers: Vec<Resource<'a>>,
    /// Record buffers.
    pub shader_record_buffers: Vec<Resource<'a>>,

    /// For Vulkan GLSL and HLSL sources, split images (i.e. `textureND`).
    pub separate_images: Vec<Resource<'a>>,

    /// For Vulkan GLSL and HLSL sources, split samplers (i.e. `sampler`).
    pub separate_samplers: Vec<Resource<'a>>,

    /// Shader built-in inputs.
    pub builtin_inputs: Vec<BuiltinResource<'a>>,
    /// Shader built-in outputs.
    pub builtin_outputs: Vec<BuiltinResource<'a>>,
}

impl Sealed for AllResources<'_> {}
impl ToStatic for AllResources<'_> {
    type Static<'a>

    = AllResources<'static>
    where
        'a: 'static;

    fn to_static(&self) -> Self::Static<'static> {
        AllResources {
            uniform_buffers: self
                .uniform_buffers
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            storage_buffers: self
                .storage_buffers
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            stage_inputs: self.stage_inputs.iter().map(ToStatic::to_static).collect(),
            stage_outputs: self.stage_outputs.iter().map(ToStatic::to_static).collect(),
            subpass_inputs: self
                .subpass_inputs
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            storage_images: self
                .storage_images
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            sampled_images: self
                .sampled_images
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            atomic_counters: self
                .atomic_counters
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            acceleration_structures: self
                .acceleration_structures
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            gl_plain_uniforms: self
                .gl_plain_uniforms
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            push_constant_buffers: self
                .push_constant_buffers
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            shader_record_buffers: self
                .shader_record_buffers
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            separate_images: self
                .separate_images
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            separate_samplers: self
                .separate_samplers
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            builtin_inputs: self
                .builtin_inputs
                .iter()
                .map(ToStatic::to_static)
                .collect(),
            builtin_outputs: self
                .builtin_outputs
                .iter()
                .map(ToStatic::to_static)
                .collect(),
        }
    }
}

/// Cloning a [`AllResources`] will detach its lifetime from the [`crate::SpirvCrossContext`] context
/// from which it originated.
impl Clone for AllResources<'_> {
    fn clone(&self) -> AllResources<'static> {
        self.to_static()
    }
}

impl<'a> ShaderResources<'a> {
    /// Get an iterator for all resources of the given type.
    pub fn resources_for_type(&self, ty: ResourceType) -> error::Result<ResourceIter<'a>> {
        // SAFETY: 'a is OK to return here:
        // https://github.com/KhronosGroup/SPIRV-Cross/blob/6a1fb66eef1bdca14acf7d0a51a3f883499d79f0/spirv_cross_c.cpp#L1802
        let mut count = 0;
        let mut out = std::ptr::null();
        unsafe {
            spirv_cross_sys::spvc_resources_get_resource_list_for_type(
                self.0.as_ptr(),
                ty,
                &mut out,
                &mut count,
            )
            .ok(self)?;
        }

        let slice = unsafe { std::slice::from_raw_parts(out, count) };

        Ok(ResourceIter(self.1.clone(), slice.iter()))
    }

    /// Get an iterator for all builtin resources of the given type.
    pub fn builtin_resources_for_type(
        &self,
        ty: BuiltinResourceType,
    ) -> error::Result<BuiltinResourceIter<'a>> {
        let mut count = 0;
        let mut out = std::ptr::null();

        // SAFETY: 'a is OK to return here:
        // https://github.com/KhronosGroup/SPIRV-Cross/blob/6a1fb66eef1bdca14acf7d0a51a3f883499d79f0/spirv_cross_c.cpp#L1826
        unsafe {
            spirv_cross_sys::spvc_resources_get_builtin_resource_list_for_type(
                self.0.as_ptr(),
                ty,
                &mut out,
                &mut count,
            )
            .ok(self)?;
        }

        let slice = unsafe { std::slice::from_raw_parts(out, count) };

        Ok(BuiltinResourceIter(self.1.clone(), slice.iter()))
    }

    /// Get all resources declared in the shader.
    #[rustfmt::skip]
    pub fn all_resources(&self) -> error::Result<AllResources<'a>> {
        Ok(AllResources {
                uniform_buffers: self.resources_for_type(ResourceType::UniformBuffer)?.collect(),
                storage_buffers: self.resources_for_type(ResourceType::StorageBuffer)?.collect(),
                stage_inputs: self.resources_for_type(ResourceType::StageInput)?.collect(),
                stage_outputs: self.resources_for_type(ResourceType::StageOutput)?.collect(),
                subpass_inputs: self.resources_for_type(ResourceType::SubpassInput)?.collect(),
                storage_images: self.resources_for_type(ResourceType::StorageImage)?.collect(),
                sampled_images: self.resources_for_type(ResourceType::SampledImage)?.collect(),
                atomic_counters: self.resources_for_type(ResourceType::AtomicCounter)?.collect(),
                acceleration_structures: self.resources_for_type(ResourceType::AccelerationStructure)?.collect(),
                gl_plain_uniforms: self.resources_for_type(ResourceType::GlPlainUniform)?.collect(),
                push_constant_buffers: self.resources_for_type(ResourceType::PushConstant)?.collect(),
                shader_record_buffers: self.resources_for_type(ResourceType::ShaderRecordBuffer)?.collect(),
                separate_images: self.resources_for_type(ResourceType::SeparateImage)?.collect(),
                separate_samplers: self.resources_for_type(ResourceType::SeparateSamplers)?.collect(),
                builtin_inputs: self.builtin_resources_for_type(BuiltinResourceType::StageInput)?.collect(),
                builtin_outputs: self.builtin_resources_for_type(BuiltinResourceType::StageOutput)?.collect(),
        })
    }
}