pub struct Compiler { /* private fields */ }
Expand description
Lazily-loaded d3dcompiler_NN.dll
Constructors
new(version: u32) -> Result<Compiler>
Compile & Preprocess HLSL to Bytecode
compile_from_file(…) - compile hlsl to bytecode
compile(…) - compile hlsl to bytecode
compile2(…) - compile hlsl to bytecode
preprocess(…) - preprocess HLSL #include
s and #define
s
Manipulate Bytecode Archives
compress_shaders(…) - compress hlsl or bytecode
decompress_shaders(…) - decompress shaders
decompress_shaders_inplace(…) - decompress shaders without allocating
decompress_shaders_count(…) - get the number of shaders in a compressed archive
Manipulate Bytecode by BlobPart
get_blob_part(…) - read a BlobPart of a shader bytecode blob
get_debug_info(…) - read BlobPart::DebugInfo of a shader bytecode blob
get_input_and_output_signature_blob(…) - read BlobPart::InputAndOutputSignatureBlob of a shader bytecode blob
get_input_signature_blob(…) - read BlobPart::InputSignatureBlob of a shader bytecode blob
get_output_signature_blob(…) - read BlobPart::OutputSignatureBlob of a shader bytecode blob
set_blob_part(…) - write a BlobPart of a shader bytecode blob
strip_shader(…) - strip debug information etc. from bytecode
Bytecode Reflection
reflect(…) - reflect over a single shader’s bytecode
reflect_library(…) - ???
Bytecode Debugging
disassemble(…) - disassemble bytecode as human readable text
disassemble_region(…) - disassemble bytecode as human readable text
get_trace_instruction_offsets_count(…) - get the number of trace instruction byte offsets
get_trace_instruction_offsets_inplace(…) - read trace instruction byte offsets
get_trace_instruction_offsets(…) - read trace instruction byte offsets
ReadOnlyBlob Utilities
create_read_only_blob(…) - create a ReadOnlyBlob from memory
read_file_to_blob(…) - read a ReadOnlyBlob from disk
write_blob_to_file(…) - write a ReadOnlyBlob to disk
D3D11 Factories & APIs
create_function_linking_graph(…) - create a d3d11::FunctionLinkingGraph
create_linker(…) - create a d3d11::Linker
load_module(…) - load a d3d11::Module
Implementations
sourceimpl Compiler
impl Compiler
sourcepub fn load_insecure(version: impl CompilerLoadInsecure) -> Result<Self, Error>
pub fn load_insecure(version: impl CompilerLoadInsecure) -> Result<Self, Error>
Attempt to load d3dcompiler_NN.dll
⚠️ Safety ⚠️
Prefer Compiler::load_system.
The possibility of DLL preloading attacks makes this function insecure. To be fair, the security of using d3dcompiler at all is questionable. If your data is untrusted, should you really be using this API at all? This is a developer focused, unfuzzed, native C++ parser and deserializer, with all the edge cases that entails.
Recommended reading, to secure more than just this call:
- Dynamic-Link Library Security
https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-security - Secure loading of libraries to prevent DLL preloading attacks
https://support.microsoft.com/en-us/topic/secure-loading-of-libraries-to-prevent-dll-preloading-attacks-d41303ec-0748-9211-f317-2edc819682e1
Additionally, one can argue about if it’s sound to consider this function memory safe (e.g. missing the unsafe
keyword.)
A user-provided custom d3dcompiler_NN.dll
could relax soundness guarantees vs a Microsoft version.
However, taking that argument to the extreme, one could argue a user-provided custom kernel32.dll breaks rust’s entire stdlib.
While Windows attempts to guard against that somewhat, the interpid could be running this executable on redox. Or on linux with wine. Or…
So, instead, I assert the following:
- Functions named
D3DCompile
,D3DCreateBlob
, etc. have an implicit - if incredibly ill defined - contract. - It should be “sound” to rely on that contract. Violations of the contract are bugs in the DLLs, not the consuming Rust code.
- That contract is narrowed by bugs in known/common d3dcompiler versions (including 3rd party ones), so please file issues if you can crash it!
- Working around intentional undefined behavior - by e.g. defining D3DCompiler with an incorrect function signature, or to immediately dereference null with any/all args just to prove a point, is not.
- If in doubt, file an issue! I can simply close it if I disagree.
Arguments
version
- the d3dcompiler.dll version to load
Returns
- Err(std::io::Error) - if
d3dcompiler_{version}.dll
could not be loaded - Ok(Compiler) -
d3dcompiler_{version}.dll
was found
Example
use thindx::d3d;
let d3dc = d3d::Compiler::load_insecure(47).unwrap();
let d3dc = d3d::Compiler::load_insecure("d3dcompiler_47.dll").unwrap();
sourcepub fn load_system(
version: impl CompilerLoadSysemVersion
) -> Result<Self, Error>
pub fn load_system(
version: impl CompilerLoadSysemVersion
) -> Result<Self, Error>
Attempt to load d3dcompiler_NN.dll via LOAD_LIBRARY_SEARCH_SYSTEM32 (e.g. %WINDOWS%\System32
)
⚠️ Safety ⚠️
The use of LOAD_LIBRARY_SEARCH_SYSTEM32 should guard somewhat against DLL preloading attacks.
However, using d3dcompiler at all on untrusted data is questionable. If your data is untrusted, should you really be using this API at all? This is a developer focused, unfuzzed, native C++ parser and deserializer, with all the edge cases that entails.
Arguments
Returns
- Err(std::io::Error) - if
d3dcompiler_{version}.dll
could not be loaded - Ok(Compiler) -
d3dcompiler_{version}.dll
was found
Example
use thindx::d3d;
let d3dc = d3d::Compiler::load_system(47).unwrap();
Remarks
sourceimpl Compiler
impl Compiler
sourcepub fn compile_from_file(
&self,
file_name: impl AsRef<Path>,
defines: impl AsShaderMacros,
include: impl AsInclude,
entrypoint: impl TryIntoAsOptCStr,
target: impl TryIntoAsCStr,
flags1: impl Into<Compile>,
flags2: impl Into<CompileEffect>
) -> Result<CompileResult, CompileError>
pub fn compile_from_file(
&self,
file_name: impl AsRef<Path>,
defines: impl AsShaderMacros,
include: impl AsInclude,
entrypoint: impl TryIntoAsOptCStr,
target: impl TryIntoAsCStr,
flags1: impl Into<Compile>,
flags2: impl Into<CompileEffect>
) -> Result<CompileResult, CompileError>
[docs.microsoft.com] D3DCompileFromFile
Note: You can use this API to develop your Windows Store apps, but you can’t use it in apps that you submit to the Windows Store. Refer to the section, “Compiling shaders for UWP”, in the remarks for compile2.
Compiles Microsoft High Level Shader Language (HLSL) code into bytecode for a given target.
Arguments
file_name
- The shader file to compiledefines
- An optional array of defines. Use None if no extra defines are desired.include
- An optional interface for dispatching#include
s. Use None if#include
s should not be supported. Use StandardFileInclude if you want to resolve#include
s relative tosource_name
.entrypoint
- An optional entrypoint such asSome("main")
. Ignored iftarget
isfx_*
.target
- A target shader profile such asps_3_0
,vs_5_0
,fx_4_0
, etc.flags1
- Compile::* constants.flags2
- CompileEffect::* constants.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_4?.dll
and earlier - D3DERR::INVALIDCALL - on invalid parameters such as nonexistant
target
s - E::FAIL - if the shader failed to compile
Examples
let pixel_shader = d3dc.compile_from_file(
r"test\data\basic.hlsl", None, None, "ps_main", "ps_4_0",
Compile::Debug, CompileEffect::None,
).unwrap();
let vertex_shader = d3dc.compile_from_file(
r"test\data\basic.hlsl", None, StandardFileInclude, "vs_main", "vs_4_0",
Compile::Debug, CompileEffect::None,
).unwrap();
// TODO: defines/includes examples
See Also
Remarks
- You can use this API to develop your Windows Store apps, but you can’t use it in apps that you submit to the Windows Store.
sourcepub fn compile(
&self,
src_data: impl AsRef<[u8]>,
source_name: impl TryIntoAsOptCStr,
defines: impl AsShaderMacros,
include: impl AsInclude,
entrypoint: impl TryIntoAsOptCStr,
target: impl TryIntoAsCStr,
flags1: impl Into<Compile>,
flags2: impl Into<CompileEffect>
) -> Result<CompileResult, CompileError>
pub fn compile(
&self,
src_data: impl AsRef<[u8]>,
source_name: impl TryIntoAsOptCStr,
defines: impl AsShaderMacros,
include: impl AsInclude,
entrypoint: impl TryIntoAsOptCStr,
target: impl TryIntoAsCStr,
flags1: impl Into<Compile>,
flags2: impl Into<CompileEffect>
) -> Result<CompileResult, CompileError>
[docs.microsoft.com] D3DCompile
Compile HLSL code or an effect file into bytecode for a given target.
Arguments
src_data
- The shader source codesource_name
- An optional shader name such asSome("myshader.hlsl")
for debug purpouses.defines
- An optional array of defines. Use None if no extra defines are desired.include
- An optional interface for dispatching#include
s. Use None if#include
s should not be supported. Use StandardFileInclude if you want to resolve#include
s relative tosource_name
.entrypoint
- An optional entrypoint such asSome("main")
. Ignored iftarget
isfx_*
.target
- A target shader profile such asps_3_0
,vs_5_0
,fx_4_0
, etc.flags1
- Compile::* constants.flags2
- CompileEffect::* constants.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_39.dll
and earlier - D3DERR::INVALIDCALL - on invalid parameters such as nonexistant
target
s - E::FAIL - if the shader failed to compile
Examples
let basic_hlsl = std::fs::read(r"test\data\basic.hlsl").unwrap();
let pixel_shader = d3dc.compile(
&basic_hlsl, r"test\data\basic.hlsl", None, None, "ps_main", "ps_4_0",
Compile::Debug, CompileEffect::None,
).unwrap();
let vertex_shader = d3dc.compile(
&basic_hlsl, r"test\data\basic.hlsl", None, None, "vs_main", "vs_4_0",
Compile::Debug, CompileEffect::None,
).unwrap();
See Also
Remarks
- This was introduced by d3dcompiler_40.dll, and is unavailable in earlier versions.
sourcepub fn compile2<'s>(
&self,
src_data: impl AsRef<[u8]>,
source_name: impl TryIntoAsOptCStr,
defines: impl AsShaderMacros,
include: impl AsInclude,
entrypoint: impl TryIntoAsOptCStr,
target: impl TryIntoAsCStr,
flags1: impl Into<Compile>,
flags2: impl Into<CompileEffect>,
secondary_data_flags: impl Into<CompileSecData>,
secondary_data: impl Into<Option<&'s [u8]>>
) -> Result<CompileResult, CompileError>
pub fn compile2<'s>(
&self,
src_data: impl AsRef<[u8]>,
source_name: impl TryIntoAsOptCStr,
defines: impl AsShaderMacros,
include: impl AsInclude,
entrypoint: impl TryIntoAsOptCStr,
target: impl TryIntoAsCStr,
flags1: impl Into<Compile>,
flags2: impl Into<CompileEffect>,
secondary_data_flags: impl Into<CompileSecData>,
secondary_data: impl Into<Option<&'s [u8]>>
) -> Result<CompileResult, CompileError>
[docs.microsoft.com] D3DCompile2
Compiles Microsoft High Level Shader Language (HLSL) code into bytecode for a given target.
Arguments
src_data
- The shader source codesource_name
- An optional shader name such asSome("myshader.hlsl")
for debug purpouses.defines
- An optional array of defines. Use None if no extra defines are desired.include
- An optional interface for dispatching#include
s. Use None if#include
s should not be supported. Use StandardFileInclude if you want to resolve#include
s relative tosource_name
.entrypoint
- An optional entrypoint such asSome("vs_main")
. Ignored iftarget
is"fx_*"
.target
- A target shader profile such asSome("ps_3_0")
,Some("vs_5_0")
,Some("fx_4_0")
, etc.flags1
- Compile::* constants.flags2
- CompileEffect::* constants.secondary_data_flags
- CompileSecData::* constants.secondary_data
- A pointer to secondary data. If you don’t pass secondary data, set to None.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_4?.dll
and earlier - D3DERR::INVALIDCALL - on invalid parameters such as nonexistant
target
s - E::FAIL - if the shader failed to compile
Examples
let basic_hlsl = std::fs::read(r"test\data\basic.hlsl").unwrap();
let pixel_shader = d3dc.compile2(
&basic_hlsl, r"test\data\basic.hlsl", None, None, "ps_main", "ps_4_0",
Compile::Debug, CompileEffect::None, CompileSecData::None, None,
).unwrap();
let vertex_shader = d3dc.compile2(
&basic_hlsl, r"test\data\basic.hlsl", None, None, "vs_main", "vs_4_0",
Compile::Debug, CompileEffect::None, CompileSecData::None, None,
).unwrap();
See Also
Remarks
The difference between compile2 and compile is that compile2
takes some optional parameters (secondary_data_flags
and secondary_data
) that can be used to control some
aspects of how bytecode is generated. Refer to the descriptions of these parameters for more details. There is
no difference otherwise to the efficiency of the bytecode generated between compile2 and
compile.
sourcepub fn preprocess(
&self,
src_data: impl AsRef<[u8]>,
source_name: impl TryIntoAsOptCStr,
defines: impl AsShaderMacros,
include: impl AsInclude
) -> Result<PreprocessResult, PreprocessError>
pub fn preprocess(
&self,
src_data: impl AsRef<[u8]>,
source_name: impl TryIntoAsOptCStr,
defines: impl AsShaderMacros,
include: impl AsInclude
) -> Result<PreprocessResult, PreprocessError>
[docs.microsoft.com] D3DPreprocess
Preprocesses uncompiled HLSL code.
Arguments
src_data
- The shader source codesource_name
- An optional shader name such asSome("myshader.hlsl")
for debug purpouses.defines
- An optional array of defines. Use()
if no extra defines are desired.include
- An optional interface for dispatching#include
s. Use()
if#include
s should not be supported. Use StandardFileInclude if you want to resolve#include
s relative tosource_name
.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_39.dll
and earlier - E::FAIL - if the shader failed to preprocess
Example
let basic_hlsl = std::fs::read(r"test\data\basic.hlsl").unwrap();
let ps = d3dc.preprocess(&basic_hlsl, r"test\data\basic.hlsl", (), None).unwrap();
println!("{}", ps.shader.to_utf8_lossy());
Output
#line 1 "C:\\local\\thindx\\test\\data\\basic.hlsl"
struct Vertex {
float4 position : POSITION0 ;
float4 color : COLOR0 ;
} ;
struct VsToPs {
...
See Also
Remarks
- This was introduced by d3dcompiler_40.dll, and is unavailable in earlier versions.
sourceimpl Compiler
impl Compiler
sourcepub fn compress_shaders(
&self,
shaders: &[ShaderData<'_>],
flags: impl Into<CompressShader>
) -> Result<BytesBlob, Error>
pub fn compress_shaders(
&self,
shaders: &[ShaderData<'_>],
flags: impl Into<CompressShader>
) -> Result<BytesBlob, Error>
[docs.microsoft.com] D3DCompressShaders
Compresses a set of shaders into a more compact form.
Arguments
shaders
- The compiled shader(s) to compress.flags
- CompressShader flags controlling compression.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_42.dll
and earlier
Example
let basic_hlsl = std::fs::read(r"test\data\basic.hlsl").unwrap();
let plain_txt = std::fs::read(r"test\data\plain.txt").unwrap();
let tocompress = [
ShaderData::from(&basic_hlsl[..]),
ShaderData::from(&plain_txt[..]),
];
println!("tocompress: [{} bytes, {} bytes]", basic_hlsl.len(), plain_txt.len());
let compress = d3dc.compress_shaders(&tocompress, CompressShader::default()).unwrap();
println!("compressed: {} bytes", compress.len());
Output
to_compress: [493 bytes, 58 bytes]
compressed: 432 bytes
Remarks
- You can use this API to develop your Windows Store apps, but you can’t use it in apps that you submit to the Windows Store.
- This was introduced by d3dcompiler_43.dll, and is unavailable in earlier versions.
sourcepub fn decompress_shaders_count(&self, src_data: &[u8]) -> Result<u32, Error>
pub fn decompress_shaders_count(&self, src_data: &[u8]) -> Result<u32, Error>
[docs.microsoft.com] D3DDecompressShaders
Get the number of compressed shaders in the src_data
archive.
Arguments
src_data
- The compressed shaders.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_42.dll
and earlier
Example
assert_eq!(2, d3dc.decompress_shaders_count(&compress).unwrap());
Remarks
- You can use this API to develop your Windows Store apps, but you can’t use it in apps that you submit to the Windows Store.
- This was introduced by d3dcompiler_43.dll, and is unavailable in earlier versions.
sourcepub fn decompress_shaders_inplace<'s>(
&self,
src_data: &[u8],
flags: impl Into<Option<Infallible>>,
start_index: u32,
out_shaders: &'s mut [Option<ReadOnlyBlob>]
) -> Result<&'s [Option<ReadOnlyBlob>], Error>
pub fn decompress_shaders_inplace<'s>(
&self,
src_data: &[u8],
flags: impl Into<Option<Infallible>>,
start_index: u32,
out_shaders: &'s mut [Option<ReadOnlyBlob>]
) -> Result<&'s [Option<ReadOnlyBlob>], Error>
[docs.microsoft.com] D3DDecompressShaders
Decompresses one or more shaders from a compressed set.
Arguments
src_data
- The compressed shaders to decompress.flags
- Reserved (pass None).start_index
- The first shader to read, by archive index order.out_shaders
- An output buffer of shaders to read. The size of the buffer dictates how many shaders will be read.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_42.dll
and earlier
Example
let mut decompressed = [None, None, None];
let decompressed2 = d3dc.decompress_shaders_inplace(
&compress, None, 0, &mut decompressed[..]
).unwrap();
assert_eq!(2, decompressed2.len());
assert_eq!(basic_hlsl, decompressed2[0].as_ref().unwrap().get_buffer());
assert_eq!(plain_txt, decompressed2[1].as_ref().unwrap().get_buffer());
assert_eq!(&basic_hlsl[..], decompressed[0].as_ref().unwrap().get_buffer());
assert_eq!(&plain_txt[..], decompressed[1].as_ref().unwrap().get_buffer());
assert!(decompressed[2].is_none());
Remarks
- You can use this API to develop your Windows Store apps, but you can’t use it in apps that you submit to the Windows Store.
- This was introduced by d3dcompiler_43.dll, and is unavailable in earlier versions.
sourcepub fn decompress_shaders(
&self,
src_data: &[u8],
flags: impl Into<Option<Infallible>>,
_range: RangeFull
) -> Result<Vec<Option<ReadOnlyBlob>>, Error>
pub fn decompress_shaders(
&self,
src_data: &[u8],
flags: impl Into<Option<Infallible>>,
_range: RangeFull
) -> Result<Vec<Option<ReadOnlyBlob>>, Error>
[docs.microsoft.com] D3DDecompressShaders
Decompresses one or more shaders from a compressed set.
Arguments
src_data
- The compressed shaders to decompress.flags
- Reserved (pass None)._range
- The archive index range to read (pass..
- other options may be supported in the future.)
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_42.dll
and earlier
Example
let decompressed = d3dc.decompress_shaders(&compress, None, ..).unwrap();
assert_eq!(2, decompressed.len());
assert_eq!(basic_hlsl, decompressed[0].as_ref().unwrap().get_buffer());
assert_eq!(plain_txt, decompressed[1].as_ref().unwrap().get_buffer());
Remarks
- You can use this API to develop your Windows Store apps, but you can’t use it in apps that you submit to the Windows Store.
- This was introduced by d3dcompiler_43.dll, and is unavailable in earlier versions.
sourceimpl Compiler
impl Compiler
sourcepub fn get_blob_part(
&self,
src_data: &Bytecode,
part: impl Into<BlobPart>,
flags: Option<Infallible>
) -> Result<BytesBlob, Error>
pub fn get_blob_part(
&self,
src_data: &Bytecode,
part: impl Into<BlobPart>,
flags: Option<Infallible>
) -> Result<BytesBlob, Error>
[docs.microsoft.com] D3DGetBlobPart
Retrieves a specific part from a compilation result.
Arguments
Errors
- THINERR::MISSING_DLL_EXPORT - on
d3dcompiler_42.dll
and earlier - D3DERR::INVALIDCALL - on data that wasn’t compiled shader code.
Example
let shader2 = d3dc.set_blob_part(
&shader, Blob::PrivateData, (), b"testing 123"
).unwrap();
assert_eq!(b"testing 123", d3dc.get_blob_part(
&shader2, Blob::PrivateData, None
).unwrap().as_bytes());
Remarks
- This was introduced by d3dcompiler_43.dll, and is unavailable in earlier versions.
sourcepub fn get_debug_info(&self, src_data: &Bytecode) -> Result<BytesBlob, Error>
pub fn get_debug_info(&self, src_data: &Bytecode) -> Result<BytesBlob, Error>
[docs.microsoft.com] D3DGetDebugInfo
Note: You can use this API to develop your Windows Store apps, but you can’t use it in apps that you submit to the Windows Store.
Gets shader debug information.
Arguments
src_data
- Shader bytecode
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_39.dll
and earlier - E::FAIL -
src_data
wasn’t compiled with d3d::Compile::Debug - E::FAIL -
src_data
’s debug info is too modern? (cannot load debug info for shaders compiled withd3dcompiler_47.dll
)
Example
let d3dc = d3d::Compiler::load_system(43).unwrap();
let debug_info : d3d::BytesBlob = d3dc.get_debug_info(&shader).unwrap();
assert!(debug_info.len() > 0);
Output
BytesBlob(2625 bytes)
Remarks
- This was introduced by d3dcompiler_40.dll, and is unavailable in earlier versions.
sourcepub fn get_input_and_output_signature_blob(
&self,
src_data: &Bytecode
) -> Result<BytesBlob, Error>
pub fn get_input_and_output_signature_blob(
&self,
src_data: &Bytecode
) -> Result<BytesBlob, Error>
[docs.microsoft.com] D3DGetInputAndOutputSignatureBlob
Note: get_input_and_output_signature_blob may be altered or unavailable for releases after Windows 8.1. Instead use get_glob_part with the Blob::InputAndOutputSignatureBlob value.
Gets the input and output signatures from a compilation result.
Example
let signature = d3dc.get_input_and_output_signature_blob(&shader).unwrap();
println!("{:?}", &signature);
Output
[68, 88, 66, 67, 97, ...
sourcepub fn get_input_signature_blob(
&self,
src_data: &Bytecode
) -> Result<BytesBlob, Error>
pub fn get_input_signature_blob(
&self,
src_data: &Bytecode
) -> Result<BytesBlob, Error>
[docs.microsoft.com] D3DGetInputSignatureBlob
Note: get_input_signature_blob may be altered or unavailable for releases after Windows 8.1. Instead use get_glob_part with the Blob::InputSignatureBlob value.
Gets the input signature from a compilation result.
Example
let signature = d3dc.get_input_signature_blob(&shader).unwrap();
println!("{:?}", &signature);
Output
[68, 88, 66, 67, 53, ...
sourcepub fn get_output_signature_blob(
&self,
src_data: &Bytecode
) -> Result<BytesBlob, Error>
pub fn get_output_signature_blob(
&self,
src_data: &Bytecode
) -> Result<BytesBlob, Error>
[docs.microsoft.com] D3DGetOutputSignatureBlob
Note: get_output_signature_blob may be altered or unavailable for releases after Windows 8.1. Instead use get_glob_part with the Blob::OutputSignatureBlob value.
Gets the output signature from a compilation result.
Example
let signature = d3dc.get_output_signature_blob(&shader).unwrap();
println!("{:?}", &signature);
Output
[68, 88, 66, 67, 210, ...
sourcepub fn set_blob_part(
&self,
src_data: &Bytecode,
part: impl Into<BlobPart>,
flags: (),
part_data: &[u8]
) -> Result<CodeBlob, Error>
pub fn set_blob_part(
&self,
src_data: &Bytecode,
part: impl Into<BlobPart>,
flags: (),
part_data: &[u8]
) -> Result<CodeBlob, Error>
[docs.microsoft.com] D3DSetBlobPart
Sets information in a compilation result.
Arguments
src_data
- The original compiled shader data.part
- What part to replace (currently only Blob::PrivateData is supported.)flags
- Resereved. Pass()
.part_data
- The part data to set.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_43.dll
and earlier
Example
let shader2 = d3dc.set_blob_part(
&shader, Blob::PrivateData, (), b"testing 123"
).unwrap();
assert_eq!(b"testing 123", d3dc.get_blob_part(
&shader2, Blob::PrivateData, None
).unwrap().as_bytes());
Remarks
- This was introduced by d3dcompiler_44.dll, and is unavailable in earlier versions.
sourcepub fn strip_shader(
&self,
src_data: &Bytecode,
strip_flags: impl Into<CompilerStripFlags>
) -> Result<CodeBlob, Error>
pub fn strip_shader(
&self,
src_data: &Bytecode,
strip_flags: impl Into<CompilerStripFlags>
) -> Result<CodeBlob, Error>
[docs.microsoft.com] D3DStripShader
Removes unwanted blobs from a compilation result.
Arguments
src_data
- The original shader bytecode.strip_flags
- The CompilerStripFlags to use.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_39.dll
and earlier
Example
let shader = d3dc.compile_from_file(
r"test\data\basic.hlsl", None, None, "ps_main", "ps_4_0",
Compile::Debug, CompileEffect::None
).unwrap();
let shader = d3dc.strip_shader(
&shader, CompilerStripFlags::DebugInfo
).unwrap();
Remarks
- This was introduced by d3dcompiler_40.dll, and is unavailable in earlier versions.
sourceimpl Compiler
impl Compiler
sourcepub fn reflect<I: Raw>(&self, src_data: &Bytecode) -> Result<I, Error> where
I::Raw: Interface,
pub fn reflect<I: Raw>(&self, src_data: &Bytecode) -> Result<I, Error> where
I::Raw: Interface,
[docs.microsoft.com] D3DReflect
Gets a pointer to a reflection interface.
Arguments
src_data
- A compiled HLSL shader.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_4?.dll
and earlier - E::INVALIDARG - On invalid
I
- D3DERR::INVALIDCALL - On invalid
src_data
- D3DERR::INVALIDCALL - On shaders not compatible with
I
(e.g. Shader Model 3 shaders withI: d3d11::ShaderReflection
Example
let shader = d3dc.compile_from_file(
r"test\data\basic.hlsl", None, None, "ps_main", "ps_4_0",
Compile::Debug, CompileEffect::None
).unwrap();
// Should succeed:
let r = d3dc.reflect::<d3d11::ShaderReflection>(&shader).unwrap();
// Invalid interface:
let r = d3dc.reflect::<Unknown>(&shader);
assert_eq!(E::INVALIDARG, r.map(|_|()));
// Invalid `src_data`:
let r = d3dc.reflect::<d3d11::ShaderReflection>(unsafe { Bytecode::from_unchecked(&[]) });
assert_eq!(D3DERR::INVALIDCALL, r.map(|_|()));
See Also
- d3d11::ShaderReflection for a more complete example
Remarks
- This was introduced by d3dcompiler_40.dll, and is unavailable in earlier versions.
sourcepub fn reflect11(&self, src_data: &Bytecode) -> Result<ShaderReflection, Error>
pub fn reflect11(&self, src_data: &Bytecode) -> Result<ShaderReflection, Error>
[docs.microsoft.com] D3DReflect
Gets a pointer to a reflection interface.
Arguments
src_data
- A compiled HLSL shader.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_4?.dll
and earlier - D3DERR::INVALIDCALL - On invalid
src_data
- D3DERR::INVALIDCALL - On shaders not compatible with
d3d11::ShaderReflection
(e.g. Shader Model 3.0 and earlier)
Example
let shader = d3dc.compile_from_file(
r"test\data\basic.hlsl", None, None, "ps_main", "ps_4_0",
Compile::Debug, CompileEffect::None
).unwrap();
// Should succeed:
let r = d3dc.reflect11(&shader).unwrap();
// Invalid `src_data`:
let r = d3dc.reflect11(unsafe { Bytecode::from_unchecked(&[]) });
assert_eq!(D3DERR::INVALIDCALL, r.map(|_|()));
See Also
- d3d11::ShaderReflection for a more complete example
Remarks
- This was introduced by d3dcompiler_40.dll, and is unavailable in earlier versions.
sourcepub fn reflect_library<I: Raw>(&self, src_data: &Bytecode) -> Result<I, Error> where
I::Raw: Interface,
pub fn reflect_library<I: Raw>(&self, src_data: &Bytecode) -> Result<I, Error> where
I::Raw: Interface,
[docs.microsoft.com] D3DReflectLibrary
Creates a library-reflection interface from source data that contains an HLSL library of functions.
Note: This function is part of the HLSL shader linking technology that you can use on all Direct3D 11 platforms to create precompiled HLSL functions, package them into libraries, and link them into full shaders at run time.
Arguments
src_data
- An HLSL library of functions.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_4?.dll
and earlier - E::INVALIDARG - On invalid
I
- D3DERR::INVALIDCALL - On invalid
src_data
- D3DERR::INVALIDCALL - On shaders not compatible with
I
(e.g. Shader Model 3 shaders withI: d3d11::ShaderReflection
Example
let shader = d3dc.compile_from_file(
r"test\data\library.hlsl", None, None, (), "lib_5_0",
Compile::Debug, CompileEffect::None
).unwrap();
// Should succeed:
let r = d3dc.reflect_library::<d3d11::LibraryReflection>(&shader).unwrap();
// Invalid interface:
let r = d3dc.reflect_library::<Unknown>(&shader);
assert_eq!(E::INVALIDARG, r.map(|_|()));
// Invalid `src_data`:
let r = d3dc.reflect_library::<d3d11::LibraryReflection>(unsafe { Bytecode::from_unchecked(&[]) });
assert_eq!(D3DERR::INVALIDCALL, r.map(|_|()));
See Also
- d3d11::LibraryReflection for a more complete example
sourcepub fn reflect_library_11(
&self,
src_data: &Bytecode
) -> Result<LibraryReflection, Error>
pub fn reflect_library_11(
&self,
src_data: &Bytecode
) -> Result<LibraryReflection, Error>
[docs.microsoft.com] D3DReflectLibrary
Creates a library-reflection interface from source data that contains an HLSL library of functions.
Note: This function is part of the HLSL shader linking technology that you can use on all Direct3D 11 platforms to create precompiled HLSL functions, package them into libraries, and link them into full shaders at run time.
Arguments
src_data
- An HLSL library of functions.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_4?.dll
and earlier - D3DERR::INVALIDCALL - On invalid
src_data
- D3DERR::INVALIDCALL - On shaders not compatible with
d3d11::LibraryReflection
(e.g. Shader Model 3.0 and earlier)
Example
let shader = d3dc.compile_from_file(
r"test\data\library.hlsl", None, None, (), "lib_5_0",
Compile::Debug, CompileEffect::None
).unwrap();
// Should succeed:
let r = d3dc.reflect_library_11(&shader).unwrap();
// Invalid `src_data`:
let r = d3dc.reflect_library_11(unsafe { Bytecode::from_unchecked(&[]) });
assert_eq!(D3DERR::INVALIDCALL, r.map(|_|()));
See Also
- d3d11::LibraryReflection for a more complete example
sourceimpl Compiler
impl Compiler
sourcepub fn disassemble(
&self,
src_data: &Bytecode,
flags: impl Into<Disasm>,
comments: impl TryIntoAsOptCStr
) -> Result<TextBlob, Error>
pub fn disassemble(
&self,
src_data: &Bytecode,
flags: impl Into<Disasm>,
comments: impl TryIntoAsOptCStr
) -> Result<TextBlob, Error>
[docs.microsoft.com] D3DDisassemble
Disassembles compiled HLSL code.
Arguments
src_data
- Compiled HLSL code.flags
- Disasm flags controlling how the compiled shader data is disassembled.comments
- Optional string at the top of the shader that identifies the shader constants and variables.
Errors
- THINERR::MISSING_DLL_EXPORT - on
d3dcompiler_39.dll
and earlier
Example
let dis = d3dc.disassemble(&shader, Disasm::None, "// example comment\n").unwrap();
println!("{}", dis.to_utf8_lossy());
Output
//
// Generated by Microsoft (R) HLSL Shader Compiler 10.1
//
// example comment
//
//
// Input signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
// COLOR 0 xyzw 0 NONE float xyzw
// SV_POSITION 0 xyzw 1 POS float
//
//
// Output signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
// SV_TARGET 0 xyzw 0 TARGET float xyzw
//
ps_4_0
dcl_input_ps linear v0.xyzw
dcl_output o0.xyzw
//
// Initial variable locations:
// v0.x <- i.color.x; v0.y <- i.color.y; v0.z <- i.color.z; v0.w <- i.color.w;
// v1.x <- i.position.x; v1.y <- i.position.y; v1.z <- i.position.z; v1.w <- i.position.w;
// o0.x <- <ps_main return value>.color.x; o0.y <- <ps_main return value>.color.y; o0.z <- <ps_main return value>.color.z; o0.w <- <ps_main return value>.color.w
//
#line 27 "C:\local\thindx\test\data\basic.hlsl"
mov o0.xyzw, v0.xyzw
ret
// Approximately 2 instruction slots used
Remarks
- This was introduced by d3dcompiler_40.dll, and is unavailable in earlier versions.
sourcepub fn disassemble_region(
&self,
src_data: &Bytecode,
flags: impl Into<Disasm>,
comments: impl TryIntoAsOptCStr,
start_byte_offset: usize,
num_insts: usize
) -> Result<DisassembledRegion, Error>
pub fn disassemble_region(
&self,
src_data: &Bytecode,
flags: impl Into<Disasm>,
comments: impl TryIntoAsOptCStr,
start_byte_offset: usize,
num_insts: usize
) -> Result<DisassembledRegion, Error>
[docs.microsoft.com] D3DDisassembleRegion
Disassembles a specific region of compiled Microsoft High Level Shader Language (HLSL) code.
Arguments
src_data
- Compiled HLSL code.flags
- Disasm flags controlling how the compiled shader data is disassembled.comments
- Optional string at the top of the shader that identifies the shader constants and variables.start_byte_offset
- The number of bytes offset into the compiled shader data where disassemble_region starts the disassembly.num_insts
- The number of instructions to disassemble.
Errors
- THINERR::MISSING_DLL_EXPORT - on
d3dcompiler_43.dll
and earlier
Example
let dr = d3dc.disassemble_region(
&shader, Disasm::None, "// example comment\n", 0, std::usize::MAX
).unwrap();
println!("finish_byte_offset: {}", dr.finish_byte_offset);
println!("{}", dr.disassembly.to_utf8_lossy());
Output
finish_byte_offset: 56
//
// Generated by Microsoft (R) HLSL Shader Compiler 10.1
//
// example comment
//
//
// Input signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
// COLOR 0 xyzw 0 NONE float xyzw
// SV_POSITION 0 xyzw 1 POS float
//
//
// Output signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
// SV_TARGET 0 xyzw 0 TARGET float xyzw
//
ps_4_0
dcl_input_ps linear v0.xyzw
dcl_output o0.xyzw
//
// Initial variable locations:
// v0.x <- i.color.x; v0.y <- i.color.y; v0.z <- i.color.z; v0.w <- i.color.w;
// v1.x <- i.position.x; v1.y <- i.position.y; v1.z <- i.position.z; v1.w <- i.position.w;
// o0.x <- <ps_main return value>.color.x; o0.y <- <ps_main return value>.color.y; o0.z <- <ps_main return value>.color.z; o0.w <- <ps_main return value>.color.w
//
#line 27 "C:\local\thindx\test\data\basic.hlsl"
mov o0.xyzw, v0.xyzw
ret
// Approximately 2 instruction slots used
Remarks
- This was introduced by d3dcompiler_44.dll, and is unavailable in earlier versions.
sourcepub fn get_trace_instruction_offsets_count(
&self,
src_data: &Bytecode,
flags: impl Into<GetInstOffsets>,
start_inst_index: usize,
num_insts: usize
) -> Result<usize, Error>
pub fn get_trace_instruction_offsets_count(
&self,
src_data: &Bytecode,
flags: impl Into<GetInstOffsets>,
start_inst_index: usize,
num_insts: usize
) -> Result<usize, Error>
[docs.microsoft.com] D3DGetTraceInstructionOffsets
Retrieves the number of byte offsets for instructions within a section of shader code.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_43.dll
and earlier
Example
println!("{}", d3dc.get_trace_instruction_offsets_count(
&shader, GetInstOffsets::None, 0, std::usize::MAX
).unwrap());
Output
2
Remarks
- This was introduced by d3dcompiler_44.dll, and is unavailable in earlier versions.
sourcepub fn get_trace_instruction_offsets_inplace<'o>(
&self,
src_data: &Bytecode,
flags: impl Into<GetInstOffsets>,
start_inst_index: usize,
offsets: &'o mut [usize]
) -> Result<&'o [usize], Error>
pub fn get_trace_instruction_offsets_inplace<'o>(
&self,
src_data: &Bytecode,
flags: impl Into<GetInstOffsets>,
start_inst_index: usize,
offsets: &'o mut [usize]
) -> Result<&'o [usize], Error>
[docs.microsoft.com] D3DGetTraceInstructionOffsets
Retrieves the byte offsets for instructions within a section of shader code.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_43.dll
and earlier
Example
let mut offsets = [0; 128];
let offsets : &[usize] = d3dc.get_trace_instruction_offsets_inplace(
&shader, GetInstOffsets::None, 0, &mut offsets
).unwrap();
println!("{:?}", offsets);
Output
[32, 52]
Remarks
- This was introduced by d3dcompiler_44.dll, and is unavailable in earlier versions.
sourcepub fn get_trace_instruction_offsets(
&self,
src_data: &Bytecode,
flags: impl Into<GetInstOffsets>,
start_inst_index: usize,
num_insts: usize
) -> Result<Vec<usize>, Error>
pub fn get_trace_instruction_offsets(
&self,
src_data: &Bytecode,
flags: impl Into<GetInstOffsets>,
start_inst_index: usize,
num_insts: usize
) -> Result<Vec<usize>, Error>
[docs.microsoft.com] D3DGetTraceInstructionOffsets
Retrieves the byte offsets for instructions within a section of shader code.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_43.dll
and earlier
Example
let offsets : Vec<usize> = d3dc.get_trace_instruction_offsets(
&shader, GetInstOffsets::None, 0, std::usize::MAX
).unwrap();
println!("{:?}", offsets);
Output
[32, 52]
Remarks
- This was introduced by d3dcompiler_44.dll, and is unavailable in earlier versions.
sourceimpl Compiler
impl Compiler
sourcepub fn create_read_only_blob(&self, data: &[u8]) -> Result<ReadOnlyBlob, Error>
pub fn create_read_only_blob(&self, data: &[u8]) -> Result<ReadOnlyBlob, Error>
[docs.microsoft.com] D3DCreateBlob
Compresses a set of shaders into a more compact form.
Arguments
data
- The data to create a ReadOnlyBlob out of.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_42.dll
and earlier
Example
let blob = d3dc.create_read_only_blob(&[1,2,3,4]).unwrap();
assert_eq!(blob.get_buffer_size(), 4 );
assert_eq!(blob.get_buffer(), &[1,2,3,4] );
Remarks
- This was introduced by d3dcompiler_43.dll, and is unavailable in earlier versions.
sourcepub fn read_file_to_blob(
&self,
file_name: impl AsRef<Path>
) -> Result<ReadOnlyBlob, Error>
pub fn read_file_to_blob(
&self,
file_name: impl AsRef<Path>
) -> Result<ReadOnlyBlob, Error>
[docs.microsoft.com] D3DReadFileToBlob
Note: You can use this API to develop your Windows Store apps, but you can’t use it in apps that you submit to the Windows Store.
Reads a file into memory.
Arguments
file_name
- The path to read the blob from.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_43.dll
and earlier - HResultError::from_win32:
- ERROR::FILE_NOT_FOUND -
file_name
not found - ERROR::ACCESS_DENIED - Access denied (
file_name
not a file? bad perms? …?)
- ERROR::FILE_NOT_FOUND -
Example
let blob : ReadOnlyBlob = d3dc.read_file_to_blob(r"test\data\basic.hlsl").unwrap();
let err = d3dc.read_file_to_blob(r"test\data\nonexistant");
assert_eq!(err, HResultError::from_win32(ERROR::FILE_NOT_FOUND));
let err = d3dc.read_file_to_blob(r"test\data");
assert_eq!(err, HResultError::from_win32(ERROR::ACCESS_DENIED));
Remarks
- This was introduced by d3dcompiler_44.dll, and is unavailable in earlier versions.
sourcepub fn write_blob_to_file(
&self,
blob: &ReadOnlyBlob,
file_name: impl AsRef<Path>,
overwrite: bool
) -> Result<(), Error>
pub fn write_blob_to_file(
&self,
blob: &ReadOnlyBlob,
file_name: impl AsRef<Path>,
overwrite: bool
) -> Result<(), Error>
[docs.microsoft.com] D3DWriteBlobToFile
Note: You can use this API to develop your Windows Store apps, but you can’t use it in apps that you submit to the Windows Store.
Writes a memory blob to a file on disk.
Arguments
blob
- The blob of data to write to disk.file_name
- The path to write it to.overwrite
- Overwrite any existing file.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_43.dll
and earlier - HResultError::from_win32:
- ERROR::PATH_NOT_FOUND - Path not found (missing filename in
file_name
) - ERROR::ACCESS_DENIED - Access denied (target
file_name
is a directory?) - ERROR::FILE_EXISTS -
file_name
already exists (if!overwrite
)
- ERROR::PATH_NOT_FOUND - Path not found (missing filename in
Example
let blob = d3dc.create_read_only_blob(&[1,2,3,4]).unwrap();
d3dc.write_blob_to_file(&blob, r"..\target\1234.bin", true).unwrap();
let err = d3dc.write_blob_to_file(&blob, r"..\target\1234.bin", false);
assert_eq!(err, HResultError::from_win32(ERROR::FILE_EXISTS));
let err = d3dc.write_blob_to_file(&blob, r"..\target\", false);
assert_eq!(err, HResultError::from_win32(ERROR::PATH_NOT_FOUND));
let err = d3dc.write_blob_to_file(&blob, r"..\target", false);
assert_eq!(err, HResultError::from_win32(ERROR::ACCESS_DENIED));
Remarks
- This was introduced by d3dcompiler_44.dll, and is unavailable in earlier versions.
sourceimpl Compiler
impl Compiler
sourcepub fn create_function_linking_graph(
&self,
flags: Option<Infallible>
) -> Result<FunctionLinkingGraph, Error>
pub fn create_function_linking_graph(
&self,
flags: Option<Infallible>
) -> Result<FunctionLinkingGraph, Error>
[docs.microsoft.com] D3DCreateFunctionLinkingGraph
Creates a function-linking-graph interface.
Note: This function is part of the HLSL shader linking technology that you can use on all Direct3D 11 platforms to create precompiled HLSL functions, package them into libraries, and link them into full shaders at run time.
Arguments
flags
- Reserved, initialize withNone
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_4?.dll
and earlier
Example
let flg: d3d11::FunctionLinkingGraph = d3dc.create_function_linking_graph(None).unwrap();
Remarks
- This was introduced by d3dcompiler_47.dll, and is unavailable in earlier versions.
sourcepub fn create_linker(&self) -> Result<Linker, Error>
pub fn create_linker(&self) -> Result<Linker, Error>
[docs.microsoft.com] D3DCreateLinker
Creates a linker interface.
Note: This function is part of the HLSL shader linking technology that you can use on all Direct3D 11 platforms to create precompiled HLSL functions, package them into libraries, and link them into full shaders at run time.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_4?.dll
and earlier
Example
let linker : d3d11::Linker = d3dc.create_linker().unwrap();
Remarks
- This was introduced by d3dcompiler_47.dll, and is unavailable in earlier versions.
sourcepub fn load_module(&self, src_data: &Bytecode) -> Result<Module, Error>
pub fn load_module(&self, src_data: &Bytecode) -> Result<Module, Error>
[docs.microsoft.com] D3DLoadModule
Creates a shader module interface from source data for the shader module.
Note: This function is part of the HLSL shader linking technology that you can use on all Direct3D 11 platforms to create precompiled HLSL functions, package them into libraries, and link them into full shaders at run time.
Arguments
src_data
- The data to load a d3d11::Module from.
Errors
- THINERR::MISSING_DLL_EXPORT -
d3dcompiler_4?.dll
and earlier
Example
let source = "export float4 example(float4 i) { return 2*i; }";
let CompileResult { shader: code_blob, errors: error_blob } = d3dc.compile(
source.as_bytes(), "example.hlsl",
None, None, (), "lib_5_0",
Compile::OptimizationLevel3, CompileEffect::None,
).unwrap();
let shader_library = d3dc.load_module(&code_blob).unwrap();
Remarks
- This was introduced by d3dcompiler_47.dll, and is unavailable in earlier versions.
Auto Trait Implementations
impl RefUnwindSafe for Compiler
impl Send for Compiler
impl Sync for Compiler
impl Unpin for Compiler
impl UnwindSafe for Compiler
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more