示例#1
0
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;
		if (fromCode&&vshader)
			VSLen = strlen(vshader);
		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;
		if (fromCode&&pshader)
			PSLen = strlen(pshader);
		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);
}
示例#2
0
	void overlay::init_shaders()
	{
		auto device = d3d_device::instance()->raw();

		com_ptr<ID3DBlob> vs_blob, ps_blob;
		const string & vs_code = vertex_shader_code();
		const string & ps_code = pixel_shader_code();

		HRESULT result = D3DCompile(vs_code.c_str(), vs_code.size(), nullptr, nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs_blob, nullptr);

		if (FAILED(result))
			throw std::runtime_error("Error compiling vertex shader");

		result = D3DCompile(ps_code.c_str(), ps_code.size(), nullptr, nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps_blob, nullptr);

		if (FAILED(result))
			throw std::runtime_error("Error compiling pixel shader");

		D3D11_INPUT_ELEMENT_DESC input_desc[] =
		{
			{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
			{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
		};

		device->CreateInputLayout(input_desc, 2, vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &input_layout);
		device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nullptr, &vertex_shader);
		device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nullptr, &pixel_shader);
	}
示例#3
0
bool Ivy::Graphics::DXShader::Compile(std::string filename, ShaderType type)
{
	unsigned int flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR;

#if defined(DEBUG) || defined(_DEBUG)
	// MakeActive 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.
	flags |= D3DCOMPILE_DEBUG;
	// Disable optimizations to further improve shader debugging
	flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif

	D3D_FEATURE_LEVEL featureLevel = device->GetID3D11Device()->GetFeatureLevel();

	ComPtr<ID3DBlob> l_pErrorBlob = nullptr;

	HRESULT hr = D3DCompileFromFile(Core::Utility::StringToWString(filename).c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE,
		"main", GetCompilerTarget(featureLevel, type).c_str(), flags, 0, const_cast<ID3DBlob**>(GetShaderBlob(type).GetAddressOf()), 
		l_pErrorBlob.GetAddressOf());

	if (FAILED(hr))
	{
        // Notify of shader error if one exists.
		if(l_pErrorBlob.Get() != nullptr)
			std::cout << reinterpret_cast<const char*>(l_pErrorBlob->GetBufferPointer()) << std::endl;
		
        // Use error shader in the event of failure.
        if (type == ShaderType::Pixel)
        {
            std::cout << "Trying prefab Pixel Shader..." << std::endl;
            std::cout << Ivy::ShaderPrefab::HLSLErrorPixelShader << std::endl;
            hr = D3DCompile(Ivy::ShaderPrefab::HLSLErrorPixelShader.c_str(), Ivy::ShaderPrefab::HLSLErrorPixelShader.size(),
                nullptr, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", GetCompilerTarget(featureLevel, type).c_str(), flags, 0,
                const_cast<ID3DBlob**>(GetShaderBlob(type).GetAddressOf()), l_pErrorBlob.GetAddressOf());
            if (FAILED(hr))
                return false;
        }
        else
        {
            std::cout << "Trying prefab Vertex Shader..." << std::endl;
            std::cout << Ivy::ShaderPrefab::HLSLErrorVertexShader << std::endl;
            hr = D3DCompile(Ivy::ShaderPrefab::HLSLErrorVertexShader.c_str(), Ivy::ShaderPrefab::HLSLErrorVertexShader.size(),
                nullptr, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", GetCompilerTarget(featureLevel, type).c_str(), flags, 0,
                const_cast<ID3DBlob**>(GetShaderBlob(type).GetAddressOf()), l_pErrorBlob.GetAddressOf());
            if (FAILED(hr))
                return false;
        }
        
        std::cout << "Prefab shader was compiled successfully..." << std::endl;
        return true;
    }

    std::cout << "Shader " << filename << " was compiled successfully..." << std::endl;
	return true;
}
示例#4
0
  bool ReloadShader( char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize )
  {
    ID3DBlob * pCode = NULL;
    ID3DBlob * pErrors = NULL;
    if (D3DCompile( szShaderCode, nShaderCodeSize, NULL, NULL, NULL, "main", "ps_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK)
    {
      memset( szErrorBuffer, 0, nErrorBufferSize );
      strncpy( szErrorBuffer, (char*)pErrors->GetBufferPointer(), nErrorBufferSize - 1 );
      return false;
    }

    if (theShader) 
    {
      theShader->Release();
      theShader = NULL;
    }

    if (pDevice->CreatePixelShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &theShader ) != S_OK)
    {
      return false;
    }
    D3DReflect( pCode->GetBufferPointer(), pCode->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pShaderReflection );
    pCBuf = pShaderReflection->GetConstantBufferByIndex(0);

    return true;
  }
示例#5
0
ID3DBlob* D3DApp::GenerateShader(const std::string& filename, const std::string& function,
	const std::string& model, const D3D_SHADER_MACRO* pDefines)
{
	HRESULT hr = S_OK;

	ID3DBlob* pCompiledShader = nullptr;
	ID3DBlob* pErrorMessages = nullptr;

	UINT flags = D3DCOMPILE_PACK_MATRIX_ROW_MAJOR;
#ifdef _DEBUG
	flags |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; // | D3DCOMPILE_WARNINGS_ARE_ERRORS;
#endif

	std::ifstream shaderFile(filename);
	std::string hlslCode((std::istreambuf_iterator<char>(shaderFile)),
		std::istreambuf_iterator<char>());

	HR(D3DCompile(
		hlslCode.c_str(),
		hlslCode.size(),
		nullptr,
		pDefines,
		nullptr,
		function.c_str(),
		model.c_str(),
		flags,
		0,
		&pCompiledShader,
		&pErrorMessages));

	ReleaseCOM(pErrorMessages);

	return(pCompiledShader);
}
示例#6
0
    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;
    }
inline HRESULT D3DCompileFromFile(
  LPCWSTR pFileName,
  const D3D_SHADER_MACRO *pDefines,
  ID3DInclude *pInclude,
  LPCSTR pEntrypoint,
  LPCSTR pTarget,
  UINT Flags1,
  UINT Flags2,
  ID3DBlob **ppCode,
  ID3DBlob **ppErrorMsgs
  )
{
    std::ifstream ifs(pFileName, std::ios::binary);
    if(!ifs){
        return E_FAIL;
    }

	ifs.seekg (0, std::ios::end);
    std::vector<unsigned char> buffer(static_cast<unsigned int>(ifs.tellg ()));
	ifs.seekg (0, std::ios::beg);
    if(buffer.empty()){
        return E_FAIL;
    }
    ifs.read ((char*)&buffer[0], buffer.size());

    return D3DCompile(&buffer[0], buffer.size(), to_MultiByte(932, pFileName).c_str()
            , pDefines
            , pInclude
            , pEntrypoint
            , pTarget
            , Flags1
            , Flags2
            , ppCode
            , ppErrorMsgs);
}
示例#8
0
bool ShaderCompiler::compile(const String& fileName, const String& entryPoint, const String& target, DataBlob& byteCode)
{
  DataBlob buffer;
  if (!readRawBlob(fileName, buffer))
    return false;

  UINT flags = D3DCOMPILE_WARNINGS_ARE_ERRORS | D3DCOMPILE_PACK_MATRIX_ROW_MAJOR;

#if defined (_DEBUG)
  flags |= (D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION);
#else
  flags |= D3DCOMPILE_OPTIMIZATION_LEVEL3;
#endif // _DEBUG

  IncludeHandler includeHandler;
  ID3DBlob* shaderByteCode = 0;
  ID3DBlob* errorMsgs = 0;
  if (FAILED(D3DCompile(buffer.getPtr(), buffer.getSize(), NULL, NULL, &includeHandler,
    entryPoint.c_str(), target.c_str(), flags, 0, &shaderByteCode, &errorMsgs)))
  {
    // parse error message
    const char* msg = (const char*)errorMsgs->GetBufferPointer();
    MessageBox(NULL, msg, "Error", MB_OK);
    if (errorMsgs)
      errorMsgs->Release();
  }
  else
  {
    byteCode.allocate(shaderByteCode->GetBufferSize());
    memcpy(byteCode.getPtr(), shaderByteCode->GetBufferPointer(), shaderByteCode->GetBufferSize());
    shaderByteCode->Release();
  }

  return true;
}
CPixelBufferView::PixelShaderPtr CPixelBufferView::CreatePixelShaderFromResource(const TCHAR* resourceName)
{
	HRESULT result = S_OK;

	auto shaderResourceInfo = FindResource(GetModuleHandle(nullptr), resourceName, _T("TEXTFILE"));
	assert(shaderResourceInfo != nullptr);

	auto shaderResourceHandle = LoadResource(GetModuleHandle(nullptr), shaderResourceInfo);
	auto shaderResourceSize = SizeofResource(GetModuleHandle(nullptr), shaderResourceInfo);

	auto shaderResource = reinterpret_cast<const char*>(LockResource(shaderResourceHandle));

	UINT compileFlags = 0;
#ifdef _DEBUG
	compileFlags |= D3DCOMPILE_DEBUG;
#endif

	Framework::Win32::CComPtr<ID3DBlob> shaderBinary;
	Framework::Win32::CComPtr<ID3DBlob> compileErrors;
	result = D3DCompile(shaderResource, shaderResourceSize, "ps", nullptr, nullptr, "main",
	                    "ps_3_0", compileFlags, 0, &shaderBinary, &compileErrors);
	assert(SUCCEEDED(result));

	PixelShaderPtr shader;
	result = m_device->CreatePixelShader(reinterpret_cast<DWORD*>(shaderBinary->GetBufferPointer()), &shader);
	assert(SUCCEEDED(result));

	return shader;
}
示例#10
0
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;
}
示例#11
0
	HRESULT ShaderBase::loadFromSource( const std::string &source, const std::string &entryPoint )
	{
		//load shader source
		unsigned int flags = D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR | D3DCOMPILE_WARNINGS_ARE_ERRORS;
#ifdef _DEBUG
		flags |= D3DCOMPILE_DEBUG | D3DCOMPILE_OPTIMIZATION_LEVEL0;
#else
		flags |= D3DCOMPILE_OPTIMIZATION_LEVEL3;
#endif

		ID3DBlob *shaderSource;
		ID3DBlob *compileErrors;
		HRESULT res = D3DCompile( source.c_str(), sizeof( source ), NULL, NULL, NULL, entryPoint.c_str(), m_target.c_str(), flags, 0u, &shaderSource, &compileErrors );
		if ( FAILED(res)  )
		{
			//TODO: parse compile errors
			std::cout << "Error (ShaderBase::loadFromSource): Error loading shader source " << std::endl;
			return res;
		}

		if ( FAILED( processLoadedShaderBlob( shaderSource ) ) )
		{
			std::cout << "Error (ShaderBase::loadFromSource): Error processing shader source " << std::endl;
			shaderSource->Release();
			return res;
		}

		shaderSource->Release();

		return S_OK;
	}
示例#12
0
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);
}
示例#13
0
com_ptr<ID3DBlob> compile_shader(const std::string& source_code, const std::string& source_filename,
	uint32_t compile_flags, const char* p_entry_point_name, const char* p_shader_model)
{
	com_ptr<ID3DBlob> p_bytecode;
	com_ptr<ID3DBlob> p_error_blob;

	const char* p_filename = (source_filename.empty()) ? nullptr : source_filename.c_str();
	HRESULT hr = D3DCompile(
		source_code.c_str(),
		source_code.size(),
		p_filename,
		nullptr,							// defines
		D3D_COMPILE_STANDARD_FILE_INCLUDE,	// includes
		p_entry_point_name,
		p_shader_model,
		compile_flags,
		0,									// effect compilation flags
		&p_bytecode.ptr,
		&p_error_blob.ptr
	);

	if (hr != S_OK) {
		std::string error(static_cast<char*>(p_error_blob->GetBufferPointer()), p_error_blob->GetBufferSize());
		throw std::runtime_error(error);
	}

	return p_bytecode;
}
示例#14
0
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;
}
示例#15
0
HRESULT WINAPI D3D10CompileShader(const char *data, SIZE_T data_size, const char *filename,
        const D3D10_SHADER_MACRO *defines, ID3D10Include *include, const char *entrypoint,
        const char *profile, UINT flags, ID3D10Blob **shader, ID3D10Blob **error_messages)
{
    /* Forward to d3dcompiler */
    return D3DCompile(data, data_size, filename, defines, include,
            entrypoint, profile, flags, 0, shader, error_messages);
}
示例#16
0
void Shader::Compile(const std::string &code, SHADER_TYPE st)
{
	HRESULT hr;
	ComPtr<ID3DBlob> errorBlob;
	switch (st)
	{
	case SHADER_TYPE::SHADER_TYPE_VERTEX:
		hr = D3DCompile(code.c_str(), code.size(), "VertexProgram.hlsl", nullptr, nullptr, "main", "vs_5_0", 0, 0, &bytecode, errorBlob.GetAddressOf());
		if (hr != S_OK)
			LOG_ERROR(RSX, "VS build failed:%s", errorBlob->GetBufferPointer());
		break;
	case SHADER_TYPE::SHADER_TYPE_FRAGMENT:
		hr = D3DCompile(code.c_str(), code.size(), "FragmentProgram.hlsl", nullptr, nullptr, "main", "ps_5_0", 0, 0, &bytecode, errorBlob.GetAddressOf());
		if (hr != S_OK)
			LOG_ERROR(RSX, "FS build failed:%s", errorBlob->GetBufferPointer());
		break;
	}
}
示例#17
0
void DxBuilder::buildPixelShader(const ASTEffect& effect, ASTTechnique& technique)
{
   const ASTFunction* pfunction = effect.findFunction(technique.mPixel.mEntry);

   String code = UTEXT("// generated pixel shader\n\n");

   String num;
   NumberConverter& conv = NumberConverter::getInstance();
   for ( std::size_t index = 0; index < effect.mTextures.size(); ++index )
   {
      ASTTexture* ptexture = effect.mTextures[index];
      code += UTEXT("Texture2D ") + ptexture->mName + UTEXT(" : register(t");

      int reg = ptexture->mRegister;
      if ( reg == -1 )
      {
         reg = (int) index;
      }
      
      code += conv.format(num, reg) + UTEXT(");\n");
      num = UTEXT("");
   }

   for ( std::size_t index = 0; index < effect.mSamplers.size(); ++index )
   {
      ASTSampler* psampler = effect.mSamplers[index];
      code += UTEXT("SamplerState ") + psampler->mName + UTEXT(" : register(s");
      
      int reg = psampler->mRegister;
      if ( reg == -1 )
      {
         reg = index;
      }
      
      code += conv.format(num, (int)reg) + UTEXT(");\n");
      num = UTEXT("");
   }

   code += buildStructs(effect, *pfunction);
   code += buildFunction(*pfunction);

   std::string data = code.toUtf8();
   std::string entry = technique.mPixel.mEntry.toUtf8();
   std::string target = technique.mPixel.mTarget.toUtf8();
   uint32_t flags = D3DCOMPILE_ENABLE_STRICTNESS;

   ID3DBlob *presult, *perror;
   HRESULT hr = D3DCompile(data.c_str(), data.length(), NULL, NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, entry.c_str(), target.c_str(), flags, 0, &presult, &perror);
   if ( FAILED(hr) )
   {
      std::string d3derror = "Shader compile error: " + std::string((const char*)perror->GetBufferPointer());
      throw std::exception(d3derror.c_str());
   }
      
   technique.mPixel.mCompiledCode.writeBlob(presult->GetBufferPointer(), presult->GetBufferSize());
}
示例#18
0
bool Cef3DDirect3D12Renderer::CompileShader(ShaderType type, unsigned flags, const char* entryPoint, const std::string& source, ID3D10Blob** outBlob)
{
	ID3DBlob* errorMsgs = 0;
	HRESULT hr = D3DCompile(source.c_str(), source.length(), "", 0, 0,
		entryPoint, type == Vertex ? "vs_5_0" : "ps_5_0", flags, 0, outBlob, &errorMsgs);

	if (FAILED(hr))
		return false;
	return true;
}
示例#19
0
文件: dx11.hpp 项目: jslhs/mgpu
	void compile(const std::string &entry, const std::string &target)
	{
		if (_src.empty()) return;
		if (entry != _entry || target != _target) _dirty = true;
		if (!_dirty) return;

		_bin = nullptr;
		_msg = nullptr;

		_hr = D3DCompile(&_src[0], _src.size(), nullptr, _defs, _inc, entry.c_str(), target.c_str(), _flags1, _flags2, &_bin, &_msg);
		_dirty = false;
	}
示例#20
0
HRESULT WINAPI D3D10CompileEffectFromMemory(void *data, SIZE_T data_size, const char *filename,
        const D3D10_SHADER_MACRO *defines, ID3D10Include *include, UINT hlsl_flags, UINT fx_flags,
        ID3D10Blob **effect, ID3D10Blob **errors)
{
    TRACE("data %p, data_size %lu, filename %s, defines %p, include %p, "
            "hlsl_flags %#x, fx_flags %#x, effect %p, errors %p.\n",
            data, data_size, wine_dbgstr_a(filename), defines, include,
            hlsl_flags, fx_flags, effect, errors);

    return D3DCompile(data, data_size, filename, defines, include,
            NULL, "fx_4_0", hlsl_flags, fx_flags, effect, errors);
}
示例#21
0
//--------------------------------------------------------------------------------------
// Helper function to compile an hlsl shader from file, 
// its binary compiled code is returned
//--------------------------------------------------------------------------------------
HRESULT D3D11Object::CompileShaderFromFile( WCHAR* szFileName, LPCSTR szEntryPoint, 
LPCSTR szShaderModel, ID3DBlob** ppBlobOut )
{
    HRESULT hr = S_OK;

    // find the file
    //WCHAR str[MAX_PATH];
    //V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, szFileName ) );
	WCHAR *str = szFileName;
    // open the file 
	//"createFile" creates or opens the file
    HANDLE hFile = CreateFile( szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, 
        OPEN_EXISTING,
        FILE_FLAG_SEQUENTIAL_SCAN, NULL );
    if( INVALID_HANDLE_VALUE == hFile )
        return E_FAIL;

    // Get the file size
    LARGE_INTEGER FileSize;
    GetFileSizeEx( hFile, &FileSize );

    // create enough space for the file data
    BYTE* pFileData = new BYTE[ FileSize.LowPart ];
    if( !pFileData )
        return E_OUTOFMEMORY;

    // read the data in
    DWORD BytesRead;
    if( !ReadFile( hFile, pFileData, FileSize.LowPart, &BytesRead, NULL ) )
        return E_FAIL; 

    CloseHandle( hFile );

    // Compile the shader
    char pFilePathName[MAX_PATH];        
    WideCharToMultiByte(CP_ACP, 0, str, -1, pFilePathName, MAX_PATH, NULL, NULL);
    ID3DBlob* pErrorBlob;
    hr = D3DCompile( pFileData, FileSize.LowPart, pFilePathName, NULL, NULL, szEntryPoint, 
                      szShaderModel, D3D10_SHADER_ENABLE_STRICTNESS, 0, ppBlobOut, &pErrorBlob );


    delete []pFileData;
  
    if( FAILED(hr) )
    {
        printf( (char*)pErrorBlob->GetBufferPointer() );
        SAFE_RELEASE( pErrorBlob );
        return hr;
    }
    SAFE_RELEASE( pErrorBlob );

    return S_OK;
}
HRESULT CompileShader( const char* Source,
                       LPCSTR strFunctionName,
                       const D3D_SHADER_MACRO* pDefines, 
                       IShaderSourceInputStreamFactory *pIncludeStreamFactory,
                       LPCSTR profile, 
                       ID3DBlob **ppBlobOut )
{
    DWORD dwShaderFlags = D3DCOMPILE_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 |= D3DCOMPILE_DEBUG;
#else
    // Warning: do not use this flag as it causes shader compiler to fail the compilation and 
    // report strange errors:
    // dwShaderFlags |= D3D10_SHADER_OPTIMIZATION_LEVEL3;
#endif
	HRESULT hr;
	do
	{
        CComPtr<ID3DBlob> errors;
        auto SourceLen = strlen(Source);
         
        D3DIncludeImpl IncludeImpl(pIncludeStreamFactory);
        hr = D3DCompile( Source, SourceLen, NULL, pDefines, &IncludeImpl, strFunctionName, profile, dwShaderFlags, 0, ppBlobOut, &errors );
       
		if( FAILED(hr) || errors )
		{
            std::wstringstream errorss;
            ComErrorDesc ErrDesc(hr);
            if( FAILED(hr) )
                Diligent::FormatMsg( errorss, "Failed to compile shader\n" );
            else
                Diligent::FormatMsg( errorss, "Shader compiler output:\n" );
            Diligent::FormatMsg( errorss, ErrDesc.Get(), "\n" );
            if( errors )
                Diligent::FormatMsg( errorss, (char*)errors->GetBufferPointer() );
            auto ErrorDesc = errorss.str();
            OutputDebugStringW( ErrorDesc.c_str() );
			if( FAILED(hr) 
#ifdef PLATFORM_WIN32
                && IDRETRY != MessageBoxW( NULL, ErrorDesc.c_str() , L"FX Error", MB_ICONERROR | (Source == nullptr ? MB_ABORTRETRYIGNORE : 0) ) 
#endif
                )
			{
				break;
			}
		}
	} while( FAILED(hr) );
	return hr;
}
示例#23
0
Impl<Shader, RendererType::DX>::Impl(DXRenderer* renderer, Shader* shader)
{
    auto& source = shader->bunch->getSourceText(ShaderBunch::BlobType::Hlsl);

    auto entryPoint = shader->entryPoint.c_str();
    auto target = shader->type == ShaderType::Vertex ? "vs_5_0" : "ps_5_0";
    UINT compileFlags = 0;

    auto result = D3DCompile(source.data(), source.size(), entryPoint, nullptr, nullptr, entryPoint, target, compileFlags, 0, &blob, nullptr);

    if (FAILED(result)) throw;
}
示例#24
0
void setupShaders(ID3D11Device* device, ID3D11DeviceContext* context)
{
	// load and compile the two shaders
	const char* shaders =
	    "#define ATTRIBUTES 5\n"
	    "struct Foo { float4 v[ATTRIBUTES]; };"
	    "float4 VS(uint index: SV_VertexId, out Foo foo: FOO): SV_Position { uint i = index % 3; [unroll] for (int j = 0; j < ATTRIBUTES; j++) foo.v[j] = j; return float4(i != 0, i != 2, 0, 1); }"
	    "float4 PS(Foo foo: FOO): SV_Target { float4 result = 0; [unroll] for (int j = 0; j < ATTRIBUTES; j++) result += foo.v[j]; return result; }";

	ID3DBlob* vsblob = 0;
	ID3DBlob* psblob = 0;
	D3DCompile(shaders, strlen(shaders), 0, 0, 0, "VS", "vs_5_0", 0, 0, &vsblob, 0);
	D3DCompile(shaders, strlen(shaders), 0, 0, 0, "PS", "ps_5_0", 0, 0, &psblob, 0);

	ID3D11VertexShader* vs = 0;
	ID3D11PixelShader* ps = 0;
	device->CreateVertexShader(vsblob->GetBufferPointer(), vsblob->GetBufferSize(), 0, &vs);
	device->CreatePixelShader(psblob->GetBufferPointer(), psblob->GetBufferSize(), 0, &ps);

	context->VSSetShader(vs, 0, 0);
	context->PSSetShader(ps, 0, 0);
}
示例#25
0
void Shader::Compile(const std::string &code, SHADER_TYPE st)
{
	HRESULT hr;
	ComPtr<ID3DBlob> errorBlob;
	UINT compileFlags;
	if (rpcs3::config.rsx.d3d12.debug_output.value())
		compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
	else
		compileFlags = 0;
	switch (st)
	{
	case SHADER_TYPE::SHADER_TYPE_VERTEX:
		hr = D3DCompile(code.c_str(), code.size(), "VertexProgram.hlsl", nullptr, nullptr, "main", "vs_5_0", compileFlags, 0, &bytecode, errorBlob.GetAddressOf());
		if (hr != S_OK)
			LOG_ERROR(RSX, "VS build failed:%s", errorBlob->GetBufferPointer());
		break;
	case SHADER_TYPE::SHADER_TYPE_FRAGMENT:
		hr = D3DCompile(code.c_str(), code.size(), "FragmentProgram.hlsl", nullptr, nullptr, "main", "ps_5_0", compileFlags, 0, &bytecode, errorBlob.GetAddressOf());
		if (hr != S_OK)
			LOG_ERROR(RSX, "FS build failed:%s", errorBlob->GetBufferPointer());
		break;
	}
}
示例#26
0
    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.";
    }
示例#27
0
// see https://msdn.microsoft.com/en-us/library/windows/desktop/dd607324(v=vs.85).aspx
bool D3D12Shader::CompileSource(const ShaderDescriptor& shaderDesc)
{
    /* Get source code */
    std::string fileContent;
    const char* sourceCode      = nullptr;
    SIZE_T      sourceLength    = 0;

    if (shaderDesc.sourceType == ShaderSourceType::CodeFile)
    {
        fileContent     = ReadFileString(shaderDesc.source);
        sourceCode      = fileContent.c_str();
        sourceLength    = fileContent.size();
    }
    else
    {
        sourceCode      = shaderDesc.source;
        sourceLength    = shaderDesc.sourceSize;
    }

    /* Get parameter from union */
    const char* entry   = shaderDesc.entryPoint;
    const char* target  = (shaderDesc.profile != nullptr ? shaderDesc.profile : "");
    auto        flags   = shaderDesc.flags;

    /* Compile shader code */
    ComPtr<ID3DBlob> code;

    auto hr = D3DCompile(
        sourceCode,
        sourceLength,
        nullptr,                            // LPCSTR               pSourceName
        nullptr,                            // D3D_SHADER_MACRO*    pDefines
        nullptr,                            // ID3DInclude*         pInclude
        entry,                              // LPCSTR               pEntrypoint
        target,                             // LPCSTR               pTarget
        DXGetCompilerFlags(flags),          // UINT                 Flags1
        0,                                  // UINT                 Flags2 (recommended to always be 0)
        code.ReleaseAndGetAddressOf(),      // ID3DBlob**           ppCode
        errors_.ReleaseAndGetAddressOf()    // ID3DBlob**           ppErrorMsgs
    );

    /* Get byte code from blob */
    if (code)
        byteCode_ = DXGetBlobData(code.Get());

    /* Store if compilation was successful */
    return !FAILED(hr);
}
示例#28
0
HRESULT WINAPI D3DX11CompileFromMemory(const char *data, SIZE_T data_size, const char *filename,
        const D3D10_SHADER_MACRO *defines, ID3D10Include *include, const char *entry_point,
        const char *target, UINT sflags, UINT eflags, ID3DX11ThreadPump *pump, ID3D10Blob **shader,
        ID3D10Blob **error_messages, HRESULT *hresult)
{
    TRACE("data %s, data_size %lu, filename %s, defines %p, include %p, entry_point %s, target %s, "
            "sflags %#x, eflags %#x, pump %p, shader %p, error_messages %p, hresult %p.\n",
            debugstr_a(data), data_size, debugstr_a(filename), defines, include, debugstr_a(entry_point),
            debugstr_a(target), sflags, eflags, pump, shader, error_messages, hresult);

    if (pump)
        FIXME("Unimplemented ID3DX11ThreadPump handling.\n");

    return D3DCompile(data, data_size, filename, defines, include, entry_point, target,
            sflags, eflags, shader, error_messages);
}
示例#29
0
	static ID3DBlobPtr CompileShader(const char* shaderCode, size_t shaderLength, const char* shaderProfile) {
		ID3DBlobPtr blob = nullptr;
		ID3DBlobPtr errors = nullptr;
		HRESULT hr = D3DCompile(shaderCode, shaderLength, nullptr, nullptr, nullptr, "Main", shaderProfile, 0, 0, &blob, &errors);

		if (FAILED(hr)) {

			if (errors) {
				OutputDebugStringA((char*)errors->GetBufferPointer());
				errors->Release();
			}

			return nullptr;
		}

		return blob;
	}
示例#30
0
HRESULT ShaderCompilerClass::compileString(MutableString&& str
	, const char* entryPoint,
	const char* shaderTarget,
	ID3DBlob** output)
{
	HRESULT hr;
	DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS | 
		D3DCOMPILE_OPTIMIZATION_LEVEL3;
#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* errorMsg = nullptr;
	ID3DBlob* compiled = nullptr;
	std::string shaderstr = str.getMultiByteString();
	std::cout << shaderstr << std::endl;
	hr = D3DCompile(shaderstr.c_str(),
		shaderstr.length(),
		nullptr,
		nullptr,
		D3D_COMPILE_STANDARD_FILE_INCLUDE,
		entryPoint,
		shaderTarget,
		dwShaderFlags, 
		0,
		output,
		&errorMsg);
	
	if (errorMsg != nullptr)
	{
		char* errorText = new char[errorMsg->GetBufferSize()];
		memcpy(errorText, errorMsg->GetBufferPointer(), errorMsg->GetBufferSize());
		MessageBoxA(NULL,errorText,"Shader Error",MB_OK);
		errorMsg->Release();
		return E_FAIL;
	}
	if (FAILED(hr))
	{
		return hr;
	}
	return S_OK;
}