//----------------------------------------------------------------------------- bool CPUTShaderDX11::ShaderRequiresPerModelPayload( CPUTConfigBlock &properties ) { ID3D11ShaderReflection *pReflector = NULL; D3DReflect( mpBlob->GetBufferPointer(), mpBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pReflector); // Walk through the shader input bind descriptors. // If any of them begin with '@', then we need a unique material per model (i.e., we need to clone the material). int ii=0; D3D11_SHADER_INPUT_BIND_DESC desc; HRESULT hr = pReflector->GetResourceBindingDesc( ii++, &desc ); while( SUCCEEDED(hr) ) { cString tagName = s2ws(desc.Name); CPUTConfigEntry *pValue = properties.GetValueByName(tagName); if( !pValue->IsValid() ) { // We didn't find our property in the file. Is it in the global config block? pValue = CPUTMaterial::mGlobalProperties.GetValueByName(tagName); } cString boundName = pValue->ValueAsString(); if( (boundName.length() > 0) && ((boundName[0] == '@') || (boundName[0] == '#')) ) { return true; } hr = pReflector->GetResourceBindingDesc( ii++, &desc ); } return false; }
void PixelShader::InitFromFile(std::string inFileName) { assert(FileUtil::FileExists(inFileName.c_str())); CleanUp(); DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; std::wstring filename = std::wstring(inFileName.begin(), inFileName.end()); #ifdef _DEBUG dwShaderFlags |= D3DCOMPILE_DEBUG; dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; #endif ID3DBlob* pPSBlob = nullptr; ID3DBlob* pErrorBlob = nullptr; D3DCall(D3DCompileFromFile(filename.c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "PS", "ps_5_0", dwShaderFlags, 0, &pPSBlob, &pErrorBlob)); if (pErrorBlob) { OutputDebugStringA(reinterpret_cast<const char*>(pErrorBlob->GetBufferPointer())); pErrorBlob->Release(); } ID3D11ShaderReflection* pPixelShaderReflection = NULL; D3DCall(D3DReflect(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pPixelShaderReflection)); D3D11_SHADER_DESC shader_desc; pPixelShaderReflection->GetDesc(&shader_desc); for (int i = 0; i < shader_desc.BoundResources; i++) { D3D11_SHADER_INPUT_BIND_DESC resource_desc; pPixelShaderReflection->GetResourceBindingDesc(i, &resource_desc); // FETCH RESOURCES switch (resource_desc.Type) { case D3D_SHADER_INPUT_TYPE::D3D_SIT_TEXTURE: mTextures[resource_desc.Name] = resource_desc.BindPoint; break; case D3D_SHADER_INPUT_TYPE::D3D_SIT_SAMPLER: mSamplers[resource_desc.Name] = resource_desc.BindPoint; break; case D3D_SHADER_INPUT_TYPE::D3D_SIT_CBUFFER: mConstantBuffers[resource_desc.Name] = resource_desc.BindPoint; break; default: break; } } D3DCall(theRenderContext.GetDevice()->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &mHandle)); pPSBlob->Release(); }
static void dx11_fill_constant_table(ShaderConstantTable& out_constants, ShaderConstantTable& out_samplers, const ShaderCode& bytecode) { out_constants.clear(); out_samplers.clear(); ID3D11ShaderReflection* refl = NULL; D3DReflect( bytecode.data(), bytecode.size(), IID_ID3D11ShaderReflection, (void**)&refl); if( refl ) { HRESULT hr = S_OK; D3D11_SHADER_DESC refl_desc; hr = refl->GetDesc(&refl_desc); for( uint32 i=0; i<refl_desc.ConstantBuffers; ++i ) { ID3D11ShaderReflectionConstantBuffer* cb = refl->GetConstantBufferByIndex(i); D3D11_SHADER_BUFFER_DESC sb_desc; cb->GetDesc(&sb_desc); for( uint32 j=0; j<sb_desc.Variables; ++j ) { ID3D11ShaderReflectionVariable* var = cb->GetVariableByIndex(j); D3D11_SHADER_VARIABLE_DESC var_desc; var->GetDesc(&var_desc); ShaderConstantDescr scd; scd.name = var_desc.Name; scd.register_index = var_desc.StartOffset/16; scd.register_count = var_desc.Size/16; out_constants.push_back(scd); } } for( uint32 i=0; i<refl_desc.BoundResources; ++i ) { D3D11_SHADER_INPUT_BIND_DESC desc; refl->GetResourceBindingDesc(i, &desc); if( desc.Type == D3D10_SIT_SAMPLER ) { ShaderConstantDescr scd; scd.name = desc.Name; scd.register_index = desc.BindPoint; scd.register_count = desc.BindCount; } } refl->Release(); } }
void ComputeShader::ShaderConstants::Enumerate( ID3DBlob& _ShaderBlob ) { ID3D11ShaderReflection* pReflector = NULL; D3DReflect( _ShaderBlob.GetBufferPointer(), _ShaderBlob.GetBufferSize(), IID_ID3D11ShaderReflection, (void**) &pReflector ); D3D11_SHADER_DESC ShaderDesc; pReflector->GetDesc( &ShaderDesc ); // Enumerate bound resources for ( int ResourceIndex=0; ResourceIndex < int(ShaderDesc.BoundResources); ResourceIndex++ ) { D3D11_SHADER_INPUT_BIND_DESC BindDesc; pReflector->GetResourceBindingDesc( ResourceIndex, &BindDesc ); BindingDesc** ppDesc = NULL; switch ( BindDesc.Type ) { case D3D_SIT_TEXTURE: ppDesc = &m_TextureName2Descriptor.Add( BindDesc.Name ); break; case D3D_SIT_CBUFFER: ppDesc = &m_ConstantBufferName2Descriptor.Add( BindDesc.Name ); break; case D3D_SIT_STRUCTURED: ppDesc = &m_StructuredBufferName2Descriptor.Add( BindDesc.Name ); break; case D3D_SIT_UAV_RWTYPED: case D3D_SIT_UAV_RWSTRUCTURED: case D3D_SIT_UAV_RWBYTEADDRESS: case D3D_SIT_UAV_APPEND_STRUCTURED: case D3D_SIT_UAV_CONSUME_STRUCTURED: case D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER: ppDesc = &m_UAVName2Descriptor.Add( BindDesc.Name ); break; } if ( ppDesc == NULL ) continue; // We're not interested in that type ! *ppDesc = new BindingDesc(); (*ppDesc)->SetName( BindDesc.Name ); (*ppDesc)->Slot = BindDesc.BindPoint; #ifdef __DEBUG_UPLOAD_ONLY_ONCE (*ppDesc)->bUploaded = false; // Not uploaded yet ! #endif } pReflector->Release(); }
void ShaderReflection::Reflect(ID3D10Blob* shader) { ID3D11ShaderReflection* reflector = 0; D3D11_SIGNATURE_PARAMETER_DESC input, output; D3D11_SHADER_INPUT_BIND_DESC resource; //Bind point is the register location D3DReflect(shader->GetBufferPointer(), shader->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&reflector); reflector->GetDesc(&shaderDesc); inputParams.paramCount = shaderDesc.InputParameters; inputParams.params = new D3D11_SIGNATURE_PARAMETER_DESC[inputParams.paramCount]; for(u32 i = 0; i < shaderDesc.InputParameters; ++i) { reflector->GetInputParameterDesc(i, &input); inputParams.params[i] = input; } outputParams.paramCount = shaderDesc.OutputParameters; outputParams.params = new D3D11_SIGNATURE_PARAMETER_DESC[outputParams.paramCount]; for(u32 i = 0; i < shaderDesc.OutputParameters; ++i) { reflector->GetOutputParameterDesc(i, &output); outputParams.params[i] = output; } for(u32 i = 0; i < shaderDesc.BoundResources; ++i) { reflector->GetResourceBindingDesc(i, &resource); if(resource.Type == D3D_SIT_CBUFFER) { ProcessCbuffer(reflector->GetConstantBufferByName(resource.Name)); } else if(resource.Type == D3D_SIT_SAMPLER) { } else if(resource.Type == D3D_SIT_TEXTURE) { } else {} } }
// http://wine-wiki.org/index.php/WineLib#Calling_a_Native_Windows_dll_from_Linux int main(int argc, char* argv[]) { D3DCompiler d3d_compiler; if (argc < 2) { PrintHelps(); return -1; } if (0 == strcmp(argv[1], "compile")) { if (argc < 8) { PrintHelps(); return -1; } char const * input_file = argv[2]; char const * entry_point = argv[3]; char const * target = argv[4]; int flags1 = atoi(argv[5]); int flags2 = atoi(argv[6]); char const * output_file = argv[7]; FILE* fp = fopen(input_file, "rb"); int hlsl_size; fread(&hlsl_size, sizeof(hlsl_size), 1, fp); char* hlsl = new char[hlsl_size + 1]; fread(hlsl, sizeof(char), hlsl_size, fp); hlsl[hlsl_size] = 0; int num_macros; fread(&num_macros, sizeof(num_macros), 1, fp); D3D_SHADER_MACRO* macros = new D3D_SHADER_MACRO[num_macros + 1]; char line_name[1024]; char line_definition[1024]; int idx = 0; while (fgets(line_name, 1024, fp) && fgets(line_definition, 1024, fp)) { char* t1 = new char[strlen(line_name) + 1]; strcpy(t1, line_name); if ('\n' == t1[strlen(t1) - 1]) { t1[strlen(t1) - 1] = '\0'; } char* t2 = new char[strlen(line_definition) + 1]; strcpy(t2, line_definition); if ('\n' == t2[strlen(t2) - 1]) { t2[strlen(t2) - 1] = '\0'; } macros[idx].Name = t1; macros[idx].Definition = t2; ++ idx; } macros[idx].Name = NULL; macros[idx].Definition = NULL; fclose(fp); ID3DBlob* code = NULL; ID3DBlob* err_msg = NULL; int hr = d3d_compiler.D3DCompile(hlsl, hlsl_size, NULL, macros, NULL, entry_point, target, flags1, flags2, &code, &err_msg); if (FAILED(hr)) { printf("Compiling error: 0x%x\n", hr); } fp = fopen(output_file, "wb"); fwrite(&hr, sizeof(hr), 1, fp); if (code != NULL) { int const size = static_cast<int>(code->GetBufferSize()); fwrite(&size, sizeof(size), 1, fp); fwrite(code->GetBufferPointer(), sizeof(char), size, fp); } else { int const size = 0; fwrite(&size, sizeof(size), 1, fp); } if (err_msg != NULL) { int const size = static_cast<int>(err_msg->GetBufferSize()); fwrite(&size, sizeof(size), 1, fp); fwrite(err_msg->GetBufferPointer(), sizeof(char), err_msg->GetBufferSize(), fp); } else { int const size = 0; fwrite(&size, sizeof(size), 1, fp); } fclose(fp); for (int i = 0; i < num_macros; ++ i) { delete[] macros[i].Name; delete[] macros[i].Definition; } delete[] macros; delete[] hlsl; } else if (0 == strcmp(argv[1], "reflect")) { if (argc < 4) { PrintHelps(); return -1; } char const * input_file = argv[2]; char const * output_file = argv[3]; FILE* fp = fopen(input_file, "rb"); fseek(fp, 0, SEEK_END); long bytecode_size = ftell(fp); fseek(fp, 0, SEEK_SET); char* bytecode = new char[bytecode_size]; fread(bytecode, sizeof(char), bytecode_size, fp); fclose(fp); ID3D11ShaderReflection* reflection; int hr = d3d_compiler.D3DReflect(bytecode, bytecode_size, IID_ID3D11ShaderReflection_47, reinterpret_cast<void**>(&reflection)); if (FAILED(hr)) { printf("Reflect error: 0x%x\n", hr); } if (reflection != NULL) { fp = fopen(output_file, "wb"); D3D11_SHADER_DESC desc; reflection->GetDesc(&desc); fwrite(&desc.Version, sizeof(desc.Version), 1, fp); WriteString(desc.Creator, fp); fwrite(&desc.Flags, sizeof(desc.Flags), 1, fp); fwrite(&desc.ConstantBuffers, sizeof(desc.ConstantBuffers), 1, fp); fwrite(&desc.BoundResources, sizeof(desc.BoundResources), 1, fp); fwrite(&desc.InputParameters, sizeof(desc.InputParameters), 1, fp); fwrite(&desc.OutputParameters, sizeof(desc.OutputParameters), 1, fp); fwrite(&desc.InstructionCount, sizeof(desc.InstructionCount), 1, fp); fwrite(&desc.TempRegisterCount, sizeof(desc.TempRegisterCount), 1, fp); fwrite(&desc.TempArrayCount, sizeof(desc.TempArrayCount), 1, fp); fwrite(&desc.DefCount, sizeof(desc.DefCount), 1, fp); fwrite(&desc.DclCount, sizeof(desc.DclCount), 1, fp); fwrite(&desc.TextureNormalInstructions, sizeof(desc.TextureNormalInstructions), 1, fp); fwrite(&desc.TextureLoadInstructions, sizeof(desc.TextureLoadInstructions), 1, fp); fwrite(&desc.TextureCompInstructions, sizeof(desc.TextureCompInstructions), 1, fp); fwrite(&desc.TextureBiasInstructions, sizeof(desc.TextureBiasInstructions), 1, fp); fwrite(&desc.TextureGradientInstructions, sizeof(desc.TextureGradientInstructions), 1, fp); fwrite(&desc.FloatInstructionCount, sizeof(desc.FloatInstructionCount), 1, fp); fwrite(&desc.IntInstructionCount, sizeof(desc.IntInstructionCount), 1, fp); fwrite(&desc.UintInstructionCount, sizeof(desc.UintInstructionCount), 1, fp); fwrite(&desc.StaticFlowControlCount, sizeof(desc.StaticFlowControlCount), 1, fp); fwrite(&desc.DynamicFlowControlCount, sizeof(desc.DynamicFlowControlCount), 1, fp); fwrite(&desc.MacroInstructionCount, sizeof(desc.MacroInstructionCount), 1, fp); fwrite(&desc.ArrayInstructionCount, sizeof(desc.ArrayInstructionCount), 1, fp); fwrite(&desc.CutInstructionCount, sizeof(desc.CutInstructionCount), 1, fp); fwrite(&desc.EmitInstructionCount, sizeof(desc.EmitInstructionCount), 1, fp); fwrite(&desc.GSOutputTopology, sizeof(desc.GSOutputTopology), 1, fp); fwrite(&desc.GSMaxOutputVertexCount, sizeof(desc.GSMaxOutputVertexCount), 1, fp); fwrite(&desc.InputPrimitive, sizeof(desc.InputPrimitive), 1, fp); fwrite(&desc.PatchConstantParameters, sizeof(desc.PatchConstantParameters), 1, fp); fwrite(&desc.cGSInstanceCount, sizeof(desc.cGSInstanceCount), 1, fp); fwrite(&desc.cControlPoints, sizeof(desc.cControlPoints), 1, fp); fwrite(&desc.HSOutputPrimitive, sizeof(desc.HSOutputPrimitive), 1, fp); fwrite(&desc.HSPartitioning, sizeof(desc.HSPartitioning), 1, fp); fwrite(&desc.TessellatorDomain, sizeof(desc.TessellatorDomain), 1, fp); fwrite(&desc.cBarrierInstructions, sizeof(desc.cBarrierInstructions), 1, fp); fwrite(&desc.cInterlockedInstructions, sizeof(desc.cInterlockedInstructions), 1, fp); fwrite(&desc.cTextureStoreInstructions, sizeof(desc.cTextureStoreInstructions), 1, fp); for (UINT c = 0; c < desc.ConstantBuffers; ++ c) { ID3D11ShaderReflectionConstantBuffer* reflection_cb = reflection->GetConstantBufferByIndex(c); D3D11_SHADER_BUFFER_DESC d3d_cb_desc; reflection_cb->GetDesc(&d3d_cb_desc); WriteString(d3d_cb_desc.Name, fp); fwrite(&d3d_cb_desc.Type, sizeof(d3d_cb_desc.Type), 1, fp); fwrite(&d3d_cb_desc.Variables, sizeof(d3d_cb_desc.Variables), 1, fp); fwrite(&d3d_cb_desc.Size, sizeof(d3d_cb_desc.Size), 1, fp); fwrite(&d3d_cb_desc.uFlags, sizeof(d3d_cb_desc.uFlags), 1, fp); for (UINT v = 0; v < d3d_cb_desc.Variables; ++ v) { ID3D11ShaderReflectionVariable* reflection_var = reflection_cb->GetVariableByIndex(v); D3D11_SHADER_VARIABLE_DESC var_desc; reflection_var->GetDesc(&var_desc); fwrite(&var_desc, sizeof(var_desc), 1, fp); WriteString(var_desc.Name, fp); fwrite(&var_desc.StartOffset, sizeof(var_desc.StartOffset), 1, fp); fwrite(&var_desc.Size, sizeof(var_desc.Size), 1, fp); fwrite(&var_desc.uFlags, sizeof(var_desc.uFlags), 1, fp); fwrite(var_desc.DefaultValue, var_desc.Size, 1, fp); fwrite(&var_desc.StartTexture, sizeof(var_desc.StartTexture), 1, fp); fwrite(&var_desc.TextureSize, sizeof(var_desc.TextureSize), 1, fp); fwrite(&var_desc.StartSampler, sizeof(var_desc.StartSampler), 1, fp); fwrite(&var_desc.SamplerSize, sizeof(var_desc.SamplerSize), 1, fp); D3D11_SHADER_TYPE_DESC type_desc; reflection_var->GetType()->GetDesc(&type_desc); fwrite(&type_desc.Class, sizeof(type_desc.Class), 1, fp); fwrite(&type_desc.Type, sizeof(type_desc.Type), 1, fp); fwrite(&type_desc.Rows, sizeof(type_desc.Rows), 1, fp); fwrite(&type_desc.Columns, sizeof(type_desc.Columns), 1, fp); fwrite(&type_desc.Elements, sizeof(type_desc.Elements), 1, fp); fwrite(&type_desc.Members, sizeof(type_desc.Members), 1, fp); fwrite(&type_desc.Offset, sizeof(type_desc.Offset), 1, fp); WriteString(type_desc.Name, fp); } } for (UINT i = 0; i < desc.BoundResources; ++ i) { D3D11_SHADER_INPUT_BIND_DESC si_desc; reflection->GetResourceBindingDesc(i, &si_desc); WriteString(si_desc.Name, fp); fwrite(&si_desc.Type, sizeof(si_desc.Type), 1, fp); fwrite(&si_desc.BindPoint, sizeof(si_desc.BindPoint), 1, fp); fwrite(&si_desc.BindCount, sizeof(si_desc.BindCount), 1, fp); fwrite(&si_desc.uFlags, sizeof(si_desc.uFlags), 1, fp); fwrite(&si_desc.ReturnType, sizeof(si_desc.ReturnType), 1, fp); fwrite(&si_desc.Dimension, sizeof(si_desc.Dimension), 1, fp); fwrite(&si_desc.NumSamples, sizeof(si_desc.NumSamples), 1, fp); } UINT const shader_type = D3D11_SHVER_GET_TYPE(desc.Version); if (shader_type == D3D11_SHVER_VERTEX_SHADER) { D3D11_SIGNATURE_PARAMETER_DESC_47 signature; for (UINT i = 0; i < desc.InputParameters; ++i) { reflection->GetInputParameterDesc(i, reinterpret_cast<D3D11_SIGNATURE_PARAMETER_DESC*>(&signature)); WriteString(signature.SemanticName, fp); fwrite(&signature.SemanticIndex, sizeof(signature.SemanticIndex), 1, fp); fwrite(&signature.Register, sizeof(signature.Register), 1, fp); fwrite(&signature.SystemValueType, sizeof(signature.SystemValueType), 1, fp); fwrite(&signature.ComponentType, sizeof(signature.ComponentType), 1, fp); fwrite(&signature.Mask, sizeof(signature.Mask), 1, fp); fwrite(&signature.ReadWriteMask, sizeof(signature.ReadWriteMask), 1, fp); fwrite(&signature.Stream, sizeof(signature.Stream), 1, fp); fwrite(&signature.MinPrecision, sizeof(signature.MinPrecision), 1, fp); } } else if (shader_type == D3D11_SHVER_COMPUTE_SHADER) { UINT cs_block_size[3]; reflection->GetThreadGroupSize(&cs_block_size[0], &cs_block_size[1], &cs_block_size[2]); fwrite(cs_block_size, sizeof(cs_block_size), 1, fp); } reflection->Release(); fclose(fp); } delete[] bytecode; } else if (0 == strcmp(argv[1], "strip")) { if (argc < 5) { PrintHelps(); return -1; } char const * input_file = argv[2]; int flags = atoi(argv[3]); char const * output_file = argv[4]; FILE* fp = fopen(input_file, "rb"); fseek(fp, 0, SEEK_END); long bytecode_size = ftell(fp); fseek(fp, 0, SEEK_SET); char* bytecode = new char[bytecode_size]; fread(bytecode, sizeof(char), bytecode_size, fp); fclose(fp); ID3DBlob* code = NULL; int hr = d3d_compiler.D3DStripShader(bytecode, bytecode_size, flags, &code); if (FAILED(hr)) { printf("Strip error: 0x%x\n", hr); } fp = fopen(output_file, "wb"); fwrite(code->GetBufferPointer(), sizeof(char), code->GetBufferSize(), fp); fclose(fp); delete[] bytecode; } return 0; }
// -------------------------------------------------------- // Loads the specified shader and builds the variable table using shader // reflection. This must be a separate step from the constructor since // we can't invoke derived class overrides in the base class constructor. // // shaderFile - A "wide string" specifying the compiled shader to load // // Returns true if shader is loaded properly, false otherwise // -------------------------------------------------------- bool ISimpleShader::LoadShaderFile(LPCWSTR shaderFile) { // Load the shader to a blob and ensure it worked ID3DBlob* shaderBlob = 0; HRESULT hr = D3DReadFileToBlob(shaderFile, &shaderBlob); if (hr != S_OK) { return false; } // Create the shader - Calls an overloaded version of this abstract // method in the appropriate child class shaderValid = CreateShader(shaderBlob); if (!shaderValid) { shaderBlob->Release(); return false; } // Set up shader reflection to get information about // this shader and its variables, buffers, etc. ID3D11ShaderReflection* refl; D3DReflect( shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&refl); // Get the description of the shader D3D11_SHADER_DESC shaderDesc; refl->GetDesc(&shaderDesc); // Create an array of constant buffers constantBufferCount = shaderDesc.ConstantBuffers; constantBuffers = new SimpleConstantBuffer[constantBufferCount]; // Handle bound resources (like shaders and samplers) unsigned int resourceCount = shaderDesc.BoundResources; for (unsigned int r = 0; r < resourceCount; r++) { // Get this resource's description D3D11_SHADER_INPUT_BIND_DESC resourceDesc; refl->GetResourceBindingDesc(r, &resourceDesc); // Check the type switch (resourceDesc.Type) { case D3D_SIT_TEXTURE: // A texture resource textureTable.insert(std::pair<std::string, unsigned int>(resourceDesc.Name, resourceDesc.BindPoint)); break; case D3D_SIT_SAMPLER: // A sampler resource samplerTable.insert(std::pair<std::string, unsigned int>(resourceDesc.Name, resourceDesc.BindPoint)); break; } } // Loop through all constant buffers for (unsigned int b = 0; b < constantBufferCount; b++) { // Get this buffer ID3D11ShaderReflectionConstantBuffer* cb = refl->GetConstantBufferByIndex(b); // Get the description of this buffer D3D11_SHADER_BUFFER_DESC bufferDesc; cb->GetDesc(&bufferDesc); // Get the description of the resource binding, so // we know exactly how it's bound in the shader D3D11_SHADER_INPUT_BIND_DESC bindDesc; refl->GetResourceBindingDescByName(bufferDesc.Name, &bindDesc); // Set up the buffer and put its pointer in the table constantBuffers[b].BindIndex = bindDesc.BindPoint; cbTable.insert(std::pair<std::string, SimpleConstantBuffer*>(bufferDesc.Name, &constantBuffers[b])); // Create this constant buffer D3D11_BUFFER_DESC newBuffDesc; newBuffDesc.Usage = D3D11_USAGE_DEFAULT; newBuffDesc.ByteWidth = bufferDesc.Size; newBuffDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; newBuffDesc.CPUAccessFlags = 0; newBuffDesc.MiscFlags = 0; newBuffDesc.StructureByteStride = 0; device->CreateBuffer(&newBuffDesc, 0, &constantBuffers[b].ConstantBuffer); // Set up the data buffer for this constant buffer constantBuffers[b].LocalDataBuffer = new unsigned char[bufferDesc.Size]; ZeroMemory(constantBuffers[b].LocalDataBuffer, bufferDesc.Size); // Loop through all variables in this buffer for (unsigned int v = 0; v < bufferDesc.Variables; v++) { // Get this variable ID3D11ShaderReflectionVariable* var = cb->GetVariableByIndex(v); // Get the description of the variable D3D11_SHADER_VARIABLE_DESC varDesc; var->GetDesc(&varDesc); // Create the variable struct SimpleShaderVariable varStruct; varStruct.ConstantBufferIndex = b; varStruct.ByteOffset = varDesc.StartOffset; varStruct.Size = varDesc.Size; // Get a string version std::string varName(varDesc.Name); // Add this variable to the table varTable.insert(std::pair<std::string, SimpleShaderVariable>(varName, varStruct)); } } // All set refl->Release(); shaderBlob->Release(); return true; }
//----------------------------------------------------------------------------- void CPUTMaterialDX11::ReadShaderSamplersAndTextures( ID3DBlob *pBlob, CPUTShaderParameters *pShaderParameter ) { // *************************** // Use shader reflection to get texture and sampler names. We use them later to bind .mtl texture-specification to shader parameters/variables. // TODO: Currently do this only for PS. Do for other shader types too. // TODO: Generalize, so easy to call for different shader types // *************************** ID3D11ShaderReflection *pReflector = NULL; D3D11_SHADER_INPUT_BIND_DESC desc; D3DReflect( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pReflector); // Walk through the shader input bind descriptors. Find the samplers and textures. int ii=0; HRESULT hr = pReflector->GetResourceBindingDesc( ii++, &desc ); while( SUCCEEDED(hr) ) { switch( desc.Type ) { case D3D_SIT_TEXTURE: pShaderParameter->mTextureParameterCount++; break; case D3D_SIT_SAMPLER: pShaderParameter->mSamplerParameterCount++; break; case D3D_SIT_CBUFFER: pShaderParameter->mConstantBufferParameterCount++; break; case D3D_SIT_TBUFFER: case D3D_SIT_STRUCTURED: case D3D_SIT_BYTEADDRESS: pShaderParameter->mBufferParameterCount++; break; case D3D_SIT_UAV_RWTYPED: case D3D_SIT_UAV_RWSTRUCTURED: case D3D_SIT_UAV_RWBYTEADDRESS: case D3D_SIT_UAV_APPEND_STRUCTURED: case D3D_SIT_UAV_CONSUME_STRUCTURED: case D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER: pShaderParameter->mUAVParameterCount++; break; } hr = pReflector->GetResourceBindingDesc( ii++, &desc ); } pShaderParameter->mpTextureParameterName = new cString[pShaderParameter->mTextureParameterCount]; pShaderParameter->mpTextureParameterBindPoint = new UINT[ pShaderParameter->mTextureParameterCount]; pShaderParameter->mpSamplerParameterName = new cString[pShaderParameter->mSamplerParameterCount]; pShaderParameter->mpSamplerParameterBindPoint = new UINT[ pShaderParameter->mSamplerParameterCount]; pShaderParameter->mpBufferParameterName = new cString[pShaderParameter->mBufferParameterCount]; pShaderParameter->mpBufferParameterBindPoint = new UINT[ pShaderParameter->mBufferParameterCount]; pShaderParameter->mpUAVParameterName = new cString[pShaderParameter->mUAVParameterCount]; pShaderParameter->mpUAVParameterBindPoint = new UINT[ pShaderParameter->mUAVParameterCount]; pShaderParameter->mpConstantBufferParameterName = new cString[pShaderParameter->mConstantBufferParameterCount]; pShaderParameter->mpConstantBufferParameterBindPoint = new UINT[ pShaderParameter->mConstantBufferParameterCount]; // Start over. This time, copy the names. ii=0; UINT textureIndex = 0; UINT samplerIndex = 0; UINT bufferIndex = 0; UINT uavIndex = 0; UINT constantBufferIndex = 0; hr = pReflector->GetResourceBindingDesc( ii++, &desc ); while( SUCCEEDED(hr) ) { switch( desc.Type ) { case D3D_SIT_TEXTURE: pShaderParameter->mpTextureParameterName[textureIndex] = s2ws(desc.Name); pShaderParameter->mpTextureParameterBindPoint[textureIndex] = desc.BindPoint; textureIndex++; break; case D3D_SIT_SAMPLER: pShaderParameter->mpSamplerParameterName[samplerIndex] = s2ws(desc.Name); pShaderParameter->mpSamplerParameterBindPoint[samplerIndex] = desc.BindPoint; samplerIndex++; break; case D3D_SIT_CBUFFER: pShaderParameter->mpConstantBufferParameterName[constantBufferIndex] = s2ws(desc.Name); pShaderParameter->mpConstantBufferParameterBindPoint[constantBufferIndex] = desc.BindPoint; constantBufferIndex++; break; case D3D_SIT_TBUFFER: case D3D_SIT_STRUCTURED: case D3D_SIT_BYTEADDRESS: pShaderParameter->mpBufferParameterName[bufferIndex] = s2ws(desc.Name); pShaderParameter->mpBufferParameterBindPoint[bufferIndex] = desc.BindPoint; bufferIndex++; break; case D3D_SIT_UAV_RWTYPED: case D3D_SIT_UAV_RWSTRUCTURED: case D3D_SIT_UAV_RWBYTEADDRESS: case D3D_SIT_UAV_APPEND_STRUCTURED: case D3D_SIT_UAV_CONSUME_STRUCTURED: case D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER: pShaderParameter->mpUAVParameterName[uavIndex] = s2ws(desc.Name); pShaderParameter->mpUAVParameterBindPoint[uavIndex] = desc.BindPoint; uavIndex++; break; } hr = pReflector->GetResourceBindingDesc( ii++, &desc ); } }
void BaseShader::Initialize(std::string vsFile, std::string psFile) { if (m_bInit) { LogManager::GetInstance().Warning("You've already initialized this Shader (%p)", this); return; } HRESULT result; ID3D10Blob* errorMessage = nullptr; ID3D10Blob* vertexShaderBuffer = nullptr; ID3D10Blob* pixelShaderBuffer = nullptr; ID3D11Device* device = Application::GetInstance().GetGraphicsDevice()->GetDXSystem()->GetDevice(); result = D3DX11CompileFromFile(vsFile.c_str(), nullptr, nullptr, "main", "vs_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, nullptr, &vertexShaderBuffer, &errorMessage, nullptr); if (FAILED(result)) { if (errorMessage) { LogManager::GetInstance().Trace("[HLSL] %s", (const char*)errorMessage->GetBufferPointer()); } else { LogManager::GetInstance().Warning("InitializeShader missing shader file (%s)", vsFile); } return; } result = D3DX11CompileFromFile(psFile.c_str(), nullptr, nullptr, "main", "ps_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, nullptr, &pixelShaderBuffer, &errorMessage, nullptr); if (FAILED(result)) { if (errorMessage) { LogManager::GetInstance().Trace("[HLSL] %s", (const char*)errorMessage->GetBufferPointer()); } else { LogManager::GetInstance().Warning("InitializeShader missing shader file (%s)", psFile); } return; } result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), nullptr, &m_vertexShader); if (FAILED(result)) { LogManager::GetInstance().Error("InitializeShader could not create vertex shader"); return; } result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), nullptr, &m_pixelShader); if (FAILED(result)) { LogManager::GetInstance().Error("InitializeShader could not create pixel shader"); return; } std::vector<D3D11_INPUT_ELEMENT_DESC> polygonLayout; ID3D11ShaderReflection* vertexShaderReflection = nullptr; ID3D11ShaderReflection* pixelShaderReflection = nullptr; result = D3DReflect(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&vertexShaderReflection); if (FAILED(result)) { LogManager::GetInstance().Error("BaseShader: Could not peek into the VertexShader"); return; } result = D3DReflect(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pixelShaderReflection); if (FAILED(result)) { LogManager::GetInstance().Error("BaseShader: Could not peek into the PixelShader"); return; } D3D11_SHADER_DESC pixelDesc; pixelShaderReflection->GetDesc(&pixelDesc); for (unsigned int i = 0; i < pixelDesc.BoundResources; i++) { D3D11_SHADER_INPUT_BIND_DESC inputDesc; pixelShaderReflection->GetResourceBindingDesc(i, &inputDesc); //BindCount is the size of the array if (inputDesc.Type == D3D_SIT_TEXTURE) { m_supportedTextures[inputDesc.BindPoint] = true; } } D3D11_SHADER_DESC shaderDesc; vertexShaderReflection->GetDesc(&shaderDesc); for (unsigned int i = 0; i < shaderDesc.InputParameters; i++) { D3D11_SIGNATURE_PARAMETER_DESC paramDesc; vertexShaderReflection->GetInputParameterDesc(i, ¶mDesc); D3D11_INPUT_ELEMENT_DESC elementDesc; elementDesc.SemanticName = paramDesc.SemanticName; elementDesc.SemanticIndex = paramDesc.SemanticIndex; elementDesc.InputSlot = 0; elementDesc.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; elementDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; elementDesc.InstanceDataStepRate = 0; if (paramDesc.Mask == 1) { switch (paramDesc.ComponentType) { case D3D_REGISTER_COMPONENT_UINT32: elementDesc.Format = DXGI_FORMAT_R32_UINT; break; case D3D_REGISTER_COMPONENT_SINT32: elementDesc.Format = DXGI_FORMAT_R32_SINT; break; case D3D_REGISTER_COMPONENT_FLOAT32: elementDesc.Format = DXGI_FORMAT_R32_FLOAT; break; default: LogManager::GetInstance().Error("Shader: Unknown RegisterComponentType, Mask = 1"); return; } } else if (paramDesc.Mask <= 3) { switch (paramDesc.ComponentType) { case D3D_REGISTER_COMPONENT_UINT32: elementDesc.Format = DXGI_FORMAT_R32G32_UINT; break; case D3D_REGISTER_COMPONENT_SINT32: elementDesc.Format = DXGI_FORMAT_R32G32_SINT; break; case D3D_REGISTER_COMPONENT_FLOAT32: elementDesc.Format = DXGI_FORMAT_R32G32_FLOAT; break; default: LogManager::GetInstance().Error("Shader: Unknown RegisterComponentType, Mask <= 3"); return; } } else if (paramDesc.Mask <= 7) { switch (paramDesc.ComponentType) { case D3D_REGISTER_COMPONENT_UINT32: elementDesc.Format = DXGI_FORMAT_R32G32B32_UINT; break; case D3D_REGISTER_COMPONENT_SINT32: elementDesc.Format = DXGI_FORMAT_R32G32B32_SINT; break; case D3D_REGISTER_COMPONENT_FLOAT32: elementDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT; break; default: LogManager::GetInstance().Error("Shader: Unknown RegisterComponentType, Mask <= 7"); return; } } else if (paramDesc.Mask <= 15) { switch (paramDesc.ComponentType) { case D3D_REGISTER_COMPONENT_UINT32: elementDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT; break; case D3D_REGISTER_COMPONENT_SINT32: elementDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT; break; case D3D_REGISTER_COMPONENT_FLOAT32: elementDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; break; default: LogManager::GetInstance().Error("Shader: Unknown RegisterComponentType, Mask <= 15"); return; } } polygonLayout.push_back(elementDesc); } result = device->CreateInputLayout(&polygonLayout[0], polygonLayout.size(), vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if (FAILED(result)) { LogManager::GetInstance().Error("Shader: Failed to create the input layout"); return; } vertexShaderReflection->Release(); vertexShaderReflection = nullptr; pixelShaderReflection->Release(); pixelShaderReflection = nullptr; D3D11_SAMPLER_DESC samplerDesc; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; result = device->CreateSamplerState(&samplerDesc, &m_sampleState); if (FAILED(result)) { LogManager::GetInstance().Error("InitializeShader could not create the texture sampler state"); return; } m_bInit = true; }
bool compileHLSLShaderDx11(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer) { BX_TRACE("DX11"); const char* profile = _cmdLine.findOption('p', "profile"); if (NULL == profile) { fprintf(stderr, "Shader profile must be specified.\n"); return false; } bool debug = _cmdLine.hasArg('\0', "debug"); uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY; flags |= debug ? D3DCOMPILE_DEBUG : 0; flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0; flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DCOMPILE_NO_PRESHADER : 0; flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DCOMPILE_PARTIAL_PRECISION : 0; flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0; flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0; bool werror = _cmdLine.hasArg('\0', "Werror"); if (werror) { flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS; } uint32_t optimization = 3; if (_cmdLine.hasArg(optimization, 'O') ) { optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx11)-1); flags |= s_optimizationLevelDx11[optimization]; } else { flags |= D3DCOMPILE_SKIP_OPTIMIZATION; } BX_TRACE("Profile: %s", profile); BX_TRACE("Flags: 0x%08x", flags); ID3DBlob* code; ID3DBlob* errorMsg; // Output preprocessed shader so that HLSL can be debugged via GPA // or PIX. Compiling through memory won't embed preprocessed shader // file path. std::string hlslfp; if (debug) { hlslfp = _cmdLine.findOption('o'); hlslfp += ".hlsl"; writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() ); } HRESULT hr = D3DCompile(_code.c_str() , _code.size() , hlslfp.c_str() , NULL , NULL , "main" , profile , flags , 0 , &code , &errorMsg ); if (FAILED(hr) || (werror && NULL != errorMsg) ) { const char* log = (char*)errorMsg->GetBufferPointer(); int32_t line = 0; int32_t column = 0; int32_t start = 0; int32_t end = INT32_MAX; if (2 == sscanf(log, "(%u,%u):", &line, &column) && 0 != line) { start = bx::uint32_imax(1, line-10); end = start + 20; } printCode(_code.c_str(), line, start, end); fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log); errorMsg->Release(); return false; } UniformArray uniforms; ID3D11ShaderReflection* reflect = NULL; hr = D3DReflect(code->GetBufferPointer() , code->GetBufferSize() , IID_ID3D11ShaderReflection , (void**)&reflect ); if (FAILED(hr) ) { fprintf(stderr, "Error: 0x%08x\n", (uint32_t)hr); return false; } D3D11_SHADER_DESC desc; hr = reflect->GetDesc(&desc); if (FAILED(hr) ) { fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x\n", (uint32_t)hr); return false; } BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version); BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers); BX_TRACE("Input:"); uint8_t numAttrs = 0; uint16_t attrs[bgfx::Attrib::Count]; if (profile[0] == 'v') // Only care about input semantic on vertex shaders { for (uint32_t ii = 0; ii < desc.InputParameters; ++ii) { D3D11_SIGNATURE_PARAMETER_DESC spd; reflect->GetInputParameterDesc(ii, &spd); BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d" , ii , spd.SemanticName , spd.SemanticIndex , spd.SystemValueType , spd.ComponentType , spd.Mask , spd.Register ); const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, spd.SemanticIndex); if (ris.m_attr != bgfx::Attrib::Count) { attrs[numAttrs] = bgfx::attribToId(ris.m_attr); ++numAttrs; } } } BX_TRACE("Output:"); for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii) { D3D11_SIGNATURE_PARAMETER_DESC spd; reflect->GetOutputParameterDesc(ii, &spd); BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType); } uint16_t size = 0; for (uint32_t ii = 0; ii < bx::uint32_min(1, desc.ConstantBuffers); ++ii) { ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii); D3D11_SHADER_BUFFER_DESC bufferDesc; hr = cbuffer->GetDesc(&bufferDesc); size = (uint16_t)bufferDesc.Size; if (SUCCEEDED(hr) ) { BX_TRACE("%s, %d, vars %d, size %d" , bufferDesc.Name , bufferDesc.Type , bufferDesc.Variables , bufferDesc.Size ); for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj) { ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj); ID3D11ShaderReflectionType* type = var->GetType(); D3D11_SHADER_VARIABLE_DESC varDesc; hr = var->GetDesc(&varDesc); if (SUCCEEDED(hr) ) { D3D11_SHADER_TYPE_DESC constDesc; hr = type->GetDesc(&constDesc); if (SUCCEEDED(hr) ) { UniformType::Enum uniformType = findUniformTypeDx11(constDesc); if (UniformType::Count != uniformType && 0 != (varDesc.uFlags & D3D_SVF_USED) ) { Uniform un; un.name = varDesc.Name; un.type = uniformType; un.num = constDesc.Elements; un.regIndex = varDesc.StartOffset; un.regCount = BX_ALIGN_16(varDesc.Size)/16; uniforms.push_back(un); BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d" , varDesc.Name , varDesc.StartOffset , varDesc.Size , varDesc.uFlags , uniformType ); } else { BX_TRACE("\t%s, unknown type", varDesc.Name); } } } } } } BX_TRACE("Bound:"); for (uint32_t ii = 0; ii < desc.BoundResources; ++ii) { D3D11_SHADER_INPUT_BIND_DESC bindDesc; hr = reflect->GetResourceBindingDesc(ii, &bindDesc); if (SUCCEEDED(hr) ) { // if (bindDesc.Type == D3D_SIT_SAMPLER) { BX_TRACE("\t%s, %d, %d, %d" , bindDesc.Name , bindDesc.Type , bindDesc.BindPoint , bindDesc.BindCount ); } } } uint16_t count = (uint16_t)uniforms.size(); bx::write(_writer, count); uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0; for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it) { const Uniform& un = *it; uint8_t nameSize = (uint8_t)un.name.size(); bx::write(_writer, nameSize); bx::write(_writer, un.name.c_str(), nameSize); uint8_t type = un.type|fragmentBit; bx::write(_writer, type); bx::write(_writer, un.num); bx::write(_writer, un.regIndex); bx::write(_writer, un.regCount); BX_TRACE("%s, %s, %d, %d, %d" , un.name.c_str() , getUniformTypeName(un.type) , un.num , un.regIndex , un.regCount ); } { ID3DBlob* stripped; hr = D3DStripShader(code->GetBufferPointer() , code->GetBufferSize() , D3DCOMPILER_STRIP_REFLECTION_DATA | D3DCOMPILER_STRIP_TEST_BLOBS , &stripped ); if (SUCCEEDED(hr) ) { code->Release(); code = stripped; } } uint16_t shaderSize = (uint16_t)code->GetBufferSize(); bx::write(_writer, shaderSize); bx::write(_writer, code->GetBufferPointer(), shaderSize); uint8_t nul = 0; bx::write(_writer, nul); bx::write(_writer, numAttrs); bx::write(_writer, attrs, numAttrs*sizeof(uint16_t) ); bx::write(_writer, size); if (_cmdLine.hasArg('\0', "disasm") ) { ID3DBlob* disasm; D3DDisassemble(code->GetBufferPointer() , code->GetBufferSize() , 0 , NULL , &disasm ); if (NULL != disasm) { std::string disasmfp = _cmdLine.findOption('o'); disasmfp += ".disasm"; writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() ); disasm->Release(); } } if (NULL != reflect) { reflect->Release(); } if (NULL != errorMsg) { errorMsg->Release(); } code->Release(); return true; }
int main(int argc, char* argv[]) { if (argc != 5) { std::cout << "Usage: " << argv[0] << " entryPoint target outfile infile" << std::endl; std::cout << " Target can be something like ps_4_0, vs_4_0" << std::endl; return 1; } // // Read the entire shader source file // std::cout << "Reading File..." << std::endl; // Open the file std::ifstream infile(argv[4], std::ios::in | std::ios::binary); if (!infile) { std::cout << "Unable to open input file " << argv[4] << std::endl; return 1; } // Read the actual data std::string shader_source; infile.seekg(0, std::ios::end); unsigned int length = infile.tellg(); shader_source.resize(length); infile.seekg(0, std::ios::beg); infile.read(&shader_source[0], shader_source.size()); infile.close(); // // Compile the source code // std::cout << "Compiling..." << std::endl; ID3DBlob *code; ID3DBlob *errors; HRESULT hr = D3DCompile( &shader_source[0], //in LPCVOID pSrcData, shader_source.size(), //in SIZE_T SrcDataSize, argv[4], //in_opt LPCSTR pSourceName, NULL, //in_opt const D3D_SHADER_MACRO *pDefines, D3D_COMPILE_STANDARD_FILE_INCLUDE, //in_opt ID3DInclude *pInclude, argv[1], //in LPCSTR pEntrypoint, argv[2], //in LPCSTR pTarget, D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE_WARNINGS_ARE_ERRORS, //in UINT Flags1, 0, //in UINT Flags2, &code, //out ID3DBlob **ppCode, &errors //out_opt ID3DBlob **ppErrorMsgs ); // Check for compilation errors if (FAILED(hr)) { if (errors) { std::cout << "D3DCompile failed!" << std::endl; std::cout << (char*) errors->GetBufferPointer() << std::endl; } else { std::cout << "D3DCompile failed!" << std::endl; } return 1; } // // Open the output file // std::ofstream outfile(argv[3]); if (!outfile) { std::cout << "Unable to open output file " << argv[3] << std::endl; return 1; } const char *INDENT = " "; outfile << "shader {" << std::endl; // // Shader Reflection information // std::cout << "Analyzing..." << std::endl; ID3D11ShaderReflection *reflection = NULL; hr = D3DReflect(code->GetBufferPointer(), code->GetBufferSize(), IID_ID3D11ShaderReflection, (void**) &reflection); if (SUCCEEDED(hr)) { D3D11_SHADER_DESC desc; reflection->GetDesc(&desc); std::cout << std::endl; std::cout << "Required Resources" << std::endl; std::cout << "------------------" << std::endl; outfile << INDENT << "resources {" << std::endl; for (int i = 0; i < desc.BoundResources; ++i) { D3D11_SHADER_INPUT_BIND_DESC rDesc; reflection->GetResourceBindingDesc(i,&rDesc); std::cout << i << " " << rDesc.Name << " " << rDesc.BindPoint << std::endl; outfile << INDENT << INDENT << "resource = \"" << rDesc.Name << "\" " << rDesc.BindPoint << std::endl; } outfile << INDENT << "}" << std::endl; } else { std::string target(argv[2]); if ( target.find("_3_") != std::string::npos || target.find("_2_") != std::string::npos || target.find("_1_") != std::string::npos) { // Build our own resource table } } // Output compiled shader bytecode std::string shader_compiled = toHexString (code->GetBufferPointer(), code->GetBufferSize()); outfile << INDENT << "shader = \"" << shader_compiled << "\"" << std::endl; // Finish off the file outfile << "}" << std::endl; return 0; }
bool getReflectionDataD3D11(ID3DBlob* _code, bool _vshader, UniformArray& _uniforms, uint8_t& _numAttrs, uint16_t* _attrs, uint16_t& _size, UniformNameList& unusedUniforms) { ID3D11ShaderReflection* reflect = NULL; HRESULT hr = D3DReflect(_code->GetBufferPointer() , _code->GetBufferSize() , s_compiler->IID_ID3D11ShaderReflection , (void**)&reflect ); if (FAILED(hr) ) { fprintf(stderr, "Error: D3DReflect failed 0x%08x\n", (uint32_t)hr); return false; } D3D11_SHADER_DESC desc; hr = reflect->GetDesc(&desc); if (FAILED(hr) ) { fprintf(stderr, "Error: ID3D11ShaderReflection::GetDesc failed 0x%08x\n", (uint32_t)hr); return false; } BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version); BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers); BX_TRACE("Input:"); if (_vshader) // Only care about input semantic on vertex shaders { for (uint32_t ii = 0; ii < desc.InputParameters; ++ii) { D3D11_SIGNATURE_PARAMETER_DESC spd; reflect->GetInputParameterDesc(ii, &spd); BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d" , ii , spd.SemanticName , spd.SemanticIndex , spd.SystemValueType , spd.ComponentType , spd.Mask , spd.Register ); const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, spd.SemanticIndex); if (ris.m_attr != bgfx::Attrib::Count) { _attrs[_numAttrs] = bgfx::attribToId(ris.m_attr); ++_numAttrs; } } } BX_TRACE("Output:"); for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii) { D3D11_SIGNATURE_PARAMETER_DESC spd; reflect->GetOutputParameterDesc(ii, &spd); BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType); } for (uint32_t ii = 0, num = bx::uint32_min(1, desc.ConstantBuffers); ii < num; ++ii) { ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii); D3D11_SHADER_BUFFER_DESC bufferDesc; hr = cbuffer->GetDesc(&bufferDesc); _size = (uint16_t)bufferDesc.Size; if (SUCCEEDED(hr) ) { BX_TRACE("%s, %d, vars %d, size %d" , bufferDesc.Name , bufferDesc.Type , bufferDesc.Variables , bufferDesc.Size ); for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj) { ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj); ID3D11ShaderReflectionType* type = var->GetType(); D3D11_SHADER_VARIABLE_DESC varDesc; hr = var->GetDesc(&varDesc); if (SUCCEEDED(hr) ) { D3D11_SHADER_TYPE_DESC constDesc; hr = type->GetDesc(&constDesc); if (SUCCEEDED(hr) ) { UniformType::Enum uniformType = findUniformType(constDesc); if (UniformType::Count != uniformType && 0 != (varDesc.uFlags & D3D_SVF_USED) ) { Uniform un; un.name = varDesc.Name; un.type = uniformType; un.num = constDesc.Elements; un.regIndex = varDesc.StartOffset; un.regCount = BX_ALIGN_16(varDesc.Size) / 16; _uniforms.push_back(un); BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d (used)" , varDesc.Name , varDesc.StartOffset , varDesc.Size , varDesc.uFlags , uniformType ); } else { if (0 == (varDesc.uFlags & D3D_SVF_USED) ) { unusedUniforms.push_back(varDesc.Name); } BX_TRACE("\t%s, unknown type", varDesc.Name); } } } } } } BX_TRACE("Bound:"); for (uint32_t ii = 0; ii < desc.BoundResources; ++ii) { D3D11_SHADER_INPUT_BIND_DESC bindDesc; hr = reflect->GetResourceBindingDesc(ii, &bindDesc); if (SUCCEEDED(hr) ) { if (D3D_SIT_SAMPLER == bindDesc.Type) { BX_TRACE("\t%s, %d, %d, %d" , bindDesc.Name , bindDesc.Type , bindDesc.BindPoint , bindDesc.BindCount ); const char * end = strstr(bindDesc.Name, "Sampler"); if (NULL != end) { Uniform un; un.name.assign(bindDesc.Name, (end - bindDesc.Name) ); un.type = UniformType::Enum(BGFX_UNIFORM_SAMPLERBIT | UniformType::Int1); un.num = 1; un.regIndex = bindDesc.BindPoint; un.regCount = bindDesc.BindCount; _uniforms.push_back(un); } } } } if (NULL != reflect) { reflect->Release(); } return true; }
void ezShaderCompilerHLSL::ReflectShaderStage(ezShaderProgramData& inout_Data, ezGALShaderStage::Enum Stage) { ID3D11ShaderReflection* pReflector = nullptr; auto byteCode = inout_Data.m_StageBinary[Stage].GetByteCode(); D3DReflect(byteCode.GetData(), byteCode.GetCount(), IID_ID3D11ShaderReflection, (void**)&pReflector); D3D11_SHADER_DESC shaderDesc; pReflector->GetDesc(&shaderDesc); for (ezUInt32 r = 0; r < shaderDesc.BoundResources; ++r) { D3D11_SHADER_INPUT_BIND_DESC shaderInputBindDesc; pReflector->GetResourceBindingDesc(r, &shaderInputBindDesc); // ezLog::Info("Bound Resource: '{0}' at slot {1} (Count: {2}, Flags: {3})", sibd.Name, sibd.BindPoint, sibd.BindCount, sibd.uFlags); ezShaderResourceBinding shaderResourceBinding; shaderResourceBinding.m_Type = ezShaderResourceBinding::Unknown; shaderResourceBinding.m_iSlot = shaderInputBindDesc.BindPoint; shaderResourceBinding.m_sName.Assign(shaderInputBindDesc.Name); if (shaderInputBindDesc.Type == D3D_SIT_TEXTURE) { switch (shaderInputBindDesc.Dimension) { case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE1D: shaderResourceBinding.m_Type = ezShaderResourceBinding::Texture1D; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE1DARRAY: shaderResourceBinding.m_Type = ezShaderResourceBinding::Texture1DArray; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE2D: shaderResourceBinding.m_Type = ezShaderResourceBinding::Texture2D; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE2DARRAY: shaderResourceBinding.m_Type = ezShaderResourceBinding::Texture2DArray; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE2DMS: shaderResourceBinding.m_Type = ezShaderResourceBinding::Texture2DMS; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE2DMSARRAY: shaderResourceBinding.m_Type = ezShaderResourceBinding::Texture2DMSArray; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE3D: shaderResourceBinding.m_Type = ezShaderResourceBinding::Texture3D; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURECUBE: shaderResourceBinding.m_Type = ezShaderResourceBinding::TextureCube; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURECUBEARRAY: shaderResourceBinding.m_Type = ezShaderResourceBinding::TextureCubeArray; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_BUFFER: shaderResourceBinding.m_Type = ezShaderResourceBinding::GenericBuffer; break; default: EZ_ASSERT_NOT_IMPLEMENTED; break; } } else if (shaderInputBindDesc.Type == D3D_SIT_UAV_RWTYPED) { switch (shaderInputBindDesc.Dimension) { case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE1D: shaderResourceBinding.m_Type = ezShaderResourceBinding::RWTexture1D; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE1DARRAY: shaderResourceBinding.m_Type = ezShaderResourceBinding::RWTexture1DArray; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE2D: shaderResourceBinding.m_Type = ezShaderResourceBinding::RWTexture2D; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_TEXTURE2DARRAY: shaderResourceBinding.m_Type = ezShaderResourceBinding::RWTexture2DArray; break; case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_BUFFER: case D3D_SRV_DIMENSION::D3D_SRV_DIMENSION_BUFFEREX: shaderResourceBinding.m_Type = ezShaderResourceBinding::RWBuffer; break; default: EZ_ASSERT_NOT_IMPLEMENTED; break; } } else if (shaderInputBindDesc.Type == D3D_SIT_UAV_RWSTRUCTURED) shaderResourceBinding.m_Type = ezShaderResourceBinding::RWStructuredBuffer; else if (shaderInputBindDesc.Type == D3D_SIT_UAV_RWBYTEADDRESS) shaderResourceBinding.m_Type = ezShaderResourceBinding::RWRawBuffer; else if (shaderInputBindDesc.Type == D3D_SIT_UAV_APPEND_STRUCTURED) shaderResourceBinding.m_Type = ezShaderResourceBinding::RWAppendBuffer; else if (shaderInputBindDesc.Type == D3D_SIT_UAV_CONSUME_STRUCTURED) shaderResourceBinding.m_Type = ezShaderResourceBinding::RWConsumeBuffer; else if (shaderInputBindDesc.Type == D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER) shaderResourceBinding.m_Type = ezShaderResourceBinding::RWStructuredBufferWithCounter; else if (shaderInputBindDesc.Type == D3D_SIT_CBUFFER) { shaderResourceBinding.m_Type = ezShaderResourceBinding::ConstantBuffer; shaderResourceBinding.m_pLayout = ReflectConstantBufferLayout(inout_Data.m_StageBinary[Stage], pReflector->GetConstantBufferByName(shaderInputBindDesc.Name)); } else if (shaderInputBindDesc.Type == D3D_SIT_SAMPLER) { shaderResourceBinding.m_Type = ezShaderResourceBinding::Sampler; if (ezStringUtils::EndsWith(shaderInputBindDesc.Name, "_AutoSampler")) { ezStringBuilder sb = shaderInputBindDesc.Name; sb.Shrink(0, ezStringUtils::GetStringElementCount("_AutoSampler")); shaderResourceBinding.m_sName.Assign(sb.GetData()); } } else { shaderResourceBinding.m_Type = ezShaderResourceBinding::GenericBuffer; } if (shaderResourceBinding.m_Type != ezShaderResourceBinding::Unknown) { inout_Data.m_StageBinary[Stage].AddShaderResourceBinding(shaderResourceBinding); } } pReflector->Release(); }
cCgShaderHelper::tHLSLDesc cCgShaderHelper::GetHLSLDesc(const zsString& hlslFilePath, const void* byteCode, size_t byteCodeSize) { // Result tHLSLDesc result; // Reflect HLSL Sm (4.0 - 5.0) shader ID3D11ShaderReflection* reflector; D3DReflect(byteCode, byteCodeSize, IID_ID3D11ShaderReflection, (void**)&reflector); D3D11_SHADER_DESC shaderDesc; reflector->GetDesc(&shaderDesc); std::unordered_map<zsString, uint16_t> textureSlots; // Collect samplers, texture names and their slot indexing for (size_t i = 0; i < shaderDesc.BoundResources; i++) { D3D11_SHADER_INPUT_BIND_DESC bindDesc; reflector->GetResourceBindingDesc((UINT)i, &bindDesc); switch (bindDesc.Type) { case D3D_SIT_SAMPLER: result.samplerInfo[bindDesc.Name + 1].samplerStateSlot = bindDesc.BindPoint; break; case D3D_SIT_TEXTURE: textureSlots[bindDesc.Name] = bindDesc.BindPoint; } } // Parse hlsl code for samplers, textures std::ifstream hlslFile(hlslFilePath); auto lines = cFileUtil::GetLines(hlslFile); for (auto it = lines.begin(); it != lines.end(); it++) { const zsString& row = *it; // Match samplers with textures int chPos = cStrUtil::Find(row, L".Sample"); if (chPos >= 0) { zsString textureName; zsString samplerName; // "].Sample" // Found arrays of samplers... if (row[chPos - 1] == ']') { // Example : _pout._color = _TMP23[0].Sample(_shadowMaps[1], _In._tex01); int leftBracketPos = cStrUtil::FindLeft(row, chPos, '['); textureName = cStrUtil::SubStrLeft(row, leftBracketPos - 1, '_'); samplerName = cStrUtil::SubStrRight(row, chPos + 9, '[', -1); } else { // Example : _pout._color = _TMP23.Sample(_diffuseTex, _In._tex01); textureName = cStrUtil::SubStrLeft(row, chPos - 1, '_'); // Go to parenthesis '(' Noob solution, good solution is to start from chPos... auto parenthesisIdx = cStrUtil::Find(row, '('); assert(parenthesisIdx > 0); samplerName = cStrUtil::SubStrRight(row, parenthesisIdx + 2, ',', -1); } auto it = textureSlots.find(textureName); if (it != textureSlots.end()) { result.samplerInfo[samplerName].textureSlot = it->second; } } } hlslFile.close(); return result; }
//------------------------------------------------------------------------------- // @ IvConstantTableD3D11::Create() //------------------------------------------------------------------------------- // Get the constant table for this shader //------------------------------------------------------------------------------- IvConstantTableD3D11* IvConstantTableD3D11::Create(ID3D11Device* device, ID3DBlob* code) { ID3D11ShaderReflection* pReflector = nullptr; D3DReflect(code->GetBufferPointer(), code->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pReflector); // first get constant table IvConstantTableD3D11* table = new IvConstantTableD3D11(); ID3D11ShaderReflectionConstantBuffer* globalConstants = pReflector->GetConstantBufferByName("$Globals"); D3D11_SHADER_BUFFER_DESC constantBufferDesc = { 0 }; HRESULT hr = globalConstants->GetDesc(&constantBufferDesc); if (FAILED(hr)) { // no constants in this shader goto get_textures; } table->mBacking = new char[constantBufferDesc.Size]; table->mBackingSize = constantBufferDesc.Size; if (nullptr == table->mBacking) { delete table; pReflector->Release(); return nullptr; } for (unsigned int i = 0; i < constantBufferDesc.Variables; ++i) { ID3D11ShaderReflectionVariable* var = globalConstants->GetVariableByIndex(i); D3D11_SHADER_VARIABLE_DESC varDesc; if (FAILED(var->GetDesc(&varDesc))) { delete table; pReflector->Release(); return nullptr; } ID3D11ShaderReflectionType* type = var->GetType(); D3D11_SHADER_TYPE_DESC typeDesc; if (FAILED(type->GetDesc(&typeDesc))) { delete table; pReflector->Release(); return nullptr; } IvConstantDesc constantDesc; constantDesc.mOffset = table->mBacking + varDesc.StartOffset; if (typeDesc.Class == D3D_SVC_SCALAR && typeDesc.Type == D3D_SVT_FLOAT) { constantDesc.mType = IvUniformType::kFloatUniform; } else if (typeDesc.Class == D3D_SVC_VECTOR && typeDesc.Type == D3D_SVT_FLOAT && typeDesc.Columns == 3) { constantDesc.mType = IvUniformType::kFloat3Uniform; } else if (typeDesc.Class == D3D_SVC_VECTOR && typeDesc.Type == D3D_SVT_FLOAT && typeDesc.Columns == 4) { constantDesc.mType = IvUniformType::kFloat4Uniform; } else if ((typeDesc.Class == D3D_SVC_MATRIX_ROWS || typeDesc.Class == D3D_SVC_MATRIX_COLUMNS) && typeDesc.Type == D3D_SVT_FLOAT && typeDesc.Rows == 4 && typeDesc.Columns == 4) { constantDesc.mType = IvUniformType::kFloatMatrix44Uniform; } else { // unsupported uniform type delete table; pReflector->Release(); return nullptr; } constantDesc.mCount = typeDesc.Elements != 0 ? typeDesc.Elements : 1; table->mConstants[varDesc.Name] = constantDesc; } D3D11_BUFFER_DESC cbDesc; cbDesc.ByteWidth = constantBufferDesc.Size; cbDesc.Usage = D3D11_USAGE_DYNAMIC; cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; cbDesc.StructureByteStride = 0; if (FAILED(device->CreateBuffer(&cbDesc, nullptr, &table->mBuffer))) { delete table; pReflector->Release(); return nullptr; } get_textures: // now get any textures and samplers D3D11_SHADER_DESC shaderDesc = { 0 }; hr = pReflector->GetDesc(&shaderDesc); if (FAILED(hr)) { pReflector->Release(); return table; } int resourceCount = shaderDesc.BoundResources; for (int i = 0; i < resourceCount; ++i) { D3D11_SHADER_INPUT_BIND_DESC bindingDesc = { 0 }; pReflector->GetResourceBindingDesc(i, &bindingDesc); if (bindingDesc.Type == D3D_SIT_TEXTURE && bindingDesc.ReturnType == D3D_RETURN_TYPE_FLOAT && bindingDesc.Dimension == D3D_SRV_DIMENSION_TEXTURE2D && bindingDesc.NumSamples == -1 && bindingDesc.BindCount == 1) { IvConstantDesc& constantDesc = table->mConstants[bindingDesc.Name]; constantDesc.mType = IvUniformType::kTextureUniform; constantDesc.mTextureSlot = bindingDesc.BindPoint; } else if (bindingDesc.Type == D3D_SIT_SAMPLER && bindingDesc.BindCount == 1) { char strippedName[256]; const char* samplerKeyword = strstr(bindingDesc.Name, "Sampler"); strncpy(strippedName, bindingDesc.Name, samplerKeyword - bindingDesc.Name); strippedName[samplerKeyword - bindingDesc.Name] = '\0'; IvConstantDesc& constantDesc = table->mConstants[strippedName]; constantDesc.mType = IvUniformType::kTextureUniform; constantDesc.mSamplerSlot = bindingDesc.BindPoint; } else if (bindingDesc.Type == D3D_SIT_CBUFFER && !_strnicmp(bindingDesc.Name, "$Globals", 8)) { // ignore this, we handled it above } else { // unsupported resource type delete table; pReflector->Release(); return nullptr; } } pReflector->Release(); return table; }
int main(void) { char const *verbose_var = getenv("D3D4LINUX_VERBOSE"); if (!verbose_var || *verbose_var != '1') dup2(open("/dev/null", O_WRONLY), STDERR_FILENO); HMODULE lib = LoadLibrary("d3dcompiler_43.dll"); /* Ensure stdout is in binary mode */ setmode(fileno(stdout), O_BINARY); setmode(fileno(stdin), O_BINARY); int syscall = read_integer(); int marker = 0; if (syscall == D3D4LINUX_COMPILE) { HRESULT (*compile)(void const *pSrcData, size_t SrcDataSize, char const *pFileName, D3D_SHADER_MACRO const *pDefines, ID3DInclude *pInclude, char const *pEntrypoint, char const *pTarget, uint32_t Flags1, uint32_t Flags2, ID3DBlob **ppCode, ID3DBlob **ppErrorMsgs); compile = (decltype(compile))GetProcAddress(lib, "D3DCompile"); /* This is a D3DCompile() call */ std::string shader_source = read_string(); int has_filename = (int)read_integer(); std::string shader_file; if (has_filename) shader_file = read_string(); std::string shader_main = read_string(); std::string shader_type = read_string(); uint32_t flags1 = (uint32_t)read_integer(); uint32_t flags2 = (uint32_t)read_integer(); marker = (int)read_integer(); if (marker != D3D4LINUX_FINISHED) goto error; ID3DBlob *shader_blob = nullptr, *error_blob = nullptr; HRESULT ret = compile(shader_source.c_str(), shader_source.size(), shader_file.c_str(), nullptr, /* unimplemented */ nullptr, /* unimplemented */ shader_main.c_str(), shader_type.c_str(), flags1, flags2, &shader_blob, &error_blob); fprintf(stderr, "[D3D4LINUX] D3DCompile([%d bytes], \"%s\", ?, ?, \"%s\", \"%s\", %04x, %04x ) = 0x%08x\n", (int)shader_source.size(), has_filename ? shader_file.c_str() : "(nullptr)", shader_main.c_str(), shader_type.c_str(), flags1, flags2, (int)ret); write_integer(ret); write_blob(shader_blob); write_blob(error_blob); write_integer(D3D4LINUX_FINISHED); if (shader_blob) shader_blob->Release(); if (error_blob) error_blob->Release(); } else if (syscall == D3D4LINUX_REFLECT) { HRESULT (*reflect)(void const *pSrcData, size_t SrcDataSize, REFIID pInterface, void **ppReflector); reflect = (decltype(reflect))GetProcAddress(lib, "D3DReflect"); std::vector<uint8_t> *data = read_data(); int iid_code = read_integer(); marker = (int)read_integer(); if (marker != D3D4LINUX_FINISHED) goto error; char const *iid_name = ""; IID iid; switch (iid_code) { case D3D4LINUX_IID_SHADER_REFLECTION: iid = IID_ID3D11ShaderReflection; iid_name = "IID_ID3D11ShaderReflection"; break; default: goto error; } void *object; HRESULT ret = reflect(data ? data->data() : nullptr, data ? data->size() : 0, iid, &object); fprintf(stderr, "[D3D4LINUX] D3DReflect([%d bytes], %s) = 0x%08x\n", data ? (int)data->size() : 0, iid_name, (int)ret); write_integer(ret); if (iid_code == D3D4LINUX_IID_SHADER_REFLECTION) { D3D11_SIGNATURE_PARAMETER_DESC param_desc; D3D11_SHADER_INPUT_BIND_DESC bind_desc; D3D11_SHADER_VARIABLE_DESC variable_desc; D3D11_SHADER_BUFFER_DESC buffer_desc; D3D11_SHADER_DESC shader_desc; ID3D11ShaderReflection *reflector = (ID3D11ShaderReflection *)object; /* Serialise D3D11_SHADER_DESC */ reflector->GetDesc(&shader_desc); write_raw(&shader_desc, sizeof(shader_desc)); write_string(shader_desc.Creator); /* Serialize all InputParameterDesc */ for (uint32_t i = 0; i < shader_desc.InputParameters; ++i) { reflector->GetInputParameterDesc(i, ¶m_desc); write_raw(¶m_desc, sizeof(param_desc)); write_string(param_desc.SemanticName); } /* Serialize all OutParameterDesc */ for (uint32_t i = 0; i < shader_desc.OutputParameters; ++i) { reflector->GetOutputParameterDesc(i, ¶m_desc); write_raw(¶m_desc, sizeof(param_desc)); write_string(param_desc.SemanticName); } /* Serialize all ResourceBindingDesc */ for (uint32_t i = 0; i < shader_desc.BoundResources; ++i) { reflector->GetResourceBindingDesc(i, &bind_desc); write_raw(&bind_desc, sizeof(bind_desc)); write_string(bind_desc.Name); } /* Serialize all ConstantBuffer */ for (uint32_t i = 0; i < shader_desc.ConstantBuffers; ++i) { ID3D11ShaderReflectionConstantBuffer *cbuffer = reflector->GetConstantBufferByIndex(i); /* Serialize D3D11_SHADER_BUFFER_DESC */ cbuffer->GetDesc(&buffer_desc); write_raw(&buffer_desc, sizeof(buffer_desc)); write_string(buffer_desc.Name); /* Serialize all Variable */ for (uint32_t j = 0; j < buffer_desc.Variables; ++j) { ID3D11ShaderReflectionVariable *var = cbuffer->GetVariableByIndex(j); /* Serialize D3D11_SHADER_VARIABLE_DESC */ var->GetDesc(&variable_desc); write_raw(&variable_desc, sizeof(variable_desc)); write_string(variable_desc.Name); write_integer(variable_desc.DefaultValue ? 1 : 0); if (variable_desc.DefaultValue) write_raw(variable_desc.DefaultValue, variable_desc.Size); } } } write_integer(D3D4LINUX_FINISHED); delete data; } else if (syscall == D3D4LINUX_STRIP) { HRESULT (*strip)(void const *pShaderBytecode, size_t BytecodeLength, uint32_t uStripFlags, ID3DBlob **ppStrippedBlob); strip = (decltype(strip))GetProcAddress(lib, "D3DStripShader"); std::vector<uint8_t> *data = read_data(); uint32_t flags = (uint32_t)read_integer(); marker = (int)read_integer(); if (marker != D3D4LINUX_FINISHED) goto error; ID3DBlob *strip_blob = nullptr; HRESULT ret = strip(data ? data->data() : nullptr, data ? data->size() : 0, flags, &strip_blob); fprintf(stderr, "[D3D4LINUX] D3DStripShader([%d bytes], %04x) = 0x%08x\n", data ? (int)data->size() : 0, flags, (int)ret); write_integer(ret); write_blob(strip_blob); write_integer(D3D4LINUX_FINISHED); if (strip_blob) strip_blob->Release(); } else if (syscall == D3D4LINUX_DISASSEMBLE) { HRESULT (*disas)(void const *pSrcData, size_t SrcDataSize, uint32_t Flags, char const *szComments, ID3DBlob **ppDisassembly); disas = (decltype(disas))GetProcAddress(lib, "D3DDisassemble"); std::vector<uint8_t> *data = read_data(); uint32_t flags = (uint32_t)read_integer(); int has_comments = (int)read_integer(); std::string comments; if (has_comments) comments = read_string(); marker = (int)read_integer(); if (marker != D3D4LINUX_FINISHED) goto error; ID3DBlob *disas_blob = nullptr; HRESULT ret = disas(data ? data->data() : nullptr, data ? data->size() : 0, flags, has_comments ? comments.c_str() : nullptr, &disas_blob); fprintf(stderr, "[D3D4LINUX] D3DDisassemble([%d bytes], %04x, %s) = 0x%08x\n", data ? (int)data->size() : 0, flags, has_comments ? "[comments]" : "(nullptr)", (int)ret); write_integer(ret); write_blob(disas_blob); write_integer(D3D4LINUX_FINISHED); if (disas_blob) disas_blob->Release(); } return EXIT_SUCCESS; error: fprintf(stderr, "[D3D4LINUX] Bad message received: %08x %08x\n", syscall, marker); }