void InitializeShaders() { D3D11_INPUT_ELEMENT_DESC inputDescription[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; // Load Vertex Shader -------------------------------------- ID3DBlob* vsBlob; D3DReadFileToBlob(L"SampleVertexShader.cso", &vsBlob); // Create the shader on the device mDevice->CreateVertexShader( vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), NULL, &mVertexShader); // Before cleaning up the data, create the input layout if (inputDescription) { if (mInputLayout != NULL) ReleaseMacro(mInputLayout); mDevice->CreateInputLayout( inputDescription, // Reference to Description 2, // Number of elments inside of Description vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), &mInputLayout); } // Clean up vsBlob->Release(); // Load Pixel Shader --------------------------------------- ID3DBlob* psBlob; D3DReadFileToBlob(L"SamplePixelShader.cso", &psBlob); // Create the shader on the device mDevice->CreatePixelShader( psBlob->GetBufferPointer(), psBlob->GetBufferSize(), NULL, &mPixelShader); // Clean up psBlob->Release(); // Constant buffers ---------------------------------------- D3D11_BUFFER_DESC cBufferTransformDesc; cBufferTransformDesc.ByteWidth = sizeof(mMatrixBuffer); cBufferTransformDesc.Usage = D3D11_USAGE_DEFAULT; cBufferTransformDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cBufferTransformDesc.CPUAccessFlags = 0; cBufferTransformDesc.MiscFlags = 0; cBufferTransformDesc.StructureByteStride = 0; mDevice->CreateBuffer(&cBufferTransformDesc, NULL, &mConstantBuffer); }
VOID InitEffects() { ID3DBlob* pErrorBlob; // Create the effect DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3D10_SHADER_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 |= D3D10_SHADER_DEBUG; #endif // Compile the effects file HRESULT hr = D3DX10CreateEffectFromFile( L"spot_light.fx", NULL, NULL, "fx_4_0", dwShaderFlags, 0, g_pd3dDevice, NULL, NULL, &g_pEffect, &pErrorBlob, NULL); // Output the error message if compile failed if(FAILED(hr)) { if(pErrorBlob != NULL) { OutputDebugStringA((CHAR*)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } } // Release the Blob if(pErrorBlob) pErrorBlob->Release(); // Obtain the technique g_pTechnique = g_pEffect->GetTechniqueByName("Render"); // Obtain the variables g_pWorldVariable = g_pEffect->GetVariableByName("World")->AsMatrix(); g_pViewVariable = g_pEffect->GetVariableByName("View")->AsMatrix(); g_pProjectionVariable = g_pEffect->GetVariableByName("Projection")->AsMatrix(); g_pLightVariable = g_pEffect->GetVariableByName("gLight"); g_pEyePosVariable = g_pEffect->GetVariableByName("gEyePoint"); g_pWorldViewProjVariable = g_pEffect->GetVariableByName("WorldViewProj")->AsMatrix(); // Get vertex declaration of Mesh const D3D10_INPUT_ELEMENT_DESC* pVertexDesc = NULL; UINT numElements; g_pSphere->GetVertexDescription(&pVertexDesc, &numElements); // Create the input layout D3D10_PASS_DESC PassDesc; g_pTechnique->GetPassByIndex( 0 )->GetDesc( &PassDesc ); hr = g_pd3dDevice->CreateInputLayout(pVertexDesc, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pVertexLayout); if(FAILED(hr)) { MessageBox(NULL, L"Create input layout failed", L"Error", 0); } }
//-------------------------------------------------------------------------------------- // Создание буфера вершин, шейдеров (shaders) и описания формата вершин (input layout) //-------------------------------------------------------------------------------------- HRESULT LoadShaders() { HRESULT hr = S_OK; // Компиляция вершинного шейдера из файла ID3DBlob* pVSBlob = NULL; // Вспомогательный объект hr = CompileShaderFromFile(LPCSTR("shaders.fx"), "VS", "vs_4_0", &pVSBlob); if (FAILED(hr)) { MessageBox(NULL, LPCSTR("Невозможно скомпилировать файл FX. Пожалуйста, запустите данную программу из папки, содержащей файл FX."), LPCSTR("Ошибка"), MB_OK); return hr; } // Создание вершинного шейдера hr = g_pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pVertexShader); if (FAILED(hr)) { pVSBlob->Release(); return hr; } // Определение шаблона вершин D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE(layout); // Создание шаблона вершин hr = g_pd3dDevice->CreateInputLayout(layout, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &g_pVertexLayout); pVSBlob->Release(); if (FAILED(hr)) return hr; // Подключение шаблона вершин g_pImmediateContext->IASetInputLayout(g_pVertexLayout); // Компиляция пиксельного шейдера из файла ID3DBlob* pPSBlob = NULL; hr = CompileShaderFromFile(LPCSTR("shaders.fx"), "PS", "ps_4_0", &pPSBlob); if(FAILED(hr)) { MessageBox(NULL, LPCSTR("Невозможно скомпилировать файл FX. Пожалуйста, запустите данную программу из папки, содержащей файл FX."), LPCSTR("Ошибка"), MB_OK); return hr; } // Создание пиксельного шейдера hr = g_pd3dDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShader); pPSBlob->Release(); if (FAILED(hr)) return hr; return hr; }
ID3DBlob *ShaderLanguageHlsl::loadShader(const char *shaderModel, const char *shaderSource, const char *entryPoint) const { // Get compile flags UINT compileFlags = D3DCOMPILE_ENABLE_STRICTNESS; switch (getOptimizationLevel()) { case OptimizationLevel::Debug: compileFlags |= D3DCOMPILE_DEBUG; compileFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; break; case OptimizationLevel::None: compileFlags |= D3DCOMPILE_SKIP_VALIDATION; compileFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; break; case OptimizationLevel::Low: compileFlags |= D3DCOMPILE_SKIP_VALIDATION; compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL0; break; case OptimizationLevel::Medium: compileFlags |= D3DCOMPILE_SKIP_VALIDATION; compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL1; break; case OptimizationLevel::High: compileFlags |= D3DCOMPILE_SKIP_VALIDATION; compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL2; break; case OptimizationLevel::Ultra: compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL3; break; } ID3DBlob *d3dBlob = nullptr; ID3DBlob *errorBlob = nullptr; if (FAILED(D3DX10CompileFromMemory(shaderSource, strlen(shaderSource), nullptr, nullptr, nullptr, entryPoint ? entryPoint : "main", shaderModel, compileFlags, 0, nullptr, &d3dBlob, &errorBlob, nullptr))) { if (nullptr != errorBlob) { ::OutputDebugStringA(static_cast<char*>(errorBlob->GetBufferPointer())); errorBlob->Release(); } // Error! return nullptr; } if (nullptr != errorBlob) { errorBlob->Release(); } // Done return d3dBlob; }
//-------------------------------------------------------------------------------------- // Helper for compiling shaders with D3DCompile // // With VS 11, we could load up prebuilt .cso files instead... //-------------------------------------------------------------------------------------- bool GraphicsDriver::CompileShaderFromFile( const char* inFileName, const char* szEntryPoint, const char* szShaderModel, std::vector< char >& outCompiledShaderCode ) { HRESULT hr = S_OK; DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #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 const size_t cSize = strlen(inFileName) + 1; size_t retCount; std::wstring wc(cSize, L'#'); mbstowcs_s(&retCount, &wc[0], cSize, inFileName, _TRUNCATE); ID3DBlob* pErrorBlob = nullptr; ID3DBlob* pBlobOut = nullptr; hr = D3DCompileFromFile(wc.c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, szEntryPoint, szShaderModel, dwShaderFlags, 0, &pBlobOut, &pErrorBlob); if( FAILED( hr ) ) { if( pErrorBlob ) { static wchar_t szBuffer[4096]; _snwprintf_s(szBuffer, 4096, _TRUNCATE, L"%hs", (char*)pErrorBlob->GetBufferPointer()); OutputDebugString(szBuffer); MessageBox(nullptr, szBuffer, L"Error", MB_OK); pErrorBlob->Release(); DbgAssert( hr == S_OK, "Shader Compilation Failed" ); } return false; } if( pErrorBlob ) { pErrorBlob->Release(); } //now copy to vector if we like it... if( pBlobOut ) { int compiledCodeSize = pBlobOut->GetBufferSize(); outCompiledShaderCode.resize( compiledCodeSize ); std::memcpy( outCompiledShaderCode.data(), pBlobOut->GetBufferPointer(), compiledCodeSize ); pBlobOut->Release(); } return hr == S_OK; }
dx11ShaderProgram::dx11ShaderProgram(const char *vshader, const char *pshader,int flags, const ConstantDesc *uniforms, const DataDesc *attributes) { bool fromCode=(flags&ShaderProgram::Flag_FromCode); long VSLen, PSLen; void *VSFile = fromCode?NULL:LoadShaderFile(vshader, "cso", &VSLen); if (!VSFile) { void *src = fromCode?(void *)vshader:LoadShaderFile(vshader, "hlsl", &VSLen); ID3DBlob *pCode; ID3DBlob *pError; D3DCompile(src, VSLen, vshader, NULL, NULL, "VShader", "vs_4_0_level_9_3", D3DCOMPILE_PREFER_FLOW_CONTROL, 0, &pCode, &pError); if (src&&(!fromCode)) free(src); if (pError) { errorLog.append("VertexShader:\n"); errorLog.append((char *) pError->GetBufferPointer(), pError->GetBufferSize()); errorLog.append("\n"); pError->Release(); } if (pCode) { VSLen = pCode->GetBufferSize(); VSFile = malloc(VSLen); memcpy(VSFile, pCode->GetBufferPointer(), VSLen); pCode->Release(); } } void *PSFile = fromCode?NULL:LoadShaderFile(pshader, "cso", &PSLen); if (!PSFile) { void *src = fromCode?(void *)pshader:LoadShaderFile(pshader, "hlsl", &PSLen); ID3DBlob *pCode; ID3DBlob *pError; D3DCompile(src, PSLen, pshader, NULL, NULL, "PShader", "ps_4_0_level_9_3", D3DCOMPILE_PREFER_FLOW_CONTROL, 0, &pCode, &pError); if (src&&(!fromCode)) free(src); if (pError) { errorLog.append("PixelShader:\n"); errorLog.append((char *) pError->GetBufferPointer(), pError->GetBufferSize()); errorLog.append("\n"); pError->Release(); } if (pCode) { PSLen = pCode->GetBufferSize(); PSFile = malloc(PSLen); memcpy(PSFile, pCode->GetBufferPointer(), PSLen); pCode->Release(); } } buildShaderProgram(VSFile, VSLen, PSFile, PSLen, flags, uniforms, attributes); if (VSFile) free(VSFile); if (PSFile) free(PSFile); }
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(); }
// From DXSDK tutorial HRESULT CompileShaderFromFile(const char* fileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut ) { HRESULT hr = S_OK; DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _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; #endif ID3DBlob* pErrorBlob; // Read text from file DX11ShaderFile shFile; if (!shFile.OpenRead(fileName)) { ReportError(std::string("Failed to open DX11 shader file ") + fileName); return ~S_OK; } std::string text; std::string s; const bool NO_TRIM = false; while (shFile.GetString(&s)) { text += s; text += "\n"; } hr = D3DX11CompileFromMemory( text.c_str(), text.size(), fileName, // path 0, 0, szEntryPoint, szShaderModel, dwShaderFlags, 0, 0, ppBlobOut, &pErrorBlob, 0); if (FAILED(hr)) { if (pErrorBlob) { ReportError((char*)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } return hr; } if (pErrorBlob) { pErrorBlob->Release(); } return S_OK; }
//-------------------------------------------------------------------------------------- // Find and compile the specified shader //-------------------------------------------------------------------------------------- HRESULT D3D11VShader::CompileShaderFromFile(const CHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut, std::vector<D3D10_SHADER_MACRO>& makros) { HRESULT hr = S_OK; char dir[260]; GetCurrentDirectoryA(260, dir); SetCurrentDirectoryA(Engine::GAPI->GetStartDirectory().c_str()); DWORD dwShaderFlags = 0; #if defined( DEBUG ) || defined( _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; #endif // Construct makros std::vector<D3D10_SHADER_MACRO> m; D3D11GraphicsEngine::ConstructShaderMakroList(m); // Push these to the front m.insert(m.begin(), makros.begin(), makros.end()); ID3DBlob* pErrorBlob; hr = D3DX11CompileFromFileA(szFileName, &m[0], NULL, szEntryPoint, szShaderModel, dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL); if (FAILED(hr)) { LogInfo() << "Shader compilation failed!"; if (pErrorBlob != NULL) { LogErrorBox() << (char*)pErrorBlob->GetBufferPointer() << "\n\n (You can ignore the next error from Gothic about too small video memory!)"; pErrorBlob->Release(); } SetCurrentDirectoryA(dir); return hr; } if (pErrorBlob) { /*if(Engine->SwapchainCreated()) Engine->GetConsole()->PostConsoleMessage((char*)pErrorBlob->GetBufferPointer()); else LogWarnBox() << (char*)pErrorBlob->GetBufferPointer() << "\n\n (You can ignore the next error from Gothic about too small video memory!)"; */ pErrorBlob->Release(); } SetCurrentDirectoryA(dir); return S_OK; }
ID3D11PixelShader* LoadPixelShaderFile(ID3D11Device* pd3dDevice, const void* pShaderFileData, char *pFuntionName, bool bBinary, ID3DBlob** pRetBlob) { HRESULT hr = S_OK; ID3D11PixelShader* pPixelShader = nullptr; ID3DBlob* pBlob = nullptr; DWORD dwSize = 0; LPCVOID lpData = NULL; if (bBinary == false) { if (pFuntionName == 0) { if (FAILED(hr = CompileShaderFromFile((TCHAR*)pShaderFileData, "PS", "ps_5_0", &pBlob))) { return nullptr; } } else { if (FAILED(hr = CompileShaderFromFile((TCHAR*)pShaderFileData, pFuntionName, "ps_5_0", &pBlob))) { return nullptr; } } dwSize = pBlob->GetBufferSize(); lpData = pBlob->GetBufferPointer(); } else { dwSize = sizeof(pShaderFileData); lpData = pShaderFileData; } if (FAILED(hr = pd3dDevice->CreatePixelShader(lpData, dwSize, NULL, &pPixelShader))) { pBlob->Release(); return nullptr; } if (pRetBlob == nullptr) { pBlob->Release(); } else { *pRetBlob = pBlob; } return pPixelShader; }
//-------------------------------------------------------------------------------------- // Helper for compiling shaders with D3DCompile // // With VS 11, we could load up prebuilt .cso files instead... //-------------------------------------------------------------------------------------- HRESULT GraphicsDriver::CompileShaderFromFile( const wchar_t* inFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, vector< char >& outCompiledShaderCode ) { HRESULT hr = S_OK; DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #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* pErrorBlob = nullptr; ID3DBlob* pBlobOut = nullptr; hr = D3DCompileFromFile( inFileName, nullptr, nullptr, szEntryPoint, szShaderModel, dwShaderFlags, 0, &pBlobOut, &pErrorBlob ); if( FAILED( hr ) ) { if( pErrorBlob ) { wstring message = StringUtils::Sprintf( L"%hs", pErrorBlob->GetBufferPointer() ); OutputDebugStringW( message.c_str() ); MessageBox( nullptr, message.c_str(), L"Error", MB_OK ); pErrorBlob->Release(); Dbg_Assert( hr == S_OK, "Shader Compilation Failed" ); } return hr; } if( pErrorBlob ) { pErrorBlob->Release(); } //now copy to vector if we like it... if( pBlobOut ) { int compiledCodeSize = pBlobOut->GetBufferSize(); outCompiledShaderCode.resize( compiledCodeSize ); std::memcpy( outCompiledShaderCode.data(), pBlobOut->GetBufferPointer(), compiledCodeSize ); pBlobOut->Release(); } return S_OK; }
ID3D11VertexShader* LoadVertexShaderFile(ID3D11Device* pd3dDevice, const void* pShaderFileData, ID3DBlob** ppBlobOut, char *pFuntionName, bool bBinary) { HRESULT hr = S_OK; ID3D11VertexShader* pVertexShader; ID3DBlob* pBlob = NULL; DWORD dwSize = 0; LPCVOID lpData = NULL; if (bBinary == false) { if (pFuntionName == 0) { if (FAILED(hr = CompileShaderFromFile((TCHAR*)pShaderFileData, "VS", "vs_5_0", &pBlob))) { return nullptr; } }else { if (FAILED(hr = CompileShaderFromFile((TCHAR*)pShaderFileData, pFuntionName, "vs_5_0", &pBlob))) { return nullptr; } } dwSize = pBlob->GetBufferSize(); lpData = pBlob->GetBufferPointer(); } else { pBlob = *ppBlobOut; if (pBlob == nullptr) return nullptr; dwSize = pBlob->GetBufferSize(); lpData = pBlob->GetBufferPointer(); } if (FAILED(hr = pd3dDevice->CreateVertexShader(lpData, dwSize, NULL, &pVertexShader))) { pBlob->Release(); return nullptr; } if (ppBlobOut == nullptr) pBlob->Release(); else *ppBlobOut = pBlob; return pVertexShader; };
ID3D11InputLayout* Technique::setVertexShader(LPCWSTR filename, LPCSTR entryPoint, LPCSTR shaderModel, ID3D11Device* g_pd3dDevice, ToshLayout layout){ HRESULT hr = S_OK; DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _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; #endif ID3DBlob* pVSBlob = nullptr; ID3DBlob* pErrorBlob = nullptr; hr = D3DCompileFromFile(filename, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, dwShaderFlags, 0, &pVSBlob, &pErrorBlob); if (FAILED(hr)) { if (pErrorBlob) { std::ofstream fout("Shader_Debug.txt"); fout << reinterpret_cast<const char*>(pErrorBlob->GetBufferPointer()); OutputDebugStringA(reinterpret_cast<const char*>(pErrorBlob->GetBufferPointer())); pErrorBlob->Release(); } } if (pErrorBlob) pErrorBlob->Release(); hr = g_pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), nullptr, &g_pVertexShader); if (FAILED(hr)) { pVSBlob->Release(); } ID3D11InputLayout* g_pVertexLayout = nullptr; hr = g_pd3dDevice->CreateInputLayout(layout.mTlayout, layout.numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &g_pVertexLayout); pVSBlob->Release(); return g_pVertexLayout; }
void ShaderCompiler::compileProgram(IO* io, const ProgramDesc& programDesc, std::weak_ptr<DX12DeviceContext> context) { auto fmt = boost::format("Compiling program \"%1%\"") % programDesc.name; LOGS_INDENT_START << boost::str(fmt); Program prog; for (auto shaderDesc : programDesc.shaders) { auto fmt = boost::format("Path: %1%, Type: %2%, Entry: %3%") % shaderDesc.path % shaderDesc.type % shaderDesc.main; LOGS << boost::str(fmt); auto buffer = io->loadFile(shaderDesc.path); ID3DBlob* shaderBlob = nullptr; ID3DBlob* errorBlob = nullptr; auto hr = D3DCompile(buffer.c_str(), buffer.size(), shaderDesc.path.c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, shaderDesc.main.c_str(), getDXShaderType(shaderDesc.type).c_str(), shaderDesc.flags, 0, &shaderBlob, &errorBlob); if (FAILED(hr)) { if (errorBlob != nullptr) { LOGE << "Compilation failed" << std::endl << static_cast<char*>(errorBlob->GetBufferPointer()); errorBlob->Release(); } if (shaderBlob != nullptr) shaderBlob->Release(); fmt = boost::format("Shader compilation failed: %1%") % shaderDesc.path; throw new std::runtime_error(boost::str(fmt)); } D3D12_SHADER_BYTECODE bc; bc.BytecodeLength = shaderBlob->GetBufferSize(); bc.pShaderBytecode = shaderBlob->GetBufferPointer(); if (shaderDesc.type == "vs") prog.vs = bc; else if (shaderDesc.type == "ps") prog.ps = bc; getShaderResources(shaderBlob, context); } LOGS_INDENT_END << "Program done."; }
bool DXPixelShader::VInitShader(File* file) { HRESULT hr = S_OK; BYTE* data = new BYTE[VIX_LARGE_BUFSIZE]; file->Seek(0, FileSeek::End); size_t _size = file->Tell(); file->Seek(0, FileSeek::Set); file->Read(data, _size); //read all of the file into memory DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #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* errorBlob = nullptr; hr = D3DCompile2(data, _size, nullptr, nullptr, nullptr, "main", "ps_5_0", NULL, NULL, NULL, NULL, NULL, &m_shaderBlob, &errorBlob); //hr = D3DReadFileToBlob(file->FilePath().c_str(), &m_shaderBlob); if (FAILED(hr)) { if (errorBlob) { OutputDebugStringA(reinterpret_cast<const char*>(errorBlob->GetBufferPointer())); errorBlob->Release(); } return false; } if (errorBlob) errorBlob->Release(); // Create the vertex shader hr = m_device->CreatePixelShader(m_shaderBlob->GetBufferPointer(), m_shaderBlob->GetBufferSize(), nullptr, &m_shader); if (FAILED(hr)) { ReleaseCOM(m_shaderBlob); return false; } return true; }
ID3D11GeometryShader* LoadGeometryShaderFile(ID3D11Device* pd3dDevice, const void* pShaderFileData, ID3DBlob** ppBlobOut, char *pFuntionName , bool bBinary ) { HRESULT hr = S_OK; ID3D11GeometryShader* pGeometryShader = nullptr; ID3DBlob* pBlob = nullptr; DWORD dwSize = 0; LPCVOID lpData = NULL; if (bBinary == false) { if (pFuntionName == 0) { if (FAILED(hr = CompileShaderFromFile( (TCHAR*)pShaderFileData, "GS", "gs_5_0", &pBlob))) { return nullptr; } } else { if (FAILED(hr = CompileShaderFromFile((TCHAR*)pShaderFileData, pFuntionName, "gs_5_0", &pBlob))) { return nullptr; } } //pBlob = *ppBlobOut; dwSize = pBlob->GetBufferSize(); lpData = pBlob->GetBufferPointer(); } else { dwSize = sizeof(pShaderFileData); lpData = pShaderFileData; } if (FAILED(hr = pd3dDevice->CreateGeometryShader(lpData, dwSize, NULL, &pGeometryShader))) { pBlob->Release(); return nullptr; } if(ppBlobOut == nullptr) pBlob->Release(); else *ppBlobOut = pBlob; //D3DCreateBlob(dwSize, ppBlobOut); return pGeometryShader; }
ID3DBlob* ShaderCompile(char * shaderName, const char * shaderSrcString, const char * profile) { ID3DBlob* pShaderCode = NULL; ID3DBlob* pErrorMsg = NULL; if (FAILED(D3DCompile(shaderSrcString, strlen(shaderSrcString),NULL,NULL,NULL, "main",profile,D3DCOMPILE_OPTIMIZATION_LEVEL3,0, &pShaderCode,&pErrorMsg))) MessageBoxA(NULL,(char *) pErrorMsg->GetBufferPointer(),"", MB_OK); if (pErrorMsg) pErrorMsg->Release(); //Now write out blob char tempString[1000]; int numDWORDs = ((int)pShaderCode->GetBufferSize())/4; DWORD * ptr = (DWORD *)pShaderCode->GetBufferPointer(); sprintf_s(tempString,"DWORD %s[%d] = {",shaderName,numDWORDs); OutputDebugStringA(tempString); for (int i = 0; i < numDWORDs; i++) { sprintf_s(tempString,"%lu,",ptr[i]); OutputDebugStringA(tempString); } OutputDebugStringA("};\n"); return(pShaderCode); }
bool CompileShader(void *p_pData, uint32 p_nSize, const char *p_sFuncName, const char *p_sProfile, ID3DBlob **p_ppBlob) { ID3DBlob *pErrorBlob = NULL; DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #ifdef SAM_DEBUG dwShaderFlags |= D3DCOMPILE_DEBUG; #endif HRESULT hResult = D3DCompile(p_pData, p_nSize, NULL, NULL, NULL, p_sFuncName, p_sProfile, dwShaderFlags, 0, p_ppBlob, &pErrorBlob); if(hResult != S_OK) { if(pErrorBlob != NULL) { g_Env->pRenderWindow->LogError(hResult, (char*)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } else { g_Env->pRenderWindow->LogError(hResult, "Unable to compile shader"); } return false; } return true; }
void D3DShader::attach(ShaderType shaderType, WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel) { HRESULT result; ID3DBlob* pShaderBlob = nullptr; CompileShaderFromFile(szFileName, szEntryPoint, szShaderModel, &pShaderBlob); if (shaderType == D3D_VERTEX_SHADER) { result = pD3D11Device->CreateVertexShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), NULL, &pVS_Shader); auto numElements = vInputLayoutDesc.size(); result = pD3D11Device->CreateInputLayout(&vInputLayoutDesc[0], numElements, pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), &pInputLayout); } else if (shaderType == D3D_PIXEL_SHADER) { result = pD3D11Device->CreatePixelShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), NULL, &pPS_Shader); } else if (shaderType == D3D_GEOMETRY_SHADER) { result = pD3D11Device->CreateGeometryShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), NULL, &pGS_Shader); } else if (shaderType == D3D_HULL_SHADER) { result = pD3D11Device->CreateHullShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), NULL, &pHS_Shader); } else if (shaderType == D3D_DOMAIN_SHADER) { result = pD3D11Device->CreateDomainShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), NULL, &pDS_Shader); } // Release the shader buffer since they are no longer needed. pShaderBlob->Release(); pShaderBlob = 0; }
void BaseShader::loadPixelShader(WCHAR* filename) { HRESULT result; ID3DBlob* errorMessage; ID3DBlob* pixelShaderBuffer; // Compile the pixel shader code. result = D3DCompileFromFile(filename, NULL, NULL, "main", "ps_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pixelShaderBuffer, &errorMessage); if (FAILED(result)) { // If the shader failed to compile it should have writen something to the error message. if (errorMessage) { OutputShaderErrorMessage(errorMessage, m_hwnd, filename); } // If there was nothing in the error message then it simply could not find the file itself. else { MessageBox(m_hwnd, filename, L"Missing Shader File", MB_OK); } exit(0); } // Create the pixel shader from the buffer. result = m_device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); pixelShaderBuffer->Release(); pixelShaderBuffer = 0; }
bool FShaderProgramInfo::Compile(ID3DBlob** CodeBlob) const { TVector<D3D_SHADER_MACRO> NullTerminatedDefines; NullTerminatedDefines.Resize(ShaderDefines.Size() + 1); for (size_t i = 0; i < ShaderDefines.Size(); i++) { NullTerminatedDefines[i] = ShaderDefines[i]; } size_t LastIndex = NullTerminatedDefines.Size() - 1; NullTerminatedDefines[LastIndex].Name = NullTerminatedDefines[LastIndex].Definition = nullptr; ID3DBlob* ErrorBlob = nullptr; HRESULT Result = D3DCompileFromFile(SourcePath.c_str(), NullTerminatedDefines.Data(), D3D_COMPILE_STANDARD_FILE_INCLUDE, EntryPoint.c_str(), ShaderTarget.c_str(), 0, 0, CodeBlob, &ErrorBlob); if (Result != S_OK) { OutputDebugString("ERROR COMPILING SHADER: "); if (ErrorBlob != nullptr) { OutputDebugString((LPCSTR)ErrorBlob->GetBufferPointer()); ErrorBlob->Release(); } } return Result == S_OK; }
static ID3DBlob* CompileShader(const char* src, const char* entryPoint, const char* target) { HRESULT hr; ID3DBlob* pCode = NULL; ID3DBlob* pErrorMsgs = NULL; UINT flags = D3DCOMPILE_ENABLE_STRICTNESS; #if _DEBUG flags |= D3DCOMPILE_DEBUG; #endif hr = D3DCompile(src, strlen(src), NULL, NULL, NULL, entryPoint, target, flags, 0, &pCode, &pErrorMsgs); if (pErrorMsgs != NULL) { OutputDebugStringA((LPCSTR)pErrorMsgs->GetBufferPointer()); pErrorMsgs->Release(); pErrorMsgs = NULL; } if (FAILED(hr)) { SafeRelease(pCode); throw std::exception("Failed to compile HLSL shader"); } return pCode; }
bool ParticleManager::CompileShader(ID3DBlob** shader, string filename, string entry, string shaderModel) { DWORD shaderFlags = 0; ID3DBlob* errorBuffer = 0; HRESULT hResult; //If debugging then compile shader in debug mode for error messages #if defined(DEBUG) || defined(_DEBUG) shaderFlags |= D3DCOMPILE_DEBUG; #endif //Compile the shader using the determined filename, entry point, shader model hResult = D3DX11CompileFromFile(filename.c_str(), 0, 0, entry.c_str(), shaderModel.c_str(), shaderFlags, 0, 0, shader, &errorBuffer, 0); //If the returned shader has errored then see what line in the .fx file if (errorBuffer != 0) { MessageBoxA(NULL, (char*)errorBuffer->GetBufferPointer(), 0, 0); errorBuffer->Release(); errorBuffer = 0; } //If the compile failed completely then return a DXTRACE msg to link back to this function call if (FAILED(hResult)) { DXTRACE_MSG(__FILE__, (DWORD)__LINE__, hResult, "D3DX11CompileFromFile", true); return false; } return true; }
ID3DBlob * ShaderSet::LoadShaderFromFile(const Resources::Shaders::ShaderTypeInfo & info, ID3D11Device * dev) { assert(dev); ID3DBlob * Errors; ID3DBlob * shaderCode; auto fileLocation = std::wstring(info.fileName.begin(), info.fileName.end()); HRESULT res = D3DCompileFromFile(fileLocation.c_str(), 0, 0, info.mainFunctionName.c_str(), info.profile.c_str(), info.compilationFlags, 0, &shaderCode, &Errors); if (FAILED(res) || Errors != nullptr) { if (Errors != nullptr) { char * compileError = static_cast<char*>(Errors->GetBufferPointer()); WinUtils::PrintErrorMessageString(compileError, "Error loading shader from file : ", "Error"); Errors->Release(); } else { WinUtils::PrintErrorMessage(res, "Error loading shader from file : ", "Error"); } return nullptr; } return shaderCode; }
bool D3D11DrawConfig::CompileVertexShader(const std::string &target, const std::string &entry, const std::string &source, ID3D11InputLayout ** ppInputLayout, D3D11_INPUT_ELEMENT_DESC const * pInputElementDescs, int numInputElements, ID3D11Device * pd3dDevice) { ID3DBlob * pBlob = NULL; pBlob = _CompileShader(target, entry, source); HRESULT hr = pd3dDevice->CreateVertexShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &_vertexShader); if (FAILED(hr)) { return false; } if (ppInputLayout && !*ppInputLayout) { hr = pd3dDevice->CreateInputLayout( pInputElementDescs, numInputElements, pBlob->GetBufferPointer(), pBlob->GetBufferSize(), ppInputLayout); if (FAILED(hr)) { return false; } } if (pBlob) pBlob->Release(); return true; }
static ID3DBlob * _CompileShader(std::string const &target, std::string const &entry, std::string const &shaderSource) { DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #ifdef _DEBUG dwShaderFlags |= D3DCOMPILE_DEBUG; #endif ID3DBlob* pBlob = NULL; ID3DBlob* pBlobError = NULL; HRESULT hr = D3DCompile(shaderSource.c_str(), shaderSource.size(), NULL, NULL, NULL, entry.c_str(), target.c_str(), dwShaderFlags, 0, &pBlob, &pBlobError); if (FAILED(hr)) { if ( pBlobError != NULL ) { OpenSubdiv::Far::Error(OpenSubdiv::Far::FAR_RUNTIME_ERROR, "Error compiling HLSL shader: %s\n", (CHAR*)pBlobError->GetBufferPointer()); pBlobError->Release(); return NULL; } } return pBlob; }
HRESULT GraphicsHandler::AddPixelShader(const std::string & alias, const std::wstring& file, const std::string & entryPoint) { HRESULT hr = S_OK; ID3DBlob* pPSBlob = nullptr; hr = CompileShaderFromFile(file.c_str(), entryPoint.c_str(), "ps_4_0", &pPSBlob); if (FAILED(hr)) { MessageBox(nullptr, L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK); return hr; } // Create the pixel shader ID3D11PixelShader* shader; hr = mpDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &shader); pPSBlob->Release(); if (FAILED(hr)) return hr; mPixelShaders.insert({ alias, shader }); return S_OK; }
void ComputeShader::CompileShaders( const char* _pShaderCode, ID3DBlob* _pCS ) { ////////////////////////////////////////////////////////////////////////// // Compile the compute shader ASSERT( _pCS != NULL || m_pEntryPointCS != NULL, "Invalid ComputeShader entry point!" ); ID3DBlob* pShader = _pCS == NULL ? Shader::CompileShader( m_pShaderFileName, _pShaderCode, m_pMacros, m_pEntryPointCS, "cs_5_0", this, true ) : _pCS; if ( pShader == NULL ) { m_bHasErrors = true; return; } ID3D11ComputeShader* tempCS = NULL; Check( m_Device.DXDevice().CreateComputeShader( pShader->GetBufferPointer(), pShader->GetBufferSize(), NULL, &tempCS ) ); if ( tempCS != NULL ) { // SUCCESS! Replace existing shader! if ( m_pCS != NULL ) m_pCS->Release(); // Release any pre-existing shader m_pCS = tempCS; #ifdef ENABLE_SHADER_REFLECTION m_CSConstants.Enumerate( *pShader ); #endif m_bHasErrors = false; // Not in error state anymore } else { // ERROR! Don't replace existing shader until errors are fixed... m_bHasErrors = true; ASSERT( false, "Failed to create compute shader!" ); } pShader->Release(); // Release shader anyway }
int TechniqueHLSL::insertGeometryShader(std::string shaderDir, std::string shaderName) { if(shaderDir.empty() || shaderName.empty() ) { return -1; } std::string shaderPath = shaderDir + ":" + shaderName; for(unsigned int i=0; i < geometryShaders->size(); i++) { if(shaderPath.size() == geometryShaders->at(i).name.size()) { if( geometryShaders->at(i).name == shaderPath ) { return i; } } } ID3DBlob* shaderBlob = NULL; HRESULT hr; GraphicsDX11* g = GraphicsDX11::getInstance(); hr = g->compileShader(shaderDir.c_str(),shaderName.c_str(),"gs_5_0",&shaderBlob ); if(FAILED(hr)) { std::string text = "Failed to compile " + shaderName + " ( " + shaderDir + " )"; MessageBox( NULL, text.c_str(),"Shader Error",MB_OK); PostQuitMessage(0); return -1; } ID3D11GeometryShader* shader; hr = device->CreateGeometryShader(shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), NULL, &shader); if( FAILED(hr) ) { hr = g->compileShader(shaderDir.c_str(),shaderName.c_str(),"gs_4_0",&shaderBlob ); if(FAILED(hr)) { std::string text = "Failed to compile " + shaderName + " ( " + shaderDir + " )"; MessageBox( NULL, text.c_str(),"Shader Error",MB_OK); PostQuitMessage(0); return -1; } hr = device->CreateGeometryShader(shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), NULL, &shader); if(FAILED(hr)) { std::string text = "Failed to compile " + shaderName + " ( " + shaderDir + " )"; MessageBox( NULL, text.c_str(),"Shader Error",MB_OK); PostQuitMessage(0); return -1; } std::cout << "Failed to create " << shaderPath << " using shader model 5. Reverting to shader model 4." << std::endl; } shaderBlob->Release(); GSstruct gs; gs.name = shaderPath; gs.geometryShader = shader; geometryShaders->push_back(gs); return geometryShaders->size()-1; }
//-------------------------------------------------------------------------------------- // Вспомогательная функция для компиляции шейдеров в D3DX11 //-------------------------------------------------------------------------------------- HRESULT CompileShaderFromFile( LPCSTR szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut ) { HRESULT hr = S_OK; DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; ID3DBlob* pErrorBlob; hr = D3DX11CompileFromFile( szFileName, NULL, NULL, szEntryPoint, szShaderModel, dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL ); if( FAILED(hr) ) { if( pErrorBlob != NULL ) OutputDebugStringA( (char*)pErrorBlob->GetBufferPointer() ); if( pErrorBlob ) pErrorBlob->Release(); return hr; } if( pErrorBlob ) pErrorBlob->Release(); return S_OK; }