Ejemplo n.º 1
0
		bool ShadowMappingShader::SetShaderParameters(D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix,
			D3DXMATRIX projectionMatrix, D3DXMATRIX lightViewMatrix, D3DXMATRIX lightProjectionMatrix,
			ID3D11ShaderResourceView* texture, ID3D11ShaderResourceView* depthMapTexture, D3DXVECTOR3 lightPosition,
			D3DXVECTOR4 ambientColor, D3DXVECTOR4 diffuseColor)
		{
			HRESULT result;
			D3D11_MAPPED_SUBRESOURCE mappedResource;
			unsigned int bufferNumber;
			MatrixBufferType* dataPtr;
			LightBufferType* dataPtr2;
			LightBufferType2* dataPtr3;


			// Transpose the matrices to prepare them for the shader.
			D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
			D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
			D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

			D3DXMatrixTranspose(&lightViewMatrix, &lightViewMatrix);
			D3DXMatrixTranspose(&lightProjectionMatrix, &lightProjectionMatrix);

			ID3D11DeviceContext* deviceContext = GraphicsDX::GetDeviceContext();

			// Lock the constant buffer so it can be written to.
			result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
			if (FAILED(result))
			{
				return false;
			}

			// Get a pointer to the data in the constant buffer.
			dataPtr = (MatrixBufferType*)mappedResource.pData;

			// Copy the matrices into the constant buffer.
			dataPtr->world = worldMatrix;
			dataPtr->view = viewMatrix;
			dataPtr->projection = projectionMatrix;

			dataPtr->lightView = lightViewMatrix;
			dataPtr->lightProjection = lightProjectionMatrix;

			// Unlock the constant buffer.
			deviceContext->Unmap(m_matrixBuffer, 0);

			// Set the position of the constant buffer in the vertex shader.
			bufferNumber = 0;

			// Now set the constant buffer in the vertex shader with the updated values.
			deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);

			// Set shader texture resource in the pixel shader.
			deviceContext->PSSetShaderResources(0, 1, &texture);

			deviceContext->PSSetShaderResources(1, 1, &depthMapTexture);

			// Lock the light constant buffer so it can be written to.
			result = deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
			if (FAILED(result))
			{
				return false;
			}

			// Get a pointer to the data in the constant buffer.
			dataPtr2 = (LightBufferType*)mappedResource.pData;

			// Copy the lighting variables into the constant buffer.
			dataPtr2->ambientColor = ambientColor;
			dataPtr2->diffuseColor = diffuseColor;

			// Unlock the constant buffer.
			deviceContext->Unmap(m_lightBuffer, 0);

			// Set the position of the light constant buffer in the pixel shader.
			bufferNumber = 0;

			// Finally set the light constant buffer in the pixel shader with the updated values.
			deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_lightBuffer);

			// Lock the second light constant buffer so it can be written to.
			result = deviceContext->Map(m_lightBuffer2, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
			if (FAILED(result))
			{
				return false;
			}

			// Get a pointer to the data in the constant buffer.
			dataPtr3 = (LightBufferType2*)mappedResource.pData;

			// Copy the lighting variables into the constant buffer.
			dataPtr3->lightPosition = lightPosition;
			dataPtr3->padding = 0.0f;

			// Unlock the constant buffer.
			deviceContext->Unmap(m_lightBuffer2, 0);

			// Set the position of the light constant buffer in the vertex shader.
			bufferNumber = 1;

			// Finally set the light constant buffer in the pixel shader with the updated values.
			deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_lightBuffer2);

			return true;
		}
Ejemplo n.º 2
0
void CLcXSkinIns::Render()
{
	HRESULT hr=-1;

	LPDIRECT3DDEVICE9 pDev = (LPDIRECT3DDEVICE9)LcDev_GetD3Device();


	CLcXSkinSrc*	pOrg = (CLcXSkinSrc*)m_pOrg;

	ID3DXEffect*	pEft	= pOrg->GetEffect();

	// Setup the projection matrix
	D3DXMATRIX matProj;
	pDev->GetTransform(D3DTS_PROJECTION, &matProj);




	D3DLIGHT9 light;
	D3DXVECTOR3 vecLightDirUnnormalized(0.0f, -1.0f, 1.0f);
	ZeroMemory( &light, sizeof(D3DLIGHT9) );
	light.Type        = D3DLIGHT_DIRECTIONAL;
	light.Diffuse.r   = 1.0f;
	light.Diffuse.g   = 1.0f;
	light.Diffuse.b   = 1.0f;
	D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecLightDirUnnormalized );
	light.Position.x   = 0.0f;
	light.Position.y   = -1.0f;
	light.Position.z   = 1.0f;
	light.Range        = 1000.0f;

	pDev->SetLight(0, &light );
	pDev->LightEnable(0, TRUE );
	
	
	// Set Light for vertex shader
	D3DXVECTOR4 vLightDir( 0.0f, 1.0f, -1.0f, 0.0f );
	D3DXVec4Normalize( &vLightDir, &vLightDir );
	
	
	// for HLSL
	{
		pEft->SetMatrix( "mViewProj", &matProj);
		pEft->SetVector( "lhtDir", &vLightDir);
	}
	
	
	
	// for shader
	{
		// set the projection matrix for the vertex shader based skinning method
		D3DXMatrixTranspose(&matProj, &matProj);
		pDev->SetVertexShaderConstantF(2, (float*)&matProj, 4);
		pDev->SetVertexShaderConstantF(1, (float*)&vLightDir, 1);
	}

	if(m_pAC)
		m_pAC->AdvanceTime(m_fElapse, NULL);

	pOrg->UpdateFrameMatrices(m_pFrameOrg, &m_mtWld);	
	pOrg->DrawFrame(m_pFrameOrg);

	static	D3DXMATRIX	mtI(1,0,0,0,  0,1,0,0,  0,0,1,0,  0,0,0,1);
	pDev->SetTransform(D3DTS_WORLD, &mtI);
}
bool TerrainShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, 
											 D3DXMATRIX projectionMatrix, D3DXVECTOR4 ambientColor, D3DXVECTOR4 diffuseColor, D3DXVECTOR3 lightDirection)
{
	HRESULT result;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
	unsigned int bufferNumber;
	MatrixBufferType* dataPtr;
	LightBufferType* dataPtr2;


	// Transpose the matrices to prepare them for the shader.
	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

	// Lock the constant buffer so it can be written to.
	result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr = (MatrixBufferType*)mappedResource.pData;

	// Copy the matrices into the constant buffer.
	dataPtr->world = worldMatrix;
	dataPtr->view = viewMatrix;
	dataPtr->projection = projectionMatrix;

	// Unlock the constant buffer.
    deviceContext->Unmap(m_matrixBuffer, 0);

	// Set the position of the constant buffer in the vertex shader.
	bufferNumber = 0;

	// Now set the constant buffer in the vertex shader with the updated values.
    deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);

	// Lock the light constant buffer so it can be written to.
	result = deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr2 = (LightBufferType*)mappedResource.pData;

	// Copy the lighting variables into the constant buffer.
	dataPtr2->ambientColor = ambientColor;
	dataPtr2->diffuseColor = diffuseColor;
	dataPtr2->lightDirection = lightDirection;
	dataPtr2->padding = 0.0f;

	// Unlock the constant buffer.
	deviceContext->Unmap(m_lightBuffer, 0);

	// Set the position of the light constant buffer in the pixel shader.
	bufferNumber = 0;

	// Finally set the light constant buffer in the pixel shader with the updated values.
	deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_lightBuffer);

	return true;
}
Ejemplo n.º 4
0
Matrix Matrix::transpose(const Matrix& matrix)
{
	return *D3DXMatrixTranspose(&tmp, &matrix);
}
Ejemplo n.º 5
0
/** Draws the visual for the given vob */
void GSkeletalMeshVisual::DrawVisual(const RenderInfo& info)
{
	GVisual::DrawVisual(info);

	// Draw the mesh using immediate states
	int n=0;
	for(auto it = VisualInfo.SkeletalMeshes.begin();it != VisualInfo.SkeletalMeshes.end(); it++)
	{
		D3DXMATRIX world; D3DXMatrixTranspose(&world, info.WorldMatrix);

		std::vector<SkeletalMeshInfo*>& meshes = (*it).second;
		for(int i=0;i<meshes.size();i++)
		{
			if(ImmediatePipelineStates[n]->BaseState.TextureIDs[0] == 0xFFFF)
			{
				// Only draw if the texture is loaded
				if((*it).first->GetTexture() && (*it).first->GetTexture()->CacheIn(0.6f) != zRES_CACHED_IN)
				{
					n++;
					continue;
				}

				// Get texture ID if everything is allright
				if((*it).first &&
					(*it).first->GetTexture() &&
					(*it).first->GetTexture()->GetSurface() &&
					(*it).first->GetTexture()->GetSurface()->GetEngineTexture())
				{
					ImmediatePipelineStates[n]->BaseState.TextureIDs[0] = (*it).first->GetTexture()->GetSurface()->GetEngineTexture()->GetID();

					// Get Alphatest
					if((*it).first->GetAlphaFunc() > 1 || (*it).first->GetTexture()->HasAlphaChannel())
						ImmediatePipelineStates[n]->BaseState.TranspacenyMode = PipelineState::ETransparencyMode::TM_MASKED;

					Engine::GraphicsEngine->SetupPipelineForStage(STAGE_DRAW_SKELETAL, ImmediatePipelineStates[n]);
				}
			}

			// Clone the state for this mesh
			PipelineState* transientState = Engine::GraphicsEngine->CreatePipelineState(ImmediatePipelineStates[n]);
			transientState->TransientState = true;

			// Input instanceCB and our bones
			transientState->BaseState.ConstantBuffersVS[1] = info.InstanceCB;
			transientState->BaseState.ConstantBuffersVS[2] = BoneConstantBuffer;

			Engine::GraphicsEngine->FillPipelineStateObject(transientState);

			// Push to renderlist
			Engine::GraphicsEngine->PushPipelineState(transientState);

			n++;
		}
	}

	return;
#ifndef DEBUG_DRAW_VISUALS
	return;
#endif

	std::vector<D3DXMATRIX> trans = *BoneTransforms;
	for(int i=0;i<trans.size();i++)
		D3DXMatrixTranspose(&trans[i], &trans[i]);

	// Debug draw the mesh as line-wireframe
	for(auto it = VisualInfo.SkeletalMeshes.begin();it != VisualInfo.SkeletalMeshes.end(); it++)
	{
		D3DXMATRIX world; D3DXMatrixTranspose(&world, info.WorldMatrix);

		std::vector<SkeletalMeshInfo*>& meshes = (*it).second;
		for(int i=0;i<meshes.size();i++)
		{
			std::vector<VERTEX_INDEX>& indices = meshes[i]->Indices;
			std::vector<ExSkelVertexStruct>& vertices = meshes[i]->Vertices;

			for(int i=0;i<indices.size();i+=3)
			{
				D3DXVECTOR3 vx[3];
				for(int v=0;v<3;v++)
				{
					D3DXVECTOR3 position = D3DXVECTOR3(0,0,0);
					ExSkelVertexStruct& input = vertices[indices[i + v]];
					for(int i=0;i<4;i++)
					{
						D3DXVECTOR3 bp; D3DXVec3TransformCoord(&bp, input.Position[i].toD3DXVECTOR3(), &trans[input.boneIndices[i]]);

						position += input.weights[i] * bp;
					}

					D3DXVec3TransformCoord(&position, &position, &world);

					vx[v] = position;				
				}

				// Don't draw too far
				if(D3DXVec3Length(&(vx[0] - Engine::GAPI->GetCameraPosition())) > 2400)
					continue;

				Engine::GraphicsEngine->GetLineRenderer()->AddTriangle(vx[0], vx[1], vx[2], D3DXVECTOR4(1,0,0,1));
			}

			//Engine::GraphicsEngine->GetLineRenderer()->AddWireframeMesh(meshes[i]->Vertices, meshes[i]->Indices, D3DXVECTOR4(0,1,0,1), &world);
		}
	}
}
Ejemplo n.º 6
0
void RobotArmDemo::drawScene()
{
	// Clear the backbuffer and depth buffer.
	HR(gd3dDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0));

	HR(gd3dDevice->BeginScene());

	HR(mFX->SetValue(mhLight, &mLight, sizeof(DirLight)));
	
	HR(mFX->SetTechnique(mhTech));
	UINT numPasses = 0;
	HR(mFX->Begin(&numPasses, 0));
	HR(mFX->BeginPass(0));

	// Build the world transforms for each bone, then render them.
	buildBoneWorldTransforms();
	D3DXMATRIX T;
	D3DXMatrixTranslation(&T, -NUM_BONES, 0.0f, 0.0f);
	for(int i = 0; i < NUM_BONES; ++i)
	{
		// Append the transformation with a slight translation to better
		// center the skeleton at the center of the scene.
		mWorld = mBones[i].toWorldXForm * T;
		HR(mFX->SetMatrix(mhWVP, &(mWorld*mView*mProj)));
		D3DXMATRIX worldInvTrans;
		D3DXMatrixInverse(&worldInvTrans, 0, &mWorld);
		D3DXMatrixTranspose(&worldInvTrans, &worldInvTrans);
		HR(mFX->SetMatrix(mhWorldInvTrans, &worldInvTrans));
		HR(mFX->SetMatrix(mhWorld, &mWorld));
		for(int j = 0; j < mMtrl.size(); ++j)
		{
			HR(mFX->SetValue(mhMtrl, &mMtrl[j], sizeof(Mtrl)));
		
			// If there is a texture, then use.
			if(mTex[j] != 0)
			{
				HR(mFX->SetTexture(mhTex, mTex[j]));
			}

			// But if not, then set a pure white texture.  When the texture color
			// is multiplied by the color from lighting, it is like multiplying by
			// 1 and won't change the color from lighting.
			else
			{
				HR(mFX->SetTexture(mhTex, mWhiteTex));
			}
		
			HR(mFX->CommitChanges());
			HR(mBoneMesh->DrawSubset(j));
		}
	}

	HR(mFX->EndPass());
	HR(mFX->End());
	
	mGfxStats->display();

	HR(gd3dDevice->EndScene());

	// Present the backbuffer.
	HR(gd3dDevice->Present(0, 0, 0, 0));
}
bool SpecularMapShader::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix, 
					     D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, 
					     ID3D11ShaderResourceView** textureArray, D3DXVECTOR3 lightDirection, 
					     D3DXVECTOR4 diffuseColor, D3DXVECTOR3 cameraPosition, D3DXVECTOR4 specularColor,
					     float specularPower)
{
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	MatrixBufferType* dataPtr;
	unsigned int bufferNumber;
	LightBufferType* dataPtr2;
	CameraBufferType* dataPtr3;

	// Transpose the matrices to prepare them for the shader.
	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

	// Lock the matrix constant buffer so it can be written to.
	result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr = (MatrixBufferType*)mappedResource.pData;

	// Copy the matrices into the constant buffer.
	dataPtr->world = worldMatrix;
	dataPtr->view = viewMatrix;
	dataPtr->projection = projectionMatrix;

	// Unlock the matrix constant buffer.
	deviceContext->Unmap(m_matrixBuffer, 0);

	// Set the position of the matrix constant buffer in the vertex shader.
	bufferNumber = 0;

	// Now set the matrix constant buffer in the vertex shader with the updated values.
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);

	// Set shader texture array resource in the pixel shader.
	deviceContext->PSSetShaderResources(0, 3, textureArray);

	// Lock the light constant buffer so it can be written to.
	result = deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr2 = (LightBufferType*)mappedResource.pData;

	// Copy the lighting variables into the constant buffer.
	dataPtr2->diffuseColor = diffuseColor;
	dataPtr2->lightDirection = lightDirection;
	dataPtr2->specularColor = specularColor;
	dataPtr2->specularPower = specularPower;

	// Unlock the constant buffer.
	deviceContext->Unmap(m_lightBuffer, 0);

	// Set the position of the light constant buffer in the pixel shader.
	bufferNumber = 0;

	// Finally set the light constant buffer in the pixel shader with the updated values.
	deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_lightBuffer);

	// Lock the camera constant buffer so it can be written to.
	result = deviceContext->Map(m_cameraBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr3 = (CameraBufferType*)mappedResource.pData;

	// Copy the camera position into the constant buffer.
	dataPtr3->cameraPosition = cameraPosition;

	// Unlock the matrix constant buffer.
	deviceContext->Unmap(m_cameraBuffer, 0);

	// Set the position of the camera constant buffer in the vertex shader as the second buffer.
	bufferNumber = 1;

	// Now set the matrix constant buffer in the vertex shader with the updated values.
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_cameraBuffer);

	return true;
}
Ejemplo n.º 8
0
void EngineMain::drawScene()
{
	// Clear the backbuffer and depth buffer.
	HR(g_d3dDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0));
	
	HR(g_d3dDevice->BeginScene());

	D3DXMATRIX wVPM = camera.GetView()*camera.GetProjection();



	// Setup the rendering FX
	Shaders::BasicFX->SetDirectionalLight(&m_DirLight);
	Shaders::BasicFX->m_FX->SetTechnique(Shaders::BasicFX->m_hTech);
	// Begin passes.
	UINT numPasses = 0;


	Shaders::BasicFX->m_FX->Begin(&numPasses, 0);
	Shaders::BasicFX->m_FX->BeginPass(0);
	skull->DrawModel(wVPM);
	dwarf->DrawModel(wVPM);
	tiny->DrawModel(wVPM);

	Shaders::BasicFX->m_FX->EndPass();
	Shaders::BasicFX->m_FX->End();

	// Animation Passes //
	Shaders::VBlendFX->SetDirectionalLight(&m_DirLight);
	//HR(Shaders::VBlendFX->m_FX->SetValue(Shaders::VBlendFX->m_hLight, &m_DirLight, sizeof(DirectionalLight))); 
	Shaders::VBlendFX->m_FX->SetTechnique(Shaders::VBlendFX->m_hTech);
	numPasses = 0;
	Shaders::VBlendFX->m_FX->Begin(&numPasses, 0);
	Shaders::VBlendFX->m_FX->BeginPass(0);


	//tiny->draw(wVPM);

	Shaders::VBlendFX->m_FX->EndPass();
	Shaders::VBlendFX->m_FX->End();
	// End //

	#pragma region Draw Grid
	HR(mFX->SetTechnique(mhTech));

	HR(mFX->SetMatrix(mhWVP, &wVPM));
	D3DXMATRIX worldInvTrans;
	D3DXMatrixInverse(&worldInvTrans, 0, &m_World);
	D3DXMatrixTranspose(&worldInvTrans, &worldInvTrans);
	HR(mFX->SetMatrix(mhWorldInvTrans, &worldInvTrans));
	HR(mFX->SetValue(mhLightVecW, &mLightVecW, sizeof(D3DXVECTOR3)));
	HR(mFX->SetValue(mhDiffuseMtrl, &mDiffuseMtrl, sizeof(D3DXCOLOR)));
	HR(mFX->SetValue(mhDiffuseLight, &mDiffuseLight, sizeof(D3DXCOLOR)));
	HR(mFX->SetValue(mhAmbientMtrl, &mAmbientMtrl, sizeof(D3DXCOLOR)));
	HR(mFX->SetValue(mhAmbientLight, &mAmbientLight, sizeof(D3DXCOLOR)));
	HR(mFX->SetValue(mhSpecularLight, &mSpecularLight, sizeof(D3DXCOLOR)));
	HR(mFX->SetValue(mhSpecularMtrl, &mSpecularMtrl, sizeof(D3DXCOLOR)));
	HR(mFX->SetFloat(mhSpecularPower, mSpecularPower));
	HR(mFX->SetMatrix(mhWorld, &m_World));
	HR(mFX->SetTexture(mhTex, mGroundTex));

	HR(g_d3dDevice->SetVertexDeclaration(VertexPNT::Decl));
	HR(g_d3dDevice->SetStreamSource(0, mGridVB, 0, sizeof(VertexPNT)));
	HR(g_d3dDevice->SetIndices(mGridIB));

	// Begin passes.
	numPasses = 0;
	HR(mFX->Begin(&numPasses, 0));
	for(UINT i = 0; i < numPasses; ++i)
	{
		HR(mFX->BeginPass(i));
		HR(g_d3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, mNumGridVertices, 0, mNumGridTriangles));
		HR(mFX->EndPass());
	}
	HR(mFX->End());

#pragma endregion

	m_GfxStats->display();

	HR(g_d3dDevice->EndScene());

	// Present the backbuffer.
	HR(g_d3dDevice->Present(0, 0, 0, 0));
}
Ejemplo n.º 9
0
bool CD3DMGEng::DrawText3D ( float x, float y, float z, D3DMATRIX * pMatView, DWORD dwColor, const TCHAR *wszText,  float fTextSize, FONTFLAGS ffFlags, FONTSET fsSet )
{
    D3DSPRITEVERTEX3D * pVertices = NULL;
    D3DXMATRIX          MatWorld, MatView, MatTranslation, MatTransposed;
    DWORD               dwTriangleCount = 0;
    float               fStartX = 0;

    ////////////////////////////////////////////////////
    // Make sure we have a valid vertex buffer.
    if ( m_pVB == NULL )
    {
        return false;
    }

    ////////////////////////////////////////////////////
    // Make sure our texture and coords are loaded.
    if ( m_pFontTexture == NULL || m_bFontInfoLoaded == false )
    {
        return false;
    }

    ///////////////////////////////////////////////////
    // Setup the rendering.
    // Convert our view matrix from D3DMATRIX to D3DXMATRIX
    MatView = *pMatView;
    D3DXMatrixTranspose ( &MatTransposed, &MatView );
    
    // Create an Inverse matrix out of the view matrix (go from view to world space).
    MatTransposed._41 = MatTransposed._42 = 
        MatTransposed._43 = MatTransposed._14 = 
        MatTransposed._24 = MatTransposed._34 = 0.0f;

    // Create an empty identity matrix.
    D3DXMatrixIdentity ( &MatWorld );

    // Add in our scaling here.
    float fSize = fTextSize / 100.0f;
    D3DXMatrixScaling ( &MatWorld, fSize, fSize, fSize );

    // Set position of text in world.
    D3DXMatrixTranslation ( &MatTranslation, x, y, z );

    // Apply settings to new world matrix.
    D3DXMatrixMultiply ( &MatWorld, &MatWorld, &MatTransposed );
    D3DXMatrixMultiply ( &MatWorld, &MatWorld, &MatTranslation );

    m_pDevice->SetFVF ( D3DFVF_SPRITEVERTEX3DTEX );
    m_pDevice->SetStreamSource ( 0, m_pVB, 0, sizeof(D3DSPRITEVERTEX3D) );
    m_pDevice->SetTexture ( 0, m_pFontTexture );
    m_pDevice->SetTransform ( D3DTS_WORLD, &MatWorld );

    x = 0;
    y = 0;

    ///////////////////////////////////////////////////
    // Do flag processing before we go any further.
    if ( ffFlags )
    {
        SIZE sz;

        // First, get extent of drawn text.
        UTIL_GetTextExtent(wszText, &sz, fTextSize);

        // Do math on x coordinate accordingly.
        switch ( ffFlags )
        {
        case D3DFF_CENTERED:
            x -= sz.cx/2;
            break;
        case D3DFF_RIGHT:
            x += sz.cx;
            break;
        case D3DFF_LEFT:
            //x += sz.cx/2;
            break;
        default:
            break;
        }
    } 
        
    
    fStartX = x;
    m_pVB->Lock( 0, 0, (void**)&pVertices, D3DLOCK_DISCARD );
    while ( *wszText )
    {
        TCHAR c = *wszText++;

        if ( c == _T('\n') )
        {
            x = fStartX;
            y += m_aFontCoords[fsSet].fHeight;
            continue;
        }

        if ( c < _T(' ') || c > _T(128) )
        {
            continue;
        }

        float tx1 = m_aFontCoords[fsSet+c-32].tx1;
        float tx2 = m_aFontCoords[fsSet+c-32].tx2;
        float ty1 = m_aFontCoords[fsSet+c-32].ty1;
        float ty2 = m_aFontCoords[fsSet+c-32].ty2;
        float   w = m_aFontCoords[fsSet+c-32].fWidth;
        float   h = m_aFontCoords[fsSet+c-32].fHeight;

        if ( c == _T(' ') )
        {
            x += w;
            continue;
        }

        // First triangle  (bottom right)
        *pVertices++ = InitFont3DVertex ( x+w, y+h, 0.0f, dwColor, tx2, ty1 ); //bottom right.
        *pVertices++ = InitFont3DVertex ( x+w,   y, 0.0f, dwColor, tx2, ty2 ); //top right.
        *pVertices++ = InitFont3DVertex ( x,   y+h, 0.0f, dwColor, tx1, ty1 ); //bottom left.

        // Second triangle (upper left)
        *pVertices++ = InitFont3DVertex ( x,     y, 0.0f, dwColor, tx1, ty2 ); //top left.
        *pVertices++ = InitFont3DVertex ( x+w,   y, 0.0f, dwColor, tx2, ty2 ); //top right.
        *pVertices++ = InitFont3DVertex ( x,   y+h, 0.0f, dwColor, tx1, ty1 ); //bottom right. 
                                            
        x += w;
        dwTriangleCount += 2;

        ////////////////////////////////////////////////////
        // If we've gone over our limit, draw what we have.
        if ( dwTriangleCount*3 >= D3DSPRITE_NUMVERTS-6 )
        {
            m_pVB->Unlock();
            m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwTriangleCount );
            m_pVB->Lock( 0, 0, (void**)&(pVertices=NULL), D3DLOCK_DISCARD );
            dwTriangleCount = 0L;
        }
    }
    m_pVB->Unlock();


    ////////////////////////////////////////////////////
    // Draw if we have anything.
    if ( dwTriangleCount > 0 )
    {
        m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwTriangleCount );
    }
    return true;
}
Ejemplo n.º 10
0
void Matrix::setTranspose( const Matrix& mat ){
	D3DXMATRIX a;
	D3DXMatrixTranspose( &a, &D3DXMATRIX((float*)&mat.m ) );
	m.set( a );
}
bool ReflectionShader::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, 
						D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* colorTexture, 
						ID3D11ShaderResourceView* normalTexture, D3DXVECTOR4 lightDiffuseColor, D3DXVECTOR3 lightDirection, 
						float colorTextureBrightness, D3DXVECTOR4 clipPlane)
{
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	unsigned int bufferNumber;
	MatrixBufferType* dataPtr;
	ClipPlaneBufferType* dataPtr1;
	LightBufferType* dataPtr2;


	// Transpose the matrices to prepare them for the shader.
	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

	// Lock the constant buffer so it can be written to.
	result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr = (MatrixBufferType*)mappedResource.pData;

	// Copy the matrices into the constant buffer.
	dataPtr->world = worldMatrix;
	dataPtr->view = viewMatrix;
	dataPtr->projection = projectionMatrix;

	// Unlock the constant buffer.
	deviceContext->Unmap(m_matrixBuffer, 0);

	// Set the position of the constant buffer in the vertex shader.
	bufferNumber = 0;

	// Now set the constant buffer in the vertex shader with the updated values.
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
	
	// Lock the clip plane constant buffer so it can be written to.
	result = deviceContext->Map(m_clipPlaneBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the clip plane constant buffer.
	dataPtr1 = (ClipPlaneBufferType*)mappedResource.pData;

	// Copy the clip plane into the clip plane constant buffer.
	dataPtr1->clipPlane = clipPlane;

	// Unlock the buffer.
	deviceContext->Unmap(m_clipPlaneBuffer, 0);

	// Set the position of the clip plane constant buffer in the vertex shader.
	bufferNumber = 1;

	// Now set the clip plane constant buffer in the vertex shader with the updated values.
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_clipPlaneBuffer);
	
	// Lock the light constant buffer so it can be written to.
	result = deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr2 = (LightBufferType*)mappedResource.pData;

	// Copy the lighting variables into the constant buffer.
	dataPtr2->lightDiffuseColor = lightDiffuseColor;
	dataPtr2->lightDirection = lightDirection;
	dataPtr2->colorTextureBrightness = colorTextureBrightness;

	// Unlock the constant buffer.
	deviceContext->Unmap(m_lightBuffer, 0);

	// Set the position of the light constant buffer in the pixel shader.
	bufferNumber = 0;

	// Finally set the light constant buffer in the pixel shader with the updated values.
	deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_lightBuffer);

	// Set the texture resources in the pixel shader.
	deviceContext->PSSetShaderResources(0, 1, &colorTexture);
	deviceContext->PSSetShaderResources(1, 1, &normalTexture);

	return true;
}
Ejemplo n.º 12
0
	void Ground::Render() {
		GetDevice()->SetFVF(D3DFVF_GROUNDCUSTOMVERTEX);

		// TODO: 행렬 계산
		D3DXMATRIXA16	MatWorld;
		D3DXMATRIXA16	MatTrans;
		D3DXMATRIXA16	MatScale;
		D3DXMATRIXA16	MatRotate;
		D3DXVECTOR3		LookPt = mPosition + mFrontVector;

		D3DXMatrixIdentity(&MatWorld);

		//프론트 백터의 값에 따라 회전
		D3DXMatrixLookAtLH(&MatRotate, &mPosition, &LookPt, &mUpVec);
		//뷰행렬을 가져왔기 때문에 로테이션한 것처럼 행렬을 변환할 필요가 있다.
		//뷰행렬은 자신이 움직이는 것이 아닌 자신을 제외한 모든 좌표들이 움직이도록 되어있는 행렬이다.
		//(카메라의 좌표계에 맞춰져있다)
		//뷰행렬의 역행렬은 transpose해준 형태와 동일하다.
		MatRotate._41 = MatRotate._42 = MatRotate._43 = 0.f;
		D3DXMatrixTranspose(&MatRotate, &MatRotate);

		D3DXMatrixTranslation(&MatTrans, mPosition.x, mPosition.y, mPosition.z);
		D3DXMatrixScaling(&MatScale, mScaleVec.x, mScaleVec.y, mScaleVec.z);

		MatWorld = MatScale*MatRotate*MatTrans;

		//mDevice->SetTransform(D3DTS_WORLD, &MatWorld);

		D3DXMATRIXA16 g_matProj;
		D3DXMATRIXA16 matView;

		mDevice->GetTransform(D3DTS_VIEW, &matView);
		mDevice->GetTransform(D3DTS_PROJECTION, &g_matProj);
		D3DXMatrixMultiply(&matView, &matView, &g_matProj);

		mEffect->SetTechnique("t1");
		mEffect->SetMatrix("mWorld", &MatWorld);
		mEffect->SetMatrix("mViewProj", &matView);

		mEffect->SetTexture("mTexture", mGroundTexture);
		mEffect->SetTexture("mAlphaMap", mAlphaMap);
		mEffect->SetTexture("mTexture2", mSandTexture);

		//디바이스에 버텍스버퍼를 전달
		GetDevice()->SetStreamSource(0, mVertexBuffer, 0, sizeof(GROUND_CUSTOM_VERTEX));

		//인덱스 설정
		GetDevice()->SetIndices(mIndexBuffer);	
		//GetDevice()->SetTexture(0, mGroundTexture);

		UINT cPasses;
		mEffect->Begin(&cPasses, 0);
		for (UINT p = 0; p < cPasses; ++p) {
			mEffect->BeginPass(p);
			GetDevice()->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, mVertexCount, 0, mIndexCount);
			mEffect->EndPass();
		}
		mEffect->End();

		
	}
Ejemplo n.º 13
0
bool PureLightShader::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, 
										   D3DXMATRIX projectionMatrix, D3DXVECTOR3 lightDirection, D3DXVECTOR4 ambientColor, D3DXVECTOR4 diffuseColor, D3DXVECTOR3 cameraPosition, D3DXVECTOR4 specularColor, 
					   float specularPower, float deltavalue)
{
	HRESULT result;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
	unsigned int bufferNumber;
	MatrixBufferType* dataPtr;
	LightBufferType* dataPtr2;
	VariableBufferType* dataPtr3;
	CameraBufferType* dataPtr4;


	// Transpose the matrices to prepare them for the shader.
	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

	// Lock the constant buffer so it can be written to.
	result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr = (MatrixBufferType*)mappedResource.pData;

	// Copy the matrices into the constant buffer.
	dataPtr->world = worldMatrix;
	dataPtr->view = viewMatrix;
	dataPtr->projection = projectionMatrix;

	// Unlock the constant buffer.
    deviceContext->Unmap(m_matrixBuffer, 0);

	// Set the position of the constant buffer in the vertex shader.
	bufferNumber = 0;

	// Now set the constant buffer in the vertex shader with the updated values.
    deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);

	//VARIABLE BUFFER
	result = deviceContext->Map(m_variableBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr3 = (VariableBufferType*)mappedResource.pData;

	// Copy the variablethe constant buffer.
	dataPtr3->delta = deltavalue;
	dataPtr3->padding =lightDirection; //this is just padding so this data isnt used.

	// Unlock the variable constant buffer.
	deviceContext->Unmap(m_variableBuffer, 0);

	// Set the position of the variable constant buffer in the vertex shader.
	bufferNumber = 1;

	// Now set the variable constant buffer in the vertex shader with the updated values.
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_variableBuffer);

	//END VARIABLE BUFFER

	// Lock the camera constant buffer so it can be written to.
	result = deviceContext->Map(m_cameraBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr4 = (CameraBufferType*)mappedResource.pData;

	// Copy the camera position into the constant buffer.
	dataPtr4->cameraPosition = cameraPosition;
	dataPtr4->padding1 = 0.0f;

	// Unlock the camera constant buffer.
	deviceContext->Unmap(m_cameraBuffer, 0);

	// Set the position of the camera constant buffer in the vertex shader.
	bufferNumber = 1;

	// Now set the camera constant buffer in the vertex shader with the updated values.
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_cameraBuffer);

	// Lock the light constant buffer so it can be written to.
	result = deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr2 = (LightBufferType*)mappedResource.pData;

	// Copy the lighting variables into the constant buffer.
	dataPtr2->ambientColor = ambientColor;
	dataPtr2->diffuseColor = diffuseColor;
	dataPtr2->lightDirection = lightDirection;
	dataPtr2->specularColor = specularColor;
	dataPtr2->specularPower = specularPower;

	// Unlock the constant buffer.
	deviceContext->Unmap(m_lightBuffer, 0);

	// Set the position of the light constant buffer in the pixel shader.
	bufferNumber = 0;

	// Finally set the light constant buffer in the pixel shader with the updated values.
	deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_lightBuffer);

	return true;
}
Ejemplo n.º 14
0
void CNameTags::Draw()
{
	if(!bbfont) 
	{ 
		bbfont = new CBBFont(m_pD3DDevice, "vcpfnt");
		bbfont->Initialise(); 
	} 

	if(!BarOldStateBlock) 
	{ 
		m_pD3DDevice->BeginStateBlock(); 
		m_pD3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE); 
		m_pD3DDevice->SetRenderState(D3DRS_FOGENABLE, FALSE); 
		m_pD3DDevice->SetRenderState(D3DRS_ZENABLE, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_FILLMODE, 3); 
		m_pD3DDevice->SetRenderState(D3DRS_CULLMODE, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_WRAP0, 0); 
		m_pD3DDevice->SetRenderState(D3DRS_CLIPPING, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_VERTEXBLEND, 0); 
		m_pD3DDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, 0); 
		m_pD3DDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 15); 
		m_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_SRCBLEND, 5); 
		m_pD3DDevice->SetRenderState(D3DRS_DESTBLEND, 6); 
		m_pD3DDevice->SetRenderState(D3DRS_BLENDOP, 1); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, 4); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, 2); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_COLORARG2, 0); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, 4); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, 2); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, 0); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, 0); 
		m_pD3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, 1); 
		m_pD3DDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); 
		m_pD3DDevice->SetVertexShader(D3DFVF_XYZ|D3DFVF_DIFFUSE); 
		m_pD3DDevice->SetStreamSource(0, NULL, 0); 
		m_pD3DDevice->EndStateBlock(&BarOldStateBlock); 
	} 

	if(!BarNewStateBlock) 
	{ 
		m_pD3DDevice->BeginStateBlock(); 
		m_pD3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE); 
		m_pD3DDevice->SetRenderState(D3DRS_FOGENABLE, FALSE); 
		m_pD3DDevice->SetRenderState(D3DRS_ZENABLE, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_FILLMODE, 3); 
		m_pD3DDevice->SetRenderState(D3DRS_CULLMODE, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_WRAP0, 0); 
		m_pD3DDevice->SetRenderState(D3DRS_CLIPPING, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_VERTEXBLEND, 0); 
		m_pD3DDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, 0); 
		m_pD3DDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 15); 
		m_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_SRCBLEND, 5); 
		m_pD3DDevice->SetRenderState(D3DRS_DESTBLEND, 6); 
		m_pD3DDevice->SetRenderState(D3DRS_BLENDOP, 1); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, 4); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, 2); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_COLORARG2, 0); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, 1); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, 2); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, 0); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); 
		m_pD3DDevice->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, 0); 
		m_pD3DDevice->SetTextureStageState(1, D3DTSS_COLOROP, 1); 
		m_pD3DDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, 1); 
		m_pD3DDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); 
		m_pD3DDevice->SetVertexShader(D3DFVF_XYZ|D3DFVF_DIFFUSE); 
		m_pD3DDevice->EndStateBlock(&BarNewStateBlock); 
	} 

	m_pD3DDevice->CaptureStateBlock(BarOldStateBlock); 
	m_pD3DDevice->ApplyStateBlock(BarNewStateBlock); 

	D3DXMATRIX matTransposed; 
	D3DXMatrixTranspose(&matTransposed, (D3DXMATRIX*)&matView); 
	matTransposed._14 = matTransposed._24 = matTransposed._34 = 0.0f; 

	if(pNetowkManager) 
	{ 
		CPlayerManager* pPlayerManager = pNetowkManager->GetPlayerManager(); 
		for(int x = 0; x < MAX_PLAYERS; x++)
		{ 
			if(pPlayerManager->GetSlotState(x) == TRUE)
			{ // Player is in use
				CRemotePlayer* Player = pPlayerManager->GetAt(x); 

				if(Player->IsActive() && (Player->GetDistanceFromLocalPlayer() <= 80.0f))
				{ // Active and within reasonable distance 
					CPlayerPed* PlayerPed = Player->GetPlayerPed(); 

					if(PlayerPed->IsOnScreen()) { // They're onscreen 
						// Get their position
						Vector3 vPos;
						PlayerPed->GetPosition(&vPos);

						// Set the matrix position
						matTransposed._41 = vPos.X;
						matTransposed._42 = vPos.Y;
						matTransposed._43 = vPos.Z + 1.0f;

						// Set the world transformation
						m_pD3DDevice->SetTransform(D3DTS_WORLD, &matTransposed); 

						// Get their health and armour
						// TODO: Use the player ped health/armour?
						float Health = Player->GetReportedHealth(); 
						float Armour = Player->GetReportedArmour();

						// Cap their health and armour if needed
						if(Health > 100.0f) Health = 100.0f; 
						if(Armour > 100.0f) Armour = 100.0f; 

						// Set the health bar offsets
						BarBGVertices[0].x = BarBGVertices[1].x = (0.0058f * Health) - 0.29f;

						// Set the health bar color
						BarVertices[0].c = BarVertices[1].c = BarVertices[2].c = BarVertices[3].c 
							= HEALTH_BAR_COLOR;

						// Draw the health bar border
						m_pD3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, BarBDRVertices, sizeof(BarVertices_s));

						// Draw the health bar fill
						m_pD3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, BarVertices, sizeof(BarVertices_s));

						// Draw the health bar background
						m_pD3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, BarBGVertices, sizeof(BarVertices_s));

						if(Armour > 0.0f) { // They have armour
							// Add an offset to the z position
							matTransposed._43 += 0.1f;

							// Set the world transformation
							m_pD3DDevice->SetTransform(D3DTS_WORLD, &matTransposed);

							// Set the armour bar offsets
							BarBGVertices[0].x = BarBGVertices[1].x = (0.0058f * Armour) - 0.29f;

							// Set the armour bar color
							BarVertices[0].c = BarVertices[1].c = BarVertices[2].c = 
								BarVertices[3].c = ARMOUR_BAR_COLOR;

							// Draw the armour bar border
							m_pD3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, BarBDRVertices, sizeof(BarVertices_s));

							// Draw the armour bar fill
							m_pD3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, BarVertices, sizeof(BarVertices_s));

							// Draw the armour bar background
							m_pD3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, BarBGVertices, sizeof(BarVertices_s));
						}

						// Draw the name tag
						if(bbfont) { 
							bbfont->Begin(); 
							//bbfont->Draw(pPlayerManager->GetPlayerName(x), 0.285f, 0xFF000000);
							bbfont->Draw(pPlayerManager->GetPlayerName(x), 0.300f, Player->GetTeamColorAsARGB()); 
							bbfont->End(); 
						} 
					} 
				} 
			} 
		} 
	} 

	m_pD3DDevice->ApplyStateBlock(BarOldStateBlock); 
}
Ejemplo n.º 15
0
//----[  buildAnimatedBones  ]-------------------------------------------------
void AnimatedMeshRenderer::buildAnimatedBones(
    const D3DXMATRIX* root_transform,
    AnimatedMeshIndex animated_mesh,
    AnimatedMeshAnimationTrack* animation_track,
    D3DXMATRIX* bone_matrices) const {
  assert(animated_mesh < animated_meshes_.size());
  assert(animation_track);
  assert(bone_matrices);

  const RenderableAnimatedMesh& renderable_animated_mesh
    = animated_meshes_.at(animated_mesh);
  AnimatedMeshAnimationTrackElement* internal_animation_track =
    reinterpret_cast<AnimatedMeshAnimationTrackElement*>(animation_track);
  RenderableAnimatedMesh::Frame* frames = renderable_animated_mesh.frames;
  size_t number_of_frames = renderable_animated_mesh.number_of_frames;
  RenderableAnimatedMesh::Bone* bones = renderable_animated_mesh.bones;
  size_t number_of_bones = renderable_animated_mesh.number_of_bones;

  // Build the frames using the data in the animation track
  D3DXMATRIXA16 matrix;
  for (size_t frame_index = 0; frame_index < number_of_frames; ++frame_index) {
    RenderableAnimatedMesh::Frame* frame = &frames[frame_index];
    AnimatedMeshAnimationTrackElement* track_element
      = &internal_animation_track[frame_index];
    AnimatedMeshAnimationTrackElement::FrameTransform* frame_transform
      = &track_element->frame_transform;

    // Build the transform matrix from the scale/rotate/translate settings
    //D3DXMatrixTransformation(&matrix,
    //                         NULL,
    //                         NULL,
    //                         frame_transform->scaling(),
    //                         NULL,
    //                         frame_transform->rotation(),
    //                         frame_transform->translation());

    // This method of constructing the transform matrices is necessary because
    // it allows us to transpose the quaternion's matrix during the build.
    D3DXMATRIXA16 cumulative, builder;
    D3DXMatrixScaling(&cumulative,
                      frame_transform->s[0],
                      frame_transform->s[1],
                      frame_transform->s[2]);

    D3DXQUATERNION quat;
    D3DXQuaternionNormalize(&quat, frame_transform->rotation());
    D3DXMatrixRotationQuaternion(&builder, &quat);
    D3DXMatrixTranspose(&builder, &builder);

    D3DXMatrixMultiply(&cumulative, &cumulative, &builder);
    D3DXMatrixTranslation(&builder,
                          frame_transform->t[0],
                          frame_transform->t[1],
                          frame_transform->t[2]);
    D3DXMatrixMultiply(&matrix, &cumulative, &builder);



    // Use the frame hierarchy to construct this frame's final transformation
    size_t parent_frame_index = frame->parent_frame_index;
    assert(!frame_index || (parent_frame_index < frame_index));
    const D3DXMATRIX* parent_frame_matrix
      = frame_index == 0 ? root_transform
                         : internal_animation_track[parent_frame_index]
                             .frameMatrix();
    D3DXMatrixMultiply(track_element->frameMatrix(),
                       &matrix,
                       parent_frame_matrix);
  }

  // Construct the bone transformations for this framte state
  for (size_t bone_index = 0; bone_index < number_of_bones; ++bone_index) {
    D3DXMATRIX* bone_matrix = bone_matrices + bone_index;
    const RenderableAnimatedMesh::Bone* bone = bones + bone_index;
    const D3DXMATRIXA16* frame_matrix
      = (internal_animation_track + bone->frame_index)->frameMatrix();
    D3DXMatrixMultiply(bone_matrix,
                       &bone->inverse_offset,
                       frame_matrix);
  }
}
Ejemplo n.º 16
0
void RenderSSAOEffect( bool lightWeight )
{
	if ( !r_ssao->GetBool() ) 
		return;

	PostFX_UpdateResources();

	r3dSetRestoreFSQuadVDecl setRestoreVDECL; (void)setRestoreVDECL;

#if R3D_ALLOW_TEMPORAL_SSAO
	int doSSAOTemporalOptimize = R3D_SSAO_TEMPORAL_OPTIMIZE == r_ssao_temporal_filter->GetInt() ;

	if( ++g_SSAO_ResetCount >= r_ssao_temporal_reset_freq->GetInt() )
	{
		g_SSAO_ResetCount = 0 ;
		doSSAOTemporalOptimize = 0 ;
	}
#else
	int doSSAOTemporalOptimize = 0 ;
#endif

	const SSAOSettings& sts = g_SSAOSettings[ lightWeight ? SSM_DEFAULT : SSM_HQ ];

	int detailEnable = sts.DetailPathEnable ;

	r3dRenderer->SetVertexShader( "VS_SSAO" ) ;

	SSAOPShaderId psid ;

	psid.num_rays				= !lightWeight ;
	psid.optimized				= !!r_optimized_ssao->GetInt() ;
	psid.detail_radius			= detailEnable ;

#if R3D_ALLOW_TEMPORAL_SSAO
	psid.temporal_optimisation	= doSSAOTemporalOptimize ;
	psid.temporal_show_passed	= g_SSAO_Temporal_Reveal ;
	psid.output_stability_mask	= r_ssao_temporal_filter->GetInt() == R3D_SSAO_TEMPORAL_FILTER ;
#endif
	
	r3dRenderer->SetPixelShader( gSSAOPSIds[ psid.Id ] ) ;

	r3dRenderer->SetRenderingMode(R3D_BLEND_NOALPHA | R3D_BLEND_NZ);

	r3dRenderer->pd3ddev->SetSamplerState( 0, D3DSAMP_ADDRESSU,   D3DTADDRESS_CLAMP );
	r3dRenderer->pd3ddev->SetSamplerState( 0, D3DSAMP_ADDRESSV,   D3DTADDRESS_CLAMP );
	r3dRenderer->pd3ddev->SetSamplerState( 1, D3DSAMP_ADDRESSU,   D3DTADDRESS_CLAMP );
	r3dRenderer->pd3ddev->SetSamplerState( 1, D3DSAMP_ADDRESSV,   D3DTADDRESS_CLAMP );
	r3dRenderer->pd3ddev->SetSamplerState( 2, D3DSAMP_ADDRESSU,   D3DTADDRESS_WRAP );
	r3dRenderer->pd3ddev->SetSamplerState( 2, D3DSAMP_ADDRESSV,   D3DTADDRESS_WRAP );

	float noiseScaleK = r_half_scale_ssao->GetInt() ? 0.5f : 1.0f;

	D3DXVECTOR4 vconst = D3DXVECTOR4( 0.5f / r3dRenderer->ScreenW, 0.5f / r3dRenderer->ScreenH, r3dRenderer->ScreenW * 0.25f * noiseScaleK, r3dRenderer->ScreenH * 0.25f * noiseScaleK );
	r3dRenderer->pd3ddev->SetVertexShaderConstantF(  0, (float *)&vconst,  1 );

	// mat proj

	float fNear = -r3dRenderer->ProjMatrix._43/(r3dRenderer->ProjMatrix._33);
	float fFar = fNear / ( 1.0f - 1.0f/(r3dRenderer->ProjMatrix._33) );

	const int RAYS_START = 7 + 3 + 3 + 3 ;

#define SSAO_ALT_DETAIL_NUM_RAYS	24

	TL_STATIC_ASSERT( SSAO_ALT_DETAIL_NUM_RAYS > SSAO_ALT_NUM_RAYS );

	const int RADIUS_SPLIT = SSAO_ALT_NUM_RAYS;

	// NOTE: sync with ssao_alt_ps.hls
	const int NUM_RAYS = 
			lightWeight ?
			SSAO_LW_NUM_RAYS 
				:
			( detailEnable ? SSAO_ALT_DETAIL_NUM_RAYS : SSAO_ALT_NUM_RAYS );

	if( !g_PrevSSAO_Valid )
	{
		D3DXMatrixIdentity( &g_PrevSSAO_View ) ;
	}

	float aspect = 1.0f ;

	D3DXVECTOR4 pconsts[ RAYS_START + SSAO_ALT_DETAIL_NUM_RAYS ];

	// float4      g_vZScale0_ColorControl     : register ( c0 );
	pconsts[ 0 ] = D3DXVECTOR4( sts.DepthRange / sts.Radius, 128.0f / sts.Radius, sts.Contrast, sts.Brightness * sts.Contrast - 1.5f * sts.Contrast + 0.5f );
	// float4      g_vProjScaleTrans           : register ( c1 );
	pconsts[ 1 ] = D3DXVECTOR4( 0.5f*r3dRenderer->ProjMatrix._11, -0.5f*r3dRenderer->ProjMatrix._22, 0.5f, 0.5f );
	// float4      g_vInvProjScaleTrans        : register ( c2 );
	pconsts[ 2 ] = D3DXVECTOR4( 2.0f / r3dRenderer->ProjMatrix._11, -2.0f / r3dRenderer->ProjMatrix._22, -1.0f / r3dRenderer->ProjMatrix._11, 1.0f / r3dRenderer->ProjMatrix._22 );
	// float4      g_vInvRes_DepthFadeRange    : register ( c3 );
	pconsts[ 3 ] = D3DXVECTOR4( 1.0f / r3dRenderer->ScreenW, 1.0f / r3dRenderer->ScreenH, 0.985f * fFar, 0.99f * fFar );
	// float4      g_vExpandRanges             : register ( c4 );
	pconsts[ 4 ] = D3DXVECTOR4( sts.RadiusExpandStart, sts.DetailRadiusExpandStart, sts.RadiusExpandCoef, sts.DetailRadiusExpandCoef );
	// float4      g_vDetail_Fade_ZScale1      : register ( c5 );
	pconsts[ 5 ] = D3DXVECTOR4( sts.DetailStrength, sts.DetailFadeOut * sts.DetailRadius, sts.DetailDepthRange / sts.DetailRadius, 128.0f / sts.DetailRadius );
	// float4      g_vTempoCtrl                : register ( c6 );
	pconsts[ 6 ] = D3DXVECTOR4( 0.00125f * sts.TemporalTolerance, 1.f / 512.f, aspect / 512.f, 0.f );

	if( doSSAOTemporalOptimize )
	{
		pconsts[ 6 ].w = r_half_scale_ssao->GetInt() ? 0.5f : 1.0f ;
	}

	// float4x3    g_mViewMtx                  : register ( c7 );
	D3DXMatrixTranspose( (D3DXMATRIX*)&pconsts[7], &r3dRenderer->ViewMatrix );
	// ^^^^
	// NOTE : last row is overwritten below

	D3DXMATRIX toPrevViewMtx = r3dRenderer->InvViewMatrix * g_PrevSSAO_View ;

	// float4x3    g_mToPrevViewMtx    : register ( c10 );
	D3DXMatrixTranspose( (D3DXMATRIX*)&pconsts[10], &toPrevViewMtx );
	// ^^^^
	// NOTE : last row is overwritten below

	// float4x3    g_mFromPrevViewMtx  : register ( c13 );
	D3DXMATRIX fromPrevViewMtx ;
	D3DXMatrixInverse( &fromPrevViewMtx, NULL, &toPrevViewMtx ) ;
	D3DXMatrixTranspose( (D3DXMATRIX*)&pconsts[13], &fromPrevViewMtx );
	// ^^^^
	// NOTE : last row is overwritten below

	int r = 0;

	if( !lightWeight )
	{
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.18486f, 0.32808f, 0.00708f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.22890f, 0.93380f,-0.09171f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.36097f, 0.18230f,-0.38227f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.06232f, 0.32664f, 0.21049f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.68342f, 0.25225f,-0.06311f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.05478f, 0.09994f, 0.34463f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.01732f, 0.36483f,-0.49192f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.72131f, 0.22451f,-0.09716f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.32283f, 0.33296f, 0.11536f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.27977f, 0.18833f, 0.16797f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.50663f, 0.08494f, 0.63250f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.35578f, 0.11564f, 0.50909f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.54817f, 0.23470f,-0.61668f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.15970f, 0.08904f,-0.66253f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.73055f, 0.08323f, 0.30949f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.68126f, 0.50000f, 0.10878f, 0 );
	}

	if( detailEnable || lightWeight )
	{
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.01209f, 0.95443f, 0.11314f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.79393f, 0.23041f, 0.11043f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.77869f, 0.26835f,-0.35691f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.24429f, 0.15942f, 0.46862f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.32674f, 0.51379f,-0.52337f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4( 0.34767f, 0.07975f, 0.67386f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.13244f, 0.06251f,-0.58013f, 0 );
		pconsts[ RAYS_START + r++ ] = D3DXVECTOR4(-0.30083f, 0.50000f, 0.09436f, 0 );
	}

	r3d_assert( r == NUM_RAYS );

	for( int i = 0, e = RADIUS_SPLIT; i < e; i ++ )
	{
		pconsts[ RAYS_START + i ] *= sts.Radius;
	}

	for( int i = RADIUS_SPLIT, e = NUM_RAYS; i < e; i ++ )
	{
		pconsts[ RAYS_START + i ] *= sts.DetailRadius;
	}

	if( !r_optimized_ssao->GetInt() )
	{
		for( int i = 0, e = NUM_RAYS; i < e; i ++ )
		{
			D3DXVec4Transform( pconsts + RAYS_START + i, pconsts + RAYS_START + i, &r3dRenderer->ViewMatrix );
		}
	}

	r3dRenderer->pd3ddev->SetPixelShaderConstantF(  0, (float*)pconsts, RAYS_START + NUM_RAYS );

	r3dSetFiltering( R3D_POINT, 0 );
	r3dSetFiltering( R3D_POINT, 1 );
	r3dSetFiltering( R3D_POINT, 2 );

	r3dRenderer->SetMipMapBias( -6, 2 );

	extern r3dScreenBuffer* gBuffer_Normal;

	r3dRenderer->SetTex( DepthBuffer->Tex		, 0	);
	r3dRenderer->SetTex( gBuffer_Normal->Tex	, 1	);
	r3dRenderer->SetTex( SSAO_RotTex2D			, 2	);

	if( doSSAOTemporalOptimize )
	{
		r3dRenderer->pd3ddev->SetSamplerState( 3, D3DSAMP_ADDRESSU,   D3DTADDRESS_CLAMP );
		r3dRenderer->pd3ddev->SetSamplerState( 3, D3DSAMP_ADDRESSV,   D3DTADDRESS_CLAMP );
		r3dRenderer->pd3ddev->SetSamplerState( 4, D3DSAMP_ADDRESSU,   D3DTADDRESS_CLAMP );
		r3dRenderer->pd3ddev->SetSamplerState( 4, D3DSAMP_ADDRESSV,   D3DTADDRESS_CLAMP );

		r3dSetFiltering( R3D_BILINEAR, 3 );
		r3dSetFiltering( R3D_POINT, 4 );

		r3dRenderer->SetTex( PrevDepthBuffer->Tex	, 3 );
		r3dRenderer->SetTex( PrevSSAOBuffer->Tex	, 4 );
	}

#if R3D_ALLOW_TEMPORAL_SSAO
	if( r_ssao_temporal_filter->GetInt() == R3D_SSAO_TEMPORAL_FILTER )
		r3dRenderer->pd3ddev->SetRenderState( D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN );
	else
#endif
		r3dRenderer->pd3ddev->SetRenderState( D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED );

	r3dDrawFullScreenQuad(!!r_half_scale_ssao->GetInt());

	r3dRenderer->SetMipMapBias(0, 2);

	r3dRenderer->SetVertexShader();
	r3dRenderer->SetPixelShader();
	r3dRenderer->pd3ddev->SetRenderState(D3DRS_COLORWRITEENABLE, 	0xffffffff );
}
Ejemplo n.º 17
0
void DistantLand::renderWaterReflection(const D3DXMATRIX *view, const D3DXMATRIX *proj)
{
    DECLARE_MWBRIDGE

    // Switch to render target
    RenderTargetSwitcher rtsw(texReflection, surfReflectionZ);
    device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, horizonCol, 1.0, 0);

    // Calculate reflected view matrix, mirror plane at water mesh level
    D3DXMATRIX reflView;
    D3DXPLANE plane(0, 0, 1.0, -(mwBridge->WaterLevel() - 1.0));
    D3DXMatrixReflect(&reflView, &plane);
    D3DXMatrixMultiply(&reflView, &reflView, view);
    effect->SetMatrix(ehView, &reflView);

    // Calculate new projection
    D3DXMATRIX reflProj = *proj;
    editProjectionZ(&reflProj, 4.0, Configuration.DL.DrawDist * kCellSize);
    effect->SetMatrix(ehProj, &reflProj);

    // Clipping setup
    D3DXMATRIX clipMat;

    // Clip geometry on opposite side of water plane
    plane *= mwBridge->IsUnderwater(eyePos.z) ? -1.0 : 1.0;

    // If using dynamic ripples, the water level can be lowered by up to 0.5 * waveheight
    // so move clip plane downwards at the cost of some reflection errors
    if(Configuration.MGEFlags & DYNAMIC_RIPPLES)
        plane.d += 0.5 * Configuration.DL.WaterWaveHeight;

    // Doing inverses separately is a lot more numerically stable
    D3DXMatrixInverse(&clipMat, 0, &reflView);
    D3DXMatrixTranspose(&clipMat, &clipMat);
    D3DXPlaneTransform(&plane, &plane, &clipMat);

    D3DXMatrixInverse(&clipMat, 0, &reflProj);
    D3DXMatrixTranspose(&clipMat, &clipMat);
    D3DXPlaneTransform(&plane, &plane, &clipMat);

    if(visDistant.size() == 0)
    {
        // Workaround for a Direct3D bug with clipping planes, where SetClipPlane
        // has no effect on the shader pipeline if the last rendered draw call was using
        // the fixed function pipeline. This is usually covered by distant statics, but
        // not in compact interiors where all distant statics may be culled.
        // Provoking a DrawPrimitive with shader here makes the following SetClipPlane work.
        effect->BeginPass(PASS_WORKAROUND);
        device->SetVertexDeclaration(WaterDecl);
        device->SetStreamSource(0, vbFullFrame, 0, 12);
        device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
        effect->EndPass();
    }

    device->SetClipPlane(0, plane);
    device->SetRenderState(D3DRS_CLIPPLANEENABLE, 1);

    // Rendering
    if(mwBridge->IsExterior() && (Configuration.MGEFlags & REFLECTIVE_WATER))
    {
        // Draw land reflection, with opposite culling
        effect->BeginPass(PASS_RENDERLANDREFL);
        device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
        renderDistantLand(effect, &reflView, &reflProj);
        effect->EndPass();
    }

    if(isDistantCell() && (Configuration.MGEFlags & REFLECT_NEAR))
    {
        // Draw statics reflection, with opposite culling and no dissolve
        DWORD p = (mwBridge->CellHasWeather() && !mwBridge->IsUnderwater(eyePos.z)) ? PASS_RENDERSTATICSEXTERIOR : PASS_RENDERSTATICSINTERIOR;
        effect->SetFloat(ehNearViewRange, 0);
        effect->BeginPass(p);
        device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
        renderReflectedStatics(&reflView, &reflProj);
        effect->EndPass();
        effect->SetFloat(ehNearViewRange, nearViewRange);
    }

    if((Configuration.MGEFlags & REFLECT_SKY) && !recordSky.empty() && !mwBridge->IsUnderwater(eyePos.z))
    {
        // Draw sky reflection, with opposite culling
        effect->BeginPass(PASS_RENDERSKY);
        device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
        renderReflectedSky();
        effect->EndPass();
    }

    // Restore view state
    device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
    effect->SetMatrix(ehView, view);
    effect->SetMatrix(ehProj, proj);
}
Ejemplo n.º 18
0
void CompositeSSAO( r3dScreenBuffer* currSSAO )
{
	D3DPERF_BeginEvent( 0, L"CompositeSSAO" ) ;

	const SSAOSettings& sts = g_SSAOSettings[ R3D_MIN( R3D_MAX( r_ssao_method->GetInt(), 0 ), SSM_COUNT - 1 ) ] ;

	r3dRenderer->SetRenderingMode(R3D_BLEND_NOALPHA);

	r3dSetRestoreFSQuadVDecl setRestoreVDECL; (void)setRestoreVDECL;

	float resK ;
	int HalfScale ;

	resK = r_half_scale_ssao->GetInt() ? 0.5f : 1.0f ;
	HalfScale = !!r_half_scale_ssao->GetInt() ;

	r3dRenderer->SetVertexShader( "VS_SSAO" ) ;
	r3dRenderer->SetPixelShader( "PS_SSAO_COMPOSITE" ) ;

	const float HISTORY_DEPTH = sts.TemporalHistoryDepth ;

	r3dTL::TFixedArray< D3DXVECTOR4, 10 > psConsts ;

	// float4   gSettings            : register ( c0 ) ;
	psConsts[ 0 ] = D3DXVECTOR4( HISTORY_DEPTH / ( HISTORY_DEPTH + 1.f ), 1.0f / ( HISTORY_DEPTH + 1.f ), 0.f, 0.125f * sts.TemporalTolerance ) ;
	// float4   g_vProjScaleTrans    : register ( c1 ) ;
	psConsts[ 1 ] = D3DXVECTOR4( 0.5f*r3dRenderer->ProjMatrix._11, -0.5f*r3dRenderer->ProjMatrix._22, 0.5f, 0.5f );
	// float4   g_vInvProjScaleTrans : register ( c2 ) ;
	psConsts[ 2 ] = D3DXVECTOR4( 2.0f / r3dRenderer->ProjMatrix._11, -2.0f / r3dRenderer->ProjMatrix._22, -1.0f / r3dRenderer->ProjMatrix._11, 1.0f / r3dRenderer->ProjMatrix._22 );
	// float4x3 g_vToPrevViewMtx     : register ( c3 ) ;
	D3DXMATRIX toPrevViewMtx = r3dRenderer->InvViewMatrix * g_PrevSSAO_View ;
	D3DXMatrixTranspose( (D3DXMATRIX*)&psConsts[3], &toPrevViewMtx );
	// float4x3 g_vFromPrevViewMtx   : register ( c6 ) ;
	D3DXMATRIX fromPrevViewMtx ;
	D3DXMatrixInverse( &fromPrevViewMtx, NULL, &toPrevViewMtx ) ;
	D3DXMatrixTranspose( (D3DXMATRIX*)&psConsts[6], &fromPrevViewMtx );

	D3D_V( r3dRenderer->pd3ddev->SetPixelShaderConstantF( 0, &psConsts[ 0 ].x, psConsts.COUNT ) ) ;

	extern r3dScreenBuffer* gBuffer_Depth ;

	r3dRenderer->SetTex( PrevSSAOBuffer->Tex, 0 ) ;
	r3dRenderer->SetTex( currSSAO->Tex, 1 ) ;
	r3dRenderer->SetTex( PrevDepthBuffer->Tex, 2 ) ;
	r3dRenderer->SetTex( gBuffer_Depth->Tex, 3 ) ;
	
	for( int i = 0 ; i < 4 ; i ++ )
	{
		r3dSetFiltering( R3D_BILINEAR, i ) ;

		D3D_V( r3dRenderer->pd3ddev->SetSamplerState( i, D3DSAMP_ADDRESSU,   D3DTADDRESS_CLAMP ) );
		D3D_V( r3dRenderer->pd3ddev->SetSamplerState( i, D3DSAMP_ADDRESSV,   D3DTADDRESS_CLAMP ) );
	}

	D3DXVECTOR4 vconst = D3DXVECTOR4( 0.5f / r3dRenderer->ScreenW, 0.5f / r3dRenderer->ScreenH, resK, resK ) ;
	r3dRenderer->pd3ddev->SetVertexShaderConstantF( 0, (float *)&vconst, 1 ) ;

	r3dDrawFullScreenQuad( !!HalfScale ) ;

	D3DPERF_EndEvent() ;
}
bool RefractionShaderClass::SetShaderParameters(ID3D11DeviceContext* context, D3DXMATRIX world, D3DXMATRIX view, D3DXMATRIX proj, ID3D11ShaderResourceView* tex, D3DXVECTOR3 lightdir, D3DXVECTOR4 ambient, D3DXVECTOR4 diffuse, D3DXVECTOR4 clipplane)
{
    HRESULT result;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    unsigned int bufferNum;
    MatrixBufferType* dataPtr;
    LightBufferType* dataPtr2;
    ClipPlaneBufferType* dataPtr3;


    D3DXMatrixTranspose(&world, &world);
    D3DXMatrixTranspose(&view, &view);
    D3DXMatrixTranspose(&proj, &proj);

    result = context->Map(_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
    if (FAILED(result))
    {
        return false;
    }

    dataPtr = (MatrixBufferType*)mappedResource.pData;

    dataPtr->world = world;
    dataPtr->view = view;
    dataPtr->proj = proj;

    context->Unmap(_matrixBuffer, 0);

    bufferNum = 0;

    context->VSSetConstantBuffers(bufferNum, 1, &_matrixBuffer);

    context->PSSetShaderResources(0, 1, &tex);

    result = context->Map(_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
    if (FAILED(result))
    {
        return false;
    }

    dataPtr2 = (LightBufferType*)mappedResource.pData;

    dataPtr2->ambientColor = ambient;
    dataPtr2->diffuse = diffuse;
    dataPtr2->lightdir = lightdir;

    context->Unmap(_lightBuffer, 0);

    bufferNum = 1;

    context->PSSetConstantBuffers(bufferNum, 1, &_lightBuffer);

    result = context->Map(_clipPlaneBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
    if (FAILED(result))
    {
        return false;
    }

    dataPtr3 = (ClipPlaneBufferType*)mappedResource.pData;

    dataPtr3->clipPlane = clipplane;

    context->Unmap(_clipPlaneBuffer, 0);

    bufferNum = 2;

    context->VSSetConstantBuffers(bufferNum, 1, &_clipPlaneBuffer);


    return true;
}
Ejemplo n.º 20
0
bool CLightShader::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX wMatrix, D3DXMATRIX vMatrix, D3DXMATRIX pMatrix, ID3D11ShaderResourceView* texture, D3DXVECTOR3 lightDirection, D3DXVECTOR4 ambientColor, D3DXVECTOR4 diffuseColor, D3DXVECTOR3 cameraPosition, D3DXVECTOR4 specularColor, float specularPower)
{
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	unsigned int bufferNumber;
	MatrixBufferType* matrixData;
	LightBufferType* lightData;
	CameraBufferType* cameraData;

	D3DXMatrixTranspose(&wMatrix, &wMatrix);
	D3DXMatrixTranspose(&vMatrix, &vMatrix);
	D3DXMatrixTranspose(&pMatrix, &pMatrix);

	// Lock the taskba- constant buffer
	result = deviceContext->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if (FAILED(result))
	{
		CLog::Write("CLightShader::SetShaderParameters() : could not lock the matrix buffer");
		return false;
	}

	matrixData = (MatrixBufferType*)mappedResource.pData;

	// copy the matrices in the constant buffer
	matrixData->world = wMatrix;
	matrixData->view = vMatrix;
	matrixData->projection = pMatrix;

	// Unlock the taskba- constant buffer
	deviceContext->Unmap(matrixBuffer, 0);

	bufferNumber = 0;

	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &matrixBuffer);

	result = deviceContext->Map(cameraBuffer, 0,D3D11_MAP_WRITE_DISCARD ,0, &mappedResource);
	if (FAILED(result))
	{
		CLog::Write("CLightShader::SetShaderParameters() : could not lock the camera buffer");
		return false;
	}

	cameraData = (CameraBufferType*)mappedResource.pData;
	cameraData->cameraPosition = cameraPosition;
	cameraData->padding = 0.0f;

	deviceContext->Unmap(cameraBuffer, 0);

	bufferNumber = 1;
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &cameraBuffer);
	deviceContext->PSSetShaderResources(0, 1, &texture);

	// Lock the taskba- light constant buffer (ok i'll stop)
	result = deviceContext->Map(lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if (FAILED(result))
	{
		CLog::Write("CLightShader::SetShaderParameters() : could not lock the light buffer");
		return false;
	}

	lightData = (LightBufferType*)mappedResource.pData;

	lightData->ambientColor = ambientColor;
	lightData->diffuseColor = diffuseColor;
	lightData->lightDirection = lightDirection;
	lightData->specularColor = specularColor;
	lightData->specularPower = specularPower;

	// Unlock the taskba- light constant buffer (I lied)
	deviceContext->Unmap(lightBuffer, 0);

	// Just in case VSSetConstantBuffers did some stupid stuff
	bufferNumber = 0;

	deviceContext->PSSetConstantBuffers(bufferNumber, 1, &lightBuffer);

	return true;
}
Ejemplo n.º 21
0
void CObject3D::_renderSkin(const GMObject& obj, const D3DXMATRIX* world, int alpha)
{
	D3DXMATRIX* bones, *invBones;
	D3DXMATRIX mat;
	int i, nID, j;

	if (m_externBones)
	{
		bones = m_externBones;
		invBones = m_externInvBones;
	}
	else
	{
		bones = m_baseBones;
		invBones = m_baseInvBones;
	}

	if (obj.usedBoneCount)
	{
		for (i = 0; i < obj.usedBoneCount; i++)
		{
			nID = obj.usedBones[i];
			mat = invBones[nID] * bones[nID];
			D3DXMatrixTranspose(&mat, &mat);
			m_device->SetVertexShaderConstantF(i * 3, (float*)&mat, 3);
		}
	}

	m_device->SetVertexDeclaration(s_skinVertexDeclaration);
	m_device->SetVertexShader(s_skinVS);
	m_device->SetStreamSource(0, obj.VB, 0, sizeof(SkinVertex));
	m_device->SetIndices(obj.IB);
	m_device->SetTransform(D3DTS_WORLD, world);

	for (i = 0; i < obj.materialBlockCount; i++)
	{
		const MaterialBlock& block = obj.materialBlocks[i];

		if (block.usedBoneCount)
		{
			for (j = 0; j < block.usedBoneCount; j++)
			{
				nID = block.usedBones[j];
				mat = invBones[nID] * bones[nID];
				D3DXMatrixTranspose(&mat, &mat);
				m_device->SetVertexShaderConstantF(j * 3, (float*)&mat, 3);
			}
		}

		_setState(block, alpha);

		if (obj.material)
		{
			const CTexture* texture = obj.materials[block.materialID].textures[m_group->currentTextureEx];
			if (texture)
				m_device->SetTexture(0, *texture);
			else
				m_device->SetTexture(0, null);
		}
		else
			m_device->SetTexture(0, null);

		m_device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, obj.vertexCount, block.startVertex, block.primitiveCount);

		_resetState(block, alpha);
	}

	m_device->SetVertexShader(null);
	m_device->SetVertexDeclaration(null);
}
Ejemplo n.º 22
0
bool LightShaderClass::setShaderParameters( 
	ID3D11DeviceContext *aD3DDeviceContext, 
	D3DXMATRIX aWorldMatrix, 
	D3DXMATRIX aViewMatrix, 
	D3DXMATRIX aProjectionMatrix, 
	ID3D11ShaderResourceView *aShaderResourceView, 
	D3DXVECTOR3 aLightDirection, 
	D3DXVECTOR4 aAmbientColor,
	D3DXVECTOR4 aDiffuseColor )
{
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	unsigned int bufferNumber;
	MatrixBufferType* dataPtr;
	LightBufferType* dataPtr2;

	D3DXMatrixTranspose(&aWorldMatrix, &aWorldMatrix);
	D3DXMatrixTranspose(&aViewMatrix, &aViewMatrix);
	D3DXMatrixTranspose(&aProjectionMatrix, &aProjectionMatrix);

	result = aD3DDeviceContext->Map(
		m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD,
		0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	dataPtr = (MatrixBufferType*)mappedResource.pData;

	dataPtr->world = aWorldMatrix;
	dataPtr->view = aViewMatrix;
	dataPtr->projection = aProjectionMatrix;

	aD3DDeviceContext->Unmap(m_matrixBuffer, 0);

	bufferNumber = 0;

	aD3DDeviceContext->VSSetConstantBuffers(
		bufferNumber, 1, &m_matrixBuffer);

	aD3DDeviceContext->PSSetShaderResources(
		0, 1, &aShaderResourceView);
	
	result = aD3DDeviceContext->Map(
		m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD,
		0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	dataPtr2 = (LightBufferType*)mappedResource.pData;

	dataPtr2->ambientColor = aAmbientColor;
	dataPtr2->diffuseColor = aDiffuseColor;
	dataPtr2->lightDirection = aLightDirection;
	dataPtr2->padding = 0.0f;

	aD3DDeviceContext->Unmap(m_lightBuffer, 0);

	bufferNumber = 0;

	aD3DDeviceContext->PSSetConstantBuffers(
		bufferNumber, 1, &m_lightBuffer);

	return true;
}
Ejemplo n.º 23
0
bool CloudsShader::SetShaderParameters(ID3D11DeviceContext* deviceContext, int indexCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, 
				 D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* cloudTexture1, ID3D11ShaderResourceView* cloudTexture2, ID3D11ShaderResourceView* perturbTexture, 
				 D3DXVECTOR2 translation, D3DXVECTOR2 scale, D3DXVECTOR2 brightness)
{
	HRESULT result;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
	MatrixBufferType* dataPtr;
	SkyBufferType* dataPtr2;
	unsigned int bufferNumber;


	// Transpose the matrices to prepare them for the shader.
	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

	// Lock the constant buffer so it can be written to.
	result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr = (MatrixBufferType*)mappedResource.pData;

	// Copy the matrices into the constant buffer.
	dataPtr->world = worldMatrix;
	dataPtr->view = viewMatrix;
	dataPtr->projection = projectionMatrix;

	// Unlock the constant buffer.
    deviceContext->Unmap(m_matrixBuffer, 0);

	// Set the position of the constant buffer in the vertex shader.
	bufferNumber = 0;

	// Finally set the constant buffer in the vertex shader with the updated values.
    deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
	
	// Lock the sky constant buffer so it can be written to.
	result = deviceContext->Map(m_skyBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr2 = (SkyBufferType*)mappedResource.pData;

	// Copy the sky variables into the constant buffer.
	dataPtr2->translation = translation;
	dataPtr2->scale = scale;
	dataPtr2->brightness = brightness;
	dataPtr2->padding = D3DXVECTOR2(0.0f, 0.0f);

	// Unlock the constant buffer.
	deviceContext->Unmap(m_skyBuffer, 0);

	// Set the position of the sky constant buffer in the pixel shader.
	bufferNumber = 0;

	// Finally set the sky constant buffer in the pixel shader with the updated values.
	deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_skyBuffer);

	// Set the shader texture resource in the pixel shader.
	deviceContext->PSSetShaderResources(0, 1, &cloudTexture1);
	deviceContext->PSSetShaderResources(1, 1, &cloudTexture2);
	deviceContext->PSSetShaderResources(2, 1, &perturbTexture);

	return true;
}
Ejemplo n.º 24
0
void r3dLight :: SetShaderConstants(r3dCamera &Cam)
{
	const int MAX_CONSTANTS = 10;
	const int COLOR_INDEX = 1;

	D3DXVECTOR4 vColor;
	vColor = D3DXVECTOR4( (R/255.0f), (G/255.0f), (B/255.0f), 1 );

	vColor.x = powf( vColor.x, 2.2f ) ;
	vColor.y = powf( vColor.y, 2.2f ) ;
	vColor.z = powf( vColor.z, 2.2f ) ;
	vColor = vColor * Intensity;


	// Common params
	D3DXVECTOR4 vConsts[ MAX_CONSTANTS ] = 
	{
		D3DXVECTOR4( Cam.X, Cam.Y, Cam.Z, 0 ),
		D3DXVECTOR4( vColor )
	};

	int NUM_CONSTANTS = 2;

	float invFadeDistance = 1.0f / (GetOuterRadius() - GetInnerRadius());

	switch (Type)
	{
	case R3D_DIRECT_LIGHT:
		{
			r3dColor Amb = r3dRenderer->AmbientColor;

			r3d_assert( NUM_CONSTANTS == 2 );
			// float4   vAmbientColor  : register(c2);
			D3DXVECTOR4 amb ( Amb.R/255.0f, Amb.G/255.0f, Amb.B/255.0f, 1.0f ) ;

			amb.x = powf( amb.x, 2.2f ) ;
			amb.y = powf( amb.y, 2.2f ) ;
			amb.z = powf( amb.z, 2.2f ) ;

			vConsts[ NUM_CONSTANTS ++ ] = amb ;

		}
		break;

	case R3D_OMNI_LIGHT:
		{
			r3d_assert( NUM_CONSTANTS == 2 );

			// float4	vLightPos: register(c2);
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( X, Y, Z, 0 );
			// float4  vLightDistanceParams: register(c3);
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4(invFadeDistance, GetInnerRadius() * invFadeDistance, 0, 0);
		}
		break;

	case R3D_SPOT_LIGHT:
		{
			Direction.Normalize();

			float spotAngleOuter = SpotAngleOuter;
			float spotAngleInner = R3D_MIN( SpotAngleInner, SpotAngleOuter - 0.33f );

			float cosInner = cosf( R3D_DEG2RAD( spotAngleInner ) );
			float cosOuter = cosf ( R3D_DEG2RAD( spotAngleOuter ) );

			float fallofX = 1.f / ( cosInner - cosOuter );
			float fallofY =  - cosOuter * fallofX;

			r3d_assert( NUM_CONSTANTS == 2 );

			// float4	vLightPos_RcpRad	: register(c2);
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( X, Y, Z, 0 );
			// float3	vLightDir			: register(c3);
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( Direction.x, Direction.y, Direction.z, 0 );
			// float4	vLightFalloff		: register(c4);
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( fallofX, fallofY, SpotAngleFalloffPow, 0 );
			// float4  vLightDistanceParams	: register(c5);
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4(invFadeDistance, GetInnerRadius() * invFadeDistance, 0, 0);;
		}
		break;

	case R3D_TUBE_LIGHT:
		{
			r3d_assert( NUM_CONSTANTS == 2 );

			// float4  vLightDistanceParams: register(c2);
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( 0.5f * 0.03125f * Radius2 * Radius2 * Radius2 * Radius2 / Length , 0.5f * Length , 0, 0 );
			
			// float4x3 mLightMtx			: register(c3);
			D3DXMATRIX lightMtx ;

			GetTubeLightMatrix( &lightMtx ) ;

			D3DXMatrixTranspose( &lightMtx, &lightMtx ) ;

			vConsts[ NUM_CONSTANTS ++ ] = *(D3DXVECTOR4*)lightMtx.m[0] ;
			vConsts[ NUM_CONSTANTS ++ ] = *(D3DXVECTOR4*)lightMtx.m[1] ;
			vConsts[ NUM_CONSTANTS ++ ] = *(D3DXVECTOR4*)lightMtx.m[2] ;

			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( X, Y, Z, 1 ) ;

		}
		break ;

	case R3D_PLANE_LIGHT:
		{
			r3d_assert( NUM_CONSTANTS == 2 );

			// float4  vLightDistanceParams: register(c2);
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( -1.f / Radius2 , 1.f, 0.5f * Length, 0.5f * Width );

			// float4x3 mLightMtx			: register(c3);
			D3DXMATRIX lightMtx ;

			GetTubeLightMatrix( &lightMtx ) ;

			D3DXMatrixTranspose( &lightMtx, &lightMtx ) ;

			vConsts[ NUM_CONSTANTS ++ ] = *(D3DXVECTOR4*)lightMtx.m[0] ;
			vConsts[ NUM_CONSTANTS ++ ] = *(D3DXVECTOR4*)lightMtx.m[1] ;
			vConsts[ NUM_CONSTANTS ++ ] = *(D3DXVECTOR4*)lightMtx.m[2] ;

			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( X, Y, Z, 1 ) ;
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( bDoubleSided ? 0.f : FLT_MAX, 0.f, 0.f, 0.f );
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( 0.f, 0.f, 0.f, 0.f  );

		}
		break ;
	case R3D_VOLUME_LIGHT:
		{
			vConsts[COLOR_INDEX] = D3DXVECTOR4( (R/255.0f), (G/255.0f), (B/255.0f), Intensity );
			
			r3d_assert( NUM_CONSTANTS == 2 );
			float DepthZ = r3dRenderer->FarClip * 0.9375f;

			// float4	vLightPos: register(c2);
			vConsts[ NUM_CONSTANTS ++ ] = D3DXVECTOR4( X, Y, Z, 1.0f / DepthZ );
		}
		break;

	case R3D_PROJECTOR_LIGHT:
		r3d_assert( false && "not implemented" );

#if 0
		LightVec = D3DXVECTOR4(X,Y,Z,0);

		r3dRenderer->pd3ddev->SetVertexShaderConstantF( 15, (float *)&LightVec,	1 );
		r3dRenderer->pd3ddev->SetPixelShaderConstantF( 4, (float *)&LightVec,	1 );

		Direction.Normalize();
		LightVec = D3DXVECTOR4(Direction.X,Direction.Y,Direction.Z,0);

		r3dVector vTo = r3dPoint3D(X,Y,Z) + Direction *100.0f;
		r3dRenderer->pd3ddev->SetPixelShaderConstantF( 5, (float *)&LightVec,	1 );
		r3dRenderer->pd3ddev->SetVertexShaderConstantF( 16, (float *)&LightVec,	1 );

		r3dRenderer->SetTex(ProjectMap,3);
		r3dRenderer->pd3ddev->SetSamplerState( 3, D3DSAMP_ADDRESSU,   D3DTADDRESS_CLAMP );
		r3dRenderer->pd3ddev->SetSamplerState( 3, D3DSAMP_ADDRESSV,   D3DTADDRESS_CLAMP );

		SetupProjectiveTransform(D3DXVECTOR3(X,Y,Z),D3DXVECTOR3(vTo.x,vTo.y, vTo.Z), SpotAngle);
		break;
#endif

	}

	r3d_assert( NUM_CONSTANTS < MAX_CONSTANTS );

	r3dRenderer->pd3ddev->SetPixelShaderConstantF( 0, (float *)vConsts, NUM_CONSTANTS );

}
Ejemplo n.º 25
0
void Viewer::onRender()
{
  static char s[40];

  // clear the vertex and face counters
  m_vertexCount = 0;
  m_faceCount = 0;


  // clear all the buffers
  g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 
						D3DCOLOR_XRGB(0,0,77), 1.0f, 0 );
  // Setup Prespective matrix
  g_pD3DDevice->BeginScene();

  D3DXMATRIX matProj,matWorld,matView, matViewInv;
  D3DXMatrixPerspectiveFovRH( &matProj, D3DX_PI/4, (float)m_width / (float)m_height, m_scale * 50.0f, m_scale * 1000.0f );
  
  
  g_pD3DDevice->SetTransform( D3DTS_PROJECTION, &matProj );
  
  D3DXMATRIX Mat1,Mat2;                // tmp matrix

  D3DXMatrixIdentity(&Mat1);

  

  D3DXMatrixTranslation(&Mat2,0.0f,0.0f,-m_distance * m_scale);
  
  D3DXMatrixMultiply(&Mat1,&Mat2,&Mat1);

  
  D3DXMatrixRotationX(&Mat2, m_tiltAngle/180.0f*3.14159f);
  D3DXMatrixMultiply(&Mat1,&Mat2,&Mat1);

  D3DXMatrixRotationZ(&Mat2, m_twistAngle/180.0f*3.14159f);
  D3DXMatrixMultiply(&Mat1,&Mat2,&Mat1);


  D3DXMatrixTranslation(&Mat2,0.0f,0.0f,-90.0f * m_scale);			//I have done à 1/1 translation
  D3DXMatrixMultiply(&matView,&Mat2,&Mat1);							//of the OpenGL version

  g_pD3DDevice->SetTransform( D3DTS_VIEW, &matView );

  D3DXMatrixIdentity(&matWorld);
  g_pD3DDevice->SetTransform( D3DTS_WORLD, &matWorld ); 

  // setup the light attributes
  D3DLIGHT9 light;
  ZeroMemory( &light, sizeof(D3DLIGHT9) );
  light.Type       = D3DLIGHT_DIRECTIONAL;
  light.Ambient.r=0.2f;light.Ambient.g=0.2f;light.Ambient.b=0.2f;light.Ambient.a=1.0f;
  light.Diffuse.r=1.0f;light.Diffuse.g=1.0f;light.Diffuse.b=1.0f;light.Diffuse.a=1.0f;
  light.Specular.r=0.1f;light.Specular.g=0.1f;light.Specular.b=0.1f;light.Specular.a=1.0f;
    
  //light.Direction= D3DXVECTOR3(0.0f,0.70f,0.70f);
  light.Direction= D3DXVECTOR3(sinf(Tick::getTick()/1000.0f),cosf(Tick::getTick()/1000.0f),-0.5f);

  float r=light.Direction.x*light.Direction.x
	  +light.Direction.y*light.Direction.y
	  +light.Direction.z*light.Direction.z;

  light.Direction.x/=r;
  light.Direction.y/=r;
  light.Direction.z/=r;  

  g_pD3DDevice->SetLight( 0, &light );
  g_pD3DDevice->LightEnable( 0, TRUE );  
  g_pD3DDevice->SetRenderState( D3DRS_LIGHTING, TRUE );

  if(m_bBump)
  {
      g_pD3DDevice->SetVertexShaderConstantF(13, (float*)&light.Diffuse, 1 );
      g_pD3DDevice->SetVertexShaderConstantF(14, (float*)&light.Specular, 1 );
      g_pD3DDevice->SetVertexShaderConstantF(15, (float*)&light.Ambient, 1 );
      g_pD3DDevice->SetVertexShaderConstantF(16, (float*)&(-((D3DXVECTOR3)light.Direction)), 1 );

	  D3DXMatrixTranspose( &Mat1, &matWorld );
      g_pD3DDevice->SetVertexShaderConstantF( 0, (float*)&Mat1, 4 );

      D3DXMatrixMultiply( &Mat1, &matView, &matProj );
      D3DXMatrixMultiply( &Mat1, &matWorld, &Mat1 );
      D3DXMatrixTranspose( &Mat1, &Mat1 );
      g_pD3DDevice->SetVertexShaderConstantF( 4, (float*)&Mat1, 4 );

	  float Const[4] = {0.5f,0.5f,0.5f,0.5f};

      g_pD3DDevice->SetVertexShaderConstantF( 20,Const, 1 );
  }
  
  // render the model
  renderModel();

  g_pD3DDevice->SetRenderState( D3DRS_LIGHTING, FALSE );

  // render the cursor
  renderCursor();

  RECT FontPosition;

  FontPosition.top = 0;
  FontPosition.left = 0;
  FontPosition.right = m_width;
  FontPosition.bottom = 100;

  sprintf(s,"%d fps, press 'b' to toggle bump mapping",m_fps);

  // 
  //  There are changes here between Direct3D SDK 9 and Direct3D SDK 9 summer 2003 update
  //

  /* Original SDK

  m_pFont->Begin();										
  m_pFont->DrawText(s,-1,&FontPosition,DT_CENTER,0xffffffff);
  m_pFont->End();

  */


  ///* Update

  m_pFont->DrawText(NULL,s,-1,&FontPosition,DT_CENTER,0xffffffff);

  //*/


  g_pD3DDevice->EndScene();


  // swap the front- and back-buffer
  g_pD3DDevice->Present( NULL, NULL, NULL, NULL );  

  // increase frame counter
  m_fpsFrames++;

}
Ejemplo n.º 26
0
/** Draws the surrounding scene into the cubemap */
void D3D11PointLight::RenderCubemap(bool forceUpdate)
{
	if(!InitDone)
		return;

	//if(!GetAsyncKeyState('X'))
	//	return;
	D3D11GraphicsEngineBase* engineBase = (D3D11GraphicsEngineBase *)Engine::GraphicsEngine;
	D3D11GraphicsEngine* engine = (D3D11GraphicsEngine *) engineBase; // TODO: Remove and use newer system!


	D3DXVECTOR3 vEyePt = LightInfo->Vob->GetPositionWorld();
	//vEyePt += D3DXVECTOR3(0,1,0) * 20.0f; // Move lightsource out of the ground or other objects (torches!)
	// TODO: Move the actual lightsource up too!

	/*if(WantsUpdate())
	{
		// Move lights with colorchanges around a bit to make it look more light torches
		vEyePt.y += (float4(LastUpdateColor).x - 0.5f) * LIGHT_COLORCHANGE_POS_MOD;
		vEyePt.x += (float4(LastUpdateColor).y - 0.5f) * LIGHT_COLORCHANGE_POS_MOD;
		vEyePt.z += (float4(LastUpdateColor).y - 0.5f) * LIGHT_COLORCHANGE_POS_MOD;
	}*/

    D3DXVECTOR3 vLookDir;
    D3DXVECTOR3 vUpDir;

	if(!NeedsUpdate() && !WantsUpdate())
	{
		if(!forceUpdate)
			return; // Don't update when we don't need to
	}else
	{
		if(LightInfo->Vob->GetPositionWorld() != LastUpdatePosition)
		{
			// Position changed, refresh our caches
			VobCache.clear();
			SkeletalVobCache.clear();

			// Invalidate worldcache
			WorldCacheInvalid = true;
		}
	}

	

	// Update indoor/outdoor-state
	LightInfo->IsIndoorVob = LightInfo->Vob->IsIndoorVob();

	D3DXMATRIX proj;

	const bool dbg = false;

	// Generate cubemap view-matrices
    vLookDir = D3DXVECTOR3( 1.0f, 0.0f, 0.0f ) + vEyePt;
    vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
	if(dbg)Engine::GraphicsEngine->GetLineRenderer()->AddLine(LineVertex(vEyePt, float4(1.0f,0,0,1)), LineVertex((vLookDir - vEyePt) * 50.0f + vEyePt, float4(1.0f,1.0f,0,1)));
    D3DXMatrixLookAtLH( &CubeMapViewMatrices[0], &vEyePt, &vLookDir, &vUpDir );
    vLookDir = D3DXVECTOR3( -1.0f, 0.0f, 0.0f ) + vEyePt;
    vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
	if(dbg)Engine::GraphicsEngine->GetLineRenderer()->AddLine(LineVertex(vEyePt, float4(1.0f,0,0,1)), LineVertex((vLookDir - vEyePt) * 50.0f + vEyePt, float4(1.0f,1.0f,0,1)));
    D3DXMatrixLookAtLH( &CubeMapViewMatrices[1], &vEyePt, &vLookDir, &vUpDir );
    vLookDir = D3DXVECTOR3( 0.0f, 0.0f + 1.0f, 0.0f ) + vEyePt;
    vUpDir = D3DXVECTOR3( 0.0f, 0.0f, -1.0f );
	if(dbg)Engine::GraphicsEngine->GetLineRenderer()->AddLine(LineVertex(vEyePt, float4(1.0f,0,0,1)), LineVertex((vLookDir - vEyePt) * 50.0f + vEyePt, float4(1.0f,1.0f,0,1)));
    D3DXMatrixLookAtLH( &CubeMapViewMatrices[2], &vEyePt, &vLookDir, &vUpDir );
    vLookDir = D3DXVECTOR3( 0.0f, 0.0f - 1.0f, 0.0f ) + vEyePt;
    vUpDir = D3DXVECTOR3( 0.0f, 0.0f, 1.0f );
	if(dbg)Engine::GraphicsEngine->GetLineRenderer()->AddLine(LineVertex(vEyePt, float4(1.0f,0,0,1)), LineVertex((vLookDir - vEyePt) * 50.0f + vEyePt, float4(1.0f,1.0f,0,1)));
    D3DXMatrixLookAtLH( &CubeMapViewMatrices[3], &vEyePt, &vLookDir, &vUpDir );
    vLookDir = D3DXVECTOR3( 0.0f, 0.0f, 1.0f ) + vEyePt;
    vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
	if(dbg)Engine::GraphicsEngine->GetLineRenderer()->AddLine(LineVertex(vEyePt, float4(1.0f,0,0,1)), LineVertex((vLookDir - vEyePt) * 50.0f + vEyePt, float4(1.0f,1.0f,0,1)));
    D3DXMatrixLookAtLH( &CubeMapViewMatrices[4], &vEyePt, &vLookDir, &vUpDir );
    vLookDir = D3DXVECTOR3( 0.0f, 0.0f, -1.0f ) + vEyePt;
    vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
	if(dbg)Engine::GraphicsEngine->GetLineRenderer()->AddLine(LineVertex(vEyePt, float4(1.0f,0,0,1)), LineVertex((vLookDir - vEyePt) * 50.0f + vEyePt, float4(1.0f,1.0f,0,1)));
    D3DXMatrixLookAtLH( &CubeMapViewMatrices[5], &vEyePt, &vLookDir, &vUpDir );

	for(int i=0;i<6;i++)
		D3DXMatrixTranspose(&CubeMapViewMatrices[i], &CubeMapViewMatrices[i]);

	// Create the projection matrix
	float zNear = 15.0f;
	float zFar = LightInfo->Vob->GetLightRange() * 2.0f;
    D3DXMatrixPerspectiveFovLH( &proj, ((float)D3DX_PI * 0.5f), 1.0f, zNear, zFar );
	D3DXMatrixTranspose(&proj, &proj);

	// Setup near/far-planes. We need linear viewspace depth for the cubic shadowmaps.
	Engine::GAPI->GetRendererState()->GraphicsState.FF_zNear = zNear;
	Engine::GAPI->GetRendererState()->GraphicsState.FF_zFar = zFar;
	Engine::GAPI->GetRendererState()->GraphicsState.SetGraphicsSwitch(GSWITCH_LINEAR_DEPTH, true);

	bool oldDepthClip = Engine::GAPI->GetRendererState()->RasterizerState.DepthClipEnable;
	Engine::GAPI->GetRendererState()->RasterizerState.DepthClipEnable = true;

	// Upload view-matrices to the GPU
	CubemapGSConstantBuffer gcb;
	for(int i=0;i<6;i++)
	{
		gcb.PCR_View[i] = CubeMapViewMatrices[i];
		gcb.PCR_ViewProj[i] = proj * CubeMapViewMatrices[i];
	}

	ViewMatricesCB->UpdateBuffer(&gcb);
	ViewMatricesCB->BindToGeometryShader(2);

	//for(int i=0;i<6;i++)
	//	RenderCubemapFace(CubeMapViewMatrices[i], proj, i);
	RenderFullCubemap();

	if(dbg)
	{
		for(auto it = VobCache.begin();it!=VobCache.end();it++)
			Engine::GraphicsEngine->GetLineRenderer()->AddLine(LineVertex(vEyePt, float4(1.0f,0,0,1)), LineVertex((*it)->Vob->GetPositionWorld(), float4(1.0f,1.0f,0,1)));
	}

	Engine::GAPI->GetRendererState()->RasterizerState.DepthClipEnable = oldDepthClip;
	Engine::GAPI->GetRendererState()->GraphicsState.SetGraphicsSwitch(GSWITCH_LINEAR_DEPTH, false);

	LastUpdateColor = LightInfo->Vob->GetLightColor();
	LastUpdatePosition = vEyePt;
	DrawnOnce = true;
}
Ejemplo n.º 27
0
void sdk_mesh::render(ID3D11DeviceContext* context, D3DXMATRIX* to_clip)
{
    D3D11_PRIMITIVE_TOPOLOGY PrimType = D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED;

    assert(context);
    context->IASetInputLayout(vertex_layout_);
    
    context->VSSetShader(vs_, nullptr, 0);
    context->GSSetShader(nullptr, nullptr, 0);
    context->PSSetShader(ps_, nullptr, 0);
    
    //context->PSSetSamplers(0, 1, &ss_);

    context->OMSetBlendState(nullptr, nullptr, 0xFF);

    auto cbvs = cb_mesh_data_vs_.map(context);
    {
        D3DXMatrixTranspose(&cbvs->world, &world);
    }
    cb_mesh_data_vs_.unmap_vs(1);

    #define MAX_D3D11_VERTEX_STREAMS D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT

    if(sdk_mesh_->GetOutstandingBufferResources())
        return;

	//sdk_mesh_->RenderMesh(0, false, context, diffuse_tex_slot_, normal_tex_slot_, specular_tex_slot_);

    for(UINT m = 0; m < sdk_mesh_->GetNumMeshes(); m++)
    {
        SDKMESH_MESH* mesh = sdk_mesh_->GetMesh(m);

        UINT strides[MAX_D3D11_VERTEX_STREAMS];
        UINT offsets[MAX_D3D11_VERTEX_STREAMS];
        ID3D11Buffer* vb[MAX_D3D11_VERTEX_STREAMS];

        if(mesh->NumVertexBuffers > MAX_D3D11_VERTEX_STREAMS)
            return;

        for(UINT i = 0; i < mesh->NumVertexBuffers; ++i)
        {
            vb[i] = sdk_mesh_->GetVB11(m, i);
            strides[i] = sdk_mesh_->GetVertexStride(m, i);
            offsets[i] = 0;
        }

        ID3D11Buffer* index_buffer = sdk_mesh_->GetIB11(m);
        DXGI_FORMAT format = sdk_mesh_->GetIBFormat11(m);
    
        context->IASetVertexBuffers(0, mesh->NumVertexBuffers, vb, strides, offsets);
        context->IASetIndexBuffer(index_buffer, format, 0);

        for(UINT s = 0; s < mesh->NumSubsets; s++)
        {
            SDKMESH_SUBSET* subset = sdk_mesh_->GetSubset(m, s);
		
            auto pt = sdk_mesh_->GetPrimitiveType11(static_cast<SDKMESH_PRIMITIVE_TYPE>(subset->PrimitiveType));
            context->IASetPrimitiveTopology(pt);

            SDKMESH_MATERIAL* material = sdk_mesh_->GetMaterial(subset->MaterialID);

            auto cb = cb_mesh_data_ps_.map(context);
            {
                cb->diffuse_color    = material->Diffuse;
                cb->has_diffuse_tex  = material->pDiffuseRV11  != nullptr && diffuse_tex_slot_  != -1 && !IsErrorResource(material->pDiffuseRV11);
                cb->has_normal_tex   = material->pNormalRV11   != nullptr && normal_tex_slot_   != -1 && !IsErrorResource(material->pNormalRV11);
                cb->has_specular_tex = material->pSpecularRV11 != nullptr && specular_tex_slot_ != -1 && !IsErrorResource(material->pSpecularRV11);
                cb->has_alpha_tex    = false;
            }
            cb_mesh_data_ps_.unmap_ps(0);

            if (cb->has_diffuse_tex)
                context->PSSetShaderResources(diffuse_tex_slot_, 1, &material->pDiffuseRV11);

            if (cb->has_normal_tex)
                context->PSSetShaderResources(normal_tex_slot_, 1, &material->pNormalRV11);

            if (cb->has_specular_tex)
                context->PSSetShaderResources(specular_tex_slot_, 1, &material->pSpecularRV11);

            UINT index_count  = static_cast<UINT>(subset->IndexCount);
            UINT index_start  = static_cast<UINT>(subset->IndexStart);
            UINT vertex_start = static_cast<UINT>(subset->VertexStart);
        
            context->DrawIndexed(index_count, index_start, vertex_start);
        }
    }

}
//Set Shader Parameters Function
bool CParticleShader::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix,
	ID3D11ShaderResourceView* textures[4], vector<CLight*> lightList, CCamera* mainCamera) {

	//Define Variables
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	MatrixBufferType* dataPtr;
	CameraBufferType* dataPtr1;
	unsigned int bufferNumber;

	//Transpose Matrices for Shader
	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

	//////////////////////////////////////////////////
	//Vertex Shader Code Below

	//Lock Constant Buffer
	result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if (FAILED(result))
	{
		return false;
	}

	//Get Pointer to Constant Buffer Data
	dataPtr = (MatrixBufferType*)mappedResource.pData;

	//Copy Matrices into Constant Buffer
	dataPtr->world = worldMatrix;
	dataPtr->view = viewMatrix;
	dataPtr->projection = projectionMatrix;

	//Unlock Constant Buffer
	deviceContext->Unmap(m_matrixBuffer, 0);

	//Set Position of Constant Buffer in Vertex Shader
	bufferNumber = 0;

	//Set Constant Buffer with Updated Values
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);

	//Lock Camera Constant Buffer
	result = deviceContext->Map(m_cameraBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if (FAILED(result))
	{
		return false;
	}

	//Get Pointer to data in Constant Buffer
	dataPtr1 = (CameraBufferType*)mappedResource.pData;

	dataPtr1->cameraPosition = mainCamera->GetPosition();
	dataPtr1->padding = 0.0f;

	//Unlock Constant Buffer
	deviceContext->Unmap(m_cameraBuffer, 0);

	//Increase Buffer number
	bufferNumber++;

	//Set Camera Constant Buffer in Vertex Shader
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_cameraBuffer);

	///////////////////////////////////////////////////
	//Geometry Shader Code Below



	//////////////////////////////////////////////////

	//////////////////////////////////////////////////
	//Pixel Shader Code Below:

	// Set shader texture resource in the pixel shader.
	deviceContext->PSSetShaderResources(0, 4, textures);

	//Set position of Constant Buffers in Pixel Shader
	bufferNumber = 0;

	//Set the Light Constant Buffer in the Pixel Shader with the updated Values
	deviceContext->PSSetConstantBuffers(bufferNumber, 0, &m_matrixBuffer);

	//////////////////////////////////////////////////


	return true;
}
bool VerticalBlurShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix,
	D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, float screenHeight)
{
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	MatrixBufferType* dataPtr;
	unsigned int bufferNumber;
	ScreenSizeBufferType* dataPtr2;

	// Transpose the matrices to prepare them for the shader.
	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

	// Lock the matrix constant buffer so it can be written to.
	result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if (FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr = (MatrixBufferType*)mappedResource.pData;

	// Copy the matrices into the constant buffer.
	dataPtr->world = worldMatrix;
	dataPtr->view = viewMatrix;
	dataPtr->projection = projectionMatrix;

	// Unlock the constant buffer.
	deviceContext->Unmap(m_matrixBuffer, 0);

	// Set the position of the constant buffer in the vertex shader.
	bufferNumber = 0;

	// Now set the constant buffer in the vertex shader with the updated values.
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);

	// Lock the screen size constant buffer so it can be written to.
	result = deviceContext->Map(m_screenSizeBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if (FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the constant buffer.
	dataPtr2 = (ScreenSizeBufferType*)mappedResource.pData;

	// Copy the data into the constant buffer.
	dataPtr2->screenHeight = screenHeight;
	dataPtr2->padding = D3DXVECTOR3(0.0f, 0.0f, 0.0f);

	// Unlock the constant buffer.
	deviceContext->Unmap(m_screenSizeBuffer, 0);

	// Set the position of the constant buffer in the vertex shader.
	bufferNumber = 1;

	// Now set the constant buffer in the vertex shader with the updated values.
	deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_screenSizeBuffer);

	// Set shader texture resource in the pixel shader.
	deviceContext->PSSetShaderResources(0, 1, &texture);

	return true;
}
/*
 *	\brief Render the gizmo
*/
void CGizmo::Render(
		D3DXMATRIX worldMatrix,					//!< 
		D3DXMATRIX viewMatrix,					//!< 
		D3DXMATRIX projectionMatrix,			//!< 
		CCamera *camera
	)
{
	m_gizmoMesh->PrepareRender(m_renderer);
		
	// move to the position, but offset the y coordinate by one, to compensate for it been drawn around 0, 0, 0 local space
	IBrush *const brush = m_brush[m_currentBrush];

	D3DXMATRIX xformmat, scalemat;
	D3DXMatrixTranslation(&xformmat, m_position.x, m_position.y < 2.0f ? 2.0f : m_position.y + 2.0f, m_position.z); 
	D3DXMatrixScaling(&scalemat, static_cast<float>(brush->GetSize()) * 0.4f, 1.0f, static_cast<float>(brush->GetSize()) * 0.4f);
	
	D3DXMatrixMultiply (&worldMatrix, &scalemat, &xformmat);

	// Transpose the matrices to prepare them for the shader.
	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);	

	// Lock the constant buffer so it can be written to.
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	result = m_renderer->GetDeviceContext()->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if (FAILED(result))
		return;
	
	// Get a pointer to the data in the constant buffer.
	CGizmo::MatrixBuffer *const matrixDataPtr = (CGizmo::MatrixBuffer*)mappedResource.pData;

	// Copy the matrices into the constant buffer.
	matrixDataPtr->world = worldMatrix;
	matrixDataPtr->view = viewMatrix;
	matrixDataPtr->projection = projectionMatrix;

	// Unlock the constant buffer.
	m_renderer->GetDeviceContext()->Unmap(m_matrixBuffer, 0);

	result = m_renderer->GetDeviceContext()->Map(m_gizmoBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if (FAILED(result))
		return;

	// Get a pointer to the data in the constant buffer.
	CGizmo::GizmoBuffer *const gizmoDataPtr = (CGizmo::GizmoBuffer*)mappedResource.pData;

	// Copy the data into the constant buffer.

	// color based upon gizmo state
	if (m_gizmoState == GizmoState::Free)
	{
		// green
		gizmoDataPtr->color = D3DXVECTOR4(0.25f * (brush->GetStrength() * brush->GetStrength()), 0.6f * brush->GetStrength(), 0.1f * (3.0f - brush->GetStrength()), 0.01f);
	}
	else
	{
		// red
		gizmoDataPtr->color = D3DXVECTOR4(0.6f, 0.0f, 0.0f, 0.01f);
	}

	// Unlock the constant buffer.
	m_renderer->GetDeviceContext()->Unmap(m_gizmoBuffer, 0);

	// Finally set the constant buffer in the vertex shader with the updated values.
	m_renderer->GetDeviceContext()->VSSetConstantBuffers(0, 1, &m_matrixBuffer);
	m_renderer->GetDeviceContext()->VSSetConstantBuffers(1, 1, &m_gizmoBuffer);

	// Set the vertex input layout.
	m_renderer->GetDeviceContext()->IASetInputLayout(m_layout);

	// Set the vertex and pixel shaders that will be used to render this triangle.
	m_renderer->GetDeviceContext()->VSSetShader(m_vertexShader, NULL, 0);
	m_renderer->GetDeviceContext()->PSSetShader(m_pixelShader, NULL, 0);

	m_renderer->EnableAlphaBlending(true);

	// Render the triangle.
	m_gizmoMesh->Draw(m_renderer);

	m_renderer->EnableAlphaBlending(false);
}