void ShaderManager::CreateInputLayout(ID3DBlob* VS, ID3D11InputLayout* &inputLayout) { HRESULT hr; std::vector<D3D11_INPUT_ELEMENT_DESC> inputElementDescArray; ID3D11ShaderReflection* pReflection; hr = D3DReflect(VS->GetBufferPointer(), VS->GetBufferSize(), IID_ID3D11ShaderReflection, (void**) &pReflection); assert(hr == S_OK); D3D11_SHADER_DESC shaderDesc; pReflection->GetDesc(&shaderDesc); unsigned int i = 0; for (; i < shaderDesc.InputParameters; ++i) { D3D11_SIGNATURE_PARAMETER_DESC paramDesc; pReflection->GetInputParameterDesc(i, ¶mDesc); D3D11_INPUT_ELEMENT_DESC inputElementDesc; inputElementDesc.SemanticName = paramDesc.SemanticName; inputElementDesc.SemanticIndex = paramDesc.SemanticIndex; if (paramDesc.Mask == 1) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) inputElementDesc.Format = DXGI_FORMAT_R32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) inputElementDesc.Format = DXGI_FORMAT_R32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) inputElementDesc.Format = DXGI_FORMAT_R32_FLOAT; } else if (paramDesc.Mask <= 3) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) inputElementDesc.Format = DXGI_FORMAT_R32G32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) inputElementDesc.Format = DXGI_FORMAT_R32G32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) inputElementDesc.Format = DXGI_FORMAT_R32G32_FLOAT; } else if (paramDesc.Mask <= 7) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) inputElementDesc.Format = DXGI_FORMAT_R32G32B32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) inputElementDesc.Format = DXGI_FORMAT_R32G32B32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) inputElementDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT; } else if (paramDesc.Mask <= 15) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) inputElementDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) inputElementDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) inputElementDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; } inputElementDesc.InputSlot = 0; inputElementDesc.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; inputElementDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; inputElementDesc.InstanceDataStepRate = 0; inputElementDescArray.push_back(inputElementDesc); } // Initialize input layout hr = D3D11Renderer::GetInstance()->m_pD3D11Device->CreateInputLayout(&inputElementDescArray[0], i, VS->GetBufferPointer(), VS->GetBufferSize(), &inputLayout); assert(hr == S_OK); pReflection->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; }
// -------------------------------------------------------- // Creates the DirectX vertex shader // // shaderBlob - The shader's compiled code // // Returns true if shader is created correctly, false otherwise // -------------------------------------------------------- bool SimpleVertexShader::CreateShader(ID3DBlob* shaderBlob) { // Clean up first, in the event this method is // called more than once on the same object this->CleanUp(); // Create the shader from the blob HRESULT result = device->CreateVertexShader( shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), 0, &shader); // Did the creation work? if (result != S_OK) return false; // Vertex shader was created successfully, so we now use the // shader code to re-reflect and create an input layout that // matches what the vertex shader expects. Code adapted from: // https://takinginitiative.wordpress.com/2011/12/11/directx-1011-basic-shader-reflection-automatic-input-layout-creation/ // Reflect shader info ID3D11ShaderReflection* refl; D3DReflect( shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&refl); // Get shader info D3D11_SHADER_DESC shaderDesc; refl->GetDesc(&shaderDesc); // Read input layout description from shader info std::vector<D3D11_INPUT_ELEMENT_DESC> inputLayoutDesc; for (unsigned int i = 0; i< shaderDesc.InputParameters; i++) { D3D11_SIGNATURE_PARAMETER_DESC paramDesc; refl->GetInputParameterDesc(i, ¶mDesc); // Fill out input element desc 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; // Determine DXGI format if (paramDesc.Mask == 1) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32_FLOAT; } else if (paramDesc.Mask <= 3) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32_FLOAT; } else if (paramDesc.Mask <= 7) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT; } else if (paramDesc.Mask <= 15) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; } // Save element desc inputLayoutDesc.push_back(elementDesc); } // Try to create Input Layout HRESULT hr = device->CreateInputLayout( &inputLayoutDesc[0], inputLayoutDesc.size(), shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), &inputLayout); // All done, clean up refl->Release(); return true; }
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; }
void VertexShader::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 // Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3DCOMPILE_DEBUG; // Disable optimizations to further improve shader debugging dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; #endif ID3DBlob* pVSBlob = nullptr; ID3DBlob* pErrorBlob = nullptr; D3DCall(D3DCompileFromFile(filename.c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "VS", "vs_5_0", dwShaderFlags, 0, &pVSBlob, &pErrorBlob)); if (pErrorBlob) { OutputDebugStringA(reinterpret_cast<const char*>(pErrorBlob->GetBufferPointer())); pErrorBlob->Release(); } D3DCall(theRenderContext.GetDevice()->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), nullptr, &mHandle)); // Reflect shader info ID3D11ShaderReflection* pVertexShaderReflection = NULL; D3DCall(D3DReflect(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pVertexShaderReflection)); // Get shader info D3D11_SHADER_DESC shaderDesc; pVertexShaderReflection->GetDesc(&shaderDesc); // Read input layout description from shader info std::vector<D3D11_INPUT_ELEMENT_DESC> inputLayoutDesc; for (int i = 0; i < shaderDesc.InputParameters; i++) { D3D11_SIGNATURE_PARAMETER_DESC paramDesc; pVertexShaderReflection->GetInputParameterDesc(i, ¶mDesc); // fill out input element desc D3D11_INPUT_ELEMENT_DESC elementDesc; elementDesc.SemanticName = paramDesc.SemanticName; elementDesc.SemanticIndex = paramDesc.SemanticIndex; elementDesc.InputSlot = 0; if (i == 0) elementDesc.AlignedByteOffset = 0; else elementDesc.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; elementDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; elementDesc.InstanceDataStepRate = 0; // determine DXGI format if (paramDesc.Mask == 1) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32_FLOAT; } else if (paramDesc.Mask <= 3) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32_FLOAT; } else if (paramDesc.Mask <= 7) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT; } else if (paramDesc.Mask <= 15) { if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT; else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; } //save element desc inputLayoutDesc.push_back(elementDesc); } // Try to create Input Layout D3DCall(theRenderContext.GetDevice()->CreateInputLayout(&inputLayoutDesc[0], inputLayoutDesc.size(), pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &mVertexLayout)); //Free allocation shader reflection memory pVertexShaderReflection->Release(); pVSBlob->Release(); }
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; }
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; }
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); }
// find existing, or create new, ID3D11InputLayout layout //----------------------------------------------------------------------------- CPUTResult CPUTInputLayoutCacheDX11::GetLayout( ID3D11Device *pDevice, D3D11_INPUT_ELEMENT_DESC *pDXLayout, CPUTVertexShaderDX11 *pVertexShader, ID3D11InputLayout **ppInputLayout ){ // Generate the vertex layout key LayoutKey layoutKey(pDXLayout, pVertexShader, true); // Do we already have one like this? if( mLayoutList[layoutKey] ) { *ppInputLayout = mLayoutList[layoutKey]; (*ppInputLayout)->AddRef(); return CPUT_SUCCESS; } // Not found, create a new ID3D11InputLayout object // How many elements are in the input layout? int numInputLayoutElements=0; while(NULL != pDXLayout[numInputLayoutElements].SemanticName) { numInputLayoutElements++; } // Create the input layout HRESULT hr; ID3DBlob *pBlob = pVertexShader->GetBlob(); hr = pDevice->CreateInputLayout( pDXLayout, numInputLayoutElements, pBlob->GetBufferPointer(), pBlob->GetBufferSize(), ppInputLayout ); if (!SUCCEEDED(hr)) { ID3D11ShaderReflection *pReflector = NULL; D3DReflect(pBlob->GetBufferPointer(), pBlob->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_SIGNATURE_PARAMETER_DESC desc; int i = 0; DEBUG_PRINT("Shader Inputs\n"); while (SUCCEEDED(pReflector->GetInputParameterDesc(i, &desc))) { DEBUG_PRINT("\t%s\n", desc.SemanticName); i++; } DEBUG_PRINT("Mesh Inputs\n"); for (int i = 0; i < numInputLayoutElements; i++) { DEBUG_PRINT("\t%s\n", pDXLayout[i].SemanticName); } DEBUG_PRINT("\n"); } ASSERT( SUCCEEDED(hr), "Error creating input layout." ); CPUTSetDebugName( *ppInputLayout, "CPUTInputLayoutCacheDX11::GetLayout()" ); // Store this layout object in our map mLayoutList[layoutKey] = *ppInputLayout; // Addref for storing it in our map as well as returning it (count should be = 2 at this point) (*ppInputLayout)->AddRef(); return CPUT_SUCCESS; }