This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit b578433e37
13 changed files with 784842 additions and 0 deletions

View file

@ -0,0 +1,72 @@
using CommunityToolkit.HighPerformance;
using CommunityToolkit.HighPerformance.Buffers;
namespace Brutal.ShaderCApi;
using String16 = string;
using StringView8 = ReadOnlySpan<byte>;
/// <summary>
/// A helper struct to convert a set of strings into a single contiguous UTF-8 encoded byte array, with a null terminator after each string.
/// </summary>
internal readonly ref struct BespokeUtf8Encoder : IDisposable
{
private readonly SpanOwner<byte> _storage;
private readonly Span<int> _indexToEndLookup;
private readonly Span<byte> _content;
public BespokeUtf8Encoder(String16 i1, String16 i2, out StringView8 o1, out StringView8 o2)
: this(i1, i2)
{
o1 = Read(0);
o2 = Read(1);
}
public BespokeUtf8Encoder(
String16 i1,
String16 i2,
String16 i3,
out StringView8 o1,
out StringView8 o2,
out StringView8 o3
)
: this(i1, i2, i3)
{
o1 = Read(0);
o2 = Read(1);
o3 = Read(2);
}
private BespokeUtf8Encoder(params ReadOnlySpan<String16> strings)
{
// work out how many bytes we're going to need to encode everything (strings + lookup table)
var headerByteCount = (int)ByteSize.Of<int>(strings.Length);
var contentByteCount = 0;
foreach (var t in strings)
contentByteCount += Utf8.GetMaxByteCount(t.Length) + 1;
// allocate the storage, then carve it into the lookup table and the content region
_storage = SpanOwner<byte>.Allocate(headerByteCount + contentByteCount);
_indexToEndLookup = _storage.Span[..headerByteCount].Cast<byte, int>();
_content = _storage.Span[headerByteCount..];
var offset = 0;
for (var index = 0; index < strings.Length; index++)
{
offset += Utf8.GetBytes(strings[index], _content[offset..]);
_content[offset] = 0;
_indexToEndLookup[index] = offset++;
}
}
private StringView8 Read(int index)
{
// grab the end index first, also serves as a bound check
var endIndex = _indexToEndLookup[index];
// the start index is the previous string's NUL terminator + 1, or zero if this is the first string
var startIndex = index > 0 ? _indexToEndLookup[index - 1] + 1 : 0;
return _content[startIndex..endIndex];
}
public void Dispose() => _storage.Dispose();
}

View file

@ -0,0 +1,484 @@
namespace Brutal.ShaderCApi
{
public enum TargetEnv : uint
{
Vulkan, // SPIR-V under Vulkan semantics
Opengl, // SPIR-V under OpenGL semantics
OpenglCompat, // SPIR-V under OpenGL semantics, including compatibility profile functions
[Obsolete("Deprecated, SPIR-V under WebGPU semantics")]
Webgpu, // Deprecated, SPIR-V under WebGPU semantics
Default = Vulkan,
}
public enum EnvVersion : uint
{
/// For Vulkan, use Vulkan's mapping of version numbers to integers.
/// See vulkan.h
Vulkan_1_0 = ((1u << 22)),
/// For Vulkan, use Vulkan's mapping of version numbers to integers.
/// See vulkan.h
Vulkan_1_1 = ((1u << 22) | (1 << 12)),
/// For Vulkan, use Vulkan's mapping of version numbers to integers.
/// See vulkan.h
Vulkan_1_2 = ((1u << 22) | (2 << 12)),
/// For Vulkan, use Vulkan's mapping of version numbers to integers.
/// See vulkan.h
Vulkan_1_3 = ((1u << 22) | (3 << 12)),
/// For Vulkan, use Vulkan's mapping of version numbers to integers.
/// See vulkan.h
Vulkan_1_4 = ((1u << 22) | (4 << 12)),
/// For OpenGL, use the number from #version in shaders.
/// TODO(dneto): Currently no difference between OpenGL 4.5 and 4.6.
/// See glslang/Standalone/Standalone.cpp
/// TODO(dneto): Glslang doesn't accept a OpenGL client version of 460.
Opengl_4_5 = 450,
[Obsolete("Deprecated, WebGPU env never defined versions")]
Webgpu, // Deprecated, WebGPU env never defined versions
}
/// The known versions of SPIR-V.
public enum SpirvVersion : uint
{
/// Use the values used for word 1 of a SPIR-V binary:
/// - bits 24 to 31: zero
/// - bits 16 to 23: major version number
/// - bits 8 to 15: minor version number
/// - bits 0 to 7: zero
_1_0 = 0x010000u,
/// Use the values used for word 1 of a SPIR-V binary:
/// - bits 24 to 31: zero
/// - bits 16 to 23: major version number
/// - bits 8 to 15: minor version number
/// - bits 0 to 7: zero
_1_1 = 0x010100u,
/// Use the values used for word 1 of a SPIR-V binary:
/// - bits 24 to 31: zero
/// - bits 16 to 23: major version number
/// - bits 8 to 15: minor version number
/// - bits 0 to 7: zero
_1_2 = 0x010200u,
/// Use the values used for word 1 of a SPIR-V binary:
/// - bits 24 to 31: zero
/// - bits 16 to 23: major version number
/// - bits 8 to 15: minor version number
/// - bits 0 to 7: zero
_1_3 = 0x010300u,
/// Use the values used for word 1 of a SPIR-V binary:
/// - bits 24 to 31: zero
/// - bits 16 to 23: major version number
/// - bits 8 to 15: minor version number
/// - bits 0 to 7: zero
_1_4 = 0x010400u,
/// Use the values used for word 1 of a SPIR-V binary:
/// - bits 24 to 31: zero
/// - bits 16 to 23: major version number
/// - bits 8 to 15: minor version number
/// - bits 0 to 7: zero
_1_5 = 0x010500u,
/// Use the values used for word 1 of a SPIR-V binary:
/// - bits 24 to 31: zero
/// - bits 16 to 23: major version number
/// - bits 8 to 15: minor version number
/// - bits 0 to 7: zero
_1_6 = 0x010600u,
}
/// Indicate the status of a compilation.
public enum CompilationStatus : uint
{
Success = 0,
InvalidStage = 1, // error stage deduction
CompilationError = 2,
InternalError = 3, // unexpected failure
NullResultObject = 4,
InvalidAssembly = 5,
ValidationError = 6,
TransformationError = 7,
ConfigurationError = 8,
}
/// Source language kind.
public enum SourceLanguage : uint
{
Glsl,
Hlsl,
}
public enum ShaderKind : uint
{
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
VertexShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
FragmentShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
ComputeShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
GeometryShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
TessControlShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
TessEvaluationShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
GlslVertexShader = VertexShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
GlslFragmentShader = FragmentShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
GlslComputeShader = ComputeShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
GlslGeometryShader = GeometryShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
GlslTessControlShader = TessControlShader,
/// Forced shader kinds. These shader kinds force the compiler to compile the
/// source code as the specified kind of shader.
GlslTessEvaluationShader = TessEvaluationShader,
/// Deduce the shader kind from #pragma annotation in the source code. Compiler
/// will emit error if #pragma annotation is not found.
GlslInferFromSource,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultVertexShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultFragmentShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultComputeShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultGeometryShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultTessControlShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultTessEvaluationShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
SpirvAssembly,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
RayGenShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
AnyHitShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
ClosestHitShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
MissShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
IntersectionShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
CallableShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslRayGenShader = RayGenShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslAnyHitShader = AnyHitShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslClosestHitShader = ClosestHitShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslMissShader = MissShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslIntersectionShader = IntersectionShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslCallableShader = CallableShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultRayGenShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultAnyHitShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultClosestHitShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultMissShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultIntersectionShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultCallableShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
TaskShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
MeshShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslTaskShader = TaskShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslMeshShader = MeshShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultTaskShader,
/// Default shader kinds. Compiler will fall back to compile the source code as
/// the specified kind of shader when #pragma annotation is not found in the
/// source code.
GlslDefaultMeshShader,
}
public enum Profile : uint
{
None, // Used if and only if GLSL version did not specify profiles.
Core,
Compatibility, // Disabled. This generates an error
Es,
}
/// Optimization level.
public enum OptimizationLevel : uint
{
Zero, // no optimization
Size, // optimize towards reducing code size
Performance, // optimize towards performance
}
/// Resource limits.
public enum Limit : uint
{
MaxLights,
MaxClipPlanes,
MaxTextureUnits,
MaxTextureCoords,
MaxVertexAttribs,
MaxVertexUniformComponents,
MaxVaryingFloats,
MaxVertexTextureImageUnits,
MaxCombinedTextureImageUnits,
MaxTextureImageUnits,
MaxFragmentUniformComponents,
MaxDrawBuffers,
MaxVertexUniformVectors,
MaxVaryingVectors,
MaxFragmentUniformVectors,
MaxVertexOutputVectors,
MaxFragmentInputVectors,
MinProgramTexelOffset,
MaxProgramTexelOffset,
MaxClipDistances,
MaxComputeWorkGroupCountX,
MaxComputeWorkGroupCountY,
MaxComputeWorkGroupCountZ,
MaxComputeWorkGroupSizeX,
MaxComputeWorkGroupSizeY,
MaxComputeWorkGroupSizeZ,
MaxComputeUniformComponents,
MaxComputeTextureImageUnits,
MaxComputeImageUniforms,
MaxComputeAtomicCounters,
MaxComputeAtomicCounterBuffers,
MaxVaryingComponents,
MaxVertexOutputComponents,
MaxGeometryInputComponents,
MaxGeometryOutputComponents,
MaxFragmentInputComponents,
MaxImageUnits,
MaxCombinedImageUnitsAndFragmentOutputs,
MaxCombinedShaderOutputResources,
MaxImageSamples,
MaxVertexImageUniforms,
MaxTessControlImageUniforms,
MaxTessEvaluationImageUniforms,
MaxGeometryImageUniforms,
MaxFragmentImageUniforms,
MaxCombinedImageUniforms,
MaxGeometryTextureImageUnits,
MaxGeometryOutputVertices,
MaxGeometryTotalOutputComponents,
MaxGeometryUniformComponents,
MaxGeometryVaryingComponents,
MaxTessControlInputComponents,
MaxTessControlOutputComponents,
MaxTessControlTextureImageUnits,
MaxTessControlUniformComponents,
MaxTessControlTotalOutputComponents,
MaxTessEvaluationInputComponents,
MaxTessEvaluationOutputComponents,
MaxTessEvaluationTextureImageUnits,
MaxTessEvaluationUniformComponents,
MaxTessPatchComponents,
MaxPatchVertices,
MaxTessGenLevel,
MaxViewports,
MaxVertexAtomicCounters,
MaxTessControlAtomicCounters,
MaxTessEvaluationAtomicCounters,
MaxGeometryAtomicCounters,
MaxFragmentAtomicCounters,
MaxCombinedAtomicCounters,
MaxAtomicCounterBindings,
MaxVertexAtomicCounterBuffers,
MaxTessControlAtomicCounterBuffers,
MaxTessEvaluationAtomicCounterBuffers,
MaxGeometryAtomicCounterBuffers,
MaxFragmentAtomicCounterBuffers,
MaxCombinedAtomicCounterBuffers,
MaxAtomicCounterBufferSize,
MaxTransformFeedbackBuffers,
MaxTransformFeedbackInterleavedComponents,
MaxCullDistances,
MaxCombinedClipAndCullDistances,
MaxSamples,
MaxMeshOutputVerticesNv,
MaxMeshOutputPrimitivesNv,
MaxMeshWorkGroupSizeXNv,
MaxMeshWorkGroupSizeYNv,
MaxMeshWorkGroupSizeZNv,
MaxTaskWorkGroupSizeXNv,
MaxTaskWorkGroupSizeYNv,
MaxTaskWorkGroupSizeZNv,
MaxMeshViewCountNv,
MaxMeshOutputVerticesExt,
MaxMeshOutputPrimitivesExt,
MaxMeshWorkGroupSizeXExt,
MaxMeshWorkGroupSizeYExt,
MaxMeshWorkGroupSizeZExt,
MaxTaskWorkGroupSizeXExt,
MaxTaskWorkGroupSizeYExt,
MaxTaskWorkGroupSizeZExt,
MaxMeshViewCountExt,
MaxDualSourceDrawBuffersExt,
}
/// Uniform resource kinds.
/// In Vulkan, uniform resources are bound to the pipeline via descriptors
/// with numbered bindings and sets.
public enum UniformKind : uint
{
/// Image and image buffer.
Image,
/// Pure sampler.
Sampler,
/// Sampled texture in GLSL, and Shader Resource View in HLSL.
Texture,
/// Uniform Buffer Object (UBO) in GLSL. Cbuffer in HLSL.
Buffer,
/// Shader Storage Buffer Object (SSBO) in GLSL.
StorageBuffer,
/// Unordered Access View, in HLSL. (Writable storage image or storage
/// buffer.)
UnorderedAccessView,
}
/// The kinds of include requests.
public enum IncludeType : uint
{
Relative, // E.g. #include "source"
Standard, // E.g. #include <source>
}
}

View file

@ -0,0 +1,265 @@
using System.Runtime.InteropServices;
namespace Brutal.ShaderCApi
{
public static partial class ShaderC
{
public static unsafe partial class PInvoke
{
[LibraryImport("shaderc")]
public static partial Compiler shaderc_compiler_initialize();
[LibraryImport("shaderc")]
public static partial void shaderc_compiler_release(Compiler arg);
[LibraryImport("shaderc")]
public static partial CompileOptions shaderc_compile_options_initialize();
[LibraryImport("shaderc")]
public static partial CompileOptions shaderc_compile_options_clone(CompileOptions options);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_release(CompileOptions options);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_add_macro_definition(
CompileOptions options,
byte* name,
ByteSize64 nameLength,
byte* value,
ByteSize64 valueLength
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_source_language(
CompileOptions options,
SourceLanguage lang
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_generate_debug_info(CompileOptions options);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_emit_nonsemantic_shader_debug_info(
CompileOptions options
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_optimization_level(
CompileOptions options,
OptimizationLevel level
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_forced_version_profile(
CompileOptions options,
int version,
Profile profile
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_include_callbacks(
CompileOptions options,
IncludeResolveFn resolver,
IncludeResultReleaseFn resultReleaser,
void* userData
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_suppress_warnings(CompileOptions options);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_target_env(
CompileOptions options,
TargetEnv target,
uint version
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_target_spirv(
CompileOptions options,
SpirvVersion version
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_warnings_as_errors(CompileOptions options);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_limit(
CompileOptions options,
Limit limit,
int value
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_auto_bind_uniforms(
CompileOptions options,
Bool8 autoBind
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_auto_combined_image_sampler(
CompileOptions options,
Bool8 upgrade
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_hlsl_io_mapping(
CompileOptions options,
Bool8 hlslIomap
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_hlsl_offsets(
CompileOptions options,
Bool8 hlslOffsets
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_binding_base(
CompileOptions options,
UniformKind kind,
uint @base
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_binding_base_for_stage(
CompileOptions options,
ShaderKind shaderKind,
UniformKind kind,
uint @base
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_preserve_bindings(
CompileOptions options,
Bool8 preserveBindings
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_max_id_bound(
CompileOptions options,
uint maxIdBound
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_auto_map_locations(
CompileOptions options,
Bool8 autoMap
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_hlsl_register_set_and_binding_for_stage(
CompileOptions options,
ShaderKind shaderKind,
byte* reg,
byte* set,
byte* binding
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_hlsl_register_set_and_binding(
CompileOptions options,
byte* reg,
byte* set,
byte* binding
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_hlsl_functionality1(
CompileOptions options,
Bool8 enable
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_hlsl_16bit_types(
CompileOptions options,
Bool8 enable
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_vulkan_rules_relaxed(
CompileOptions options,
Bool8 enable
);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_invert_y(CompileOptions options, Bool8 enable);
[LibraryImport("shaderc")]
public static partial void shaderc_compile_options_set_nan_clamp(CompileOptions options, Bool8 enable);
[LibraryImport("shaderc")]
public static partial CompilationResult shaderc_compile_into_spv(
Compiler compiler,
byte* sourceText,
ByteSize64 sourceTextSize,
ShaderKind shaderKind,
byte* inputFileName,
byte* entryPointName,
CompileOptions additionalOptions
);
[LibraryImport("shaderc")]
public static partial CompilationResult shaderc_compile_into_spv_assembly(
Compiler compiler,
byte* sourceText,
ByteSize64 sourceTextSize,
ShaderKind shaderKind,
byte* inputFileName,
byte* entryPointName,
CompileOptions additionalOptions
);
[LibraryImport("shaderc")]
public static partial CompilationResult shaderc_compile_into_preprocessed_text(
Compiler compiler,
byte* sourceText,
ByteSize64 sourceTextSize,
ShaderKind shaderKind,
byte* inputFileName,
byte* entryPointName,
CompileOptions additionalOptions
);
[LibraryImport("shaderc")]
public static partial CompilationResult shaderc_assemble_into_spv(
Compiler compiler,
byte* sourceAssembly,
ByteSize64 sourceAssemblySize,
CompileOptions additionalOptions
);
[LibraryImport("shaderc")]
public static partial void shaderc_result_release(CompilationResult result);
[LibraryImport("shaderc")]
public static partial ByteSize64 shaderc_result_get_length(CompilationResult result);
[LibraryImport("shaderc")]
public static partial ByteSize64 shaderc_result_get_num_warnings(CompilationResult result);
[LibraryImport("shaderc")]
public static partial ByteSize64 shaderc_result_get_num_errors(CompilationResult result);
[LibraryImport("shaderc")]
public static partial CompilationStatus shaderc_result_get_compilation_status(CompilationResult arg);
[LibraryImport("shaderc")]
public static partial byte* shaderc_result_get_bytes(CompilationResult result);
[LibraryImport(
"shaderc",
StringMarshalling = StringMarshalling.Custom,
StringMarshallingCustomType = typeof(Brutal.Interop.InteropStringMarshaller)
)]
public static partial string shaderc_result_get_error_message(CompilationResult result);
[LibraryImport("shaderc")]
public static partial void shaderc_get_spv_version(uint* version, uint* revision);
[LibraryImport("shaderc")]
public static partial Bool8 shaderc_parse_version_profile(byte* str, int* version, Profile* profile);
}
}
}

View file

@ -0,0 +1,288 @@
using System.Runtime.InteropServices.Marshalling;
using Brutal.Interop;
namespace Brutal.ShaderCApi
{
[InteropHandle]
public readonly unsafe partial struct Compiler : IDisposable
{
public void Dispose() => ShaderC.PInvoke.shaderc_compiler_release(this);
public CompilationResult CompileIntoSpv(
ReadOnlySpan<byte> sourceText,
ShaderKind shaderKind,
RefString8 inputFileName,
RefString8 entryPointName,
CompileOptions additionalOptions
)
{
fixed (byte* sourceTextFixed = sourceText)
{
fixed (byte* inputFileNameFixed = inputFileName)
{
fixed (byte* entryPointNameFixed = entryPointName)
{
return ShaderC.PInvoke.shaderc_compile_into_spv(
this,
sourceTextFixed,
ByteSize.Of(sourceText),
shaderKind,
inputFileNameFixed,
entryPointNameFixed,
additionalOptions
);
}
}
}
}
public CompilationResult CompileIntoSpvAssembly(
ReadOnlySpan<byte> sourceText,
ShaderKind shaderKind,
RefString8 inputFileName,
RefString8 entryPointName,
CompileOptions additionalOptions
)
{
fixed (byte* sourceTextFixed = sourceText)
{
fixed (byte* inputFileNameFixed = inputFileName)
{
fixed (byte* entryPointNameFixed = entryPointName)
{
return ShaderC.PInvoke.shaderc_compile_into_spv_assembly(
this,
sourceTextFixed,
ByteSize.Of(sourceText),
shaderKind,
inputFileNameFixed,
entryPointNameFixed,
additionalOptions
);
}
}
}
}
public CompilationResult CompileIntoPreprocessedText(
ReadOnlySpan<byte> sourceText,
ShaderKind shaderKind,
RefString8 inputFileName,
RefString8 entryPointName,
CompileOptions additionalOptions
)
{
fixed (byte* sourceTextFixed = sourceText)
{
fixed (byte* inputFileNameFixed = inputFileName)
{
fixed (byte* entryPointNameFixed = entryPointName)
{
return ShaderC.PInvoke.shaderc_compile_into_preprocessed_text(
this,
sourceTextFixed,
ByteSize.Of(sourceText),
shaderKind,
inputFileNameFixed,
entryPointNameFixed,
additionalOptions
);
}
}
}
}
public CompilationResult AssembleIntoSpv(ReadOnlySpan<byte> sourceAssembly, CompileOptions additionalOptions)
{
fixed (byte* sourceAssemblyFixed = sourceAssembly)
{
return ShaderC.PInvoke.shaderc_assemble_into_spv(
this,
sourceAssemblyFixed,
ByteSize.Of(sourceAssembly),
additionalOptions
);
}
}
}
[InteropHandle]
public readonly unsafe partial struct CompileOptions : IDisposable
{
public CompileOptions Clone() => ShaderC.PInvoke.shaderc_compile_options_clone(this);
public void Dispose() => ShaderC.PInvoke.shaderc_compile_options_release(this);
public void AddMacroDefinition(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
{
fixed (byte* nameFixed = name)
{
fixed (byte* valueFixed = value)
{
ShaderC.PInvoke.shaderc_compile_options_add_macro_definition(
this,
nameFixed,
ByteSize.Of(name),
valueFixed,
ByteSize.Of(value)
);
}
}
}
public void SetSourceLanguage(SourceLanguage lang) =>
ShaderC.PInvoke.shaderc_compile_options_set_source_language(this, lang);
public void SetGenerateDebugInfo() => ShaderC.PInvoke.shaderc_compile_options_set_generate_debug_info(this);
public void SetEmitNonsemanticShaderDebugInfo() =>
ShaderC.PInvoke.shaderc_compile_options_set_emit_nonsemantic_shader_debug_info(this);
public void SetOptimizationLevel(OptimizationLevel level) =>
ShaderC.PInvoke.shaderc_compile_options_set_optimization_level(this, level);
public void SetForcedVersionProfile(int version, Profile profile) =>
ShaderC.PInvoke.shaderc_compile_options_set_forced_version_profile(this, version, profile);
public void SetIncludeCallbacks(
IncludeResolveFn resolver,
IncludeResultReleaseFn resultReleaser,
void* userData
) => ShaderC.PInvoke.shaderc_compile_options_set_include_callbacks(this, resolver, resultReleaser, userData);
public void SetSuppressWarnings() => ShaderC.PInvoke.shaderc_compile_options_set_suppress_warnings(this);
public void SetTargetEnv(TargetEnv target, uint version) =>
ShaderC.PInvoke.shaderc_compile_options_set_target_env(this, target, version);
public void SetTargetSpirv(SpirvVersion version) =>
ShaderC.PInvoke.shaderc_compile_options_set_target_spirv(this, version);
public void SetWarningsAsErrors() => ShaderC.PInvoke.shaderc_compile_options_set_warnings_as_errors(this);
public void SetLimit(Limit limit, int value) =>
ShaderC.PInvoke.shaderc_compile_options_set_limit(this, limit, value);
public void SetAutoBindUniforms(Bool8 autoBind) =>
ShaderC.PInvoke.shaderc_compile_options_set_auto_bind_uniforms(this, autoBind);
public void SetAutoCombinedImageSampler(Bool8 upgrade) =>
ShaderC.PInvoke.shaderc_compile_options_set_auto_combined_image_sampler(this, upgrade);
public void SetHlslIoMapping(Bool8 hlslIomap) =>
ShaderC.PInvoke.shaderc_compile_options_set_hlsl_io_mapping(this, hlslIomap);
public void SetHlslOffsets(Bool8 hlslOffsets) =>
ShaderC.PInvoke.shaderc_compile_options_set_hlsl_offsets(this, hlslOffsets);
public void SetBindingBase(UniformKind kind, uint @base) =>
ShaderC.PInvoke.shaderc_compile_options_set_binding_base(this, kind, @base);
public void SetBindingBaseForStage(ShaderKind shaderKind, UniformKind kind, uint @base) =>
ShaderC.PInvoke.shaderc_compile_options_set_binding_base_for_stage(this, shaderKind, kind, @base);
public void SetPreserveBindings(Bool8 preserveBindings) =>
ShaderC.PInvoke.shaderc_compile_options_set_preserve_bindings(this, preserveBindings);
public void SetMaxIdBound(uint maxIdBound) =>
ShaderC.PInvoke.shaderc_compile_options_set_max_id_bound(this, maxIdBound);
public void SetAutoMapLocations(Bool8 autoMap) =>
ShaderC.PInvoke.shaderc_compile_options_set_auto_map_locations(this, autoMap);
public void SetHlslRegisterSetAndBindingForStage(
ShaderKind shaderKind,
RefString8 reg,
RefString8 set,
RefString8 binding
)
{
fixed (byte* regFixed = reg)
{
fixed (byte* setFixed = set)
{
fixed (byte* bindingFixed = binding)
{
ShaderC.PInvoke.shaderc_compile_options_set_hlsl_register_set_and_binding_for_stage(
this,
shaderKind,
regFixed,
setFixed,
bindingFixed
);
}
}
}
}
public void SetHlslRegisterSetAndBinding(RefString8 reg, RefString8 set, RefString8 binding)
{
fixed (byte* regFixed = reg)
{
fixed (byte* setFixed = set)
{
fixed (byte* bindingFixed = binding)
{
ShaderC.PInvoke.shaderc_compile_options_set_hlsl_register_set_and_binding(
this,
regFixed,
setFixed,
bindingFixed
);
}
}
}
}
public void SetHlslFunctionality1(Bool8 enable) =>
ShaderC.PInvoke.shaderc_compile_options_set_hlsl_functionality1(this, enable);
public void SetHlsl16BitTypes(Bool8 enable) =>
ShaderC.PInvoke.shaderc_compile_options_set_hlsl_16bit_types(this, enable);
public void SetVulkanRulesRelaxed(Bool8 enable) =>
ShaderC.PInvoke.shaderc_compile_options_set_vulkan_rules_relaxed(this, enable);
public void SetInvertY(Bool8 enable) => ShaderC.PInvoke.shaderc_compile_options_set_invert_y(this, enable);
public void SetNanClamp(Bool8 enable) => ShaderC.PInvoke.shaderc_compile_options_set_nan_clamp(this, enable);
}
/// An include result.
public unsafe partial struct IncludeResult
{
/// The name of the source file. The name should be fully resolved
/// in the sense that it should be a unique name in the context of the
/// includer. For example, if the includer maps source names to files in
/// a filesystem, then this name should be the absolute path of the file.
/// For a failed inclusion, this string is empty.
public byte* SourceName;
public ByteSize64 SourceNameLength;
/// The text contents of the source file in the normal case.
/// For a failed inclusion, this contains the error message.
public byte* Content;
public ByteSize64 ContentLength;
/// User data to be passed along with this request.
public void* UserData;
}
[InteropHandle]
public readonly unsafe partial struct CompilationResult : IDisposable
{
public void Dispose() => ShaderC.PInvoke.shaderc_result_release(this);
public ByteSize64 GetLength() => ShaderC.PInvoke.shaderc_result_get_length(this);
public ByteSize64 GetNumWarnings() => ShaderC.PInvoke.shaderc_result_get_num_warnings(this);
public ByteSize64 GetNumErrors() => ShaderC.PInvoke.shaderc_result_get_num_errors(this);
public CompilationStatus GetCompilationStatus() => ShaderC.PInvoke.shaderc_result_get_compilation_status(this);
public byte* GetBytes() => ShaderC.PInvoke.shaderc_result_get_bytes(this);
public string GetErrorMessage() => ShaderC.PInvoke.shaderc_result_get_error_message(this);
}
}

View file

@ -0,0 +1,3 @@
// Global using directives
global using Brutal.Strings;

297
Brutal.ShaderC/HighLevel.cs Normal file
View file

@ -0,0 +1,297 @@
namespace Brutal.ShaderCApi;
/// <summary>
/// Extension methods providing a high-level throwing API over the generated <see cref="Compiler"/> surface.
/// </summary>
public static class CompilerExtensions
{
/// <summary>
/// Returns <paramref name="result"/> unchanged when compilation succeeded; otherwise throws the
/// typed <see cref="ShaderException"/> that corresponds to the <see cref="CompilationStatus"/>.
/// </summary>
/// <remarks>
/// <para>
/// This method is fluent and does <b>not</b> dispose <paramref name="result"/>; ownership remains
/// with the caller regardless of whether it succeeds or throws.
/// </para>
/// </remarks>
/// <param name="result">The compilation result to inspect.</param>
/// <returns><paramref name="result"/> when <see cref="CompilationStatus.Success"/>.</returns>
/// <exception cref="ShaderInvalidStageException">
/// Thrown when the status is <see cref="CompilationStatus.InvalidStage"/>.
/// </exception>
/// <exception cref="ShaderCompilationException">
/// Thrown when the status is <see cref="CompilationStatus.CompilationError"/>.
/// </exception>
/// <exception cref="ShaderInternalException">
/// Thrown when the status is <see cref="CompilationStatus.InternalError"/>.
/// </exception>
/// <exception cref="ShaderNullResultObjectException">
/// Thrown when the status is <see cref="CompilationStatus.NullResultObject"/>.
/// </exception>
/// <exception cref="ShaderInvalidAssemblyException">
/// Thrown when the status is <see cref="CompilationStatus.InvalidAssembly"/>.
/// </exception>
/// <exception cref="ShaderValidationException">
/// Thrown when the status is <see cref="CompilationStatus.ValidationError"/>.
/// </exception>
/// <exception cref="ShaderTransformationException">
/// Thrown when the status is <see cref="CompilationStatus.TransformationError"/>.
/// </exception>
/// <exception cref="ShaderConfigurationException">
/// Thrown when the status is <see cref="CompilationStatus.ConfigurationError"/>.
/// </exception>
/// <exception cref="ShaderException">Thrown when the status is unrecognised.</exception>
public static CompilationResult ThrowIfFailed(this in CompilationResult result) =>
result.GetCompilationStatus() switch
{
CompilationStatus.Success => result,
CompilationStatus.InvalidStage => throw new ShaderInvalidStageException(result),
CompilationStatus.CompilationError => throw new ShaderCompilationException(result),
CompilationStatus.InternalError => throw new ShaderInternalException(result),
CompilationStatus.NullResultObject => throw new ShaderNullResultObjectException(result),
CompilationStatus.InvalidAssembly => throw new ShaderInvalidAssemblyException(result),
CompilationStatus.ValidationError => throw new ShaderValidationException(result),
CompilationStatus.TransformationError => throw new ShaderTransformationException(result),
CompilationStatus.ConfigurationError => throw new ShaderConfigurationException(result),
_ => throw new ShaderException(result),
};
/// <summary>
/// Returns <paramref name="result"/> when compilation succeeded; otherwise disposes the intermediate
/// result and rethrows the typed <see cref="ShaderException"/>, so a failed compile never leaks the
/// native handle while a successful one stays owned by the caller.
/// </summary>
private static CompilationResult ThrowIfFailedOrDispose(this in CompilationResult result)
{
try
{
return result.ThrowIfFailed();
}
catch
{
result.Dispose();
throw;
}
}
/// <summary>
/// Compiles GLSL/HLSL <paramref name="source"/> to binary SPIR-V, throwing a typed
/// <see cref="ShaderException"/> on failure.
/// </summary>
/// <remarks>
/// <para>
/// On success the returned <see cref="CompilationResult"/> is owned by the caller and must be
/// disposed. While the result is undisposed the raw SPIR-V bytes are accessible via
/// <see cref="CompilationResult.GetBytes()"/>.
/// </para>
/// <para>
/// On failure the intermediate result is disposed before the exception propagates, so no
/// native handle is leaked.
/// </para>
/// </remarks>
/// <param name="c">The compiler to use.</param>
/// <param name="source">The GLSL/HLSL source code encoded as UTF-8.</param>
/// <param name="kind">The shader stage.</param>
/// <param name="inputFileName">Source file name used in diagnostic messages.</param>
/// <param name="entryPoint">Name of the entry-point function.</param>
/// <param name="options">Compilation options.</param>
/// <returns>
/// A <see cref="CompilationResult"/> with <see cref="CompilationStatus.Success"/> containing
/// the compiled SPIR-V bytes.
/// </returns>
/// <exception cref="ShaderException">Thrown on any compilation failure.</exception>
public static CompilationResult Compile(
this in Compiler c,
ReadOnlySpan<byte> source,
ShaderKind kind,
RefString8 inputFileName,
RefString8 entryPoint,
CompileOptions options
)
{
return c.CompileIntoSpv(source, kind, inputFileName, entryPoint, options).ThrowIfFailedOrDispose();
}
/// <summary>
/// Pre-processes GLSL/HLSL <paramref name="source"/>, throwing a typed
/// <see cref="ShaderException"/> on failure.
/// </summary>
/// <remarks>
/// <para>
/// On success the returned <see cref="CompilationResult"/> is owned by the caller and must be
/// disposed. While the result is undisposed the pre-processed text bytes are accessible via
/// <see cref="CompilationResult.GetBytes()"/>.
/// </para>
/// <para>
/// On failure the intermediate result is disposed before the exception propagates, so no
/// native handle is leaked.
/// </para>
/// </remarks>
/// <param name="c">The compiler to use.</param>
/// <param name="source">The GLSL/HLSL source code encoded as UTF-8.</param>
/// <param name="kind">The shader stage.</param>
/// <param name="inputFileName">Source file name used in diagnostic messages.</param>
/// <param name="entryPoint">Name of the entry-point function.</param>
/// <param name="options">Compilation options.</param>
/// <returns>
/// A <see cref="CompilationResult"/> with <see cref="CompilationStatus.Success"/> containing
/// the pre-processed text.
/// </returns>
/// <exception cref="ShaderException">Thrown on any pre-processing failure.</exception>
public static CompilationResult Preprocess(
this in Compiler c,
ReadOnlySpan<byte> source,
ShaderKind kind,
RefString8 inputFileName,
RefString8 entryPoint,
CompileOptions options
)
{
return c.CompileIntoPreprocessedText(source, kind, inputFileName, entryPoint, options).ThrowIfFailedOrDispose();
}
/// <summary>
/// Compiles GLSL/HLSL <paramref name="source"/> (supplied as a managed <see cref="string"/>) to binary
/// SPIR-V, throwing a typed <see cref="ShaderException"/> on failure.
/// </summary>
/// <remarks>
/// <para>
/// This overload UTF-8 encodes <paramref name="source"/>, <paramref name="inputFileName"/>, and
/// <paramref name="entryPoint"/> then delegates to the span-based <see cref="Compile(in Compiler, ReadOnlySpan{byte}, ShaderKind, RefString8, RefString8, CompileOptions)"/> overload.
/// </para>
/// <para>
/// On success the returned <see cref="CompilationResult"/> is owned by the caller and must be
/// disposed. While the result is undisposed the raw SPIR-V bytes are accessible via
/// <see cref="CompilationResult.GetBytes()"/>.
/// </para>
/// <para>
/// On failure the intermediate result is disposed before the exception propagates, so no
/// native handle is leaked.
/// </para>
/// <para>
/// When <paramref name="options"/> is omitted (default), no custom compilation options or include
/// callbacks are applied; shaderc compiles with its built-in defaults.
/// </para>
/// </remarks>
/// <param name="c">The compiler to use.</param>
/// <param name="source">The GLSL/HLSL source code as a managed string.</param>
/// <param name="kind">The shader stage.</param>
/// <param name="inputFileName">Source file name used in diagnostic messages.</param>
/// <param name="entryPoint">Name of the entry-point function. Defaults to <c>"main"</c>.</param>
/// <param name="options">
/// Compilation options, or <see langword="default"/> to use shaderc built-in defaults with no
/// include callbacks.
/// </param>
/// <returns>
/// A <see cref="CompilationResult"/> with <see cref="CompilationStatus.Success"/> containing
/// the compiled SPIR-V bytes.
/// </returns>
/// <exception cref="ShaderException">Thrown on any compilation failure.</exception>
public static CompilationResult Compile(
this in Compiler c,
string source,
ShaderKind kind,
string inputFileName,
string entryPoint = "main",
CompileOptions options = default
)
{
using var writer = new BespokeUtf8Encoder(
source,
inputFileName,
entryPoint,
out var source8,
out var inputFileName8,
out var entryPoint8
);
return c.Compile(source8, kind, inputFileName8, entryPoint8, options);
}
/// <summary>
/// Reads the file at <paramref name="path"/> and compiles its GLSL/HLSL content to binary SPIR-V,
/// throwing a typed <see cref="ShaderException"/> on failure.
/// </summary>
/// <remarks>
/// <para>
/// The file is read with <see cref="File.ReadAllBytes(string)"/> and passed as raw bytes to the
/// span-based <see cref="Compile(in Compiler, ReadOnlySpan{byte}, ShaderKind, RefString8, RefString8, CompileOptions)"/> overload. <paramref name="path"/> is passed as the
/// <c>inputFileName</c>, so when include support is enabled by passing <paramref name="options"/>
/// configured with <see cref="CompileOptions.SetDefaultIncludeCallbacks"/>, relative <c>#include</c>
/// paths anchor against it. With the default <paramref name="options"/> shaderc has no include
/// support, so a source containing <c>#include</c> fails to compile.
/// </para>
/// <para>
/// On success the returned <see cref="CompilationResult"/> is owned by the caller and must be
/// disposed. While the result is undisposed the raw SPIR-V bytes are accessible via
/// <see cref="CompilationResult.GetBytes()"/>.
/// </para>
/// <para>
/// On failure the intermediate result is disposed before the exception propagates, so no
/// native handle is leaked.
/// </para>
/// <para>
/// When <paramref name="options"/> is omitted (default), no custom compilation options or include
/// callbacks are applied; shaderc compiles with its built-in defaults.
/// </para>
/// </remarks>
/// <param name="c">The compiler to use.</param>
/// <param name="path">Path to the shader source file.</param>
/// <param name="kind">The shader stage.</param>
/// <param name="entryPoint">Name of the entry-point function. Defaults to <c>"main"</c>.</param>
/// <param name="options">
/// Compilation options, or <see langword="default"/> to use shaderc built-in defaults with no
/// include callbacks.
/// </param>
/// <returns>
/// A <see cref="CompilationResult"/> with <see cref="CompilationStatus.Success"/> containing
/// the compiled SPIR-V bytes.
/// </returns>
/// <exception cref="ShaderException">Thrown on any compilation failure.</exception>
/// <exception cref="System.IO.FileNotFoundException">Thrown if no file exists at <paramref name="path"/>.</exception>
/// <exception cref="System.IO.IOException">Thrown if the file at <paramref name="path"/> cannot be read.</exception>
public static CompilationResult CompileFile(
this in Compiler c,
string path,
ShaderKind kind,
string entryPoint = "main",
CompileOptions options = default
)
{
using var writer = new BespokeUtf8Encoder(path, entryPoint, out var path8, out var entryPoint8);
var sourceUtf8 = File.ReadAllBytes(path).AsSpan(); // wip: improve allocation strategy
return c.Compile(sourceUtf8, kind, path8, entryPoint8, options);
}
/// <summary>
/// Assembles SPIR-V text assembly in <paramref name="sourceAssembly"/> into binary SPIR-V,
/// throwing a typed <see cref="ShaderException"/> on failure.
/// </summary>
/// <remarks>
/// <para>
/// On success the returned <see cref="CompilationResult"/> is owned by the caller and must be
/// disposed. While the result is undisposed the raw SPIR-V bytes are accessible via
/// <see cref="CompilationResult.GetBytes()"/>.
/// </para>
/// <para>
/// On failure the intermediate result is disposed before the exception propagates, so no
/// native handle is leaked.
/// </para>
/// </remarks>
/// <param name="c">The compiler to use.</param>
/// <param name="sourceAssembly">The SPIR-V text assembly encoded as UTF-8.</param>
/// <param name="options">Compilation options.</param>
/// <returns>
/// A <see cref="CompilationResult"/> with <see cref="CompilationStatus.Success"/> containing
/// the assembled SPIR-V bytes.
/// </returns>
/// <exception cref="ShaderException">Thrown on any assembly failure.</exception>
public static CompilationResult Assemble(
this in Compiler c,
ReadOnlySpan<byte> sourceAssembly,
CompileOptions options
)
{
return c.AssembleIntoSpv(sourceAssembly, options).ThrowIfFailedOrDispose();
}
}

File diff suppressed because it is too large Load diff

149
Brutal.ShaderC/ShaderC.cs Normal file
View file

@ -0,0 +1,149 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Brutal.ShaderCApi;
/// <summary>
/// Provides access to the shaderc library for compiling GLSL/HLSL shaders to SPIR-V.
/// </summary>
/// <remarks>
/// <para>
/// The native <c>shaderc_shared</c> library is loaded in the type initializer. If the library is not
/// present in the assembly directory at the time the type is first accessed, the runtime will throw a
/// <see cref="TypeInitializationException"/>, a common deployment pitfall.
/// </para>
/// <para>
/// On macOS the library is loaded as <c>shaderc_shared.1</c> (versioned dylib); all other platforms
/// use <c>shaderc_shared</c>. This platform difference is managed internally.
/// </para>
/// <para>
/// All handles returned by the factory methods (<see cref="CreateCompiler"/>,
/// <see cref="CreateCompilerOptions"/>) wrap native memory and must be disposed when no longer needed.
/// Each handle must be disposed <em>exactly once</em>: disposing twice or copying a handle struct and
/// disposing both copies passes an invalid handle to native code and results in undefined behavior
/// (heap corruption or crash). A structural dispose-guard is tracked upstream against the
/// <c>[InteropHandle]</c> generator.
/// </para>
/// </remarks>
public static partial class ShaderC
{
private const string DLL = "shaderc";
static ShaderC()
{
var assembly = typeof(ShaderC).Assembly;
// EXCEPTION: The dll name is different on macOS, so we need to handle that case
var nativeDll = NativeLibrary.Load(
OperatingSystem.IsMacOS() ? "shaderc_shared.1" : "shaderc_shared",
assembly,
DllImportSearchPath.AssemblyDirectory
);
// Set the DllImportResolver for the assembly to resolve the shaderc library
NativeLibrary.SetDllImportResolver(
assembly,
(libraryName, _, _) =>
{
// We should only ever be resolving the shaderc library, so we assert that the library name is correct.
Debug.Assert(libraryName == "shaderc", "Unexpected library name requested for resolution.");
return nativeDll;
}
);
}
/// <summary>Creates a new shaderc compiler handle.</summary>
/// <returns>
/// A <see cref="Compiler"/> handle wrapping native memory. The caller is responsible for disposing
/// the handle to release native resources.
/// </returns>
/// <remarks>
/// <para>
/// The returned handle wraps a native <c>shaderc_compiler_t</c> object. It must be disposed
/// when no longer needed; failing to do so leaks native memory. Dispose the handle exactly
/// once; a second <c>Dispose</c> call (or disposing two copies of the same struct) passes an
/// invalid handle to native code and results in undefined behavior.
/// </para>
/// <para>
/// A <see cref="Compiler"/> handle is <strong>not thread-safe</strong>: do not use the same
/// handle concurrently across threads. Create a separate handle per thread if concurrent
/// compilation is required.
/// </para>
/// <para>
/// If the underlying native initialization fails, shaderc returns a null handle, which this
/// method propagates as-is (an uninitialized <see cref="Compiler"/> struct).
/// </para>
/// </remarks>
public static Compiler CreateCompiler()
{
return PInvoke.shaderc_compiler_initialize();
}
/// <summary>Creates a new shaderc compile-options handle.</summary>
/// <returns>
/// A <see cref="CompileOptions"/> handle wrapping native memory. The caller is responsible for
/// disposing the handle to release native resources.
/// </returns>
/// <remarks>
/// <para>
/// The returned handle wraps a native <c>shaderc_compile_options_t</c> object. It must be
/// disposed when no longer needed; failing to do so leaks native memory. Dispose the handle
/// exactly once; a second <c>Dispose</c> call (or disposing two copies of the same struct)
/// passes an invalid handle to native code and results in undefined behavior.
/// </para>
/// <para>
/// A <see cref="CompileOptions"/> handle is <strong>not thread-safe</strong>: do not mutate
/// options from multiple threads simultaneously. The options instance must also outlive any
/// compilation that uses it.
/// </para>
/// <para>
/// If the underlying native initialization fails, shaderc returns a null handle, which this
/// method propagates as-is (an uninitialized <see cref="CompileOptions"/> struct).
/// </para>
/// </remarks>
public static CompileOptions CreateCompilerOptions()
{
return PInvoke.shaderc_compile_options_initialize();
}
/// <summary>Gets the SPIR-V version and revision that shaderc was built against.</summary>
/// <param name="version">
/// Packed SPIR-V version: major version in the upper 16 bits, minor version in the lower 16 bits.
/// </param>
/// <param name="revision">SPIR-V revision number.</param>
public static unsafe void GetSpvVersion(out uint version, out uint revision)
{
fixed (uint* v = &version)
fixed (uint* r = &revision)
{
PInvoke.shaderc_get_spv_version(v, r);
}
}
/// <summary>Tries to parse a GLSL version/profile string such as "450core".</summary>
/// <param name="str">UTF-8 encoded, null-terminated version/profile string.</param>
/// <param name="version">
/// When this method returns <c>true</c>, the parsed GLSL version number (e.g. 450).
/// </param>
/// <param name="profile">
/// When this method returns <c>true</c>, the parsed profile. Undefined when this method returns
/// <c>false</c>.
/// </param>
/// <returns><c>true</c> if parsing succeeded; otherwise <c>false</c>.</returns>
/// <remarks>
/// <c>str</c> must be null-terminated: the underlying shaderc API treats the pointer as a C string
/// and will overread if no null terminator is present. A <see cref="ReadOnlySpan{T}"/> obtained
/// from a string literal or a stack-allocated buffer with an explicit <c>\0</c> satisfies this
/// requirement.
/// </remarks>
public static unsafe bool TryParseVersionProfile(ReadOnlySpan<byte> str, out int version, out Profile profile)
{
fixed (byte* s = str)
fixed (int* v = &version)
fixed (Profile* p = &profile)
{
return PInvoke.shaderc_parse_version_profile(s, v, p);
}
}
}

View file

@ -0,0 +1,83 @@
namespace Brutal.ShaderCApi;
/// <summary>
/// Contains methods for inferring shader kind from file paths.
/// </summary>
public static partial class ShaderC
{
/// <summary>
/// Attempts to infer the shader kind from a file path's extension.
/// </summary>
/// <param name="path">The file path to infer the shader kind from.</param>
/// <param name="kind">
/// When this method returns <see langword="true"/>, the inferred shader kind. When it returns
/// <see langword="false"/> it is set to <see langword="default"/>, which is a real stage
/// (<see cref="ShaderKind.VertexShader"/>), so callers must branch on the return value, not on
/// <paramref name="kind"/>.
/// </param>
/// <returns>True if the extension was recognized, false otherwise.</returns>
public static bool TryInferShaderKind(ReadOnlySpan<char> path, out ShaderKind kind)
{
// Path.GetExtension returns the extension including the leading '.', and ignores dots that
// appear in directory names. It is empty when there is no extension (including a trailing '.').
ReadOnlySpan<char> extension = Path.GetExtension(path);
if (extension.Length <= 1)
{
kind = default;
return false;
}
extension = extension[1..]; // drop the leading '.'
// Lowercase into a small stack buffer; an extension longer than this is not one we recognise.
Span<char> lowercased = stackalloc char[16];
if (extension.Length > lowercased.Length)
{
kind = default;
return false;
}
int written = extension.ToLowerInvariant(lowercased);
ReadOnlySpan<char> lower = lowercased[..written];
// Single match table: a recognised extension yields its kind, anything else yields null so the
// caller can distinguish "no match" from the (zero-valued) VertexShader default.
ShaderKind? match = lower switch
{
"vert" => ShaderKind.VertexShader,
"frag" => ShaderKind.FragmentShader,
"comp" => ShaderKind.ComputeShader,
"geom" => ShaderKind.GeometryShader,
"tesc" => ShaderKind.TessControlShader,
"tese" => ShaderKind.TessEvaluationShader,
"mesh" => ShaderKind.MeshShader,
"task" => ShaderKind.TaskShader,
"rgen" => ShaderKind.RayGenShader,
"rmiss" => ShaderKind.MissShader,
"rchit" => ShaderKind.ClosestHitShader,
"rahit" => ShaderKind.AnyHitShader,
"rint" => ShaderKind.IntersectionShader,
"rcall" => ShaderKind.CallableShader,
_ => null,
};
kind = match ?? default;
return match.HasValue;
}
/// <summary>
/// Infers the shader kind from a file path's extension.
/// </summary>
/// <param name="path">The file path to infer the shader kind from.</param>
/// <returns>The inferred shader kind.</returns>
/// <exception cref="ArgumentException">Thrown if the extension is not recognized.</exception>
public static ShaderKind InferShaderKind(ReadOnlySpan<char> path)
{
if (!TryInferShaderKind(path, out var kind))
{
throw new ArgumentException($"Could not infer ShaderKind from path '{path}'.", nameof(path));
}
return kind;
}
}

View file

@ -0,0 +1,29 @@
namespace Brutal.ShaderCApi;
/// <summary>
/// An object that contains options for compiling shaders.
/// </summary>
public partial struct CompileOptions
{
/// <summary>Installs the built-in disk-based include resolver on this options instance.</summary>
/// <remarks>
/// <para>
/// Overwrites any include callbacks previously set on this instance (destructive replacement).
/// The resolver reads the requested file from disk relative to the directory of the requesting
/// source, so the source name passed to the compiler must be a real, accessible file path.
/// </para>
/// <para>
/// This options instance must outlive any compilation that uses it; the native shaderc API
/// holds a raw pointer to the callbacks for the duration of the compile.
/// </para>
/// </remarks>
public unsafe void SetDefaultIncludeCallbacks()
{
ShaderC.PInvoke.shaderc_compile_options_set_include_callbacks(
this,
new IncludeResolveFn(&ShaderC.Callbacks.Resolve),
new IncludeResultReleaseFn(&ShaderC.Callbacks.Release),
null
);
}
}

View file

@ -0,0 +1,70 @@
namespace Brutal.ShaderCApi;
/// <summary>
/// A function-pointer wrapper for the shaderc include-resolve callback.
/// </summary>
/// <remarks>
/// <para>
/// Wraps the native <c>shaderc_include_resolve_fn</c> callback, whose C signature is:
/// </para>
/// <code>
/// typedef shaderc_include_result* (*shaderc_include_resolve_fn)(
/// void* user_data,
/// const char* requested_source,
/// int type,
/// const char* requesting_source,
/// size_t include_depth);
/// </code>
/// <para>The parameters, in order, are:</para>
/// <list type="bullet">
/// <item><description><c>user_data</c>: opaque client context pointer passed through from the options.</description></item>
/// <item><description><c>requested_source</c>: NUL-terminated UTF-8 C string; the path being included.</description></item>
/// <item><description><c>type</c>: an <see cref="IncludeType"/> value indicating relative vs. standard inclusion.</description></item>
/// <item><description><c>requesting_source</c>: NUL-terminated UTF-8 C string; the source file containing the <c>#include</c>.</description></item>
/// <item><description><c>include_depth</c>: nesting depth (1 = top-level include).</description></item>
/// </list>
/// <para>
/// <strong>Ownership.</strong> The callee allocates the returned <see cref="IncludeResult"/> and its
/// buffers; shaderc calls the matching <see cref="IncludeResultReleaseFn"/> when it is done with the
/// result. The result and its contents must remain valid until that release call.
/// </para>
/// <para>
/// The full consumer-visible contract is documented on
/// <see cref="ShaderC.Callbacks.Resolve"/> and <see cref="CompileOptions.SetDefaultIncludeCallbacks"/>.
/// </para>
/// </remarks>
public readonly unsafe struct IncludeResolveFn(
delegate* unmanaged[Cdecl]<void*, byte*, IncludeType, byte*, nuint, IncludeResult*> handle
)
{
/// <summary>The underlying unmanaged function pointer.</summary>
public readonly delegate* unmanaged[Cdecl]<void*, byte*, IncludeType, byte*, nuint, IncludeResult*> Invoke = handle;
}
/// <summary>
/// A function-pointer wrapper for the shaderc include-result release callback.
/// </summary>
/// <remarks>
/// <para>
/// Wraps the native <c>shaderc_include_result_release_fn</c> callback, whose C signature is:
/// </para>
/// <code>
/// typedef void (*shaderc_include_result_release_fn)(
/// void* user_data,
/// shaderc_include_result* include_result);
/// </code>
/// <para>
/// This callback is the matching deallocator for <see cref="IncludeResolveFn"/>: it must free the
/// <see cref="IncludeResult"/> and all buffers allocated by the resolver. Use the same
/// allocator/deallocator pair; do not mix allocators between the resolve and release callbacks.
/// </para>
/// <para>
/// The full consumer-visible contract is documented on
/// <see cref="ShaderC.Callbacks.Release"/> and <see cref="CompileOptions.SetDefaultIncludeCallbacks"/>.
/// </para>
/// </remarks>
public readonly unsafe struct IncludeResultReleaseFn(delegate* unmanaged[Cdecl]<void*, IncludeResult*, void> handle)
{
/// <summary>The underlying unmanaged function pointer.</summary>
public readonly delegate* unmanaged[Cdecl]<void*, IncludeResult*, void> Invoke = handle;
}

View file

@ -0,0 +1,193 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Brutal.Memory;
using Brutal.Pointers.Extensions;
namespace Brutal.ShaderCApi;
public static partial class ShaderC
{
/// <summary>
/// Default callbacks for the shader compiler.
/// </summary>
public static class Callbacks
{
// Guards against #include cycles by bounding nesting depth (shaderc increments depth per
// nesting level). 200 is far above any realistic include tree, so a legitimate compile never
// reaches it; a self- or mutually-recursive #include climbs to the limit and is reported as a
// cycle instead of looping until the stack overflows.
private const nuint MaxIncludeDepth = 200;
/// <summary>
/// Resolves an <c>#include</c> request by reading the requested file from disk relative to the
/// requesting source's directory.
/// </summary>
/// <param name="data">Opaque user-data pointer passed through from the options (unused by this implementation).</param>
/// <param name="source">NUL-terminated UTF-8 C string naming the file being requested (the include path).</param>
/// <param name="type">The kind of inclusion request (<see cref="IncludeType.Relative"/> or <see cref="IncludeType.Standard"/>).</param>
/// <param name="requestingSource">NUL-terminated UTF-8 C string naming the source file that contains the <c>#include</c> directive.</param>
/// <param name="depth">Include nesting depth; 1 indicates a top-level include from the root source.</param>
/// <returns>
/// A pointer to a heap-allocated <see cref="IncludeResult"/> whose <c>Content</c> and
/// <c>SourceName</c> buffers are also heap-allocated. The caller (shaderc) must invoke
/// <see cref="Release"/> on the result when it is no longer needed.
/// </returns>
/// <remarks>
/// <para>
/// This method and <see cref="Release"/> form a matching allocator/deallocator pair: all
/// allocations are performed with <c>Mem.Alloc</c> and must be freed by <see cref="Release"/>
/// using <c>Mem.Free</c>. A custom resolver that replaces this implementation must honor the
/// same contract.
/// </para>
/// <para>
/// The returned <see cref="IncludeResult"/> and its buffers must remain valid until
/// <see cref="Release"/> is called on it. Do not free or modify the result after returning it.
/// </para>
/// <para>
/// Any exception thrown during resolution (e.g., <see cref="FileNotFoundException"/>) is
/// caught and surfaced as a shaderc include-failure result whose <c>Content</c> field
/// contains the exception message. The exception does <strong>not</strong> propagate as a
/// managed exception; include-resolution failures appear only in the compiler's error output.
/// </para>
/// </remarks>
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
public static unsafe IncludeResult* Resolve(
void* data,
byte* source,
IncludeType type,
byte* requestingSource,
nuint depth
)
{
// Allocate a new result
var result = Mem.AllocZeroed<IncludeResult>();
try
{
ResolveInternal(
ref result.Value,
data,
Utf8.GetNullTerminatedSpan(source),
type,
Utf8.GetNullTerminatedSpan(requestingSource),
depth
);
}
catch (Exception ex)
{
// Free any previously allocated memory in Content (we are going to replace it)
if (result.Value.Content != null)
{
Mem.Free(result.Value.Content);
result.Value.Content = null;
result.Value.ContentLength = ByteSize.Zero;
}
// Free and reset SourceName (API says it should be empty on failure)
if (result.Value.SourceName != null)
{
Mem.Free(result.Value.SourceName);
result.Value.SourceName = null;
result.Value.SourceNameLength = ByteSize.Zero;
}
// Write the error message to Content
var byteCount = Utf8.GetByteCount(ex.Message);
var span = Mem.Alloc<byte>(byteCount);
Utf8.GetBytes(ex.Message, span);
result.Value.Content = span.AsPointer();
result.Value.ContentLength = ByteSize.Of(byteCount);
}
return result;
}
private static unsafe void ResolveInternal(
ref IncludeResult result,
void* data,
ReadOnlySpan<byte> source,
IncludeType type,
ReadOnlySpan<byte> requestingSource,
nuint depth
)
{
if (depth > MaxIncludeDepth)
throw new InvalidOperationException(
$"Include depth {depth} exceeded the maximum of {MaxIncludeDepth}; possible #include cycle."
);
// Get the path to the include file, relative to the requesting source.
// Decode the path once and reuse it for the error message and file open.
var path = Utf8.Path.Combine(Utf8.Path.GetDirectoryName(requestingSource), source);
var pathStr = Utf8.GetString(path);
// Open directly instead of File.Exists + open, which would stat the file twice on every
// include. A missing file surfaces as the framework's own FileNotFoundException /
// DirectoryNotFoundException, which is caught by Resolve and reported as an include failure.
using (var handle = File.OpenHandle(pathStr))
{
// Allocate null-terminated storage for SourceName.
// shaderc treats source_name as a C string and re-feeds it as requesting_source,
// so the buffer must be null-terminated even though SourceNameLength stays path.Length.
var copy = Mem.Alloc<byte>(path.Length + 1);
path.CopyTo(copy);
copy[path.Length] = 0;
result.SourceName = copy.AsPointer();
result.SourceNameLength = ByteSize.Of(path.Length);
// Read the include file into memory using RandomAccess to avoid the FileStream buffer.
var length = RandomAccess.GetLength(handle);
if (length > int.MaxValue)
throw new IOException($"Include file is too large to read ({length} bytes): {pathStr}");
var dataSize = (int)length;
var memory = Mem.Alloc<byte>(dataSize);
result.Content = memory.AsPointer();
result.ContentLength = ByteSize.Of(dataSize);
// RandomAccess.Read is permitted to return a short count, so loop until the buffer fills.
Span<byte> destination = memory;
var totalRead = 0;
while (totalRead < dataSize)
{
var read = RandomAccess.Read(handle, destination[totalRead..], totalRead);
if (read == 0)
break;
totalRead += read;
}
if (totalRead != dataSize)
throw new IOException($"Failed to read expected {dataSize} bytes, read {totalRead} bytes instead.");
}
}
/// <summary>
/// Frees an <see cref="IncludeResult"/> previously returned by <see cref="Resolve"/>.
/// </summary>
/// <param name="data">Opaque user-data pointer passed through from the options (unused by this implementation).</param>
/// <param name="result">Pointer to the <see cref="IncludeResult"/> to release, or <c>null</c> (no-op).</param>
/// <remarks>
/// <para>
/// This method is the matching deallocator for <see cref="Resolve"/>: it frees the
/// <c>SourceName</c> buffer, the <c>Content</c> buffer, and the <see cref="IncludeResult"/>
/// struct itself, all previously allocated via <c>Mem.Alloc</c>.
/// </para>
/// <para>
/// A custom resolver that replaces <see cref="Resolve"/> must provide a matching release
/// callback that frees whatever its resolver allocated. Do not mix allocators (e.g., do not
/// allocate in one callback and free in the other).
/// </para>
/// </remarks>
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
public static unsafe void Release(void* data, IncludeResult* result)
{
if (result != null)
{
// UserData ownership belongs to whoever allocates it; do not free it here.
Mem.Free(result->SourceName);
Mem.Free(result->Content);
Mem.Free(result);
}
}
}
}

View file

@ -0,0 +1,60 @@
namespace Brutal.ShaderCApi;
/// <summary>
/// Base class of all shader exceptions. Captures the compiler diagnostic message from a
/// <see cref="CompilationResult"/> at the point of construction.
/// </summary>
/// <remarks>
/// <para>
/// The exception does <b>not</b> take ownership of <paramref name="result"/>; the caller remains
/// responsible for disposing it. <see cref="CompilationResult.GetErrorMessage()"/> is evaluated
/// eagerly during construction, so <paramref name="result"/> must still be valid at the point of
/// <c>throw</c>. The captured message is the raw shaderc diagnostic text.
/// </para>
/// </remarks>
/// <param name="result">
/// The compilation result whose error message is captured. The exception does not take ownership;
/// the caller remains responsible for disposing <paramref name="result"/>. The message is read
/// eagerly at construction time, so the result must still be valid at the point of <c>throw</c>.
/// </param>
public class ShaderException(in CompilationResult result) : Exception(result.GetErrorMessage());
/// <summary>
/// Triggers when the shader stage could not be inferred from the source code.
/// </summary>
public class ShaderInvalidStageException(in CompilationResult result) : ShaderException(result);
/// <summary>
/// Triggers when the shader compilation failed.
/// </summary>
public class ShaderCompilationException(in CompilationResult result) : ShaderException(result);
/// <summary>
/// Triggers when the shader compiler encountered an internal error.
/// </summary>
public class ShaderInternalException(in CompilationResult result) : ShaderException(result);
/// <summary>
/// Triggers when the shader compiler returned a null result object.
/// </summary>
public class ShaderNullResultObjectException(in CompilationResult result) : ShaderException(result);
/// <summary>
/// Triggers when the SPIR-V assembly is invalid.
/// </summary>
public class ShaderInvalidAssemblyException(in CompilationResult result) : ShaderException(result);
/// <summary>
/// Triggers when SPIR-V validation failed (when validation is enabled).
/// </summary>
public class ShaderValidationException(in CompilationResult result) : ShaderException(result);
/// <summary>
/// Triggered when transformation to SPIR-V failed.
/// </summary>
public class ShaderTransformationException(in CompilationResult result) : ShaderException(result);
/// <summary>
/// Triggered when configuration of the shader compiler is invalid.
/// </summary>
public class ShaderConfigurationException(in CompilationResult result) : ShaderException(result);