Beispiel #1
0
HRESULT HookIDirect3DDevice9::CreateVertexShader(LPVOID _this,
												 CONST DWORD* pFunction,
												 IDirect3DVertexShader9** ppShader)
{
	LOG_API();
	return pD3Dev->CreateVertexShader(pFunction, ppShader);
}
void CompileShader()
{
	DWORD dwShaderFlags = 0;

#if defined( DEBUG ) || defined( _DEBUG )
    // Set the D3DXSHADER_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 |= D3DXSHADER_DEBUG;
    #endif

#ifdef DEBUG_VS
        dwShaderFlags |= D3DXSHADER_SKIPOPTIMIZATION|D3DXSHADER_DEBUG;
    #endif
#ifdef DEBUG_PS
        dwShaderFlags |= D3DXSHADER_SKIPOPTIMIZATION|D3DXSHADER_DEBUG;
    #endif
	
	WCHAR* shader_file = L"torus_shader.hlsl";

	// Compile Vertex Shader
	LPD3DXBUFFER pVertexShaderCode;
	HRESULT hr = D3DXCompileShaderFromFile(shader_file, NULL, NULL, "VS", "vs_3_0", dwShaderFlags, &pVertexShaderCode, NULL, NULL);
	if(FAILED(hr))
	{
		MessageBox(NULL, L"Error", L"Compile Vertex Shader Failed!", 0);
	}

	// Create Vertex Shader
	hr = g_pd3dDevice->CreateVertexShader((DWORD*)pVertexShaderCode->GetBufferPointer(), &g_pVertexShader);
	if(FAILED(hr))
	{
		MessageBox(NULL, L"Error", L"Create Vertex Shader Failed!", 0);
	}

	// Compile Pixel Shader
	LPD3DXBUFFER pPixelShaderCode;
	hr = D3DXCompileShaderFromFile(shader_file, NULL, NULL, "PS", "ps_3_0", dwShaderFlags, &pPixelShaderCode, NULL, NULL);
	if(FAILED(hr))
	{
		MessageBox(NULL, L"Error", L"Compile Pixel Shader Failed!", 0);
	}

	// Create Pixel Shader
	hr = g_pd3dDevice->CreatePixelShader((DWORD*)pPixelShaderCode->GetBufferPointer(), &g_pPixelShader);
	if(FAILED(hr))
	{
		MessageBox(NULL, L"Error", L"Create Pixel Shader Failed!", 0);
	}

	// cleanup
	pVertexShaderCode->Release();
	pPixelShaderCode->Release();
}
HRESULT InitVS()
{
	D3DVERTEXELEMENT9	decl[MAX_FVF_DECL_SIZE];
	// FVF를 사용해서 정점선언값을 자동으로 채워넣는다
	D3DXDeclaratorFromFVF( MYVERTEX::FVF, decl );
	// 정점선언값으로 g_pDecl을 생성한다.
	g_pd3dDevice->CreateVertexDeclaration( decl, &g_pDecl );
	LPD3DXBUFFER pCode;

	// simple.vs 파일을 읽어와서 정점쉐이더 인터페이스를 생성한다.
	if( FAILED( D3DXAssembleShaderFromFile( "simple.vs", NULL, NULL, 0, &pCode, NULL ) ) )
		return E_FAIL;

	g_pd3dDevice->CreateVertexShader( (DWORD*)pCode->GetBufferPointer(), &g_pVS);

	S_REL( pCode );

	return S_OK;
}
Beispiel #4
0
bool CObject3D::InitStaticDeviceObjects(LPDIRECT3DDEVICE9 device)
{
	D3DVERTEXELEMENT9 decl[] =
	{
		{ 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
		{ 0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 },
		{ 0, 20, D3DDECLTYPE_SHORT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 },
		{ 0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
		{ 0, 36, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
		D3DDECL_END()
	};

	if (FAILED(device->CreateVertexDeclaration(decl, &s_skinVertexDeclaration)))
	{
		qCritical("Can't create skin vertex declaration. You must (re)install the lastest DirectX9 runtime on http://www.microsoft.com/en-us/download/details.aspx?id=8109");
		return false;
	}

	LPD3DXBUFFER code;
	if (FAILED(D3DXAssembleShaderFromResource(NULL, MAKEINTRESOURCE(IDR_SKINVS), NULL, NULL, 0, &code, NULL)))
	{
		qCritical("Can't assemble skin vertex shader from resource. You must (re)install the lastest DirectX9 runtime on http://www.microsoft.com/en-us/download/details.aspx?id=8109");
		return false;
	}

	if (FAILED(device->CreateVertexShader((DWORD*)code->GetBufferPointer(), &s_skinVS)))
	{
		qCritical("Can't create skin vertex shader. You must (re)install the lastest DirectX9 runtime on http://www.microsoft.com/en-us/download/details.aspx?id=8109");
		Release(code);
		return false;
	}
	Release(code);

	s_reflectTexture.SetDevice(device);
	if (!s_reflectTexture.Load("Model/Texture/etc_reflect.tga"))
	{
		qCritical("Can't load Model/Texture/etc_reflect.tga");
		return false;
	}

	return true;
}
Beispiel #5
0
bool Create_VS(char* hlsl, char* name, LPDIRECT3DVERTEXSHADER9* shader, LPD3DXCONSTANTTABLE* table, LPDIRECT3DDEVICE9 pDevice)
{
	HRESULT hr;
	LPD3DXBUFFER err;
	LPD3DXBUFFER code;
	// hlsl読み込み
	hr = D3DXCompileShaderFromFile(hlsl, NULL, NULL, name, "vs_3_0", 0, &code, &err, table);
	if (FAILED(hr)){
		MessageBox(NULL, (LPCSTR)err->GetBufferPointer(), name, MB_OK);
		err->Release();
		return false;
	}
	// ピクセルシェーダ作成 
	hr = pDevice->CreateVertexShader((DWORD*)code->GetBufferPointer(), shader);
	if (FAILED(hr)){
		MessageBox(NULL, (LPCSTR)err->GetBufferPointer(), name, MB_OK);
		return false;
	}
	return true;
}
Beispiel #6
0
bool CompileVertexShader(const char *code, LPDIRECT3DVERTEXSHADER9 *pShader, LPD3DXCONSTANTTABLE *pShaderTable, std::string &errorMessage) {
	ID3DXBuffer* pShaderCode = NULL;
	ID3DXBuffer* pErrorMsg = NULL;

	HRESULT hr = -1;

	// Compile pixel shader.
	hr = dyn_D3DXCompileShader(code,
		(UINT)strlen(code),
		NULL,
		NULL,
		"main",
		"vs_2_0",
		0,
		&pShaderCode,
		&pErrorMsg,
		pShaderTable);

	if (pErrorMsg) {
		errorMessage = (CHAR *)pErrorMsg->GetBufferPointer();
		pErrorMsg->Release();
	} else {
		errorMessage = "";
	}

	if (FAILED(hr)) {
		if (pShaderCode)
			pShaderCode->Release();
		return false;
	}

	// Create pixel shader.
	pD3Ddevice->CreateVertexShader( (DWORD*)pShaderCode->GetBufferPointer(), 
		pShader );

	pShaderCode->Release();

	return true;
}
// Load and compiler a HLSL vertex shader from a file. Provide the source code filename and pointers
// to the variables to hold the resultant shader and it associated constant table
bool LoadVertexShader( const string& fileName, LPDIRECT3DVERTEXSHADER9* vertexShader,
					   LPD3DXCONSTANTTABLE* constants )
{
	// Temporary variable to hold compiled pixel shader code
    LPD3DXBUFFER pShaderCode;

	// Compile external HLSL pixel shader into shader code to submit to the hardware
	string fullFileName = ShaderFolder + fileName;
	HRESULT hr = 
		D3DXCompileShaderFromFile( fullFileName.c_str(),// File containing pixel shader (HLSL)
			                       NULL, NULL,       // Advanced compilation options - not needed here
								   "main",           // Name of main function in the shader
								   "vs_3_0",         // Target vertex shader hardware - vs_1_1 is lowest level
												     // and will work on all video cards with a pixel shader
								   SHADER_FLAGS,     // Additional compilation flags (such as debug flags)
								   &pShaderCode,     // Ptr to variable to hold compiled shader code
								   NULL,             // Ptr to variable to hold error messages (not needed)
								   constants );      // Ptr to variable to hold constants for the shader
    if (FAILED(hr))
	{
		// Return if compilation failed
		return false;
	}

	// Create the pixel shader using the compiled shader code
    hr = g_pd3dDevice->CreateVertexShader( (DWORD*)pShaderCode->GetBufferPointer(), vertexShader );
    
	// Discard the shader code now the shader has been created 
	pShaderCode->Release();

	// If the creation failed then return (wait until after shader code has been discarded)
    if (FAILED(hr))
	{
		return false;
	}

	return true;
}
Beispiel #8
0
bool CompileVertexShader(const char * code, LPDIRECT3DVERTEXSHADER9 * pShader, LPD3DXCONSTANTTABLE * pShaderTable) {
	LPD3DXCONSTANTTABLE shaderTable = *pShaderTable;

	ID3DXBuffer* pShaderCode = NULL;
	ID3DXBuffer* pErrorMsg = NULL;

	HRESULT hr = -1;

	// Compile pixel shader.
#ifdef _XBOX
	hr = D3DXCompileShader( code, 
		(UINT)strlen( code ),
		NULL, 
		NULL, 
		"main", 
		"vs_3_0", 
		0, 
		&pShaderCode, 
		&pErrorMsg,
		pShaderTable );
#endif
	if( FAILED(hr) )
	{
		OutputDebugStringA((CHAR*)pErrorMsg->GetBufferPointer());
		DebugBreak();
		return false;
	}

	// Create pixel shader.
	pD3Ddevice->CreateVertexShader( (DWORD*)pShaderCode->GetBufferPointer(), 
		pShader );

	pShaderCode->Release();

	return true;
}
void D3D9VertexShader::Reset(LPDIRECT3DDEVICE9 Device)
{
    FreeMemory();

    HRESULT hr;

    _Device = Device;
    Assert(Device != NULL, "Device == NULL");

    _Decl.Init(Device);

    // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the 
    // shader debugger. Debugging vertex shaders requires either REF or software vertex 
    // processing, and debugging pixel shaders requires REF.  The 
    // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the 
    // shader debugger.  It enables source level debugging, prevents instruction 
    // reordering, prevents dead code elimination, and forces the compiler to compile 
    // against the next higher available software target, which ensures that the 
    // unoptimized shaders do not exceed the shader model limitations.  Setting these 
    // flags will cause slower rendering since the shaders will be unoptimized and 
    // forced into software.  See the DirectX documentation for more information about 
    // using the shader debugger.
    DWORD dwShaderFlags = 0;
    #ifdef DEBUG_VS
        dwShaderFlags |= D3DXSHADER_SKIPOPTIMIZATION|D3DXSHADER_DEBUG;
    #endif

    LPD3DXBUFFER pCode = NULL;
    LPD3DXBUFFER pErrors = NULL;

    PersistentAssert(Utility::FileExists(_ShaderFile), String(_ShaderFile) + String(" not found."));

    // Assemble the vertex shader from the file
    hr = D3DXCompileShaderFromFile( _ShaderFile.CString(), NULL, NULL, "VShaderEntry",
                                    "vs_3_0", dwShaderFlags, &pCode,
                                    &pErrors, &_ConstantTable );
    
    if(pErrors)
    {
        char *ErrorMessage = (char *)pErrors->GetBufferPointer();
        DWORD ErrorLength = pErrors->GetBufferSize();

        ofstream file("ShaderDebug.txt");
        for(UINT i = 0; i < ErrorLength; i++)
        {
            file << ErrorMessage[i];
        }
        file.close();
    }

    Assert(!FAILED(hr), "D3DXCompileShaderFromFile failed.  See ShaderDebug.txt for details.");

    // Create the vertex shader
    hr = Device->CreateVertexShader( (DWORD*)pCode->GetBufferPointer(),
                                            &_Shader );

    if(pErrors)
    {
        pErrors->Release();
    }
    if(pCode)
    {
        pCode->Release();
    }
    Assert(!FAILED(hr), "CreateVertexShader failed");
}
/**
* Render the Oculus Rift View.
***/
void* OculusRenderer::Provoke(void* pThis, int eD3D, int eD3DInterface, int eD3DMethod, DWORD dwNumberConnected, int& nProvokerIndex)	
{
	// return if wrong call
	if ((eD3D >= (int)AQU_DirectXVersion::DirectX_9_0) &&
		(eD3D <= (int)AQU_DirectXVersion::DirectX_9_29))
	{
		if (((eD3DInterface == INTERFACE_IDIRECT3DDEVICE9) &&
			(eD3DMethod == METHOD_IDIRECT3DDEVICE9_PRESENT)) || 
			((eD3DInterface == INTERFACE_IDIRECT3DDEVICE9) &&
			(eD3DMethod == METHOD_IDIRECT3DDEVICE9_ENDSCENE)) ||
			((eD3DInterface == INTERFACE_IDIRECT3DSWAPCHAIN9) &&
			(eD3DMethod == METHOD_IDIRECT3DSWAPCHAIN9_PRESENT)))
		{
			(pThis);
		}
		else return nullptr;
	}
	else
		return nullptr;

	// get input data
	if (m_paInput[(int)ORN_Decommanders::LeftTexture])
		m_pcTextureLeft = *(LPDIRECT3DTEXTURE9*)m_paInput[(int)ORN_Decommanders::LeftTexture];
	else 
		m_pcTextureLeft = nullptr;
	if (m_paInput[(int)ORN_Decommanders::RightTexture])
		m_pcTextureRight = *(LPDIRECT3DTEXTURE9*)m_paInput[(int)ORN_Decommanders::RightTexture];
	else m_pcTextureRight = nullptr;

	if (m_paInput[(int)ORN_Decommanders::DistortionVertexBufferLeft])
		if (*(LPDIRECT3DVERTEXBUFFER9**)m_paInput[(int)ORN_Decommanders::DistortionVertexBufferLeft])
			m_pcDistortionVertexBufferLeft = **(LPDIRECT3DVERTEXBUFFER9**)m_paInput[(int)ORN_Decommanders::DistortionVertexBufferLeft];
		else m_pcDistortionVertexBufferLeft = nullptr;
	else m_pcDistortionVertexBufferLeft = nullptr;
	if (m_paInput[(int)ORN_Decommanders::DistortionVertexBufferRight])
		if (*(LPDIRECT3DVERTEXBUFFER9**)m_paInput[(int)ORN_Decommanders::DistortionVertexBufferRight])
			m_pcDistortionVertexBufferRight = **(LPDIRECT3DVERTEXBUFFER9**)m_paInput[(int)ORN_Decommanders::DistortionVertexBufferRight];
		else m_pcDistortionVertexBufferRight = nullptr;
	else m_pcDistortionVertexBufferRight = nullptr;
	if (m_paInput[(int)ORN_Decommanders::DistortionIndexBufferLeft])
		if (*(LPDIRECT3DINDEXBUFFER9**)m_paInput[(int)ORN_Decommanders::DistortionIndexBufferLeft])
			m_pcDistortionIndexBufferLeft = **(LPDIRECT3DINDEXBUFFER9**)m_paInput[(int)ORN_Decommanders::DistortionIndexBufferLeft];
		else m_pcDistortionIndexBufferLeft = nullptr;
	else m_pcDistortionIndexBufferLeft = nullptr;
	if (m_paInput[(int)ORN_Decommanders::DistortionIndexBufferRight])
		if (*(LPDIRECT3DINDEXBUFFER9**)m_paInput[(int)ORN_Decommanders::DistortionIndexBufferRight])
			m_pcDistortionIndexBufferRight = **(LPDIRECT3DINDEXBUFFER9**)m_paInput[(int)ORN_Decommanders::DistortionIndexBufferRight];
		else m_pcDistortionIndexBufferRight = nullptr;
	else m_pcDistortionIndexBufferRight = nullptr;
	if (m_paInput[(int)ORN_Decommanders::OculusVertexDeclaration])
		if (*(LPDIRECT3DVERTEXDECLARATION9**)m_paInput[(int)ORN_Decommanders::OculusVertexDeclaration])
			m_pcVertexDecl = **(LPDIRECT3DVERTEXDECLARATION9**)m_paInput[(int)ORN_Decommanders::OculusVertexDeclaration];
		else m_pcVertexDecl = nullptr;
	else m_pcVertexDecl = nullptr;
	if (m_paInput[(int)ORN_Decommanders::DefaultEyeFovLeft])
		if (*(ovrFovPort**)m_paInput[(int)ORN_Decommanders::DefaultEyeFovLeft])
			m_psFOVPortLeft = *(ovrFovPort**)m_paInput[(int)ORN_Decommanders::DefaultEyeFovLeft];
		else m_psFOVPortLeft = nullptr;
	else m_psFOVPortLeft = nullptr;
	if (m_paInput[(int)ORN_Decommanders::DefaultEyeFovRight])
		if (*(ovrFovPort**)m_paInput[(int)ORN_Decommanders::DefaultEyeFovRight])
			m_psFOVPortRight = *(ovrFovPort**)m_paInput[(int)ORN_Decommanders::DefaultEyeFovRight];
		else m_psFOVPortRight = nullptr;
	else m_psFOVPortRight = nullptr;

	// get device 
	LPDIRECT3DDEVICE9 pcDevice = nullptr;
	bool bReleaseDevice = false;
	if (eD3DInterface == INTERFACE_IDIRECT3DDEVICE9)
	{
		pcDevice = (LPDIRECT3DDEVICE9)pThis;
	}
	else if (eD3DInterface == INTERFACE_IDIRECT3DSWAPCHAIN9)
	{
		LPDIRECT3DSWAPCHAIN9 pSwapChain = (LPDIRECT3DSWAPCHAIN9)pThis;
		if (!pSwapChain) 
		{
			OutputDebugString(L"Oculus Renderer Node : No swapchain !");
			return nullptr;
		}
		pSwapChain->GetDevice(&pcDevice);
		bReleaseDevice = true;
	}
	if (!pcDevice)
	{
		OutputDebugString(L"Oculus Renderer Node : No device !");
		return nullptr;
	}

	// Original code (LibOVR) :
	// pShaderCode = ShaderCompile("precompiledVertexShaderSrc",VertexShaderSrc,"vs_2_0");
	// pShaderCode = ShaderCompile("precompiledVertexShaderTimewarpSrc",VertexShaderTimewarpSrc,"vs_3_0");
	// pShaderCode = ShaderCompile("precompiledPixelShaderSrc",PixelShaderSrc,"ps_3_0");

	// pixel shader created ?
	if (!m_pcOculusPixelShader)
	{
		LPD3DXBUFFER pShader;

		// compile and create shader
		if (SUCCEEDED(D3DXCompileShader(PixelShaderSrc,strlen(PixelShaderSrc),NULL,NULL,"main","ps_3_0",NULL,&pShader,NULL,&m_pcOculusPixelShaderCT)))
		{
			OutputDebugString(L"Pixel shader compiled!");
			pcDevice->CreatePixelShader((DWORD*)pShader->GetBufferPointer(), &m_pcOculusPixelShader);
		}
	}

	// vertex shader created ?
	if (!m_pcOculusVertexShader)
	{
		LPD3DXBUFFER pShader;

		// compile and create shader
		if (SUCCEEDED(D3DXCompileShader(VertexShaderSrc,strlen(VertexShaderSrc),NULL,NULL,"main","vs_2_0",NULL,&pShader,NULL,&m_pcOculusVertexShaderCT)))
		{
			OutputDebugString(L"Vertex shader compiled!");
			pcDevice->CreateVertexShader((DWORD*)pShader->GetBufferPointer(), &m_pcOculusVertexShader);
		}
	}

	// side by side pixel shader ?
	if (!m_pcSideBySidePixelShader)
	{
		LPD3DXBUFFER pShader;

		// compile and create shader
		if (SUCCEEDED(D3DXCompileShader(PixelShaderSrcSideBySide,strlen(PixelShaderSrcSideBySide),NULL,NULL,"SBS","ps_2_0",NULL,&pShader,NULL,&m_pcSideBySidePixelShaderCT)))
		{
			OutputDebugString(L"Pixel shader compiled!");
			pcDevice->CreatePixelShader((DWORD*)pShader->GetBufferPointer(), &m_pcSideBySidePixelShader);
		}

	}

	// test textures created ?
	if ((!m_pcTextureRightTest) || (!m_pcTextureLeftTest))
	{
		HMODULE hModule = GetModuleHandle(L"OculusRenderer.dll");

		if (!m_pcTextureLeftTest)
		{
			// create a test texture
			if (SUCCEEDED(D3DXCreateTextureFromResource(pcDevice, hModule, MAKEINTRESOURCE(IMG_BACKGROUND01), &m_pcTextureLeftTest)))
				OutputDebugString(L"Texture created !");
			else m_pcTextureLeftTest = nullptr;
		}
		if (!m_pcTextureRightTest)
		{
			// create a test texture
			if (SUCCEEDED(D3DXCreateTextureFromResource(pcDevice, hModule, MAKEINTRESOURCE(IMG_BACKGROUND02), &m_pcTextureRightTest)))
				OutputDebugString(L"Texture created !");
			else m_pcTextureRightTest = nullptr;
		}
	}

	// default vertex buffer ?
	if (!m_pcVertexBufferDefault)
	{
		InitDefaultVertexBuffer(pcDevice);
		if (!m_pcVertexBufferDefault) return nullptr;
	}

	// vertex buffers ? index buffers ? not all present ?
	if ((!m_pcDistortionVertexBufferLeft) || (!m_pcDistortionVertexBufferRight) ||
		(!m_pcDistortionIndexBufferLeft) || (!m_pcDistortionIndexBufferRight) ||
		(!m_pcVertexDecl))
	{
		if (m_bBuffersConnected)
		{
			// clear all descriptions for safety
			ZeroMemory(&m_sVertexBufferDescLeft, sizeof(D3DVERTEXBUFFER_DESC));
			ZeroMemory(&m_sVertexBufferDescRight, sizeof(D3DVERTEXBUFFER_DESC));
			ZeroMemory(&m_sIndexBufferDescLeft, sizeof(D3DINDEXBUFFER_DESC));
			ZeroMemory(&m_sIndexBufferDescRight, sizeof(D3DINDEXBUFFER_DESC));

			m_bBuffersConnected = false;
		}
	}
	else
	{
		m_bBuffersConnected = true;

		// vertex buffer description ? left
		if (!m_sVertexBufferDescLeft.Size)
			m_pcDistortionVertexBufferLeft->GetDesc(&m_sVertexBufferDescLeft);

		// vertex buffer length matches oculus vertex type ?
		if ((m_sVertexBufferDescLeft.Size % sizeof(ovrDistortionVertex)) != 0)
		{
			OutputDebugString(L"OculusRenderer Node : Connected vertex buffer size mismatch !");
			return nullptr;
		}

		// and right
		if (!m_sVertexBufferDescRight.Size)
			m_pcDistortionVertexBufferRight->GetDesc(&m_sVertexBufferDescRight);

		// vertex buffer length matches oculus vertex type ?
		if ((m_sVertexBufferDescRight.Size % sizeof(ovrDistortionVertex)) != 0)
		{
			OutputDebugString(L"OculusRenderer Node : Connected vertex buffer size mismatch !");
			return nullptr;
		}

		// index buffer ?
		if ((!m_pcDistortionIndexBufferLeft) || (!m_pcDistortionIndexBufferRight))
			return nullptr;

		// index buffer description ?
		if (!m_sIndexBufferDescLeft.Size)
		{
			m_pcDistortionIndexBufferLeft->GetDesc(&m_sIndexBufferDescLeft);

			// index buffer length matches vertex buffer size ? TODO !!
			/*if ()
			{
			OutputDebugString(L"OculusRenderer Node : Connected index buffer size mismatch !");
			return nullptr;
			}*/
		}
		if (!m_sIndexBufferDescRight.Size)
		{
			m_pcDistortionIndexBufferRight->GetDesc(&m_sIndexBufferDescRight);

			// index buffer length matches vertex buffer size ? TODO !!
			/*if ()
			{
			OutputDebugString(L"OculusRenderer Node : Connected index buffer size mismatch !");
			return nullptr;
			}*/
		}
	}

	// start to render
	pcDevice->BeginScene();

	// save states
	IDirect3DStateBlock9* pStateBlock = nullptr;
	pcDevice->CreateStateBlock(D3DSBT_ALL, &pStateBlock);

	// set ALL render states to default
	SetAllRenderStatesDefault(pcDevice);

	// set states
	pcDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
	pcDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
	pcDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
	pcDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_CONSTANT);
	pcDevice->SetTextureStageState(0, D3DTSS_CONSTANT, 0xffffffff);
	pcDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
	pcDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
	pcDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
	pcDevice->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, 0);
	pcDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
	pcDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
	pcDevice->SetSamplerState(0, D3DSAMP_ADDRESSW, D3DTADDRESS_CLAMP);
	pcDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC);
	pcDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC);
	pcDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);

	D3DCOLOR clearColor = D3DCOLOR_RGBA(0, 0, 0, 0);

	pcDevice->Clear(0, NULL, D3DCLEAR_TARGET, clearColor, 0, 0);

	// required fields
	D3DSURFACE_DESC sSurfaceDesc;
	ovrSizei sTextureSize;
	ovrRecti sRenderViewport;
	ovrVector2f UVScaleOffset[2];

	// LEFT EYE :

	// left eye, first set stream source, indices
	if (m_bBuffersConnected)
	{
		// no timewarp here, use standard vertex shader, set pixel shader, set vertex declaration
		pcDevice->SetVertexShader( m_pcOculusVertexShader);
		pcDevice->SetPixelShader( m_pcOculusPixelShader );
		pcDevice->SetVertexDeclaration( m_pcVertexDecl );

		// set texture
		if (m_pcTextureLeft)
			pcDevice->SetTexture( 0, m_pcTextureLeft );
		else if (m_pcTextureLeftTest)
			pcDevice->SetTexture( 0, m_pcTextureLeftTest );
		else pcDevice->SetTexture( 0, 0);

		// get texture size
		if (m_pcTextureLeft)
			m_pcTextureLeft->GetLevelDesc(0, &sSurfaceDesc);
		else if (m_pcTextureLeftTest)
			m_pcTextureLeftTest->GetLevelDesc(0, &sSurfaceDesc);
		else ZeroMemory(&sSurfaceDesc, sizeof(D3DSURFACE_DESC));
		sTextureSize.w = (int)sSurfaceDesc.Width;
		sTextureSize.h = (int)sSurfaceDesc.Height;

		// set render viewport size the same size as the texture size (!)
		sRenderViewport.Pos.x = 0;
		sRenderViewport.Pos.y = 0;
		sRenderViewport.Size.w = sTextureSize.w;
		sRenderViewport.Size.h = sTextureSize.h;

		// get and set scale and offset
		if (m_psFOVPortLeft)
			ovrHmd_GetRenderScaleAndOffset(*m_psFOVPortLeft, sTextureSize, sRenderViewport, UVScaleOffset);
		else
			ovrHmd_GetRenderScaleAndOffset(m_sDefaultFOVPortLeft, sTextureSize, sRenderViewport, UVScaleOffset);
		pcDevice->SetVertexShaderConstantF( 0, ( FLOAT* )&UVScaleOffset[0], 1 );
		pcDevice->SetVertexShaderConstantF( 2, ( FLOAT* )&UVScaleOffset[1], 1 );

		pcDevice->SetStreamSource( 0, m_pcDistortionVertexBufferLeft,0, sizeof(ovrDistortionVertex) );
		pcDevice->SetIndices( m_pcDistortionIndexBufferLeft);

		// draw
		pcDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST,0,0, m_sVertexBufferDescLeft.Size / sizeof(ovrDistortionVertex) , 0, m_sIndexBufferDescLeft.Size / 6 );
	}
	else
	{
		pcDevice->SetSamplerState(1, D3DSAMP_SRGBTEXTURE, 0);
		pcDevice->SetSamplerState(1, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
		pcDevice->SetSamplerState(1, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
		pcDevice->SetSamplerState(1, D3DSAMP_ADDRESSW, D3DTADDRESS_CLAMP);
		pcDevice->SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC);
		pcDevice->SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC);
		pcDevice->SetSamplerState(1, D3DSAMP_MIPFILTER, D3DTEXF_NONE);

		// side by side render
		pcDevice->SetVertexShader(NULL);
		pcDevice->SetPixelShader(m_pcSideBySidePixelShader);
		pcDevice->SetVertexDeclaration( NULL );
		pcDevice->SetFVF(D3DFVF_TEXVERTEX);

		// set textures
		if (m_pcTextureLeft)
			pcDevice->SetTexture( 0, m_pcTextureLeft );
		else if (m_pcTextureLeftTest)
			pcDevice->SetTexture( 0, m_pcTextureLeftTest );
		else pcDevice->SetTexture( 0, 0);
		if (m_pcTextureRight)
			pcDevice->SetTexture( 1, m_pcTextureRight );
		else if (m_pcTextureRightTest)
			pcDevice->SetTexture( 1, m_pcTextureRightTest );
		else pcDevice->SetTexture( 1, 0);

		// set stream and draw
		pcDevice->SetStreamSource( 0, m_pcVertexBufferDefault,0, sizeof(TEXVERTEX) );
		pcDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2);
	}

	// RIGHT EYE:
	if (m_bBuffersConnected)
	{
		// set texture
		if (m_pcTextureRight)
			pcDevice->SetTexture( 0, m_pcTextureRight );
		else if (m_pcTextureRightTest)
			pcDevice->SetTexture( 0, m_pcTextureRightTest );
		else pcDevice->SetTexture( 0, 0);

		// get texture size
		if (m_pcTextureRight)
			m_pcTextureRight->GetLevelDesc(0, &sSurfaceDesc);
		else if (m_pcTextureRightTest)
			m_pcTextureRightTest->GetLevelDesc(0, &sSurfaceDesc);
		else ZeroMemory(&sSurfaceDesc, sizeof(D3DSURFACE_DESC));
		sTextureSize.w = (int)sSurfaceDesc.Width;
		sTextureSize.h = (int)sSurfaceDesc.Height;

		// get and set scale and offset
		if (m_psFOVPortRight)
			ovrHmd_GetRenderScaleAndOffset(*m_psFOVPortRight, sTextureSize, sRenderViewport, UVScaleOffset);
		else
			ovrHmd_GetRenderScaleAndOffset(m_sDefaultFOVPortRight, sTextureSize, sRenderViewport, UVScaleOffset);
		pcDevice->SetVertexShaderConstantF( 0, ( FLOAT* )&UVScaleOffset[0], 1 );
		pcDevice->SetVertexShaderConstantF( 2, ( FLOAT* )&UVScaleOffset[1], 1 );

		// set stream source, indices, draw
		pcDevice->SetStreamSource( 0, m_pcDistortionVertexBufferRight,0, sizeof(ovrDistortionVertex) );
		pcDevice->SetIndices( m_pcDistortionIndexBufferRight);

		// draw
		pcDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST,0,0, m_sVertexBufferDescRight.Size / sizeof(ovrDistortionVertex) , 0, m_sIndexBufferDescRight.Size / 6 );
	}

	pcDevice->EndScene();

	// apply and release state block
	if (pStateBlock)
	{
		pStateBlock->Apply();
		pStateBlock->Release();
	}

	// release device if provided by swapchain
	if (bReleaseDevice) pcDevice->Release();

	return nullptr;
}
Beispiel #11
0
//=============================================================================
// 初期化
//=============================================================================
HRESULT CMeshField::Init(LPDIRECT3DDEVICE9 pDevice,int nType, D3DXVECTOR3 pos, D3DXVECTOR3 rot,
								int nNumBlockX, int nNumBlockZ, float fSizeBlockX, float fSizeBlockZ)
{
	m_pDevice=pDevice;

	// ブロック数の設定
	m_nNumBlockX = nNumBlockX;
	m_nNumBlockZ = nNumBlockZ;

	// 頂点数の設定
	m_nNumVertex = (nNumBlockX + 1) * (nNumBlockZ + 1);

	// インデックス数の設定
	m_nNumVertexIndex = (nNumBlockX + 1) * 2 * nNumBlockZ + (nNumBlockZ - 1) * 2;

	// ポリゴン数の設定
	m_nNumPolygon = nNumBlockX * nNumBlockZ * 2 + (nNumBlockZ - 1) * 4;

	// ブロックサイズの設定
	m_fSizeBlockX = fSizeBlockX;
	m_fSizeBlockZ = fSizeBlockZ;

	// テクスチャの読み込み
	m_texid = m_apTexture[nType];
	//D3DXCreateTextureFromFile(m_pDevice,m_apTextureName[nType],&m_pD3DTex);

	//フィールドの初期化
	m_Pos = pos;
	m_Rot = rot;
	m_Scl = D3DXVECTOR3(1.0f,1.0f,1.0f);

	// オブジェクトの頂点バッファを生成
	if(FAILED(m_pDevice->CreateVertexBuffer(sizeof(VERTEX_3D)*m_nNumVertex,
											D3DUSAGE_WRITEONLY,
											FVF_VERTEX_3D,
											D3DPOOL_MANAGED,
											&m_pD3DVtxBuff,
											NULL)))
	{
		return E_FAIL;
	}

	// オブジェクトのインデックスバッファを生成
	if(FAILED(m_pDevice->CreateIndexBuffer(sizeof(WORD)*m_nNumVertexIndex,
											D3DUSAGE_WRITEONLY,
											D3DFMT_INDEX16,
											D3DPOOL_MANAGED,
											&m_pD3DIndexBuff,
											NULL)))
	{
		return E_FAIL;
	}

	// 法線算出用バッファ確保
	m_pBuffNormal = new D3DXVECTOR3 [(m_nNumBlockX * 2) * m_nNumBlockZ];

	{//頂点バッファの中身を埋める
		VERTEX_3D *pVtx;
		const float texSizeX = 1.0f;
		const float texSizeZ = 1.0f;

		// 頂点データの範囲をロックし、頂点バッファへのポインタを取得
		m_pD3DVtxBuff->Lock(0, 0, (void**)&pVtx, 0);

		for(int nCntVtxZ = 0; nCntVtxZ < (m_nNumBlockZ + 1); nCntVtxZ++)
		{
			for(int nCntVtxX = 0; nCntVtxX < (m_nNumBlockX + 1); nCntVtxX++)
			{
				// 頂点座標の設定
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].vtx.x = -(m_nNumBlockX / 2.0f) * m_fSizeBlockX + nCntVtxX * m_fSizeBlockX;
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].vtx.z = (m_nNumBlockZ / 2.0f) * m_fSizeBlockZ - nCntVtxZ * m_fSizeBlockZ;

				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].vtx.y = HIGHT_MAP[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX];

				// 反射光の設定
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);

				// テクスチャ座標の設定
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].tex.x = texSizeX * nCntVtxX;
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].tex.y = texSizeZ * nCntVtxZ;
			}
		}

		// 頂点データをアンロックする
		m_pD3DVtxBuff->Unlock();
	}

	{// 法線の算出
		VERTEX_3D *pVtx;

		// 頂点データの範囲をロックし、頂点バッファへのポインタを取得
		m_pD3DVtxBuff->Lock(0, 0, (void**)&pVtx, 0);

		D3DXVECTOR3 *pNor = m_pBuffNormal;
		for(int nCntVtxZ = 0; nCntVtxZ < m_nNumBlockZ; nCntVtxZ++)
		{
			for(int nCntVtxX = 0; nCntVtxX < m_nNumBlockX; nCntVtxX++)
			{
				// 法線の設定
				D3DXVECTOR3 v0,v1,v2;
				D3DXVECTOR3 normal;
				D3DXVECTOR3 *pVtx0,*pVtx1,*pVtx2;

				pVtx0 = &pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].vtx;
				pVtx1 = &pVtx[(nCntVtxZ + 1) * (m_nNumBlockX + 1) + nCntVtxX].vtx;
				pVtx2 = &pVtx[(nCntVtxZ + 1) * (m_nNumBlockX + 1) + nCntVtxX + 1].vtx;

				v0.x = pVtx1->x - pVtx2->x;
				v0.y = pVtx1->y - pVtx2->y;
				v0.z = pVtx1->z - pVtx2->z;
				v1.x = pVtx0->x - pVtx2->x;
				v1.y = pVtx0->y - pVtx2->y;
				v1.z = pVtx0->z - pVtx2->z;

				D3DXVec3Cross(&v2, &v0, &v1);
				D3DXVec3Normalize(&normal, &v2);

				*pNor = normal;
				pNor++;

				pVtx0 = &pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].vtx;
				pVtx1 = &pVtx[(nCntVtxZ + 1) * (m_nNumBlockX + 1) + nCntVtxX + 1].vtx;
				pVtx2 = &pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX + 1].vtx;

				v0.x = pVtx1->x - pVtx2->x;
				v0.y = pVtx1->y - pVtx2->y;
				v0.z = pVtx1->z - pVtx2->z;
				v1.x = pVtx0->x - pVtx2->x;
				v1.y = pVtx0->y - pVtx2->y;
				v1.z = pVtx0->z - pVtx2->z;
				D3DXVec3Cross(&v2, &v0, &v1);
				D3DXVec3Normalize(&normal, &v2);

				*pNor = normal;
				pNor++;
			}
		}

		// 頂点データをアンロックする
		m_pD3DVtxBuff->Unlock();
	}

	{//頂点バッファの中身を埋める
		VERTEX_3D *pVtx;

		// 頂点データの範囲をロックし、頂点バッファへのポインタを取得
		m_pD3DVtxBuff->Lock(0, 0, (void**)&pVtx, 0);

		D3DXVECTOR3 *pNor = m_pBuffNormal;
		for(int nCntVtxZ = 0; nCntVtxZ < (m_nNumBlockZ + 1); nCntVtxZ++)
		{
			for(int nCntVtxX = 0; nCntVtxX < (m_nNumBlockX + 1); nCntVtxX++)
			{
				// 法線の設定
				D3DXVECTOR3 normal;
				D3DXVECTOR3 norAvg0, norAvg1;

				if(nCntVtxZ == 0)
				{
					if(nCntVtxX == 0)
					{
						normal = (pNor[0] + pNor[1]) / 2;
					}
					else if(nCntVtxX == m_nNumBlockX)
					{
						normal = pNor[m_nNumBlockX * 2 - 1];
					}
					else
					{
						norAvg0 = (pNor[nCntVtxX * 2] + pNor[nCntVtxX * 2 + 1]) / 2;
						normal = (pNor[nCntVtxX * 2 - 1] + norAvg0) / 2;
					}
				}
				else if(nCntVtxZ == m_nNumBlockZ)
				{
					if(nCntVtxX == 0)
					{
						normal = pNor[(m_nNumBlockZ - 1) * m_nNumBlockX * 2];
					}
					else if(nCntVtxX == m_nNumBlockX)
					{
						normal = (pNor[m_nNumBlockZ * m_nNumBlockX * 2 - 2] + pNor[m_nNumBlockZ * m_nNumBlockX * 2 - 1]) / 2;
					}
					else
					{
						norAvg0 = (pNor[(m_nNumBlockZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 2] + pNor[(m_nNumBlockZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 1]) / 2;
						normal = (norAvg0 + pNor[(m_nNumBlockZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2]) / 2;
					}
				}
				else
				{
					if(nCntVtxX == 0)
					{
						norAvg0 = (pNor[nCntVtxZ * m_nNumBlockX * 2] + pNor[nCntVtxZ * m_nNumBlockX * 2 + 1]) / 2;
						normal = (pNor[(nCntVtxZ - 1) * m_nNumBlockX * 2] + norAvg0) / 2;
					}
					else if(nCntVtxX == m_nNumBlockX)
					{
						norAvg0 = (pNor[(nCntVtxZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 1] + pNor[(nCntVtxZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 2]) / 2;
						normal = (norAvg0 + pNor[nCntVtxZ * m_nNumBlockX * 2 + nCntVtxX * 2 - 1]) / 2;
					}
					else
					{
						int nIdx0 = (nCntVtxZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 2;
						int nIdx1 = (nCntVtxZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 1;
						int nIdx2 = (nCntVtxZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2;
						int nIdx3 = nCntVtxZ * m_nNumBlockX * 2 + nCntVtxX * 2 - 1;
						int nIdx4 = nCntVtxZ * m_nNumBlockX * 2 + nCntVtxX * 2;
						int nIdx5 = nCntVtxZ * m_nNumBlockX * 2 + nCntVtxX * 2 + 1;

						norAvg0 = (pNor[nIdx0] + pNor[nIdx1]) / 2;
						norAvg1 = (pNor[nIdx4] + pNor[nIdx5]) / 2;
						normal = (norAvg0 + pNor[nIdx2] + pNor[nIdx3] + norAvg1) / 4;
					}
				}

				D3DXVec3Normalize(&normal, &normal);
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].nor = normal;
			}
		}

		// 頂点データをアンロックする
		m_pD3DVtxBuff->Unlock();
	}

	{//インデックスバッファの中身を埋める
		WORD *pIdx;

		// インデックスデータの範囲をロックし、頂点バッファへのポインタを取得
		m_pD3DIndexBuff->Lock(0, 0, (void**)&pIdx, 0);

		int nCntIdx = 0;
		for(int nCntVtxZ = 0; nCntVtxZ < m_nNumBlockZ; nCntVtxZ++)
		{
			if(nCntVtxZ > 0)
			{// 縮退ポリゴンのためのダブりの設定
				pIdx[nCntIdx] = (nCntVtxZ + 1) * (m_nNumBlockX + 1) + 0;
				nCntIdx++;
			}

			for(int nCntVtxX = 0; nCntVtxX < (m_nNumBlockX + 1); nCntVtxX++)
			{
				pIdx[nCntIdx] = (nCntVtxZ + 1) * (m_nNumBlockX + 1) + nCntVtxX;
				nCntIdx++;
				pIdx[nCntIdx] = nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX;
				nCntIdx++;
			}

			if(nCntVtxZ < (m_nNumBlockZ - 1))
			{// 縮退ポリゴンのためのダブりの設定
				pIdx[nCntIdx] = nCntVtxZ * (m_nNumBlockX + 1) + m_nNumBlockX;
				nCntIdx++;
			}
		}

		// インデックスデータをアンロックする
		m_pD3DIndexBuff->Unlock();
	}

	HRESULT hr;
	LPD3DXBUFFER err;
	LPD3DXBUFFER code;

	//ピクセルシェーダー用に変換
	hr = D3DXCompileShaderFromFile("source/shader/basicPS.hlsl", NULL, NULL, "PS_SHADOW", "ps_2_0", 0, &code, &err, &_psc);

	if (FAILED(hr))
	{
		MessageBox(NULL, (LPCSTR)err->GetBufferPointer(), "D3DXCompileShaderFromFile", MB_OK);
		err->Release();
		return false;
	}
	//シェーダーの登録
	hr = pDevice->CreatePixelShader((DWORD*)code->GetBufferPointer(), &_ps);

	if (FAILED(hr))
	{
		MessageBox(NULL, "FAILED", "CreatePixelShader", MB_OK);
		return false;
	}

	//バーテックスシェーダー用に変換1
	hr = D3DXCompileShaderFromFile("source/shader/basicVS.hlsl", NULL, NULL, "VS_SHADOW", "vs_2_0", 0, &code, &err, &_vsc[0]);
	if (FAILED(hr))
	{
		MessageBox(NULL, (LPCSTR)err->GetBufferPointer(), "D3DXCompileShaderFromFile", MB_OK);
		err->Release();
		return false;
	}
	//シェーダーの登録
	hr = pDevice->CreateVertexShader((DWORD*)code->GetBufferPointer(), &_vs[0]);
	if (FAILED(hr))
	{
		MessageBox(NULL, "FAILED", "CreateVertexShader", MB_OK);
		return false;
	}

	//バーテックスシェーダー用に変換1
	hr = D3DXCompileShaderFromFile("source/shader/basicVS.hlsl", NULL, NULL, "VS", "vs_2_0", 0, &code, &err, &_vsc[1]);
	if (FAILED(hr))
	{
		MessageBox(NULL, (LPCSTR)err->GetBufferPointer(), "D3DXCompileShaderFromFile", MB_OK);
		err->Release();
		return false;
	}
	//シェーダーの登録
	hr = pDevice->CreateVertexShader((DWORD*)code->GetBufferPointer(), &_vs[1]);
	if (FAILED(hr))
	{
		MessageBox(NULL, "FAILED", "CreateVertexShader", MB_OK);
		return false;
	}

	// マテリアルの設定
	m_material.Ambient = D3DXCOLOR(0.25f, 0.25f, 0.25f, 1.0f);
	m_material.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
	m_material.Emissive = D3DXCOLOR(0, 0, 0, 0);
	m_material.Specular = D3DXCOLOR(0, 0, 0, 0);
	m_material.Power = 2.0f;

	return S_OK;
}
Beispiel #12
0
	bool CShaderHLSL::Create(P3D::sShaderDesc &desc)
	{
		const char *pData;
		ULONG fsize;
		IFileSystem* pFS = CRenderer::mEngine()->mFilesystem();
		wchar path[P3DMAX_PATH];
		wsprintf(path, P3DMAX_PATH-1, _W("shaders/%s.rshader"), desc.ShaderFile.Get());
		FSFILE *fp = pFS->Load(path, (BYTE *&)pData, fsize, true);
		if (!fp)
		{
			CON(MSG_ERR, _W("Can't open %s.hlsl shader file from data/shaders directory!"), desc.ShaderFile.Get());
			return false;
		}

		ID3DXBuffer *pShaderBlob = NULL;
		ID3DXBuffer *pErrors = NULL;
		DWORD flags = D3DXSHADER_DEBUG;  //D3DXSHADER_OPTIMIZATION_LEVEL3

		char profile[128];
		switch(desc.ShaderType)
		{
		case SHADERTYPE_VERTEX_SHADER:
			strcpy(profile, D3DXGetVertexShaderProfile(g_pD3ddev));
			break;
		case SHADERTYPE_PIXEL_SHADER:
			strcpy(profile, D3DXGetPixelShaderProfile(g_pD3ddev));
			break;
		case SHADERTYPE_GEOMETRY_SHADER:
			CON(MSG_ERR, _W("DX9 does not support geometry shaders."));
			return false;
		default:
			CON(MSG_ERR, _W("Chader creation failed. No apropriate ShaderType given."));
			return false;
		}

		CIncludeHandler includeHandler;
		
		D3DXMACRO Shader_Macros[] = 
		{
			{ "DX9", NULL },
			{ "SM3", NULL },
			NULL
		};

		if(FAILED(D3DXCompileShader(
			pData, 
			fsize, 
			Shader_Macros, 
			&includeHandler, 
			_W2A(desc.EntryFunction.Get()), 
			profile, 
			flags,
			&pShaderBlob, 
			&pErrors,
			&m_pConstTable
			)))
		{
			if(pErrors) CON(MSG_ERR, _W("%s"), _A2W((char*)pErrors->GetBufferPointer()));
			else CON(MSG_ERR, _W("Error description not given"));
			CON(MSG_ERR, _W("Shader %s could not be compiled"), desc.ShaderFile.Get());
			SAFE_RELEASE(pErrors);
			return false;
		}

		pFS->UnLoad(fp, (BYTE *)pData);

		//save to cache
		fp = pFS->Open(_W("cache/shaders/hlsl"), _W("wb"));
		const char* cs = (const char*)pShaderBlob->GetBufferPointer();
		pFS->Write(cs, 1, pShaderBlob->GetBufferSize(), fp);
		pFS->Close(fp);

		bool shaderCreated = false;
		switch(desc.ShaderType)
		{
		case SHADERTYPE_VERTEX_SHADER:
			shaderCreated = SUCCEEDED(g_pD3ddev->CreateVertexShader((const DWORD*)pShaderBlob->GetBufferPointer(), &m_pVS));
			break;
		case SHADERTYPE_PIXEL_SHADER:
			shaderCreated = SUCCEEDED(g_pD3ddev->CreatePixelShader((const DWORD*)pShaderBlob->GetBufferPointer(), &m_pPS));
			break;
		}

		if(!shaderCreated)
		{
			CON(MSG_ERR, _W("Shader creation error"));
			return false;
		}

		//set constant to their default values 
		m_pConstTable->SetDefaults(g_pD3ddev);

		//create vertex declaration
		if(desc.ShaderType == SHADERTYPE_VERTEX_SHADER)
			m_pVertDecl = new CVertexDeclaration(CRenderer::cGraphicsManager()->GetVertexDescByID(desc.VertexDescID), pShaderBlob);

		SAFE_RELEASE(pShaderBlob);

		m_desc = desc;

		CON(MSG_INFO, _W("Shader '%s' created"), desc.ShaderFile);

		return true;
	}
Beispiel #13
0
void CompileShaders() {
	ID3DXBuffer* pShaderCode = NULL;
	ID3DXBuffer* pErrorMsg = NULL;
	HRESULT hr = -1;

#ifdef _XBOX

	// Compile vertex shader.
	hr = D3DXCompileShader( vscode, 
		(UINT)strlen( vscode ),
		NULL, 
		NULL, 
		"main", 
		"vs_2_0", 
		0, 
		&pShaderCode, 
		&pErrorMsg,
		NULL );
#endif 

	if( FAILED(hr) )
	{
		OutputDebugStringA((CHAR*)pErrorMsg->GetBufferPointer());
		DebugBreak();
	}

	// Create pixel shader.
	pD3Ddevice->CreateVertexShader( (DWORD*)pShaderCode->GetBufferPointer(), 
		&pFramebufferVertexShader );

	pShaderCode->Release();

#ifdef _XBOX
	// Compile pixel shader.
	hr = D3DXCompileShader( pscode, 
		(UINT)strlen( pscode ),
		NULL, 
		NULL, 
		"main", 
		"ps_2_0", 
		0, 
		&pShaderCode, 
		&pErrorMsg,
		NULL );
#endif

	if( FAILED(hr) )
	{
		OutputDebugStringA((CHAR*)pErrorMsg->GetBufferPointer());
		DebugBreak();
	}

	// Create pixel shader.
	pD3Ddevice->CreatePixelShader( (DWORD*)pShaderCode->GetBufferPointer(), 
		&pFramebufferPixelShader );

	pShaderCode->Release();

	pD3Ddevice->CreateVertexDeclaration( VertexElements, &pFramebufferVertexDecl );
	pD3Ddevice->SetVertexDeclaration( pFramebufferVertexDecl );

	pD3Ddevice->CreateVertexDeclaration( SoftTransVertexElements, &pSoftVertexDecl );
}
bool CVertexShader::LoadVariant( IShaderDefines *pDefines, bool bCompile )
{
	// check for already compiled default version of the shader
	if (pDefines == NULL && m_VertexShader != NULL)
		return true;
	// check for already compiled variant of the shader
	if (pDefines != NULL)
	{
		unsigned long iEncoding = pDefines->GetValuesEncoding().iEncoding;
		SHADERVARIANTSMAP::iterator itr = m_ShaderVariants.find( iEncoding );
		if (itr != m_ShaderVariants.end())
			return true;
	}

	D3DXMACRO *pMacros = NULL;
	if (pDefines)
	{
		const int iMaxShaderDefineCount = 32;
		const int iValueCharSize = 64;
		static char szValues[iMaxShaderDefineCount][iValueCharSize];
		static D3DXMACRO vMacros[iMaxShaderDefineCount + 1];
		if (iMaxShaderDefineCount < pDefines->GetDefineCount())
		{
			m_ToolBox->Log( LOGFATALERROR, _T("Shader Define Count exceeds the internal buffer!\n") );
			return false;
		}

		DWORD i;
		for (i=0; i < pDefines->GetDefineCount(); i++)
		{
			vMacros[i].Name = pDefines->GetDefineName(i);
			vMacros[i].Definition = _itoa(pDefines->GetDefineValue(i), szValues[i], 10);
		}
		// null terminate macro list
		vMacros[i].Name = NULL;
		vMacros[i].Definition = NULL;
		pMacros = vMacros;
	}

	LPDIRECT3DVERTEXSHADER9 pShader = NULL;
	LPD3DXBUFFER shaderBuf = NULL;
	LPD3DXBUFFER pErrorMsgs = NULL;
	CDX9IncludeManager includeInterface;
	LPDIRECT3DDEVICE9 pDevice = (LPDIRECT3DDEVICE9)m_Renderer->GetAPIDevice();
	if( pDevice )
	{
		int len = _tcslen( (const TCHAR*)m_Code );
		LPCSTR profile = D3DXGetVertexShaderProfile( pDevice );

		bool bLoadedCompiled = false;
		HRESULT hr = E_FAIL;

		const TCHAR *szFile = GetName()->GetString();
		TCHAR drive[MAX_PATH];
		TCHAR directory[MAX_PATH];
		TCHAR filename[MAX_PATH];
		TCHAR fileext[MAX_PATH];
		TCHAR szDefinesTemp[65] = { '\0' };
		_tsplitpath( szFile, drive, directory, filename, fileext );

		StdString szCompiledFile;
		szCompiledFile += drive;
		szCompiledFile += directory;
		szCompiledFile += _T("Compiled\\");
		szCompiledFile += filename;
		if (pDefines)
		{
			szCompiledFile += _T("_enc");
			szCompiledFile += _itot(pDefines->GetValuesEncoding().iEncoding, szDefinesTemp, 10);
		}
		szCompiledFile += fileext;
#ifdef XBOX
		szCompiledFile = SetPathDrive( szCompiledFile, EngineGetToolBox()->GetDrive() );
#endif

		LPVOID pShaderFileData = NULL;
		UINT shaderLen = 0;
		struct _stat shaderFilestat;
		// checking if compiled version exists, if we can load it into a buffer and if the file stats of the shader (not compiled) are readable
		if (CheckFileExists(szCompiledFile) &&	( _tstat( szFile, &shaderFilestat ) == 0) && LoadFileIntoBuffer( szCompiledFile, pShaderFileData, shaderLen, true ))
		{
			m_ToolBox->Log( LOGINFORMATION, _T("Reading compiled shader file: %s\n"), szCompiledFile.c_str() );
			// create a shader buffer to store the compiled shader
			hr = D3DXCreateBuffer( shaderLen, &shaderBuf );
			if (SUCCEEDED(hr))
			{
				time_t storedMTime = 0;
				// get the compiled date out of the file
				memcpy( &storedMTime, pShaderFileData, sizeof(time_t) );
			
				// if the stored modified time in the compiled shader file is the same as the current
				// modified time of the shader file
				if( storedMTime == shaderFilestat.st_mtime )
				{
					// reduce the buffer size by the preamble (mod time)
					shaderLen -= (int)sizeof(time_t);
						
					// copy the compiled shader into the shader buffer
					memcpy( shaderBuf->GetBufferPointer(), ((TCHAR *) pShaderFileData)+ sizeof(time_t), shaderLen);
					bLoadedCompiled = true;
				}
			}
			SAFE_DELETE_ARRAY( pShaderFileData );
		}

		if (!bLoadedCompiled && bCompile)
		{
			if (pDefines)
				EngineGetToolBox()->Log( LOGINFORMATION, _T("Compiling shader %s:%d\n"), GetName()->GetString(), pDefines->GetValuesEncoding().iEncoding );
			else
				EngineGetToolBox()->Log( LOGINFORMATION, _T("Compiling shader %s\n"), GetName()->GetString() );

			hr = D3DXCompileShader( m_Code,
										len,//length of string in bytes
										pMacros, //can add that matrix of macros here
										&includeInterface, //for include directories
										"main",//? temp
										profile, //vs_1_1 for example
										0, //compiling options?
										&shaderBuf,
										&pErrorMsgs,
										NULL );
		}

		//now actually create the shader
		if( hr == D3D_OK &&
			shaderBuf )
		{
			if (!bLoadedCompiled)
			{
				struct _stat shaderFilestat;
				// get the shader file's modified time
				if (_tstat( szFile, &shaderFilestat ) == 0)
				{
					m_ToolBox->Log( LOGINFORMATION, _T("Writing compiled shader file: %s\n"), szCompiledFile.c_str() );
					// open a compiled shader file for writing
					FILE *fp = fopen( szCompiledFile, "wb" );
					if (fp)
					{
						// write shader file's modified time
						fwrite( &shaderFilestat.st_mtime, sizeof(time_t), 1, fp );
						// write compiled shader data
						fwrite( shaderBuf->GetBufferPointer(), shaderBuf->GetBufferSize(), 1, fp );
						fclose(fp);
					}
					else
					{
						m_ToolBox->Log( LOGWARNING, _T("Failed to write compiled shader file: %s\n"), szCompiledFile.c_str() );
					}
				}
			}

			hr = pDevice->CreateVertexShader( (DWORD *) shaderBuf->GetBufferPointer(), &pShader );
			assert( SUCCEEDED(hr) );
			if (!SUCCEEDED(hr))
			{
				m_ToolBox->Log( LOGWARNING, _T("Failed to create shader : %s\n"), szCompiledFile.c_str() );
			}

			SAFE_RELEASE( shaderBuf );
			SAFE_RELEASE( pErrorMsgs );

			if (pDefines == NULL) // we are compiling the default shader with no macro defines
			{
				assert( m_VertexShader == NULL ); // the default shader should only be compiled on Init when this is NULL
				m_VertexShader = pShader;
			}
			else if (pDefines != NULL) // we are compiling a variant of the shader
			{
				unsigned long iEncoding = pDefines->GetValuesEncoding().iEncoding;
				m_ShaderVariants[iEncoding] = pShader;
			}
			return true;
		}
	}	
	if( pErrorMsgs )
	{
		IHashString * name = GetName();
		TCHAR* debug_errors = (TCHAR*)pErrorMsgs->GetBufferPointer();
		m_ToolBox->Log( LOGERROR, _T("Could not create Vertex shader %s\nError message: %s\n"),
			name->GetString(), debug_errors );				
		SAFE_RELEASE( pErrorMsgs );				
	}
	SAFE_RELEASE( shaderBuf );

	return false;
}
Beispiel #15
0
//-----------------------------------------------------------------------------
// Name: InitD3D()
// Desc: Initializes Direct3D
//-----------------------------------------------------------------------------
HRESULT InitD3D( HWND hWnd )
{
	// Create the D3D object.
	if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
		return E_FAIL;

	// Set up the structure used to create the D3DDevice. Since we are now
	// using more complex geometry, we will create a device with a zbuffer.
	D3DPRESENT_PARAMETERS d3dpp; 
	ZeroMemory( &d3dpp, sizeof(d3dpp) );
	d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
	d3dpp.EnableAutoDepthStencil = TRUE;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

	// Create the D3DDevice
	if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
		D3DCREATE_SOFTWARE_VERTEXPROCESSING,
		&d3dpp, &g_pd3dDevice ) ) )
	{
		return E_FAIL;
	}

	// Turn on the zbuffer
	g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
	//Turn off culling, so we see the front and back of the triangle
	g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
	g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE );
	g_pd3dDevice->LightEnable( 0, TRUE );
	g_pd3dDevice->SetRenderState(D3DRS_SPECULARENABLE, TRUE);
	g_pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0xffffffff );


	////VS TUTORIAL STUFF

	LPD3DXBUFFER pCode;                  // Buffer with the assembled shader code				////VS TUTORIAL STUFF
	// This is our error buffer
	LPD3DXBUFFER pErrorMsgs = 0;             // Buffer with error messages							////VS TUTORIAL STUFF


	for ( int i = 0;  i < maxShaders;  i++ ) // load all the shader files
	{
		if(FAILED(D3DXAssembleShaderFromFile( shaders[i].c_str(),  NULL, NULL, 0,					////VS TUTORIAL STUFF
			&pCode, &pErrorMsgs )))	{   
				// Error(s) have occured.   
				// Allocate a character buffer the size of the ID3DXBuffer  
				if(pErrorMsgs != 0) {
					char* data = new char[pErrorMsgs->GetBufferSize()];   
					// Copy the buffer data over   
					memcpy( data, pErrorMsgs->GetBufferPointer(), pErrorMsgs->GetBufferSize() );   
					// Open a file and output the error string(s)   
					FILE* file;
					fopen_s(&file,"errors.txt", "w" );   
					fprintf( file, "%s", data );   
					fclose( file );   
					// Release allocated objects   
					delete[] data;   
					pErrorMsgs->Release();   
					MessageBox(hWnd,L"see errors.txt",L"vertex assemble problem",NULL);
				}
				return E_FAIL;
		}

		switch ( i )	// create the vertex shader and assosiate it with the proper variable
		{
			case 0 :	g_pd3dDevice->CreateVertexShader((DWORD*)pCode->GetBufferPointer(),	&g_pVertexShader);
			case 1 :	g_pd3dDevice->CreateVertexShader((DWORD*)pCode->GetBufferPointer(),	&g_pVertexShader2);
			case 2 :	g_pd3dDevice->CreateVertexShader((DWORD*)pCode->GetBufferPointer(),	&g_pVertexShader3);
			case 3 :	g_pd3dDevice->CreateVertexShader((DWORD*)pCode->GetBufferPointer(),	&g_pVertexShader4);
			case 4 :	g_pd3dDevice->CreateVertexShader((DWORD*)pCode->GetBufferPointer(),	&g_pVertexShader5);
			case 5 :	g_pd3dDevice->CreateVertexShader((DWORD*)pCode->GetBufferPointer(),	&g_pVertexShader6);
		}
		pCode->Release();
	}



	cameraPos.x = 0.0f;
	cameraPos.y = 15.0f;
	cameraPos.z = 20.0f;

	lightPos.x = -10.0f;
	lightPos.y = 0.0f;
	lightPos.z = 3.0f;



	return S_OK;
}