//[-------------------------------------------------------]
	//[ Public static methods                                 ]
	//[-------------------------------------------------------]
	ID3DBlob *ShaderLanguageHlsl::loadShader(const char *shaderModel, const char *shaderSource, const char *entryPoint)
	{
		// TODO(co) Cleanup
		ID3DBlob *d3dBlob;
	
		HRESULT hr = S_OK;

		DWORD shaderFlags = 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.
		shaderFlags |= D3DCOMPILE_DEBUG;
	#endif

		ID3DBlob *errorBlob;
		hr = D3DX11CompileFromMemory(shaderSource, strlen(shaderSource), nullptr, nullptr, nullptr, entryPoint ? entryPoint : "main", shaderModel, 
			shaderFlags, 0, nullptr, &d3dBlob, &errorBlob, nullptr );

		if (FAILED(hr))
		{
			if( errorBlob != nullptr )
				OutputDebugStringA( (char*)errorBlob->GetBufferPointer() );
			if( errorBlob ) errorBlob->Release();
			return nullptr;
		}
		if (nullptr != errorBlob ) errorBlob->Release();

		// Done
		return d3dBlob;
	}
Ejemplo n.º 2
0
void D3D10VertexShader::CreateVertexShaderBlob(ShaderBlob &blob, CTSTR lpShader, CTSTR lpFileName)
{
    D3D10System *d3d10Sys = static_cast<D3D10System*>(GS);
    LPCSTR lpVSType = d3d10Sys->bDisableCompatibilityMode ? "vs_4_0" : "vs_4_0_level_9_3";

    ComPtr<ID3D10Blob> errorMessages, shaderBlob;

    LPSTR lpAnsiShader = tstr_createUTF8(lpShader);
    LPSTR lpAnsiFileName = tstr_createUTF8(lpFileName);

    HRESULT err = D3DX11CompileFromMemory(lpAnsiShader, strlen(lpAnsiShader), lpAnsiFileName, NULL, NULL, "main", lpVSType, D3D10_SHADER_OPTIMIZATION_LEVEL3, 0, NULL, shaderBlob.Assign(), errorMessages.Assign(), NULL);

    Free(lpAnsiFileName);
    Free(lpAnsiShader);

    if (FAILED(err))
    {
        if (errorMessages)
        {
            if (errorMessages->GetBufferSize())
            {
                LPSTR lpErrors = (LPSTR)errorMessages->GetBufferPointer();
                Log(TEXT("Error compiling vertex shader '%s':\r\n\r\n%S\r\n"), lpFileName, lpErrors);
            }
        }

        CrashError(TEXT("Compilation of vertex shader '%s' failed, result = %08lX"), lpFileName, err);
        return;
    }

    blob.assign((char*)shaderBlob->GetBufferPointer(), (char*)shaderBlob->GetBufferPointer() + shaderBlob->GetBufferSize());
}
Ejemplo n.º 3
0
void GSDevice11::CompileShader(const char* source, size_t size, const char *fn, const char* entry, D3D11_SHADER_MACRO* macro, ID3D11ComputeShader** cs)
{
	HRESULT hr;

	vector<D3D11_SHADER_MACRO> m;

	PrepareShaderMacro(m, macro);

	CComPtr<ID3D11Blob> shader, error;

	hr = D3DX11CompileFromMemory(source, size, fn, &m[0], NULL, entry, m_shader.cs.c_str(), 0, 0, NULL, &shader, &error, NULL);

	if(error)
	{
		printf("%s\n", (const char*)error->GetBufferPointer());
	}

	if(FAILED(hr))
	{
		throw GSDXRecoverableError();
	}

	hr = m_dev->CreateComputeShader((void*)shader->GetBufferPointer(), shader->GetBufferSize(), NULL, cs);

	if(FAILED(hr))
	{
		throw GSDXRecoverableError();
	}
}
Ejemplo n.º 4
0
void GSDevice11::CompileShader(const char* source, size_t size, const char* fn, const char* entry, D3D11_SHADER_MACRO* macro, ID3D11GeometryShader** gs, D3D11_SO_DECLARATION_ENTRY* layout, int count)
{
	HRESULT hr;

	vector<D3D11_SHADER_MACRO> m;

	PrepareShaderMacro(m, macro);

	CComPtr<ID3D11Blob> shader, error;

	hr = D3DX11CompileFromMemory(source, size, fn, &m[0], NULL, entry, m_shader.gs.c_str(), 0, 0, NULL, &shader, &error, NULL);

	if(error)
	{
		printf("%s\n", (const char*)error->GetBufferPointer());
	}

	if(FAILED(hr))
	{
		throw GSDXRecoverableError();
	}

	hr = m_dev->CreateGeometryShaderWithStreamOutput((void*)shader->GetBufferPointer(), shader->GetBufferSize(), layout, count, NULL, 0, D3D11_SO_NO_RASTERIZED_STREAM, NULL, gs);

	if(FAILED(hr))
	{
		throw GSDXRecoverableError();
	}
}
Ejemplo n.º 5
0
bool scShader::CompileFromMemory( ID3DBlob** buffer, const char* shaderSrc )
{
	DWORD shaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;

	SIZE_T shaderSrcLen = strlen(shaderSrc);
	ID3DBlob* errorBuffer = 0;
	HRESULT result;

	result = D3DX11CompileFromMemory(shaderSrc, shaderSrcLen, "default", 0, 0, mEntry.c_str(), mShaderModel.c_str(),
		shaderFlags, 0, 0, buffer, &errorBuffer, 0);

	if( FAILED( result ) )
	{
		if( errorBuffer != 0 )
		{
			scErrMsg( ( char* )errorBuffer->GetBufferPointer( ) );
			errorBuffer->Release( );
		}
		return false;
	}

	if( errorBuffer != 0 )
	{
		scErrMsg( ( char* )errorBuffer->GetBufferPointer( ) );
		errorBuffer->Release( );
	}

	return true;
}
Ejemplo n.º 6
0
	ID3DBlob *ShaderLanguageHlsl::loadShader(const char *shaderModel, const char *shaderSource, const char *entryPoint) const
	{
		// TODO(co) Cleanup
		ID3DBlob *d3dBlob;
	
		HRESULT hr = S_OK;

		// 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 *errorBlob;
		hr = D3DX11CompileFromMemory(shaderSource, strlen(shaderSource), nullptr, nullptr, nullptr, entryPoint ? entryPoint : "main", shaderModel, 
			compileFlags, 0, nullptr, &d3dBlob, &errorBlob, nullptr );

		if (FAILED(hr))
		{
			if( errorBlob != nullptr )
				OutputDebugStringA( (char*)errorBlob->GetBufferPointer() );
			if( errorBlob ) errorBlob->Release();
			return nullptr;
		}
		if (nullptr != errorBlob ) errorBlob->Release();

		// Done
		return d3dBlob;
	}
Ejemplo n.º 7
0
        static void createVS( 
            unsigned int target,
            const ShaderScripts& ss, 
            nlEngineContext& cxt )
        {
            const ShaderScript& shaderScript = ss.vsScripts.scripts[target];
            const nlInt8* script   = shaderScript.script;
            const nlInt8* funcName = "main";
            const nlInt8* unitName = shaderScript.name;
            nlVertexShader& vs = cxt.vss[target];
            NL_ASSERT( !vs.shader_ );
            /**/
            ID3DBlob* pBlob = NULL;
            ID3DBlob* pErrorBlob = NULL;
            /* commonと連結 */
            const nlInt8* commonScript = ss.commonScripts.script;
            const nlUint32 scriptLen = nlStrlen( script ) + nlStrlen( commonScript );
            nlInt8* conbinedScript = (nlInt8*)nlMalloc( (scriptLen+1)*sizeof(nlInt8) );
            nlStrcat( conbinedScript, commonScript );
            nlStrcat( conbinedScript, script );

            //printf( conbinedScript );

#ifndef INTROMODE
            const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR;
            HRESULT hr = D3D10CompileShader( conbinedScript, nlStrlen(conbinedScript), unitName, shaderMacros, NULL, funcName, "vs_4_0", flag, &pBlob, &pErrorBlob );
            /* ロードが失敗したらエラーを出力した後に確実にロードが成功するシェーダをロードする */
            if(FAILED( hr ) )
            {
                /**/
                NL_ERR( ERR_005, (nlInt8*)pErrorBlob->GetBufferPointer() );
                /**/
                const nlInt8 script[] =
                {
                    "cbuffer Const0 : register(b0){ f4x4 world; }"
                    "cbuffer Const2 : register(b2){ f4x4 viewProj; }"
                    "float4 main( float4 in_pos:P, float4 in_normal:N, float4 in_col:C ):SV_POSITION"
                    "{ return mul( in_pos, mul(world,viewProj)); }"
                };
                HRESULT hr = D3D10CompileShader( script, sizeof(script)/sizeof(nlInt8), unitName, shaderMacros, NULL, "main", "vs_4_0", flag, &pBlob, &pErrorBlob );
            }
#else
            const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR | D3D10_SHADER_OPTIMIZATION_LEVEL3;
            HRESULT hr = D3DX11CompileFromMemory( conbinedScript, nlStrlen(conbinedScript), funcName, shaderMacros, NULL, funcName, "vs_4_0", flag, 0, NULL, &pBlob, &pErrorBlob, NULL );
            if(FAILED( hr ) )
            {
                MessageBoxA(NULL,(nlInt8*)pErrorBlob->GetBufferPointer(),"",MB_OK);
            }
#endif
            /**/
            nlFree( (void*)conbinedScript );
            /* create shader */
            NL_HR_VALID( cxt.d3dDevice->CreateVertexShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &vs.shader_ ) );
            /* create inputlayout */
            NL_HR_VALID( cxt.d3dDevice->CreateInputLayout(NLM_INPUT_ELEMENT, _countof(NLM_INPUT_ELEMENT), pBlob->GetBufferPointer(), pBlob->GetBufferSize(), &vs.inputLayout_  ) );
        }
Ejemplo n.º 8
0
// 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;
}
Ejemplo n.º 9
0
	HRESULT dx11render::compileShaderFromMem(LPCSTR pFileBuf, SIZE_T FileSize, LPCSTR szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut )
	{
		HRESULT hr = S_OK;

		DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;

		ID3DBlob* pErrorBlob;
		hr = D3DX11CompileFromMemory( pFileBuf, FileSize, szFileName, NULL, NULL, szEntryPoint, szShaderModel, 
			dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL );
		if( FAILED(hr) )
		{
			if( pErrorBlob ) pErrorBlob->Release();
			return hr;
		}
		if( pErrorBlob ) pErrorBlob->Release();

		return S_OK;
	}
// Use DX11 compile from file method to do all the heavy lifting
//-----------------------------------------------------------------------------
CPUTResult CPUTAssetLibraryDX11::CompileShaderFromMemory(
    const char     *pShaderSource,
    const cString  &shaderMain,
    const cString  &shaderProfile,
    ID3DBlob      **ppBlob
)
{
    CPUTResult result = CPUT_SUCCESS;

    char pShaderMainAsChar[128];
    char pShaderProfileAsChar[128];
    ASSERT( shaderMain.length()     < 128, _L("Shader main name '")    + shaderMain    + _L("' longer than 128 chars.") );
    ASSERT( shaderProfile.length()  < 128, _L("Shader profile name '") + shaderProfile + _L("' longer than 128 chars.") );
    size_t count;
    wcstombs_s( &count, pShaderMainAsChar,    shaderMain.c_str(),    128 );
    wcstombs_s( &count, pShaderProfileAsChar, shaderProfile.c_str(), 128 );

    // use DirectX to compile the shader file
    ID3DBlob *pErrorBlob = NULL;
    D3D10_SHADER_MACRO pShaderMacros[2] = { "_CPUT", "1", NULL, NULL }; // TODO: Support passed-in, and defined in .mtl file.  Perhaps under [Shader Defines], etc
    char *pShaderMainAsChars = ws2s(shaderMain.c_str());
    HRESULT hr = D3DX11CompileFromMemory(
        pShaderSource,     // shader as a string
        strlen( pShaderSource ), //
        pShaderMainAsChars, // Use entrypoint as file name
        pShaderMacros,        // macro define's
        NULL,                 // includes
        pShaderMainAsChar,    // main function name
        pShaderProfileAsChar, // shader profile/feature level
        0,                    // flags 1
        0,                    // flags 2
        NULL,                 // threaded load? (no for right now)
        ppBlob,               // blob data with compiled code
        &pErrorBlob,          // any compile errors stored here
        NULL
    );
    ASSERT( SUCCEEDED(hr), _L("Error compiling shader '") + shaderMain + _L("'.\n") + (pErrorBlob ? s2ws((char*)pErrorBlob->GetBufferPointer()) : _L("no error message") ) );
    if(pErrorBlob)
    {
        pErrorBlob->Release();
    }
    delete pShaderMainAsChars;
    return result;
}
Ejemplo n.º 11
0
//--------------------------------------------------------------------------------------
// Find and compile the specified shader
//--------------------------------------------------------------------------------------
HRESULT CompileShaderFromFile(TCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut)
{
	HRESULT hr = S_OK;
	size_t _size;
	void* data;

	data = pHGE->Resource_Load((char*)szFileName, &_size);
	if (!data) return NULL;

	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;
	hr = D3DX11CompileFromMemory(
		(LPCSTR)data,
		_size,
		NULL,
		NULL,
		NULL,
		szEntryPoint,
		szShaderModel,
		dwShaderFlags,
		0,
		NULL,
		ppBlobOut,
		&pErrorBlob,
		NULL);
	if (FAILED(hr))
	{
		if (pErrorBlob != NULL)
			OutputDebugStringA((char*)pErrorBlob->GetBufferPointer());
		SAFE_RELEASE(pErrorBlob);
		return hr;
	}
	SAFE_RELEASE(pErrorBlob);

	return S_OK;
}
PixelShader* PixelShader::FromBuffer(Buffer& buf, Renderer* pRender) {
	ID3D10Blob* pBuffer = NULL;
	ID3D10Blob* pError = NULL;

	HRESULT hr = D3DX11CompileFromMemory(
		(LPCSTR)buf.GetPtr(),		//[in]   LPCSTR pSrcData,
		buf.GetSize(),		//[in]   SIZE_T SrcDataLen,
		NULL,				//[in]   LPCSTR pFileName,
		NULL,				//[in]   const D3D10_SHADER_MACRO *pDefines,
		NULL,				//[in]   LPD3D10INCLUDE pInclude,
		_FunctionName,		//[in]   LPCSTR pFunctionName,
		_Profile,			//[in]   LPCSTR pProfile,
		D3D10_SHADER_DEBUG, //[in]   UINT Flags1,
		NULL,				//[in]   UINT Flags2,
		NULL,				//[in]   ID3DX10ThreadPump *pPump,
		&pBuffer,			//[out]  ID3D10Blob **ppShader,
		&pError,			//[out]  ID3D10Blob **ppErrorMsgs,
		NULL				//[out]  HRESULT *pHResult
		);

	if (pError != NULL) {
		//bError->GetBufferPointer()
		SafeRelease(pError);
		SafeRelease(pBuffer);
		return NULL;
	}
	if FAILED(hr) {
		SafeRelease(pBuffer);
		return NULL;
	}

	PixelShader* pPixelShader = new PixelShader(
		pBuffer->GetBufferPointer(), 
		pBuffer->GetBufferSize(),
		pRender
		);
	SafeRelease(pBuffer);
	return pPixelShader;
}
Ejemplo n.º 13
0
void GSDevice11::CompileShader(const char* source, size_t size, const char* fn, const char* entry, D3D11_SHADER_MACRO* macro, ID3D11VertexShader** vs, D3D11_INPUT_ELEMENT_DESC* layout, int count, ID3D11InputLayout** il)
{
	HRESULT hr;

	vector<D3D11_SHADER_MACRO> m;

	PrepareShaderMacro(m, macro);

	CComPtr<ID3D11Blob> shader, error;

	hr = D3DX11CompileFromMemory(source, size, fn, &m[0], NULL, entry, m_shader.vs.c_str(), 0, 0, NULL, &shader, &error, NULL);

	if(error)
	{
		printf("%s\n", (const char*)error->GetBufferPointer());
	}

	if(FAILED(hr))
	{
		throw GSDXRecoverableError();
	}

	hr = m_dev->CreateVertexShader((void*)shader->GetBufferPointer(), shader->GetBufferSize(), NULL, vs);

	if(FAILED(hr))
	{
		throw GSDXRecoverableError();
	}

	hr = m_dev->CreateInputLayout(layout, count, shader->GetBufferPointer(), shader->GetBufferSize(), il);

	if(FAILED(hr))
	{
		throw GSDXRecoverableError();
	}
}
Ejemplo n.º 14
0
HRESULT LineDraw_Hlsl_Shader::OnRestore(Scene *pScene)
{
	HRESULT hr = S_OK;

	SAFE_RELEASE(m_pEffect);
	SAFE_RELEASE(m_pcbDiffuseColor);
	SAFE_RELEASE(m_pVertexLayout11);
	SAFE_RELEASE(m_pcbChangePerFrame);
	SAFE_RELEASE(m_pcbRenderTargetSize);

	shared_ptr<D3DRenderer11> d3dRenderer11 = static_pointer_cast<D3DRenderer11>(pScene->GetRenderer());

	//========================================================
	// Set up the vertex shader and related constant buffers

	// Compile the vertex shader using the lowest possible profile for broadest feature level support
	ID3DBlob* pVertexShaderBuffer = NULL;

	std::string hlslFileName = "Effects\\LineDraw.hlsl";
	Resource resource(hlslFileName.c_str());
	shared_ptr<ResHandle> pResourceHandle = g_pApp->m_ResCache->GetHandle(&resource);  // this actually loads the HLSL file from the zip file

	// Compile effect from HLSL file into binary Blob in memory
	// The code in this function was found here - http://asawicki.info/news_1371_effects_in_directx_11.html

	ID3D10Blob *effectBlob = 0, *errorsBlob = 0;
	hr = D3DX11CompileFromMemory(
		pResourceHandle->Buffer(),                   // srcData
		pResourceHandle->Size(),                     // srcLen
		0, 0, 0, 0,                                  // fileName, pDefines, pInclude, functionName
		"fx_5_0", 0, 0, 0,                           // profile, flags1, flags2, pump
		&effectBlob, &errorsBlob, 0);                // shader, errorMsg, pResult
	assert(SUCCEEDED(hr) && effectBlob);
	if (errorsBlob) errorsBlob->Release();

	// Create D3DX11 effect from compiled binary memory block
	if (FAILED(D3DX11CreateEffectFromMemory(
		effectBlob->GetBufferPointer(), effectBlob->GetBufferSize(), 0, g_pDX11W->GetD3D11Device(), &m_pEffect)))
	{
			return hr;
	}

	effectBlob->Release();

	m_EffectTechnique = m_pEffect->GetTechniqueByIndex(0);
	AC_ASSERT(m_EffectTechnique && m_EffectTechnique->IsValid());

	m_EffectPass = m_EffectTechnique->GetPassByIndex(0);
	AC_ASSERT(m_EffectPass && m_EffectPass->IsValid());    

	D3DX11_PASS_SHADER_DESC effectVsDesc;
	m_EffectPass->GetVertexShaderDesc(&effectVsDesc);
	D3DX11_EFFECT_SHADER_DESC effectVsDesc2;
	effectVsDesc.pShaderVariable->GetShaderDesc(effectVsDesc.ShaderIndex, &effectVsDesc2);
	const void *vsCodePtr = effectVsDesc2.pBytecode;
	unsigned vsCodeLen = effectVsDesc2.BytecodeLength;

    if (SUCCEEDED (g_pDX11W->GetD3D11Device()->CreateInputLayout( D3D11VertexLayout_Position, ARRAYSIZE( D3D11VertexLayout_Position ), vsCodePtr, vsCodeLen, &m_pVertexLayout11)))
	{
		//DXUT_SetDebugName(m_pVertexLayout11, "Primary");

		// Setup constant buffers
		D3D11_BUFFER_DESC Desc;
		Desc.Usage = D3D11_USAGE_DYNAMIC;
		Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
		Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		Desc.MiscFlags = 0;

		Desc.ByteWidth = sizeof(Vec4);
		V_RETURN(g_pDX11W->GetD3D11Device()->CreateBuffer(&Desc, NULL, &m_pcbRenderTargetSize));
		//DXUT_SetDebugName( m_pcbRenderTargetSize, "Vec4_RenderTargetSize" );

		Desc.ByteWidth = sizeof(Mat4x4);
		V_RETURN(g_pDX11W->GetD3D11Device()->CreateBuffer(&Desc, NULL, &m_pcbChangePerFrame));
		//DXUT_SetDebugName( m_pcbChangePerFrame, "LineDrawerChangePerFrameBuffer" );

		Desc.ByteWidth = sizeof(Vec4);
		V_RETURN(g_pDX11W->GetD3D11Device()->CreateBuffer(&Desc, NULL, &m_pcbDiffuseColor));
		//DXUT_SetDebugName( m_pcbDiffuseColor, "DiffuseColor" );
	}

    SAFE_RELEASE(pVertexShaderBuffer);

    return S_OK;
}
Ejemplo n.º 15
0
bool ShaderClass::Init(ID3D11Device *pDevice, HWND hwnd)
{
	HRESULT res = S_OK;
	ID3D10Blob *pErr = NULL; // 存放编译shader的错误信息
	ID3D10Blob *pVertexShaderBuffer = NULL; // 编译出来的VS字节
	ID3D10Blob *pPixelShaderBuffer = NULL; // 编译出来的PS字节
	D3D11_INPUT_ELEMENT_DESC polygonLayout[3]; // 描述
	unsigned int numElem = sizeof(polygonLayout)/sizeof(polygonLayout[0]); // 一个点中的成员量
	D3D11_BUFFER_DESC matrixBufferDesc = { 0 };

	// 编译VS
	res = D3DX11CompileFromMemory((LPCSTR)s_lpShaderContentStr,
		sizeof(s_lpShaderContentStr),
		NULL, NULL, NULL,
		"ColorVertexShader",
		"vs_5_0",
		D3D10_SHADER_ENABLE_STRICTNESS,
		0, NULL, &pVertexShaderBuffer, &pErr, NULL);
	assert(SUCCEEDED(res));
	
	// 编译PS
	res = D3DX11CompileFromMemory((LPCSTR)s_lpShaderContentStr,
		sizeof(s_lpShaderContentStr),
		NULL, NULL, NULL,
		"ColorPixelShader",
		"ps_5_0",
		D3D10_SHADER_ENABLE_STRICTNESS,
		0, NULL, &pPixelShaderBuffer, &pErr, NULL);
	assert(SUCCEEDED(res));
	// 创建VS Shader
	res = pDevice->CreateVertexShader(pVertexShaderBuffer->GetBufferPointer(),
								pVertexShaderBuffer->GetBufferSize(),
								NULL, &m_pVertexShader);
	assert(SUCCEEDED(res));
		
	// 创建PS Shader
	res = pDevice->CreatePixelShader(pPixelShaderBuffer->GetBufferPointer(),
								pPixelShaderBuffer->GetBufferSize(),
								NULL, &m_pPixelShader);
	assert(SUCCEEDED(res));

	// 创建定点布局,在Input-Assemble 阶段使用
	polygonLayout[0].SemanticName = "POSITION";	// 语义
	polygonLayout[0].SemanticIndex = 0;	// 语义
	polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;	// 语义
	polygonLayout[0].InputSlot = 0;
	polygonLayout[0].AlignedByteOffset = 0;
	polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[0].InstanceDataStepRate = 0;

	polygonLayout[1].SemanticName = "COLOR";	// 语义
	polygonLayout[1].SemanticIndex = 0;	// 语义
	polygonLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT;	// 语义
	polygonLayout[1].InputSlot = 0;
	polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
	polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[1].InstanceDataStepRate = 0;

	polygonLayout[2].SemanticName = "TEXCOORD";	// 语义
	polygonLayout[2].SemanticIndex = 0;	// 语义
	polygonLayout[2].Format = DXGI_FORMAT_R32G32_FLOAT;	// 语义
	polygonLayout[2].InputSlot = 0;
	polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
	polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[2].InstanceDataStepRate = 0;
	
	res = pDevice->CreateInputLayout(polygonLayout,
		numElem,
		pVertexShaderBuffer->GetBufferPointer(),
		pVertexShaderBuffer->GetBufferSize(),
		&m_pLayout);
	assert(SUCCEEDED(res));

	pVertexShaderBuffer->Release();
	pVertexShaderBuffer = NULL;
	pPixelShaderBuffer->Release();
	pPixelShaderBuffer = NULL;
	
	// 创建Content 矩阵Buffer	
	matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
	matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	matrixBufferDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
	matrixBufferDesc.MiscFlags = 0;
	matrixBufferDesc.StructureByteStride = 0;
	
	res = pDevice->CreateBuffer(&matrixBufferDesc, 
								NULL, 
								&m_pConstantBuffer);
	assert(SUCCEEDED(res));
	
	// 创建纹理采样描述
	D3D11_SAMPLER_DESC samplerDesc;
	samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;	// 线性插值方式采样
	// 地址模式
	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;
	// 创建纹理采样状态.
	res = pDevice->CreateSamplerState(&samplerDesc, &m_pSampleState);
	assert(SUCCEEDED(res));
	if (FAILED(res))
	{
		return false;
	}
	return true;
}
Ejemplo n.º 16
0
void hwRendererHelperDX::initializeDrawTextureEffect()
{
	if( fDXContext == NULL )
		return;

	// Create the effect
	if( fDrawTextureEffect == NULL )
	{
		const char* simpleShaderCode =	"Texture2D myTexture; \r\n" \

										"SamplerState SamplerLinearWrap \r\n" \
										"{ \r\n" \
										"	Filter = MIN_MAG_MIP_LINEAR; \r\n" \
										"	AddressU = Wrap; \r\n" \
										"	AddressV = Wrap; \r\n" \
										"}; \r\n" \

										"struct APP_TO_VS \r\n" \
										"{ \r\n" \
										"	float3 Pos : POSITION; \r\n" \
										"	float2 TextCoord : TEXTCOORD; \r\n" \
										"}; \r\n" \

										"struct VS_TO_PS \r\n" \
										"{ \r\n" \
										"	float4 Pos : SV_Position; \r\n" \
										"	float2 TextCoord : TEXTCOORD; \r\n" \
										"}; \r\n" \

										"VS_TO_PS BasicVS(APP_TO_VS IN) \r\n" \
										"{ \r\n" \
										"	VS_TO_PS OUT; \r\n" \
										"	OUT.Pos = float4(IN.Pos, 1.0f); \r\n" \
										"	OUT.TextCoord = IN.TextCoord; \r\n" \
										"	return OUT; \r\n" \
										"} \r\n" \

										"float4 BasicPS(VS_TO_PS IN) : SV_Target \r\n" \
										"{ \r\n" \
										"	float4 color = myTexture.Sample(SamplerLinearWrap, IN.TextCoord); \r\n" \
										"	return color; \r\n" \
										"} \r\n" \

										"technique10 simple \r\n" \
										"{ \r\n" \
										"	pass p0 \r\n" \
										"	{ \r\n" \
										"		SetVertexShader( CompileShader( vs_4_0, BasicVS() ) ); \r\n" \
										"		SetGeometryShader( NULL ); \r\n" \
										"		SetPixelShader( CompileShader( ps_4_0, BasicPS() ) ); \r\n" \
										"	} \r\n" \
										"} \r\n";
		const unsigned int simpleShaderLength = (unsigned int)strlen(simpleShaderCode);

		const D3D10_SHADER_MACRO macros[] = { { "DIRECT3D_VERSION", "0xb00" }, { NULL, NULL } };

#ifdef _DEBUG
		const unsigned int flags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#else
		const unsigned int flags = 0;
#endif

		ID3DBlob *shader = NULL;
		ID3DBlob *error = NULL;
#if _MSC_VER >= 1700
		HRESULT hr = D3DCompile((char*)simpleShaderCode, simpleShaderLength, NULL, macros, NULL, "", "fx_5_0", flags, 0, &shader, &error);
#else
		HRESULT hr = D3DX11CompileFromMemory((char*)simpleShaderCode, simpleShaderLength, NULL, macros, NULL, "", "fx_5_0", flags, 0, NULL, &shader, &error, NULL);
#endif
		if( SUCCEEDED( hr ) && shader != NULL )
		{
			hr = D3DX11CreateEffectFromMemory(shader->GetBufferPointer(), shader->GetBufferSize(), 0, fDXDevice, &fDrawTextureEffect);
			if( SUCCEEDED( hr ) && fDrawTextureEffect != NULL )
			{
				ID3DX11EffectVariable* textureVariable = fDrawTextureEffect->GetVariableByName( "myTexture" );
				if( textureVariable != NULL )
				{
					fDrawTextureShaderVariable = textureVariable->AsShaderResource();
				}

				ID3DX11EffectTechnique* technique = fDrawTextureEffect->GetTechniqueByIndex(0);
				if( technique )
				{
					fDrawTexturePass = technique->GetPassByIndex(0);
				}
			}
		}
		else
		{
			MString errorStr( (error && error->GetBufferSize() > 0) ? (char*) error->GetBufferPointer() : (char*) NULL );

			MGlobal::displayWarning( hwApiTextureTestStrings::getString( hwApiTextureTestStrings::kDxErrorEffect, errorStr ) );
		}
		
		if( shader != NULL )
		{
			shader->Release();
		}
	}
	
	// Create the vertex buffers and the input layout
	if( fDrawTextureInputLayout == NULL && fDrawTexturePass != NULL )
	{
		fDrawTextureVertexBuffersCount = 0;

		D3D11_INPUT_ELEMENT_DESC inputDesc[MAX_VERTEX_BUFFERS];

		HRESULT hr;

		// Create the position stream
		{
			const float position[] = {	-1, -1, 0,		// bottom-left
										-1,  1, 0,		// top-left
										 1,  1, 0,		// top-right
										 1, -1, 0 };	// bottom-right

			const D3D11_BUFFER_DESC bufDesc = { sizeof(position), D3D11_USAGE_IMMUTABLE, D3D11_BIND_VERTEX_BUFFER, 0, 0, 0 };
			const D3D11_SUBRESOURCE_DATA bufData = { position, 0, 0 };
			ID3D11Buffer *buffer = NULL;
			hr = fDXDevice->CreateBuffer(&bufDesc, &bufData, &buffer);
			if( SUCCEEDED( hr ) && buffer != NULL )
			{
				inputDesc[fDrawTextureVertexBuffersCount].SemanticName = "POSITION";
				inputDesc[fDrawTextureVertexBuffersCount].SemanticIndex = 0;
				inputDesc[fDrawTextureVertexBuffersCount].Format = DXGI_FORMAT_R32G32B32_FLOAT;
				inputDesc[fDrawTextureVertexBuffersCount].InputSlot = fDrawTextureVertexBuffersCount;
				inputDesc[fDrawTextureVertexBuffersCount].AlignedByteOffset = 0;
				inputDesc[fDrawTextureVertexBuffersCount].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
				inputDesc[fDrawTextureVertexBuffersCount].InstanceDataStepRate = 0;

				fDrawTextureVertexBuffers[fDrawTextureVertexBuffersCount] = buffer;
				fDrawTextureVertexBuffersStrides[fDrawTextureVertexBuffersCount] = 3 * sizeof(float);
				fDrawTextureVertexBuffersOffsets[fDrawTextureVertexBuffersCount] = 0;

				++fDrawTextureVertexBuffersCount;
			}
		}

		// Create the texture coord stream
		if( SUCCEEDED( hr ) )
		{
			const float textCoord[] = {	0, 1,		// bottom-left
										0, 0,		// top-left
										1, 0,		// top-right
										1, 1 };		// bottom-right

			const D3D11_BUFFER_DESC bufDesc = { sizeof(textCoord), D3D11_USAGE_IMMUTABLE, D3D11_BIND_VERTEX_BUFFER, 0, 0, 0 };
			const D3D11_SUBRESOURCE_DATA bufData = { textCoord, 0, 0 };
			ID3D11Buffer *buffer = NULL;
			hr = fDXDevice->CreateBuffer(&bufDesc, &bufData, &buffer);
			if( SUCCEEDED( hr ) && buffer != NULL )
			{
				inputDesc[fDrawTextureVertexBuffersCount].SemanticName = "TEXTCOORD";
				inputDesc[fDrawTextureVertexBuffersCount].SemanticIndex = 0;
				inputDesc[fDrawTextureVertexBuffersCount].Format = DXGI_FORMAT_R32G32_FLOAT;
				inputDesc[fDrawTextureVertexBuffersCount].InputSlot = fDrawTextureVertexBuffersCount;
				inputDesc[fDrawTextureVertexBuffersCount].AlignedByteOffset = 0;
				inputDesc[fDrawTextureVertexBuffersCount].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
				inputDesc[fDrawTextureVertexBuffersCount].InstanceDataStepRate = 0;

				fDrawTextureVertexBuffers[fDrawTextureVertexBuffersCount] = buffer;
				fDrawTextureVertexBuffersStrides[fDrawTextureVertexBuffersCount] = 2 * sizeof(float);
				fDrawTextureVertexBuffersOffsets[fDrawTextureVertexBuffersCount] = 0;

				++fDrawTextureVertexBuffersCount;
			}
		}

		if( SUCCEEDED( hr ) )
		{
			D3DX11_PASS_DESC descPass;
			fDrawTexturePass->GetDesc(&descPass);

			hr = fDXDevice->CreateInputLayout(inputDesc, fDrawTextureVertexBuffersCount, descPass.pIAInputSignature, descPass.IAInputSignatureSize, &fDrawTextureInputLayout);
			if( FAILED( hr ) )
			{
				MGlobal::displayWarning( hwApiTextureTestStrings::getString( hwApiTextureTestStrings::kDxErrorInputLayout ) );
			}
		}
	}
	
	// Create the index buffer
	if( fDrawTextureIndexBuffer == NULL && fDrawTextureVertexBuffersCount > 0  && fDrawTextureInputLayout != NULL )
	{
		const unsigned int indices[] = { 0, 1, 3, 3, 2, 1 };
		fDrawTextureIndexBufferCount = _countof(indices);

		const D3D11_BUFFER_DESC bufDesc = { sizeof(indices), D3D11_USAGE_IMMUTABLE, D3D11_BIND_INDEX_BUFFER, 0, 0, 0 };
		const D3D11_SUBRESOURCE_DATA bufData = { indices, 0, 0 };
		fDXDevice->CreateBuffer(&bufDesc, &bufData, &fDrawTextureIndexBuffer);
	}
}
Ejemplo n.º 17
0
bool RectClass::Initialize(ID3D11Device* pDevice, int rectRidus, float z)
{
	float radius = rectRidus;
	float negRadius = -1 * radius;
	RectClass::VertexType s_RectClassVertexs[] = {
			{ D3DXVECTOR3(negRadius, radius, z), D3DXVECTOR4(0.0f, 0.0f, 0.0f, 0.0f), D3DXVECTOR2(0.0f, 0.0f) },
			{ D3DXVECTOR3(radius, radius, z), D3DXVECTOR4(0.0f, 0.0f, 0.0f, 0.0f), D3DXVECTOR2(1.0f, 0.0f) },
			{ D3DXVECTOR3(negRadius, negRadius, z), D3DXVECTOR4(0.0f, 0.0f, 0.0f, 0.0f), D3DXVECTOR2(0.0f, 1.0f) },
			{ D3DXVECTOR3(radius, negRadius, z), D3DXVECTOR4(0.0f, 0.0f, 0.0f, 0.0f), D3DXVECTOR2(1.0f, 1.0f) },
	};
	int s_RectClassIndexs[] = {0,1,2,2,1,3};

	D3D11_BUFFER_DESC vertexBufferDesc;	// 顶点缓存的描述
	D3D11_BUFFER_DESC indexBufferDesc; // 顶点索引缓存的描述
	D3D11_SUBRESOURCE_DATA vertexData; // 顶点需要访问的资源
	D3D11_SUBRESOURCE_DATA indexData; // 顶点索引需要访问的资源
	HRESULT res = S_OK;

	// 设置顶点缓冲描述
	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.ByteWidth = sizeof(s_RectClassVertexs);
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; // 将资源绑定到顶点,供管线访问
	vertexBufferDesc.CPUAccessFlags = 0;
	vertexBufferDesc.MiscFlags = 0;
	vertexBufferDesc.StructureByteStride = 0;

	// 指向保存顶点数据的临时缓冲.
	vertexData.pSysMem = s_RectClassVertexs; // 将三角形的顶点数据放入顶点缓冲中
	vertexData.SysMemPitch = 0;
	vertexData.SysMemSlicePitch = 0;

	// 创建顶点缓冲.
	res = pDevice->CreateBuffer(&vertexBufferDesc, &vertexData, &m_pVertexBuffer);
	assert(SUCCEEDED(res));

	// 设置顶点索引缓冲描述
	indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	indexBufferDesc.ByteWidth = sizeof(s_RectClassIndexs);
	indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; // 将资源绑定到顶点索引,供管线访问
	indexBufferDesc.CPUAccessFlags = 0;
	indexBufferDesc.MiscFlags = 0;
	indexBufferDesc.StructureByteStride = 0;

	// 指向保存顶点数据的临时缓冲.
	indexData.pSysMem = s_RectClassIndexs; // 将三角形的顶点数据放入顶点缓冲中
	indexData.SysMemPitch = 0;
	indexData.SysMemSlicePitch = 0;

	// 创建顶点缓冲.
	res = pDevice->CreateBuffer(&indexBufferDesc, &indexData, &m_pIndexBuffer);
	assert(SUCCEEDED(res));

	// 初始化Shader
	ID3D10Blob *pErr = NULL; // 存放编译shader的错误信息
	ID3D10Blob *pVertexShaderBuffer = NULL; // 编译出来的VS字节
	ID3D10Blob *pPixelShaderBuffer = NULL; // 编译出来的PS字节
	D3D11_INPUT_ELEMENT_DESC polygonLayout[3]; // 描述
	unsigned int numElem = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // 一个点中的成员量
	D3D11_BUFFER_DESC matrixBufferDesc = { 0 };

	// 编译VS
	res = D3DX11CompileFromMemory((LPCSTR)s_RectShaderStr,
		sizeof(s_RectShaderStr),
		NULL, NULL, NULL,
		"ColorVertexShader",
		"vs_5_0",
		D3D10_SHADER_ENABLE_STRICTNESS,
		0, NULL, &pVertexShaderBuffer, &pErr, NULL);
	assert(SUCCEEDED(res));

	// 编译PS
	res = D3DX11CompileFromMemory((LPCSTR)s_RectShaderStr,
		sizeof(s_RectShaderStr),
		NULL, NULL, NULL,
		"ColorPixelShader",
		"ps_5_0",
		D3D10_SHADER_ENABLE_STRICTNESS,
		0, NULL, &pPixelShaderBuffer, &pErr, NULL);
	assert(SUCCEEDED(res));
	// 创建VS Shader
	res = pDevice->CreateVertexShader(pVertexShaderBuffer->GetBufferPointer(),
		pVertexShaderBuffer->GetBufferSize(),
		NULL, &m_pVertexShader);
	assert(SUCCEEDED(res));

	// 创建PS Shader
	res = pDevice->CreatePixelShader(pPixelShaderBuffer->GetBufferPointer(),
		pPixelShaderBuffer->GetBufferSize(),
		NULL, &m_pPixelShader);
	assert(SUCCEEDED(res));

	// 创建定点布局,在Input-Assemble 阶段使用
	polygonLayout[0].SemanticName = "POSITION";	// 语义
	polygonLayout[0].SemanticIndex = 0;	// 语义
	polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;	// 语义
	polygonLayout[0].InputSlot = 0;
	polygonLayout[0].AlignedByteOffset = 0;
	polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[0].InstanceDataStepRate = 0;

	polygonLayout[1].SemanticName = "COLOR";	// 语义
	polygonLayout[1].SemanticIndex = 0;	// 语义
	polygonLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT;	// 语义
	polygonLayout[1].InputSlot = 0;
	polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
	polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[1].InstanceDataStepRate = 0;

	polygonLayout[2].SemanticName = "TEXCOORD";	// 语义
	polygonLayout[2].SemanticIndex = 0;	// 语义
	polygonLayout[2].Format = DXGI_FORMAT_R32G32_FLOAT;	// 语义
	polygonLayout[2].InputSlot = 0;
	polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
	polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[2].InstanceDataStepRate = 0;

	res = pDevice->CreateInputLayout(polygonLayout,
		numElem,
		pVertexShaderBuffer->GetBufferPointer(),
		pVertexShaderBuffer->GetBufferSize(),
		&m_pLayout);
	assert(SUCCEEDED(res));

	pVertexShaderBuffer->Release();
	pVertexShaderBuffer = NULL;
	pPixelShaderBuffer->Release();
	pPixelShaderBuffer = NULL;

	// 创建Content 矩阵Buffer	
	matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
	matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	matrixBufferDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
	matrixBufferDesc.MiscFlags = 0;
	matrixBufferDesc.StructureByteStride = 0;

	res = pDevice->CreateBuffer(&matrixBufferDesc,
		NULL,
		&m_pContantBuffer);
	assert(SUCCEEDED(res));

	return true;
}