示例#1
0
bool SphereVS::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFileName, CHAR* entryFuncName)
{
	HRESULT result;
	ID3D10Blob* errorMessage;
	ID3D10Blob* vertexShaderBuffer;
	ID3D10Blob* pixelShaderBuffer;
	unsigned int numElements;



	// Initialize the pointers this function will use to null.
	errorMessage = 0;
	vertexShaderBuffer = 0;

	// Compile the vertex shader code.
	bool xresult = D3DXUtils::CompileShaderFromFile(COMPILE_TYPE_VS, hwnd, vsFileName, entryFuncName, &vertexShaderBuffer, &errorMessage);
	if (!xresult)
		return false;

	// Create the vertex shader from the buffer.
	result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), 
		vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader);
	if(FAILED(result))
	{
		return false;
	}

	D3D11_INPUT_ELEMENT_DESC solidColorLayout[] =
	{
		{ "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 }
	};

	unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout );

	// Create the vertex input layout.
	result = device->CreateInputLayout(solidColorLayout, totalLayoutElements, vertexShaderBuffer->GetBufferPointer(), 
		vertexShaderBuffer->GetBufferSize(), &m_layout);
	if(FAILED(result))
	{
		return false;
	}

	// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
	vertexShaderBuffer->Release();
	vertexShaderBuffer = 0;



	return true;
}
示例#2
0
bool D3D11Shader::loadHLSLBlob( ID3D10Blob** blob, char* filename, char* fcnName, const char* shaderModel )
{
  ID3D10Blob *errorblob;

  if( !DX_CHECK( D3DX11CompileFromFileA(
    filename,
    NULL, NULL,
    fcnName,
    shaderModel, // usually "ps_5_0" or "vs_5_0"
    D3D10_SHADER_ENABLE_STRICTNESS, NULL,
    NULL,
    blob, &errorblob,
    NULL ), "compiling fx" ) )
  {
    if( !errorblob )
    {
      error( "%s shader file not found!", filename ) ;
      return false ;
    }
    else
    {
      int size = errorblob->GetBufferSize() ;
      char* errstr = (char*)malloc( size+1 ) ;
      strncpy( errstr, (char*)errorblob->GetBufferPointer(), size ) ;
      errstr[ size ] = 0 ;
      error( errstr );
      free( errstr ) ;
    }
    SAFE_RELEASE( errorblob );
    bail( "Couldn't compile your fx file", true ) ; // (exits)
    return false ;
  }
    
  return true ; // successful load  
}
示例#3
0
void BoxApp::BuildFX()
{
	DWORD shaderFlags = 0;
#if defined( DEBUG ) || defined( _DEBUG )
    shaderFlags |= D3D10_SHADER_DEBUG;
	shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
#endif
 
	ID3D10Blob* compiledShader = 0;
	ID3D10Blob* compilationMsgs = 0;
	HRESULT hr = D3DX11CompileFromFile(L"FX/color.fx", 0, 0, 0, "fx_5_0", shaderFlags, 
		0, 0, &compiledShader, &compilationMsgs, 0);

	// compilationMsgs can store errors or warnings.
	if( compilationMsgs != 0 )
	{
		MessageBoxA(0, (char*)compilationMsgs->GetBufferPointer(), 0, 0);
		ReleaseCOM(compilationMsgs);
	}
	
	// Even if there are no compilationMsgs, check to make sure there were no other errors.
	if(FAILED(hr))
	{
		// DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX11CompileFromFile", true);
	}

	HR(D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), 
		0, md3dDevice, &mFX));

	// Done with compiled shader.
	ReleaseCOM(compiledShader);

	mTech    = mFX->GetTechniqueByName("ColorTech");
	mfxWorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix();
}
示例#4
0
void BaseShader::loadGeometryShader(WCHAR* filename)
{
	HRESULT result;
	ID3D10Blob* errorMessage;
	ID3D10Blob* geometryShaderBuffer;

	// Compile the domain shader code.
	result = D3DCompileFromFile(filename, NULL, NULL, "main", "gs_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &geometryShaderBuffer, &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 shader file itself.
		else
		{
			MessageBox(m_hwnd, filename, L"Missing Shader File", MB_OK);
		}

		exit(0);
	}

	// Create the domain shader from the buffer.
	m_device->CreateGeometryShader(geometryShaderBuffer->GetBufferPointer(), geometryShaderBuffer->GetBufferSize(), NULL, &m_geometryShader);

	geometryShaderBuffer->Release();
	geometryShaderBuffer = 0;
}
ID3DX11Effect* Assignment5::InitialiseShader(const std::wstring& a_FilePath)
{
    DWORD shaderFlags = 0;
#if defined( DEBUG ) || defined( _DEBUG )
    shaderFlags |= D3D10_SHADER_DEBUG;
    shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
#endif

    ID3D10Blob* compiledShader = 0;
    ID3D10Blob* compilationMsgs = 0;
    HRESULT hr = D3DX11CompileFromFile(std::wstring(L"FX/" + a_FilePath).c_str(),
        0, 0, 0, "fx_5_0", shaderFlags,
        0, 0, &compiledShader, &compilationMsgs, 0);

    // compilationMsgs can store errors or warnings.
    if(compilationMsgs != 0)
    {
        MessageBoxA(0, (char*)compilationMsgs->GetBufferPointer(), 0, 0);
        ReleaseCOM(compilationMsgs);
    }

    // Even if there are no compilationMsgs, check to make sure there were no other errors.
    if(FAILED(hr))
    {
        DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX11CompileFromFile", true);
    }
    ID3DX11Effect* shader;
    HR(D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(),
        0, md3dDevice, &shader));

    // Done with compiled shader.
    ReleaseCOM(compiledShader);
    return shader;
}
BOOL	IRenderer::mFunction_Init_CreateEffectFromFile(NFilePath fxPath)
{
    HRESULT hr = S_OK;

    DWORD shaderFlags = 0;
#if defined(DEBUG)||defined(_DEBUG)
    shaderFlags |= D3D10_SHADER_DEBUG;
    shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
#endif
    ID3D10Blob*	compiledFX;
    ID3D10Blob*	compilationMsg;

    //编译fx文件
    hr = D3DX11CompileFromFileA(
             fxPath.c_str(),0,0,0,"fx_5_0",
             shaderFlags,0,0,&compiledFX,
             &compilationMsg,0);

    //看看编译有无错误信息
    //To see if there is compiling error
    if (compilationMsg != 0)
    {
        DEBUG_MSG1("Noise Renderer : Shader Compilation Failed !!");
        ReleaseCOM(compilationMsg);
    }


    hr = D3DX11CreateEffectFromMemory(
             compiledFX->GetBufferPointer(),
             compiledFX->GetBufferSize(),
             0,g_pd3dDevice11,&m_pFX);
    HR_DEBUG(hr,"Create Basic Effect Fail!");

    return TRUE;
};
示例#7
0
void CDX10Core::InitBasicEffects()
{
	ID3D10Blob*	pBlobErrors = NULL;
	HRESULT hr = D3DX10CreateEffectFromFile( _T("effects/BasicShaders.fx"),
		NULL, NULL,
		"fx_4_0",
		D3D10_SHADER_ENABLE_STRICTNESS,
		0, m_pDevice,
		NULL, NULL,
		&m_pBasicEffect,
		&pBlobErrors, NULL);
	if ( FAILED ( hr ) )
	{
		UINT size = pBlobErrors->GetBufferSize() + 1;
		TCHAR *szError = new TCHAR[size];
#ifdef UNICODE
		char * pErrorString = (char *)pBlobErrors->GetBufferPointer();		
		mbstowcs(szError, pErrorString, size);
		szError[size - 1] = 0;
#else
		_tcscpy_s(szError, size, pBlobErrors->GetBufferPointer());
#endif
		MessageBox(m_hWnd, szError, _T("DirectX 10 shader Error"), MB_OK );
		SAFE_DX_RELEASE(pBlobErrors);
		delete[] szError;
		exit(1);
	}
	SAFE_DX_RELEASE(pBlobErrors);

	m_pBasicTechnique = m_pBasicEffect->GetTechniqueByName("BasicRender");
	
	m_pViewMatrixEffectVariable			= m_pBasicEffect->GetVariableByName( "View" )->AsMatrix();
	m_pProjectionMatrixEffectVariable	= m_pBasicEffect->GetVariableByName( "Projection" )->AsMatrix();
	m_pWorldMatrixEffectVariable		= m_pBasicEffect->GetVariableByName( "World" )->AsMatrix();
}
示例#8
0
// 载入Pixel Shader
// file = HLSL shader file
// entry = pixel shader entry point
// profile = shader version
ID3D10PixelShader * GutLoadPixelShaderDX10_HLSL(const char *filename, const char *entry, const char *profile)
{
    DWORD dwShaderFlags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY;

#if defined( DEBUG ) || defined( _DEBUG )
	dwShaderFlags |= D3D10_SHADER_DEBUG;
#endif

	ID3D10PixelShader *pShader = NULL;
    ID3D10Blob	*pBuf = NULL;
	ID3D10Blob	*pErrorMessage = NULL;

	char filename_fullpath[128];
	sprintf(filename_fullpath, "%s%s", GutGetShaderPath(), filename);

	if ( D3D_OK==D3DX10CompileFromFile(filename_fullpath, g_pHLSL_Macros, NULL, entry, profile, dwShaderFlags, NULL, NULL, &pBuf, &pErrorMessage, NULL) )
	{
		g_pd3dDevice->CreatePixelShader( (DWORD*) pBuf->GetBufferPointer(), pBuf->GetBufferSize(), &pShader);
	}
	else
	{
		if ( pErrorMessage )
		{
			printf("Failed to compile %s : %s\n", pErrorMessage->GetBufferPointer());
		}
	}

	SAFE_RELEASE(pErrorMessage);
	SAFE_RELEASE(pBuf);
	
	return pShader;
}
示例#9
0
文件: Effect.cpp 项目: panmar/pg2
    void Effect::CreateDXEffectFromFile(const string& filepath) {
        ID3D11Device* device = GraphicsManager::Get()->GetDevice();

        U32 flags = 0;

        #ifdef _DEBUG
            flags |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION | D3DCOMPILE_WARNINGS_ARE_ERRORS;
        #endif

        ID3D10Blob* effectBlob = nullptr;
        ID3D10Blob* error = nullptr;

        try {

            HRESULT hr;
            while(FAILED(D3DX11CompileFromFile(filepath.c_str(), nullptr, nullptr, nullptr, "fx_5_0", flags, 0, nullptr, &effectBlob, &error, &hr))) {
                if (error) {
                    U8* begin = (U8*) error->GetBufferPointer();
                    U8* end = begin + error->GetBufferSize();
                    string message(begin, end);
                    Logger::Get()->Log(message, Logger::Error);

                    #ifdef _DEBUG
                        I32 retVal = Logger::Get()->ShowMessage("Effect compilation error", message.c_str());
                        if (retVal != IDRETRY) {
                            throw DXException(hr, message.c_str());
                        }
                    #else
                        throw Exception("DirectX: Cannot compile effect file '" + filepath + "'. Check log file for more details.");
                    #endif
                }
            }

            _ASSERT(effectBlob);
            DXCall(D3DX11CreateEffectFromMemory(effectBlob->GetBufferPointer(), effectBlob->GetBufferSize(), 0, device, &dx11Effect));
            ReleaseCOM(effectBlob);
            ReleaseCOM(error);

        } catch (const Exception& exception) {
            ReleaseCOM(effectBlob);
            ReleaseCOM(error);
            throw exception;
        } catch (...) {
            _ASSERT(false);
        }
    }
示例#10
0
bool ShaderClass::createVertexShaderAndInputLayout(ID3D11Device* pDevice, WCHAR* fileName, CHAR* EntryPoint, D3D11_INPUT_ELEMENT_DESC *vertexDesc, int numElements, ID3D11VertexShader** ppVshader, ID3D11InputLayout** ppLayout)
{
	HRESULT hr;
	bool result;
	// Initialize the vertex shader
	ID3D10Blob* vertexShaderBuffer;
	ID3D10Blob* errorMessages;

	hr = D3DCompileFromFile(
		fileName,
		NULL,
		NULL,
		EntryPoint,
		"vs_5_0",
		0,
		0,
		&vertexShaderBuffer,
		&errorMessages);

	if (FAILED(hr))
	{
		// If the shader failed to compile it should have writen something to the error message.
		if (errorMessages)
		{
			OutputShaderErrorMessage(errorMessages, fileName);
			return false;
		}
		// If there was nothing in the error message then it simply could not find the shader file itself.
		else
		{
			MessageBox(0, fileName, L"Missing Shader File", MB_OK);
			return false;
		}
	}

	// Create the vertex shader from the buffer.
	hr = pDevice->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, ppVshader);
	if (FAILED(hr))
	{
		MessageBox(0, L"Failed to create vertex shader", 0, MB_OK);
		return false;
	}

	if (FAILED(hr))
	{
		MessageBox(0, L"Could not create VertexShader.", 0, 0);
		return false;
	}

	result = createInputLayout(pDevice, vertexDesc, vertexShaderBuffer, numElements, ppLayout);
	if (!result)
	{
		return false;
	}

	vertexShaderBuffer->Release();
	return true;
}
示例#11
0
Effect::Effect(ID3D11Device * pDevice, const std::wstring &fileName)
	:m_pShader(nullptr)
{

#if DEBUG_SHADER
	DWORD shaderFlags = 0;
	//这些一般在shader编译器中设置的选项
#if defined(DEBUG) || defined(_DEBUG)
	shaderFlags |= D3D10_SHADER_DEBUG;
	shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
#endif


	ID3D10Blob * compiledShader = nullptr;
	ID3D10Blob * compilationMsgs = nullptr;

	HRESULT hr = D3DX11CompileFromFile(fileName.c_str(), nullptr, nullptr, nullptr, "fx_5_0", shaderFlags,
		0, nullptr, &compiledShader, &compilationMsgs, nullptr);

	//这些信息是编译错误信息
	if (compilationMsgs != 0)
	{
		MessageBoxA(0, (char *)compilationMsgs->GetBufferPointer(), 0, 0);
		ReleaseCOM(compilationMsgs);
	}

	//Even if there are no compliation msgs,check to make sure there no other errors.
	if (FAILED(hr))
	{
		DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX11CompileFromFile", true);
	}

	HR(D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(),
		compiledShader->GetBufferSize(), 0, pDevice, &m_pShader));

	//Done with compiled shader
	ReleaseCOM(compiledShader);

	/************************************************************************/

#else
	std::ifstream fin(fileName, std::ios::binary);

	fin.seekg(0, std::ios_base::end);//定位至文件末尾,以求长度
	int size = (int)fin.tellg();
	fin.seekg(0, std::ios_base::beg);
	std::vector<char> compiledShaderFile(size);

	fin.read(&compiledShaderFile[0], size);
	fin.close();

	HR(D3DX11CreateEffectFromMemory(&compiledShaderFile[0],
		size, 0, pDevice, &m_pShader));


#endif
}
示例#12
0
bool BlurShaderH::Initalize(ID3D11Device* pd3dDevice)
{
	blurSizeH = (1.0f/400);

	ID3D10Blob*	pBlob = NULL;
	ID3D10Blob*	pErrorBlob = NULL;

	DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;

	#if defined( DEBUG ) || defined( _DEBUG )
	// Il settaggio di questo flag permette di eseguire il debug diretto dello shader, senza
	// impattare in modo marcato sulle performance.
	dwShaderFlags |= D3DCOMPILE_DEBUG;
	#endif
	// Creazione effetto in g_pEffect, caricandolo dal file fx
	HRESULT hr = D3DX11CompileFromFile(L"Shaders/blur_h.fx", NULL, NULL,NULL, "fx_5_0", dwShaderFlags, 0,
		NULL, &pBlob, &pErrorBlob, NULL);


    if( FAILED( hr ) )
    {
		MessageBox(NULL, L"Problema nel caricamento di blur_h.fx.", L"Error", MB_OK );

		if (pErrorBlob)
		{
			MessageBoxA(0, (char*)pErrorBlob->GetBufferPointer(), 0, 0);
		}
		return false;
    }

	D3DX11CreateEffectFromMemory(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, pd3dDevice ,&m_Effect);

	// Trova la tecnica definita nel .fx - nota come un effetto.fx può avere diverse tecniche.
	m_Technique = m_Effect->GetTechniqueByName( "Blur_h" );


	//Definiamo gli input da agganciare (bind) al vertex shader
	//In questo caso passeremo solo le informazioni sulla posizione con un vertex buffer
	D3D11_INPUT_ELEMENT_DESC layout[] =
	{
		{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
		{"TEXCOORD",   0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
	};

	UINT numElements = sizeof( layout ) / sizeof( layout[0] );

	// Creiamo e configuriamo il layout di input
	D3DX11_PASS_DESC PassDesc;
	m_Technique->GetPassByIndex( 0 )->GetDesc( &PassDesc );
	hr = pd3dDevice->CreateInputLayout(layout, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &m_VertexLayout );
	if( FAILED( hr ) )
		return false;

	m_Effect->GetVariableByName("blurSizeH")->AsScalar()->SetFloat(blurSizeH);

	return true;
}
示例#13
0
void DX11PixelShader::Initialize(const string& shaderFileName,
    ID3D11Device* pDevice)
{
    //Force strict compile, which might not allow for legacy syntax.
    UINT compileFlags = D3DCOMPILE_ENABLE_STRICTNESS;

#ifdef POLY_DEBUG_SHADERS
    //Insert debug file/line/type/symbol information into the output code.
    compileFlags |= D3DCOMPILE_DEBUG;

    //Treat all warnings as errors.
    compileFlags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
#endif

    //Interfaces used to return arbitrary length data.
    ID3D10Blob* pErrorMessage;
    ID3D10Blob* pPixelShaderBlob;

    //Load and compile the pixel shader.
    HRESULT result = D3DX11CompileFromFile(
        (std::wstring(shaderFileName.begin(),shaderFileName.end())).c_str(),
        nullptr,nullptr,"Main","ps_5_0",compileFlags,0,nullptr,
        &pPixelShaderBlob,&pErrorMessage,nullptr);

    if (FAILED(result))
    {
        if (pErrorMessage != nullptr)
        {
            //Log the shader compilation errors.
            string compileErrors((char*)(pErrorMessage->GetBufferPointer()));

            pErrorMessage->Release();

            throw Exception("Direct3D 11 init failed (CompilePixelShader): " +
                compileErrors + "." + DEBUG_INFO,result);
        }
        else
        {
            throw Exception("Direct3D 11 init failed (CompilePixelShader)." +
                DEBUG_INFO,result);
        }
    }

    //Encapsulate the pixel shader into a shader object.
    result = pDevice->CreatePixelShader(pPixelShaderBlob->GetBufferPointer(),
        pPixelShaderBlob->GetBufferSize(),nullptr,&mpPixelShader);

    if (FAILED(result))
    {
        throw Exception("Direct3D 11 init failed (CreatePixelShader)." +
            DEBUG_INFO,result);
    }

    //This object is no longer needed.
    pPixelShaderBlob->Release();
}
//--------------------------------------------------------------------------------------
// Create any D3D10 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D10CreateDevice(ID3D10Device* pd3dDevice,
									 const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext)
{
	HRESULT hr;
	g_device = pd3dDevice;
	V_RETURN(g_DialogResourceManager.OnD3D10CreateDevice(pd3dDevice));
	V_RETURN(g_D3DSettingsDlg.OnD3D10CreateDevice(pd3dDevice));
	V_RETURN(D3DX10CreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
							  OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
							  L"Arial", &g_pFont10));
	V_RETURN(D3DX10CreateSprite(pd3dDevice, 512, &g_pSprite10));
	g_pTxtHelper = new CDXUTTextHelper(NULL, NULL, g_pFont10, g_pSprite10, 15);
	V_RETURN(CDXUTDirectionWidget::StaticOnD3D10CreateDevice(pd3dDevice));
	// Read the D3DX effect file
	WCHAR str[MAX_PATH];
	ID3D10Blob* pErrBlob = NULL;
	V_RETURN(DXUTFindDXSDKMediaFileCch(str, MAX_PATH, L"Effect_Undistort.fx"));
	hr = D3DX10CreateEffectFromFile(str, NULL, NULL, "fx_4_0",
									D3D10_SHADER_ENABLE_STRICTNESS, 0,
									pd3dDevice, NULL, NULL, &g_pEffect10, &pErrBlob, NULL);

	if (FAILED(hr))
	{
		std::string errStr((LPCSTR)pErrBlob->GetBufferPointer(),
						   pErrBlob->GetBufferSize());
		WCHAR err[256];
		MultiByteToWideChar(CP_ACP, 0, errStr.c_str(), (int)errStr.size(), err,
							errStr.size());
		MessageBox(NULL, (LPCWSTR)err, L"Error", MB_OK);
		return hr;
	}

	// Setup the vector image and the display
	UINT width = (DXUTIsAppRenderingWithD3D9()) ?
				 DXUTGetD3D9BackBufferSurfaceDesc()->Width :
				 DXUTGetDXGIBackBufferSurfaceDesc()->Width;
	UINT height = (DXUTIsAppRenderingWithD3D9()) ?
				  DXUTGetD3D9BackBufferSurfaceDesc()->Height :
				  DXUTGetDXGIBackBufferSurfaceDesc()->Height;
	g_vsObj = new VSObject(pd3dDevice);
	D3D10_RASTERIZER_DESC rasterizerState;
	rasterizerState.FillMode = D3D10_FILL_SOLID;
	rasterizerState.CullMode = D3D10_CULL_NONE;
	rasterizerState.FrontCounterClockwise = true;
	rasterizerState.DepthBias = false;
	rasterizerState.DepthBiasClamp = 0;
	rasterizerState.SlopeScaledDepthBias = 0;
	rasterizerState.DepthClipEnable = true;
	rasterizerState.ScissorEnable = false;
	rasterizerState.MultisampleEnable = false;
	rasterizerState.AntialiasedLineEnable = false;
	pd3dDevice->CreateRasterizerState(&rasterizerState, &g_pRasterState);
	return S_OK;
}
示例#15
0
void Effects::InitAll(ID3D11Device* device)
{
	ID3D10Blob* blob;
	ID3D10Blob *effectBytecode;
	ID3DX11Effect *effect;
	//D3DX11CompileEffectFromFile
	HR(D3DX11CompileFromFile(L"FX/Billboard.fx", NULL, NULL, "Light2Tex", "fx_5_0", 0, 0, 0, &effectBytecode, &blob, NULL));

	HRESULT hr = D3DX11CreateEffectFromMemory(effectBytecode->GetBufferPointer(), effectBytecode->GetBufferSize(), 0, device, &effect);

	BasicFX = new BasicEffect(device, L"FX/UberShader.fxo");
	SkyFX   = new SkyEffect(device, L"FX/Sky.fxo");
	BillboardFX  = new BillboardEffect(device, L"FX/Billboard.fx", effect);
	//BillboardFX->mFX = effect;
}
示例#16
0
void InitDirect3DApp::BuildEffect()
{
	DWORD shaderFlags = 0;

	#if defined( DEBUG ) || defined( _DEBUG )
		shaderFlags |= D3D10_SHADER_DEBUG;
		shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
	#endif

	ID3D10Blob* compiledShader = 0;
	ID3D10Blob* compilationErrors = 0;

	HRESULT hr = D3DX11CompileFromFile(L"FX/color.fx",		// Name of the .fx file
									   0,					// Advanced option
									   0,					// Advanced option
									   0,					// Using the effects framework so set it to null
									   "fx_5_0",			// Shader version we are using
									   shaderFlags,			// Flags to specify how the code should be compiled
									   0,					// Advanced effect compilation options
									   0,					// Advanced option to compile the shader asynchronously
									   &compiledShader,		// Pointer to the compiled shader
									   &compilationErrors,	// Pointer to compilation errors if there are any
									   0);                  // Return error code for compiling asynchronously
	
	// Check for any compilation errors
	if (compilationErrors != 0)
	{
		MessageBoxA(0, (char*)compilationErrors->GetBufferPointer(), 0, 0);
		ReleaseCOM(compilationErrors);
	}

	// Check for any other errors with compiling the shader
	if (FAILED(hr))
	{
		DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX11CompileFromFile", true);
	}

	// Shader compiled successfully, time to create the effect
	HR(D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), 0, md3dDevice, &effect));

	ReleaseCOM(compiledShader);

	// Get the technique location from the effect
	technique = effect->GetTechniqueByName("ColorTechnique");

	// Get the World View Proj Matrix location from the effect
	worldViewProj = effect->GetVariableByName("WorldViewProj")->AsMatrix();
}
void BoxApp::BuildFX()
{
	DWORD shaderFlags = 0;
#if defined( DEBUG ) || defined( _DEBUG )
    shaderFlags |= D3D10_SHADER_DEBUG;
	shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
#endif
 
	ID3D10Blob* compiledShader = 0;
	ID3D10Blob* compilationMsgs = 0;
	HRESULT hr = D3DX11CompileFromFile(L"FX/Lighting.fx", 0, 0, 0, "fx_5_0", shaderFlags, 
		0, 0, &compiledShader, &compilationMsgs, 0);

	// compilationMsgs can store errors or warnings.
	if( compilationMsgs != 0 )
	{
		MessageBoxA(0, (char*)compilationMsgs->GetBufferPointer(), 0, 0);
		ReleaseCOM(compilationMsgs);
	}

	// Even if there are no compilationMsgs, check to make sure there were no other errors.
	if(FAILED(hr))
	{
		DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX11CompileFromFile", true);
	}

	HR(D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), 
		0, md3dDevice, &mFX));

	// Done with compiled shader.
	ReleaseCOM(compiledShader);

	mTech                = mFX->GetTechniqueByName("LightTech");
	mTech2				 = mFX->GetTechniqueByName("IllumTech");
	mTechSkyBox			 = mFX->GetTechniqueByName("SkyBoxTech");
	mfxWorldViewProj     = mFX->GetVariableByName("gWorldViewProj")->AsMatrix();
	mfxWorld             = mFX->GetVariableByName("gWorld")->AsMatrix();
	mfxWorldInvTranspose = mFX->GetVariableByName("gWorldInvTranspose")->AsMatrix();
	mfxEyePosW           = mFX->GetVariableByName("gEyePosW")->AsVector();
	mfxDirLight          = mFX->GetVariableByName("gDirLight");
	mfxPointLight        = mFX->GetVariableByName("gPointLight");
	mfxPointLight2       = mFX->GetVariableByName("gPointLight2");
	mfxSpotLight         = mFX->GetVariableByName("gSpotLight");
	mfxMaterial          = mFX->GetVariableByName("gMaterial");

	diffuseMap = mFX->GetVariableByName("gDiffuseMap")->AsShaderResource();
}
示例#18
0
bool ShaderClass::createGeometryShader(ID3D11Device* pDevice, WCHAR* fileName, CHAR* EntryPoint, ID3D11GeometryShader** ppGShader)
{

	HRESULT hr;
	// Initialie Geometry shader
	ID3D10Blob* geometryShaderBuffer;
	ID3D10Blob* errorMessages;
	hr = D3DCompileFromFile(
		fileName,
		NULL,
		NULL,
		EntryPoint,
		"gs_5_0",
		0,
		0,
		&geometryShaderBuffer,
		&errorMessages);

	if (FAILED(hr))
	{
		// If the shader failed to compile it should have writen something to the error message.
		if (errorMessages)
		{
			OutputShaderErrorMessage(errorMessages, fileName);
			return false;
		}
		// If there was nothing in the error message then it simply could not find the shader file itself.
		else
		{
			MessageBox(0, fileName, L"Missing Shader File", MB_OK);
			return false;
		}
	}

	// Create the geometry shader from the buffer.
	hr = pDevice->CreateGeometryShader(geometryShaderBuffer->GetBufferPointer(), geometryShaderBuffer->GetBufferSize(), NULL, ppGShader);
	if (FAILED(hr))
	{
		MessageBox(0, L"Failed to create geometry shader", 0, MB_OK);
		return false;
	}

	geometryShaderBuffer->Release();

	return true;
}
示例#19
0
template<> unique_ptr<ID3D10Effect> ResourceService::LoadResource<ID3D10Effect>(const std::tstring& filePath)
{
	ID3D10Blob* pErrorBlob;
	ID3D10Effect* pEffect;
	
	HRESULT hr = D3DX10CreateEffectFromFile(filePath.c_str(),
				 NULL,
				 NULL,
				 "fx_4_0",
#ifndef NDEBUG
				 D3D10_SHADER_DEBUG|D3D10_SHADER_SKIP_OPTIMIZATION|D3D10_SHADER_WARNINGS_ARE_ERRORS|D3D10_SHADER_PACK_MATRIX_ROW_MAJOR, //HLSL Flags: http://msdn.microsoft.com/en-us/library/windows/desktop/bb172416%28v=vs.85%29.aspx
#else
				 D3D10_SHADER_OPTIMIZATION_LEVEL3|D3D10_SHADER_IEEE_STRICTNESS|D3D10_SHADER_PACK_MATRIX_ROW_MAJOR,
#endif
				 0,
				 MyServiceLocator::GetInstance()->GetService<IGraphicsService>()->GetGraphicsDevice()->GetDevice(),
				 NULL,
				 NULL,
				 &pEffect,
				 &pErrorBlob,
				 NULL);

	if(FAILED(hr))
	{
		tstringstream ss;
		
		if(pErrorBlob!=nullptr)
		{
			char *errors = (char*)pErrorBlob->GetBufferPointer();
 
			for(unsigned int i = 0; i < pErrorBlob->GetBufferSize(); i++)
				ss<<errors[i];
 
			OutputDebugString(ss.str().c_str());
			pErrorBlob->Release();
			
			throw LoaderException(_T("effect ") + filePath, ss.str() );
		}
		MyServiceLocator::GetInstance()->GetService<DebugService>()->LogDirectXError(hr, __LINE__, __FILE__);
	}

	return unique_ptr<ID3D10Effect>(pEffect);
}
示例#20
0
bool xGL2PixelShader::load(const wchar_t* fileName , const unsigned int8* buf , size_t bufLen, unsigned long arg)
{
	unload();

	ID3D10Blob* pShaderCode = NULL;
	ID3D10Blob* pErroMsg    = NULL;
	GL2_SHADER_MACRO* pMacroDef = NULL;
	ID3D10Include*      pInclude  = NULL;
	const char*         func_name = "main";

	DWORD dwShaderFlags = 0;
#if defined( DEBUG ) || defined( _DEBUG )
	dwShaderFlags |= GL2_SHADER_DEBUG;
#endif

	HRESULT  hr = GL2CompileShader((LPCSTR)buf,bufLen,NULL,pMacroDef,pInclude,func_name,"ps_4_0",dwShaderFlags,&pShaderCode,&pErroMsg );

	if( FAILED(hr) )
	{
		const char* strErroMsg = (const char*)pErroMsg->GetBufferPointer();
		XEVOL_LOG(eXL_ERROR_FALT,strErroMsg);
		XSAFE_RELEASE(pShaderCode);
		XSAFE_RELEASE(pErroMsg);
		return false;
	}

	xGL2RenderApi* pD10Api = (xGL2RenderApi*)m_pRenderApi;
	hr = pD10Api->d10Device()->CreatePixelShader(pShaderCode->GetBufferPointer() , pShaderCode->GetBufferSize() , &m_pPixelShader);
	if( FAILED(hr) )
	{
		XSAFE_RELEASE(pShaderCode);
		XSAFE_RELEASE(pErroMsg);
		return false;
	}

	afterLoad(pShaderCode);

	XSAFE_RELEASE(pShaderCode);
	XSAFE_RELEASE(pErroMsg);
	m_Name = fileName;
	return true;
}
void RenderDevice::InitShaders( const char * vertex_shader, const char * pixel_shader, ShaderSet ** pShaders, ID3D11InputLayout ** pVertexIL,
				  D3D11_INPUT_ELEMENT_DESC * DistortionMeshVertexDesc, int num_elements)
{
    ID3D10Blob* vsData = CompileShader("vs_4_0", vertex_shader);

    Ptr<VertexShader> vtxShader = *new VertexShader(this, vsData);

	ID3D11InputLayout** objRef   = pVertexIL;

	HRESULT validate = Device->CreateInputLayout(
        DistortionMeshVertexDesc, num_elements,
        vsData->GetBufferPointer(), vsData->GetBufferSize(), objRef);
	if(FAILED(validate)) OVR_ASSERT(false);
    
	(*pShaders) = CreateShaderSet();
	(*pShaders)->SetShader(vtxShader);
 
    ID3D10Blob *pShader = CompileShader("ps_4_0", pixel_shader);
    Ptr<PixelShader> ps  = *new PixelShader(this, pShader);

    (*pShaders)->SetShader(ps);
}
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;
}
bool OmniMaterial::D3DCreateDevice(ID3D11Device* d3dDevice, const DXGI_SURFACE_DESC* BackBufferSurfaceDesc)
{	

	materialVS = new VertexShader(d3dDevice, L"Shaders\\OmniMaterial.hlsl", "OmniMaterialVS");
	materialPS = new PixelShader(d3dDevice, L"Shaders\\OmniMaterial.hlsl", "OmniMaterialPS");

	if(!omniCBuffer->D3DCreateDevice(d3dDevice, BackBufferSurfaceDesc)) return false;

	// Create  mesh input layout
	// isn't there an easier and better way to do this???

	// We need the vertex shader bytecode for this... rather than try to wire that all through the
	// shader interface, just recompile the vertex shader.
	UINT shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR;
	ID3D10Blob *bytecode = 0;
	HRESULT hr = D3DX11CompileFromFile(L"Shaders\\OmniMaterial.hlsl", NULL, 0, "OmniMaterialVS", "vs_5_0", shaderFlags, 0, 0, &bytecode, 0, 0);
	if (FAILED(hr)) 
	{
		assert(false);
	}

	const D3D11_INPUT_ELEMENT_DESC layout[] =
	{
		{ "POSITION",  0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,  D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "NORMAL",    0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};

	d3dDevice->CreateInputLayout( 
		layout, ARRAYSIZE(layout), 
		bytecode->GetBufferPointer(),
		bytecode->GetBufferSize(), 
		&_InputLayout);

	bytecode->Release();

	DXUT_SetDebugName(_InputLayout, "OmniMaterial_InputLayout"); 
	return hr == S_OK;
}
	//-----------------------------------------------------------------------
	ID3D11InputLayout*  D3D11VertexDeclaration::getILayoutByShader(D3D11HLSLProgram* boundVertexProgram)
	{
		ShaderToILayoutMapIterator foundIter = mShaderToILayoutMap.find(boundVertexProgram);

		ID3D11InputLayout*  pVertexLayout = 0; 

		if (foundIter == mShaderToILayoutMap.end())
		{
			// if not found - create

			DWORD dwShaderFlags = 0;
			ID3D10Blob* pVSBuf = boundVertexProgram->getMicroCode();
			D3D11_INPUT_ELEMENT_DESC * pVertexDecl=getD3DVertexDeclaration();
			HRESULT hr = mlpD3DDevice->CreateInputLayout( 
				pVertexDecl, 
				(UINT)getElementCount(), 
				pVSBuf->GetBufferPointer(), 
				pVSBuf->GetBufferSize(),
				&pVertexLayout );

			if (FAILED(hr)|| mlpD3DDevice.isError())
			{
				String errorDescription = mlpD3DDevice.getErrorDescription();

				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set D3D11 vertex declaration"+errorDescription , 
					"D3D11VertexDeclaration::getILayoutByShader");
			}

			mShaderToILayoutMap[boundVertexProgram] = pVertexLayout;

		}
		else
		{
			pVertexLayout = foundIter->second;
		}

		return pVertexLayout;
	}
示例#25
0
void D3DRenderer::InitEffects()
{
	ID3D10Blob* compiledShader = 0;
	ID3D10Blob* compilationMsgs = 0;
	HRESULT hr = D3DX11CompileFromFile(L"Effects/color.fx", 0, 0, 0, "fx_5_0", 0, 0, 0, &compiledShader, &compilationMsgs, 0);

	if (compilationMsgs !=0)
	{
		MessageBoxA(0, (char*)compilationMsgs->GetBufferPointer(), 0 ,0);
		ReleaseCOM(compilationMsgs);
	}

	if (FAILED(hr))
	{
		DXTrace(__FILE__,(DWORD)__LINE__, hr, L"D3DX11CompileFromFile", true);
	}

	HR(D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(),
		0, md3dDevice, &mEffect));

	ReleaseCOM(compiledShader);
	mETech = mEffect->GetTechniqueByName("ColorTech");
}
VertexShader* VertexShader::FromFile(LPCTSTR pFileName, Renderer* pRender) {
	ID3D10Blob* pBuffer = NULL;
	ID3D10Blob* pError = NULL;

	// Compile the pixel shader from the file
	HRESULT hr = D3DX11CompileFromFile(
		pFileName,				//[in]   LPCTSTR pSrcFile,
		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;
	}

	VertexShader* pVertexShader = new VertexShader(
		pBuffer->GetBufferPointer(), 
		pBuffer->GetBufferSize(),
		pRender);
	SafeRelease(pBuffer);
	return pVertexShader;
}
ID3D11ComputeShader* CDXGIManager::CompileCS( wchar_t* pszFileName, char* pszEntryPoint )
{
    ID3D10Blob* pIL = NULL;			// Intermediate Language, Bytecode del shader en DXIL
    ID3D10Blob* pErrors = NULL;		// Error log buffer.
    ID3D11ComputeShader* pCS = NULL; // The compute shader

#ifdef _DEBUG
    DWORD dwOption = D3DCOMPILE_SKIP_OPTIMIZATION | D3DCOMPILE_ENABLE_STRICTNESS |
                     D3DCOMPILE_DEBUG;
#else
    DWORD dwOption = D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE_ENABLE_STRICTNESS |
                     D3DCOMPILE_DEBUG;
#endif

    HRESULT hr = D3DCompileFromFile( pszFileName, NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE,
                                     pszEntryPoint, "cs_5_0", dwOption, 0, &pIL, &pErrors );
    if( FAILED(hr) )
    {
        if( pErrors )
            MessageBoxA( NULL, (char*)pErrors->GetBufferPointer(), "ERRORES", MB_ICONERROR );

        SAFE_RELEASE( pErrors );
        SAFE_RELEASE( pIL );
        return NULL;
    }
    // Crear el compute shader en código nativo
    hr = m_pDevice->CreateComputeShader( pIL->GetBufferPointer(), pIL->GetBufferSize(), NULL, &pCS );
    if( FAILED(hr) )
    {
        SAFE_RELEASE( pErrors );
        SAFE_RELEASE( pIL );
        return NULL;
    }
    SAFE_RELEASE( pErrors );
    SAFE_RELEASE( pIL );
    return pCS;
}
示例#28
0
bool CGEClipPlaneShader::_initialize_shader(ID3D11Device* pDevice, HWND hWnd, WCHAR* vsFilename, WCHAR* psFilename)
{
	HRESULT result;
	ID3D10Blob* pErrorMessage;
	ID3D10Blob* pVertexShaderBuf;
	ID3D10Blob* pPixelShaderBuf;

	D3D11_BUFFER_DESC matrixBufDesc;
	D3D11_BUFFER_DESC clipPlaneBufDesc;
	D3D11_SAMPLER_DESC samplerDesc;
	D3D11_INPUT_ELEMENT_DESC polygonLayout[2];

	unsigned int numElement;

	pErrorMessage = 0;
	pVertexShaderBuf = 0;
	pPixelShaderBuf = 0;

	result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "ClipPlaneVS", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS,
		0, NULL, &pVertexShaderBuf, &pErrorMessage, NULL);
	if( FAILED(result) )
	{
		if( pErrorMessage )
		{
			this->_output_error_message(pErrorMessage, hWnd, vsFilename);
		}

		else
		{
			MessageBox(hWnd, vsFilename, L"Missing Shader File", MB_OK);
		}

		return false;
	}

	result = D3DX11CompileFromFile(psFilename, NULL, NULL, "ClipPlanePS", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS,
		0, NULL, &pPixelShaderBuf, &pErrorMessage, NULL);
	if( FAILED(result) )
	{
		if( pErrorMessage )
		{
			this->_output_error_message(pErrorMessage, hWnd, psFilename);
		}

		else
		{
			MessageBox(hWnd, psFilename, L"Missing Shader File", MB_OK);
		}

		return false;
	}

	result = pDevice->CreateVertexShader(pVertexShaderBuf->GetBufferPointer(), pVertexShaderBuf->GetBufferSize(),
		NULL, &this->m_pVertexShader);
	if( FAILED(result) )
		return false;

	result = pDevice->CreatePixelShader(pPixelShaderBuf->GetBufferPointer(), pPixelShaderBuf->GetBufferSize(), NULL,
		&this->m_pPixelShader);
	if( FAILED(result) )
		return false;

	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 = "TEXCOORD";
	polygonLayout[1].SemanticIndex = 0;
	polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
	polygonLayout[1].InputSlot = 0;
	polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
	polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[1].InstanceDataStepRate = 0;

	numElement = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

	result = pDevice->CreateInputLayout(polygonLayout, numElement, pVertexShaderBuf->GetBufferPointer(),
		pVertexShaderBuf->GetBufferSize(), &this->m_pInputLayout);
	if( FAILED(result) )
		return false;

	::ReleaseWithoutDel<ID3D10Blob*>(pVertexShaderBuf);
	::ReleaseWithoutDel<ID3D10Blob*>(pPixelShaderBuf);

	matrixBufDesc.Usage = D3D11_USAGE_DYNAMIC;
	matrixBufDesc.ByteWidth = sizeof(MatrixBufferType);
	matrixBufDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	matrixBufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	matrixBufDesc.MiscFlags = 0;
	matrixBufDesc.StructureByteStride = 0;

	result = pDevice->CreateBuffer(&matrixBufDesc, NULL, &this->m_pMatrixBuffer);
	if( FAILED(result) )
		return false;

	clipPlaneBufDesc.Usage = D3D11_USAGE_DYNAMIC;
	clipPlaneBufDesc.ByteWidth = sizeof(MatrixBufferType);
	clipPlaneBufDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	clipPlaneBufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	clipPlaneBufDesc.MiscFlags = 0;
	clipPlaneBufDesc.StructureByteStride = 0;

	result = pDevice->CreateBuffer(&clipPlaneBufDesc, NULL, &this->m_pClipPlaneBuffer);
	if( FAILED(result) )
		return false;

	samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
	samplerDesc.MaxAnisotropy = 1;
	samplerDesc.MipLODBias = 0.0f;
	samplerDesc.BorderColor[0] = 0.0f;
	samplerDesc.BorderColor[1] = 0.0f;
	samplerDesc.BorderColor[2] = 0.0f;
	samplerDesc.BorderColor[3] = 0.0f;
	samplerDesc.MinLOD = 0;
	samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

	result = pDevice->CreateSamplerState(&samplerDesc, &this->m_pSamplerState);
	if( FAILED(result) )
		return false;

	return true;
}
bool TransparentShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
	HRESULT result;
	ID3D10Blob* errorMessage;
	ID3D10Blob* vertexShaderBuffer;
	ID3D10Blob* pixelShaderBuffer;
	D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
	unsigned int numElements;
	D3D11_BUFFER_DESC matrixBufferDesc;
    D3D11_SAMPLER_DESC samplerDesc;
	D3D11_BUFFER_DESC transparentBufferDesc;


	// Initialize the pointers this function will use to null.
	errorMessage = 0;
	vertexShaderBuffer = 0;
	pixelShaderBuffer = 0;

    // Compile the vertex shader code.
	result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "TransparentVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 
								   0, NULL, &vertexShaderBuffer, &errorMessage, NULL);
	if(FAILED(result))
	{
		// If the shader failed to compile it should have writen something to the error message.
		if(errorMessage)
		{
			OutputShaderErrorMessage(errorMessage, hwnd, vsFilename);
		}
		// If there was  nothing in the error message then it simply could not find the shader file itself.
		else
		{
			MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK);
		}

		return false;
	}

    // Compile the pixel shader code.
	result = D3DX11CompileFromFile(psFilename, NULL, NULL, "TransparentPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 
								   0, NULL, &pixelShaderBuffer, &errorMessage, NULL);
	if(FAILED(result))
	{
		// If the shader failed to compile it should have writen something to the error message.
		if(errorMessage)
		{
			OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
		}
		// If there was  nothing in the error message then it simply could not find the file itself.
		else
		{
			MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK);
		}

		return false;
	}

    // Create the vertex shader from the buffer.
    result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, 
										&m_vertexShader);
	if(FAILED(result))
	{
		return false;
	}

    // Create the vertex shader from the buffer.
    result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, 
									   &m_pixelShader);
	if(FAILED(result))
	{
		return false;
	}

	// Create the vertex input layout description.
	// This setup needs to match the VertexType stucture in the ModelClass and in the shader.
	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 = "TEXCOORD";
	polygonLayout[1].SemanticIndex = 0;
	polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
	polygonLayout[1].InputSlot = 0;
	polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
	polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	polygonLayout[1].InstanceDataStepRate = 0;

	// Get a count of the elements in the layout.
    numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

	// Create the vertex input layout.
	result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), 
									   vertexShaderBuffer->GetBufferSize(), &m_layout);
	if(FAILED(result))
	{
		return false;
	}

	// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
	vertexShaderBuffer->Release();
	vertexShaderBuffer = 0;

	pixelShaderBuffer->Release();
	pixelShaderBuffer = 0;

    // Setup the description of the dynamic constant buffer that is in the vertex shader.
    matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
    matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    matrixBufferDesc.MiscFlags = 0;
	matrixBufferDesc.StructureByteStride = 0;

	// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
	result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer);
	if(FAILED(result))
	{
		return false;
	}

	// Create a texture sampler state description.
    samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.MipLODBias = 0.0f;
    samplerDesc.MaxAnisotropy = 1;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    samplerDesc.BorderColor[0] = 0;
	samplerDesc.BorderColor[1] = 0;
	samplerDesc.BorderColor[2] = 0;
	samplerDesc.BorderColor[3] = 0;
    samplerDesc.MinLOD = 0;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

	// Create the texture sampler state.
    result = device->CreateSamplerState(&samplerDesc, &m_sampleState);
	if(FAILED(result))
	{
		return false;
	}

    // Setup the description of the transparent dynamic constant buffer that is in the pixel shader.
    transparentBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	transparentBufferDesc.ByteWidth = sizeof(TransparentBufferType);
    transparentBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    transparentBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    transparentBufferDesc.MiscFlags = 0;
	transparentBufferDesc.StructureByteStride = 0;

	// Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class.
	result = device->CreateBuffer(&transparentBufferDesc, NULL, &m_transparentBuffer);
	if(FAILED(result))
	{
		return false;
	}

	return true;
}
示例#30
0
bool App::CompileShaders()
{
	if(vertexShader)
	{
		vertexShader->Release();
		vertexShader = 0;
	}

	if(pixelShader)
	{
		pixelShader->Release();
		pixelShader = 0;
	}

	// Compile shaders
	ID3D10Blob* vs = 0;
	ID3D10Blob* ps = 0;
	ID3D10Blob* errorblob = 0;
	D3DX11CompileFromFile(L"..\\ExplosionDemo\\effect.fx", 0, 0, "vertexShader", "vs_5_0", 0, 0, 0, &vs, &errorblob, 0);

	if(errorblob)
	{
		MessageBoxA(0, (char*)errorblob->GetBufferPointer(), 0, MB_OK);
		errorblob->Release();
		errorblob = 0;
	}

	D3DX11CompileFromFile(L"..\\ExplosionDemo\\effect.fx", 0, 0, "rayMarcher", "ps_5_0", 0, 0, 0, &ps, &errorblob, 0);
	if(errorblob)
	{
		MessageBoxA(0, (char*)errorblob->GetBufferPointer(), 0, MB_OK);
		errorblob->Release();
		errorblob = 0;
	}

	if(!(vs && ps))
	{
		MessageBox(0, L"Shader compilation failed", 0, MB_OK | MB_ICONWARNING);
		return false;
	}

	dev->CreateVertexShader(vs->GetBufferPointer(), vs->GetBufferSize(), NULL, &vertexShader);
	dev->CreatePixelShader(ps->GetBufferPointer(), ps->GetBufferSize(), NULL, &pixelShader);

	devContext->VSSetShader(vertexShader, 0, 0);
	devContext->PSSetShader(pixelShader, 0, 0);

	D3D11_INPUT_ELEMENT_DESC inElDesc[] =
	{
		{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
		{"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, sizeof(float)*3, D3D11_INPUT_PER_VERTEX_DATA, 0}
	};

	dev->CreateInputLayout(inElDesc, 2, vs->GetBufferPointer(), vs->GetBufferSize(), &inLayout);

	vs->Release();
	ps->Release();

	return true;

}