Esempio n. 1
0
    void Update(float dt)
    {
      // Remove all models no longer being referenced.
      for (auto it = models.begin(); it != models.end();)
      {
        if (it->second.unique())
        {
          it = models.erase(it);
        }
        else
        {
          ++it;
        }
      }

      if (!d3d.Context || !d3d.RenderTarget) return;

      // Clear the render target.
      float clearColor [] = { 0.0f, 0.125f, 0.6f, 1.0f };
      d3d.Context->ClearRenderTargetView(d3d.RenderTarget, clearColor);

      // Clear the depth buffer to max depth (1.0).
      d3d.Context->ClearDepthStencilView(d3d.DSView, D3D11_CLEAR_DEPTH, 1, 0);

      // Set the vertex layout for the input assembler stage.
      d3d.Context->IASetInputLayout(inputLayout);
      // Set the render target to the depth-stencil view.
      d3d.Context->OMSetRenderTargets(1, d3d.RenderTarget, d3d.DSView);

      // Some hard-coded light directions and colors.
      XMFLOAT4 lightDirections [] =
      {
        { -.577f, .577f, -.577f, 1 },
        { 0, 0, -1, 1 }
      };
      XMFLOAT4 lightColors [] =
      {
        { 1, 1, 1, 1 },
        { 1, 1, 0, 1 }
      };

      SceneConstants sceneConstants;

      // Update elapsed time.
      static float t = 0.0f;
      static DWORD dwTimeStart = 0;
      DWORD dwTimeCur = GetTickCount();
      if (dwTimeStart == 0)
        dwTimeStart = dwTimeCur;
      t = (dwTimeCur - dwTimeStart) / 1000.0f;

      // Rotate the second light's direction.
      auto rotate = XMMatrixRotationY(-2 * t);
      XMStoreFloat4(&lightDirections[1], XMVector3Transform(XMLoadFloat4(&lightDirections[1]), rotate));

      // Store the view projection and light info in the constant buffer.
      XMStoreFloat4x4(
        &sceneConstants.viewProjection,
        XMMatrixTranspose(
        XMLoadFloat4x4(&Camera.ViewProjectionMatrix())));
      sceneConstants.lightDirections = { lightDirections[0], lightDirections[1] };
      sceneConstants.lightColors = { lightColors[0], lightColors[1] };

      d3d.Context->UpdateSubresource(cbScene, 0, nullptr, &sceneConstants, 0, 0);
      d3d.Context->VSSetConstantBuffers(0, 1, cbScene);
      d3d.Context->PSSetConstantBuffers(0, 1, cbScene);

      // Draw all models.
      for (auto& modelPair : models)
      {
        modelPair.second->Draw();
      }

      // Debug drawing.
      DebugDrawer::Instance().Update();

      // Present the back buffer to the display.
      d3d.SwapChain->Present(0, 0);
    }
// Fill the command list with all the render commands and dependent state.
void D3D12PipelineStateCache::PopulateCommandList()
{
	// Command list allocators can only be reset when the associated
	// command lists have finished execution on the GPU; apps should use
	// fences to determine GPU execution progress.
	ThrowIfFailed(m_commandAllocators[m_frameIndex]->Reset());

	// However, when ExecuteCommandList() is called on a particular command
	// list, that command list can then be reset at any time and must be before
	// re-recording.
	ThrowIfFailed(m_commandList->Reset(m_commandAllocators[m_frameIndex].Get(), nullptr));

	// Set necessary state.
	m_commandList->SetGraphicsRootSignature(m_rootSignature.Get());

	ID3D12DescriptorHeap* ppHeaps[] = { m_srvHeap.Get() };
	m_commandList->SetDescriptorHeaps(_countof(ppHeaps), ppHeaps);

	m_commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	m_commandList->RSSetViewports(1, &m_viewport);
	m_commandList->RSSetScissorRects(1, &m_scissorRect);

	CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart(), m_frameIndex, m_rtvDescriptorSize);
	CD3DX12_CPU_DESCRIPTOR_HANDLE intermediateRtvHandle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart(), FrameCount, m_rtvDescriptorSize);
	CD3DX12_GPU_DESCRIPTOR_HANDLE srvHandle(m_srvHeap->GetGPUDescriptorHandleForHeapStart());

	m_commandList->OMSetRenderTargets(1, &intermediateRtvHandle, FALSE, nullptr);

	// Record commands.
	m_commandList->ClearRenderTargetView(intermediateRtvHandle, IntermediateClearColor, 0, nullptr);

	// Draw the scene as normal into the intermediate buffer.
	PIXBeginEvent(m_commandList.Get(), 0, L"Draw cube");
	{
		static float rot = 0.0f;
		DrawConstantBuffer* drawCB = (DrawConstantBuffer*)m_dynamicCB.GetMappedMemory(m_drawIndex, m_frameIndex);
		drawCB->worldViewProjection = XMMatrixTranspose(XMMatrixRotationY(rot) * XMMatrixRotationX(-rot) * m_camera.GetViewMatrix() * m_projectionMatrix);

		rot += 0.01f;

		m_commandList->IASetVertexBuffers(0, 1, &m_cubeVbv);
		m_commandList->IASetIndexBuffer(&m_cubeIbv);
		m_psoLibrary.SetPipelineState(m_device.Get(), m_rootSignature.Get(), m_commandList.Get(), BaseNormal3DRender, m_frameIndex);

		m_commandList->SetGraphicsRootConstantBufferView(RootParameterCB, m_dynamicCB.GetGpuVirtualAddress(m_drawIndex, m_frameIndex));
		m_commandList->DrawIndexedInstanced(36, 1, 0, 0, 0);
		m_drawIndex++;
	}
	PIXEndEvent(m_commandList.Get());

	// Set up the state for a fullscreen quad.
	m_commandList->IASetVertexBuffers(0, 1, &m_quadVbv);
	m_commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);

	// Indicate that the back buffer will be used as a render target and the
	// intermediate render target will be used as a SRV.
	D3D12_RESOURCE_BARRIER barriers[] = {
		CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_frameIndex].Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET),
		CD3DX12_RESOURCE_BARRIER::Transition(m_intermediateRenderTarget.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)
	};

	m_commandList->ResourceBarrier(_countof(barriers), barriers);
	m_commandList->SetGraphicsRootDescriptorTable(RootParameterSRV, m_srvHeap->GetGPUDescriptorHandleForHeapStart());

	const float black[] = { 0.0f, 0.0f, 0.0f, 0.0f };
	m_commandList->ClearRenderTargetView(rtvHandle, black, 0, nullptr);
	m_commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, nullptr);

	// Draw some quads using the rendered scene with some effect shaders.
	PIXBeginEvent(m_commandList.Get(), 0, L"Post-processing");
	{
		UINT quadCount = 0;
		static const UINT quadsX = 3;
		static const UINT quadsY = 3;

		// Cycle through all of the effects.
		for (UINT i = PostBlit; i < EffectPipelineTypeCount; i++)
		{
			if (m_enabledEffects[i])
			{
				D3D12_VIEWPORT viewport = {};
				viewport.TopLeftX = (quadCount % quadsX) * (m_viewport.Width / quadsX);
				viewport.TopLeftY = (quadCount / quadsY) * (m_viewport.Height / quadsY);
				viewport.Width = m_viewport.Width / quadsX;
				viewport.Height = m_viewport.Height / quadsY;
				viewport.MinDepth = 0.0f;
				viewport.MaxDepth = 0.0f;

				PIXBeginEvent(m_commandList.Get(), 0, g_cEffectNames[i]);
				m_commandList->RSSetViewports(1, &viewport);
				m_psoLibrary.SetPipelineState(m_device.Get(), m_rootSignature.Get(), m_commandList.Get(), static_cast<EffectPipelineType>(i), m_frameIndex);
				m_commandList->DrawInstanced(4, 1, 0, 0);
				PIXEndEvent(m_commandList.Get());
			}

			quadCount++;
		}
	}
	PIXEndEvent(m_commandList.Get());

	// Revert resource states back to original values.
	barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
	barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
	barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
	barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;

	m_commandList->ResourceBarrier(_countof(barriers), barriers);

	ThrowIfFailed(m_commandList->Close());
}
	void CubeDemo::update(const GameTimer & timer)
	{
		mCamera->update(timer);
		mAngle += XM_PI * static_cast<float>(timer.elapsedGameTime());
		XMStoreFloat4x4(&mWorldMatrix, XMMatrixRotationY(mAngle));
	}
Esempio n. 4
0
void Game::Update()
{
	m_pCube->Update();
	XMVECTOR cameraPos = XMLoadFloat3(&m_pCamera->GetCameraPos());
	/*cameraPos += XMVectorSet(0.0001f,0.0f,0.0f,0.0f);
	XMFLOAT3 newCameraPos;
	XMStoreFloat3(&newCameraPos,cameraPos);*/
	//cameraPos * XMMatrixRotationY(XM_PIDIV2/9.0f);

	//Camera Rotation code
	/*XMFLOAT3 newCameraPos;
	cameraPos = XMVector3Rotate(cameraPos,XMQuaternionRotationMatrix(XMMatrixRotationY(-(XM_PIDIV2/9000.0f))));
	XMStoreFloat3(&newCameraPos,cameraPos);
	m_pCamera->SetCameraPos(newCameraPos);
	m_pCamera->UpdateViewMatrix();*/

	//keyboard input test code
	//bool pressed = ENGINE->GetInputManager()->IsKeyDown(VK_UP);

	//cout << pressed;
	XMFLOAT3 newCameraPos;
	if(ENGINE->GetInputManager()->IsKeyDown(VK_UP))
	{
		cameraPos = XMVector3Rotate(cameraPos,XMQuaternionRotationMatrix(XMMatrixRotationX((XM_PIDIV2/9000.0f))));
	}
	if(ENGINE->GetInputManager()->IsKeyDown(VK_DOWN))
	{
		cameraPos = XMVector3Rotate(cameraPos,XMQuaternionRotationMatrix(XMMatrixRotationX(-(XM_PIDIV2/9000.0f))));
	}
	if(ENGINE->GetInputManager()->IsKeyDown(VK_LEFT))
	{
		cameraPos = XMVector3Rotate(cameraPos,XMQuaternionRotationMatrix(XMMatrixRotationY((XM_PIDIV2/9000.0f))));
	}
	//if(ENGINE->GetInputManager()->IsKeyDown(VK_RIGHT))
	if(ENGINE->GetInputManager()->IsCommandDown(L"RIGHT"))
	{
		cameraPos = XMVector3Rotate(cameraPos,XMQuaternionRotationMatrix(XMMatrixRotationY(-(XM_PIDIV2/9000.0f))));
	}
	if(ENGINE->GetInputManager()->IsKeyDown(0x57))//W
	{
		cameraPos = XMVector3Transform(cameraPos,XMMatrixTranslation(0,0,0.01f));
	}
	if(ENGINE->GetInputManager()->IsKeyDown(0x53))//S
	{
		cameraPos = XMVector3Transform(cameraPos,XMMatrixTranslation(0,0,-0.01f));
	}
	if(ENGINE->GetInputManager()->IsKeyDown(0x41))//A
	{
		cameraPos = XMVector3Transform(cameraPos,XMMatrixTranslation(-0.01f,0,0));
	}
	if(ENGINE->GetInputManager()->IsKeyDown(0x44))//D
	{
		cameraPos = XMVector3Transform(cameraPos,XMMatrixTranslation(0.01f,0,0));
	}
	if(ENGINE->GetInputManager()->IsKeyDown(0x51))//Q
	{
		cameraPos = XMVector3Transform(cameraPos,XMMatrixTranslation(0,-0.01f,0));
	}
	if(ENGINE->GetInputManager()->IsKeyDown(0x45))//E
	{
		cameraPos = XMVector3Transform(cameraPos,XMMatrixTranslation(0,0.01f,0));
	}
	
	XMStoreFloat3(&newCameraPos,cameraPos);
	m_pCamera->SetCameraPos(newCameraPos);
	m_pCamera->UpdateViewMatrix();
}
void Enemy::move(FLOAT dt)
{


	bool dontUpdate = false;

	XMMATRIX startingworldMatrix = XMLoadFloat4x4(&mEnemyStartingWorld);
	XMVECTOR S;
	XMVECTOR P;
	XMVECTOR Q;

	XMMatrixDecompose(&S, &Q, &P, startingworldMatrix);


	XMVECTOR enemyPosition = XMLoadFloat3(&mEnemyPosition);



	FLOAT newPos = XMVectorGetZ(enemyPosition);
	FLOAT oldPos = XMVectorGetZ(P);

	direction = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);



	FLOAT diffX;
	FLOAT diffY;
	FLOAT diffZ;

	diffX = 0;
	diffY = 0;
	diffZ = 0;





	if (travelToPoint == 2)
	{


		diffX = mEnemyPosition.x - mEnemyPositionTwo.x;
		diffY = mEnemyPosition.y - mEnemyPositionTwo.y;
		diffZ = mEnemyPosition.z - mEnemyPositionTwo.z;
		mEnemyPositionThree.x;

	
	
	

		int nothing = 0;
		if (diffX < 0.0f)
		{

			diffX *= -1;
		}
		if (diffY < 0.0f)
		{

			diffY *= -1;
		}
		if (diffZ < 0.0f)
		{

			diffZ *= -1;
		}

		//////////////////////////////////
		if (diffX < 0.01)
		{

			mEnemyPosition.x = mEnemyPositionTwo.x;
		}
		if (diffY < 0.01)
		{

			mEnemyPosition.y = mEnemyPositionTwo.y;
		}
		if (diffZ < 0.01)
		{

			mEnemyPosition.z = mEnemyPositionTwo.z;
		}
		////////////////////////////////


		if (mEnemyPosition.x > mEnemyPositionTwo.x)
		{

			direction += XMVectorSet(-1.0f, 0.0f, 0, 0.0f);


		}
		else if (mEnemyPosition.x < mEnemyPositionTwo.x)
		{

			direction += XMVectorSet(1.0f, 0.0f, 0, 0.0f);

		}



		if (mEnemyPosition.z > mEnemyPositionTwo.z)
		{

			direction += XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);


		}
		else if (mEnemyPosition.z < mEnemyPositionTwo.z)
		{

			direction += XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);

		}


		if (mEnemyPosition.y > mEnemyPositionTwo.y)
		{

			direction += XMVectorSet(0.0f, -1.0f, 0.0f, 0.0f);


		}
		else if (mEnemyPosition.y < mEnemyPositionTwo.y)
		{

			direction += XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

		}
		if (diffX < 0.05f && diffY < 0.05f && diffZ < 0.05f)
		{

		
			if (timesThrough == 0)
			{
				if (mEnemyPositionThree.x == 0)
				{

					dontUpdate = true;
					travelToPoint = 1;

					lastPoint = mEnemyPositionTwo;

				}
				else if (mEnemyPositionThree.x != 0)
				{
					dontUpdate = true;
					travelToPoint = 3;

					lastPoint = mEnemyPositionTwo;

				}
			}
			else
			{
				dontUpdate = true;

				travelToPoint = 1;
				lastPoint = mEnemyPositionTwo;
			}

			int something = 1;
		}

	}



	/////////////////////////////////////////
	else if (travelToPoint == 1)
	{

		timesThrough = 0;

		diffX = mEnemyPosition.x - mEnemyPositionOne.x;
		diffY = mEnemyPosition.y - mEnemyPositionOne.y;
		diffZ = mEnemyPosition.z - mEnemyPositionOne.z;



		if (diffX < 0.0f)
		{

			diffX *= -1;
		}
		if (diffY < 0.0f)
		{

			diffY *= -1;
		}
		if (diffZ < 0.0f)
		{

			diffZ *= -1;
		}


		//////////////////////////////////
		if (diffX < 0.01)
		{

			mEnemyPosition.x = mEnemyPositionOne.x;
		}
		if (diffY < 0.01)
		{

			mEnemyPosition.y = mEnemyPositionOne.y;
		}
		if (diffZ < 0.01)
		{

			mEnemyPosition.z = mEnemyPositionOne.z;
		}
		////////////////////////////////



		if (mEnemyPosition.x > mEnemyPositionOne.x)
		{

			direction += XMVectorSet(-1.0f, 0.0f, 0, 0.0f);


		}
		if (mEnemyPosition.x < mEnemyPositionOne.x)
		{

			direction += XMVectorSet(1.0f, 0.0f,0, 0.0f);

		}



		if (mEnemyPosition.z > mEnemyPositionOne.z && diffZ > 0.01)
		{

			direction += XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);


		}
		if (mEnemyPosition.z < mEnemyPositionOne.z && diffZ > 0.01)
		{

			direction += XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);

		}


		if (mEnemyPosition.y > mEnemyPositionOne.y)
		{

			direction += XMVectorSet(0.0f, -1.0f, 0.0f, 0.0f);


		}
		if (mEnemyPosition.y < mEnemyPositionOne.y)
		{

			direction += XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

		}
		if (diffX < 0.05f && diffY < 0.05f && diffZ < 0.05f)
		{
			
			travelToPoint = 2;

			lastPoint = mEnemyPositionOne;

		}
	}



	////////////////////////////////////////////////////////////////////////////////
	else if (travelToPoint == 3 && timesThrough == 0)
	{


		diffX = mEnemyPosition.x - mEnemyPositionThree.x;
		diffY = mEnemyPosition.y - mEnemyPositionThree.y;
		diffZ = mEnemyPosition.z - mEnemyPositionThree.z;


		int nothing;
		if (diffX < 0.0f)
		{

			diffX *= -1;
		}
		if (diffY < 0.0f)
		{

			diffY *= -1;
		}
		if (diffZ < 0.0f)
		{

			diffZ *= -1;
		}


		//////////////////////////////////
		if (diffX < 0.01)
		{

			mEnemyPosition.x = mEnemyPositionThree.x;
		}
		if (diffY < 0.01)
		{

			mEnemyPosition.y = mEnemyPositionThree.y;
		}
		if (diffZ < 0.01)
		{

			mEnemyPosition.z = mEnemyPositionThree.z;
		}
		////////////////////////////////



		if (mEnemyPosition.x > mEnemyPositionThree.x)
		{

			direction += XMVectorSet(-1.0f, 0.0f, 0, 0.0f);


		}
		if (mEnemyPosition.x < mEnemyPositionThree.x)
		{

			direction += XMVectorSet(1.0f, 0.0f, 0, 0.0f);

		}



		if (mEnemyPosition.z > mEnemyPositionThree.z)
		{

			direction += XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);


		}
		if (mEnemyPosition.z < mEnemyPositionThree.z)
		{

			direction += XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);

		}


		if (mEnemyPosition.y > mEnemyPositionThree.y)
		{

			direction += XMVectorSet(0.0f, -1.0f, 0.0f, 0.0f);


		}
		if (mEnemyPosition.y < mEnemyPositionThree.y)
		{

			direction += XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

		}
		if (diffX < 0.05f && diffY < 0.05f && diffZ < 0.05f)
		{

			if (mEnemyPositionFour.x == NULL)
			{
					


				travelToPoint = 2;
				timesThrough = 1;
			}
			else
			{
				
				travelToPoint = 4;
		
			}
		}
	}


	else if (travelToPoint == 4)
	{


		diffX = mEnemyPosition.x - mEnemyPositionFour.x;
		diffY = mEnemyPosition.y - mEnemyPositionFour.y;
		diffZ = mEnemyPosition.z - mEnemyPositionFour.z;

		if (diffX < 0.0f)
		{

			diffX *= -1;
		}
		if (diffY < 0.0f)
		{

			diffY *= -1;
		}
		if (diffZ < 0.0f)
		{

			diffZ *= -1;
		}

		//////////////////////////////////
		if (diffX < 0.001)
		{

			mEnemyPosition.x = mEnemyPositionFour.x;
		}
		if (diffY < 0.001)
		{

			mEnemyPosition.y = mEnemyPositionFour.y;
		}
		if (diffZ < 0.001)
		{

			mEnemyPosition.z = mEnemyPositionFour.z;
		}
		////////////////////////////////



		if (mEnemyPosition.x > mEnemyPositionFour.x)
		{

			direction += XMVectorSet(-1.0f, 0.0f, 0, 0.0f);


		}
		if (mEnemyPosition.x < mEnemyPositionFour.x)
		{

			direction += XMVectorSet(1.0f, 0.0f,0, 0.0f);

		}



		if (mEnemyPosition.z > mEnemyPositionFour.z && diffZ > 0.01)
		{

			direction += XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);


		}
		if (mEnemyPosition.z < mEnemyPositionFour.z && diffZ > 0.01)
		{

			direction += XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);

		}


		if (mEnemyPosition.y > mEnemyPositionFour.y)
		{

			direction += XMVectorSet(0.0f, -1.0f, 0.0f, 0.0f);


		}
		if (mEnemyPosition.y < mEnemyPositionFour.y)
		{

			direction += XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

		}
		if (diffX < 0.05f && diffY < 0.05f && diffZ < 0.05f)
		{

			
			travelToPoint = 1;

			lastPoint = mEnemyPositionFour;
		}
	}












	XMMATRIX worldMatrix = XMLoadFloat4x4(&mEnemyWorld);
	XMVECTOR r = XMLoadFloat3(&mEnemyPosition);



	// Normalize our destinated direction vector
	direction = XMVector3Normalize(direction);





	/////character spinning make it more smooth

	if (XMVectorGetX(XMVector3Dot(direction, oldCharDirection)) == -1)
	{
		oldCharDirection += XMVectorSet(1.11f, 1.0f, 0.0f, 0.0f);
	}


	///////get characters position in world space
	charPosition = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
	charPosition = XMVector3TransformCoord(charPosition, worldMatrix);



	///// rotate the character
	float destDirLength = 10.0f * dt;



	currCharDirection = (oldCharDirection)+(direction * destDirLength);
	currCharDirection = XMVector3Normalize(currCharDirection);


	// get the angle 
	float charDirAngle = XMVectorGetX(XMVector3AngleBetweenNormals(XMVector3Normalize(currCharDirection), XMVector3Normalize(EnemyForward)));



	if (XMVectorGetY(XMVector3Cross(currCharDirection, EnemyForward)) > 0.0f)
	{
		charDirAngle = -charDirAngle;
	}



	float Speed = speed * dt;



	direction = direction * Speed;



	charPosition = charPosition + direction;



	XMMATRIX rotationMatrix;





	XMMATRIX Translation = XMMatrixTranslation(XMVectorGetX(charPosition), XMVectorGetY(charPosition), XMVectorGetZ(charPosition));

	rotationMatrix = XMMatrixRotationY(charDirAngle - 3.14159265f);		// Subtract PI from angle so the character doesn't run backwards



	worldMatrix = rotationMatrix * Translation;


	XMMatrixDecompose(&S, &Q, &P, worldMatrix);


	XMStoreFloat3(&mEnemyPosition, P);

	XMStoreFloat4(&mEnemyRotationQuad, Q);




	XMStoreFloat4x4(&mEnemyWorld, worldMatrix);



	oldCharDirection = currCharDirection;



}
Esempio n. 6
0
void Application::Update()
{
    // Update our time
    static float t = 0.0f;


    if (_driverType == D3D_DRIVER_TYPE_REFERENCE)
    {
        t += (float) XM_PI * 0.0125f;
    }
    else
    {
        static DWORD dwTimeStart = 0;
        DWORD dwTimeCur = GetTickCount();

        if (dwTimeStart == 0)
            dwTimeStart = dwTimeCur;

        t = (dwTimeCur - dwTimeStart) / -5000.0f;
		
    }

	time = t;

	if (GetAsyncKeyState(VK_ESCAPE))
	{
		PostQuitMessage(0);
	}

	short UKeyState = GetAsyncKeyState('U');

	if ((1 << 16) & UKeyState)
	{
		_pImmediateContext->RSSetState(_wireFrame);
	}

	short YKeyState = GetAsyncKeyState('Y');

	if ((1 << 16) & YKeyState)
	{
		_pImmediateContext->RSSetState(_solidFill);
	}

	// Definitions for input keys
	short LeftKeyState = GetAsyncKeyState('A');
	short ForwardKeyState = GetAsyncKeyState('W');
	short BackwardKeyState = GetAsyncKeyState('S');
	short RightKeyState = GetAsyncKeyState('D');
	short RotateLeftKeyState = GetAsyncKeyState(VK_LEFT);
	short RotateRightState = GetAsyncKeyState(VK_RIGHT);
	short PitchUpKeyState = GetAsyncKeyState(VK_DOWN);
	short PitchDownKeyState = GetAsyncKeyState(VK_UP);
	short Cam1KeyState = GetAsyncKeyState(VK_NUMPAD1);
	short Cam2KeyState = GetAsyncKeyState(VK_NUMPAD2);
	short Cam3KeyState = GetAsyncKeyState(VK_NUMPAD3);
	short Cam4KeyState = GetAsyncKeyState(VK_NUMPAD4);

	// Camera state switchers
	if ((0x8000) & Cam1KeyState)
	{
		cam1state = true;
		cam2state = false;
		cam3state = false;
		cam4state = false;
	}
	
	if ((0x8000) & Cam2KeyState)
	{
		cam1state = false;
		cam2state = true;
		cam3state = false;
		cam4state = false;
	}

	if ((0x8000) & Cam3KeyState)
	{
		cam1state = false;
		cam2state = false;
		cam3state = true;
		cam4state = false;
	}

	if ((0x8000) & Cam4KeyState)
	{
		cam1state = false;
		cam2state = false;
		cam3state = false;
		cam4state = true;
	}

	if (cam1state) // Camera 1: Birds-Eye View
	{
		_view = _camera.ViewFL();
		eyePosition = _camera.GetPosition();
		_projection = _camera.ProjFL();

		if ((0x8000) & LeftKeyState)
		{
			_camera.Strafe(-0.5f);
		}

		if ((0x8000) & RightKeyState)
		{
			_camera.Strafe(0.5f);
		}

		if ((0x8000) & ForwardKeyState)
		{
			_camera.Walk(0.5f);
		}

		if ((0x8000) & BackwardKeyState)
		{
			_camera.Walk(-0.5f);
		}

		if ((0x8000) & RotateLeftKeyState)
		{
			_camera.RotateY(-0.004f);
		}

		if ((0x8000) & RotateRightState)
		{
			_camera.RotateY(0.004f);
		}

		if ((0x8000) & PitchUpKeyState)
		{
			_camera.Pitch(-0.004f);
		}

		if ((0x8000) & PitchDownKeyState)
		{
			_camera.Pitch(0.004f);
		}

		_camera.UpdateViewMatrix();
		camPos = _camera.GetPosition();

		XMFLOAT3 camPos = _camera.GetPosition();

		XMStoreFloat4x4(&_skyBox, XMMatrixScaling(5000.0f, 5000.0f, 5000.0f) * XMMatrixTranslation(camPos.x, camPos.y, camPos.z));
		XMStoreFloat4x4(&_gridWorld3, XMMatrixTranslation(camPos.x, -70.0f, camPos.z));
	}
	else if (cam2state) // Camera 2: Static Ground view
	{
		_view = _camera2.ViewFL();
		eyePosition = _camera2.GetPosition();
		_projection = _camera2.ProjFL();

		_camera2.UpdateViewMatrix();
		camPos = _camera2.GetPosition();

		XMFLOAT3 cam2Pos = _camera2.GetPosition();

		XMStoreFloat4x4(&_skyBox, XMMatrixScaling(5000.0f, 5000.0f, 5000.0f) * XMMatrixTranslation(cam2Pos.x, cam2Pos.y, cam2Pos.z));
		XMStoreFloat4x4(&_gridWorld3, XMMatrixTranslation(cam2Pos.x, -70.0f, cam2Pos.z));
	}
	else if (cam3state) // Camera 3: Fuselage View
	{
		_view = _camera3.ViewFL();
		eyePosition = _camera3.GetPosition();
		_projection = _camera3.ProjFL();


		objMesh4->ForwardBackward(0.2f);
		camObjPos = objPos;

		
		_camera3.SetPosition(camObjPos.x, camObjPos.y + 5, camObjPos.z);

		XMFLOAT3 CamLook = _camera3.GetPosition();
		float rotationY = objMesh4->getRotationY();
		float rotationX = objMesh4->getRotationX();
		
		
		objMesh4->UpdateWorldPlane();

		if ((0x8000) & RotateLeftKeyState) // Rotates the plane left
		{
			//_camera3.Strafe(2.002f);
			_camera3.RotateY(-0.002f);
			objMesh4->LeftRight(-0.002f);
			objMesh4->SetRotation(rotationX, rotationY - 0.002f, 0.0f);
			camObjPos = objPos;
			objMesh4->UpdateWorldPlane();
			objMesh4->UpdateWorld();

			_camera3.SetPosition(camObjPos.x, camObjPos.y + 5, camObjPos.z);
			_camera3.UpdateViewMatrix();
		}

		if ((0x8000) & RotateRightState) // Rotates the plane right
		{
			_camera3.RotateY(0.002f);
			objMesh4->LeftRight(0.002f);
			objMesh4->SetRotation(rotationX, rotationY  + 0.002f, 0.0f);
			camObjPos = objPos;
			objMesh4->UpdateWorldPlane();
			objMesh4->UpdateWorld();
		}

		if ((0x8000) & PitchUpKeyState) // Pitches the plane upwards
		{
			_camera3.Pitch(-0.002f);
			objMesh4->UpDown(-0.002f);
			objMesh4->SetRotation(rotationX + 0.002f, rotationY, 0.0f);
			camObjPos = objPos;
			objMesh4->UpdateWorldPlane();
			objMesh4->UpdateWorld();
		}

		if ((0x8000) & PitchDownKeyState) // Pitches the plane downwards
		{
			_camera3.Pitch(0.002f);
			objMesh4->UpDown(0.002f);
			objMesh4->SetRotation(rotationX - 0.002f, rotationY, 0.0f);
			camObjPos = objPos;
			objMesh4->UpdateWorldPlane();
			objMesh4->UpdateWorld();
		}

		
		_camera3.UpdateViewMatrix();
		camPos = _camera3.GetPosition();

		XMFLOAT3 cam3Pos = _camera3.GetPosition();

		XMStoreFloat4x4(&_skyBox, XMMatrixScaling(5000.0f, 5000.0f, 5000.0f) * XMMatrixTranslation(cam3Pos.x, cam3Pos.y, cam3Pos.z));
		XMStoreFloat4x4(&_gridWorld3, XMMatrixTranslation(cam3Pos.x, -70.0f, cam3Pos.z));
	}
	else if (cam4state) //3rd Person Aircraft view
	{
		_view = _camera4.ViewFL();
		eyePosition = _camera4.GetPosition();
		_projection = _camera4.ProjFL();

		objMesh4->ForwardBackward(0.2f);
		camObjPos = objPos;


		_camera4.SetPosition(camObjPos.x, camObjPos.y + 15, camObjPos.z + 30);
		objMesh4->UpdateWorldPlane();

		float rotationY = objMesh4->getRotationY();
		float rotationX = objMesh4->getRotationX();

		if ((0x8000) & RotateLeftKeyState) // Rotates the plane left
		{
			//_camera3.Strafe(2.002f);
			_camera3.RotateY(-0.002f);
			objMesh4->LeftRight(-0.002f);
			objMesh4->SetRotation(rotationX, rotationY - 0.002f, 0.0f);
			camObjPos = objPos;
			objMesh4->UpdateWorldPlane();
			objMesh4->UpdateWorld();

			_camera4.SetPosition(camObjPos.x, camObjPos.y + 15, camObjPos.z + 30);
			_camera4.UpdateViewMatrix();
		}

		if ((0x8000) & RotateRightState) // Rotates the plane right
		{
			_camera3.RotateY(0.002f);
			objMesh4->LeftRight(0.002f);
			objMesh4->SetRotation(rotationX, rotationY + 0.002f, 0.0f);
			camObjPos = objPos;
			objMesh4->UpdateWorldPlane();
			objMesh4->UpdateWorld();
		}

		if ((0x8000) & PitchUpKeyState) // Pitches the plane upwards
		{
			_camera3.Pitch(-0.002f);
			objMesh4->UpDown(-0.002f);
			objMesh4->SetRotation(rotationX + 0.002f, rotationY, 0.0f);
			camObjPos = objPos;
			objMesh4->UpdateWorldPlane();
			objMesh4->UpdateWorld();
		}

		if ((0x8000) & PitchDownKeyState) // Pitches the plane downwards
		{
			_camera3.Pitch(0.002f);
			objMesh4->UpDown(0.002f);
			objMesh4->SetRotation(rotationX - 0.002f, rotationY, 0.0f);
			camObjPos = objPos;
			objMesh4->UpdateWorldPlane();
			objMesh4->UpdateWorld();
		}

		
		XMFLOAT3 cam4Pos = _camera4.GetPosition();
		_camera3.UpdateViewMatrix();
		_camera4.UpdateViewMatrix();
		XMStoreFloat4x4(&_skyBox, XMMatrixScaling(6800.0f, 6800.0f, 6800.0f) * XMMatrixTranslation(cam4Pos.x, cam4Pos.y, cam4Pos.z));
		XMStoreFloat4x4(&_gridWorld3, XMMatrixTranslation(cam4Pos.x, -70.0f, cam4Pos.z));
		camPos = _camera4.GetPosition();
	}

	
	objPos = objMesh4->GetPosition();

    //
    // Animate the Game objects
    //
	objMesh->SetScale(3.0f, 3.0f, 3.0f); objMesh->SetRotation(5 * t, 5 * t, 5 * t); objMesh->SetTranslation(0.0f, 100.0f, 0.0f);
	objMesh->UpdateWorld();

	//Planet 1
	objMesh2->SetScale(1.0f, 1.0f, 1.0f); objMesh2->SetTranslation(8.0, 100.0f, 0); objMesh2->SetRotation(7 * t, 0, 0); objMesh2->SetYaw(7 * t);
	objMesh2->UpdateWorld();

	//Planet 2
	objMesh3->SetScale(1.5f, 1.5f, 1.5f); objMesh3->SetTranslation(-19.0f, 100.0f, 0.0f); objMesh3->SetRotation(-5 * t, 0, 0); objMesh3->SetYaw(-3 * t);
	objMesh3->UpdateWorld();

	objMesh4->UpdateWorld();

	XMStoreFloat4x4(&_world4, XMMatrixScaling(0.2f, 0.2f, 0.2f) * XMMatrixRotationY(7 * t) * XMMatrixTranslation(3.0f, 0.0f, 0.0f) * XMMatrixRotationY(7 * t) * XMMatrixTranslation(8.0f, 100.0f, 0.0f) * XMMatrixRotationY(7 * t)); //Planet 1 Moon
	XMStoreFloat4x4(&_world5, XMMatrixScaling(0.2f, 0.2f, 0.2f) * XMMatrixRotationY(10 * t) * XMMatrixTranslation(6.0f, 0.0f, 0.0f) * XMMatrixRotationY(9 * t) * XMMatrixTranslation(-19.0f, 100.0f, 0.0f) * XMMatrixRotationY(-3 * t)); //Planet 2 Moon

	for (int i = 0; i < 100; i++)
	{
		//XMStoreFloat4x4(&objMesh6[i]->GetWorld(), XMMatrixScaling(0.1f, 0.1f, 0.1f) * XMMatrixRotationY(6 * t) * XMMatrixTranslation(9.0f, 0.0f, 0.0f) * XMMatrixRotationY(7*t) * XMMatrixRotationY(_asteroidSpeed[i]));
		objMesh6[i]->SetScale(0.6, 0.6, 0.6); objMesh6[i]->SetRotation(t, 6 * t, 0); objMesh6[i]->SetTranslation(25.0f, 100.0f, 0);  objMesh6[i]->SetYaw(_asteroidSpeed[i]);
		objMesh6[i]->UpdateWorld();
	}

	XMStoreFloat4x4(&_gridWorld , XMMatrixTranslation(0.0f, -80.0f, 0.0f));

}
Esempio n. 7
0
//--------------------------------------------------------------------------------------
// Render a frame
//--------------------------------------------------------------------------------------
void Render()
{
	// Update our time
	static float t = 0.0f;
	if (!paused)
	{
		if (g_driverType == D3D_DRIVER_TYPE_REFERENCE)
		{
			t += (float)XM_PI * 0.0125f;
		}
		else
		{
			static DWORD dwTimeStart = 0;
			DWORD dwTimeCur = GetTickCount();
			if (dwTimeStart == 0)
				dwTimeStart = dwTimeCur;
			if (restarted)
			{
				restarted = false;
				t = dwLastT;
				dwTimeStart = dwTimeCur - t * 1000.0f;
			}
			else
			{
				t = (dwTimeCur - dwTimeStart) / 1000.0f;
			}
		}
		dwLastT = t;
	}

	// 1st Cube: Rotate around the origin
	// JPE : Se verifica si debe rotar
	if (rotate)
	{
		//JPE: Para mesh del mono
		if (modelo == ModeloMono)
		{
			g_World1 = XMMatrixRotationX(-1.570796f) * XMMatrixRotationY(t);
		}
		else // Para cubo
		{
			g_World1 = XMMatrixRotationY(t);
		}
	}
	else
	{
		//JPE: Para mesh del mono
		if (modelo == ModeloMono)
		{
			g_World1 = XMMatrixRotationX(-1.570796f);
			g_World1 *= XMMatrixRotationY(2 * -1.570796f);
		}
		else // Para cubo
		{
			g_World1 = XMMatrixIdentity();
		}
	}
	XMVECTOR Det;
	g_Normal1 = XMMatrixTranspose(XMMatrixInverse(&Det, g_World1));

	// 2nd Cube:  Rotate around origin
	XMMATRIX mSpin = XMMatrixRotationZ(-t);
	XMMATRIX mOrbit = XMMatrixRotationY(-t * 2.0f);
	XMMATRIX mTranslate = XMMatrixTranslation(-4.0f, 0.0f, 0.0f);
	XMMATRIX mScale = XMMatrixScaling(0.3f, 0.3f, 0.3f);

	g_World2 = mScale * mSpin * mTranslate * mOrbit;

	//
	// Clear the back buffer
	//
	float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; //red, green, blue, alpha
	g_pImmediateContext->ClearRenderTargetView(g_pRenderTargetView, ClearColor);

	//
	// Clear the depth buffer to 1.0 (max depth)
	//
	g_pImmediateContext->ClearDepthStencilView(g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);


	// JPE:	
	// CARGA LOS CONSTANT BUFFERS
	if (!constBuffer)
	{
		g_pImmediateContext->PSSetConstantBuffers(1, 1, &g_pConstantBufferPS);
		g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer);
		g_pImmediateContext->VSSetConstantBuffers(1, 1, &g_pConstantBufferPS);
		// Set shader texture resource in the pixel shader.
		g_pImmediateContext->PSSetShaderResources(0, 1, &m_texture);
		g_pImmediateContext->PSSetShaderResources(1, 1, &m_normalmap);
		g_pImmediateContext->PSSetShaderResources(2, 1, &m_specularmap);
		// Set the sampler state in the pixel shader.
		g_pImmediateContext->PSSetSamplers(0, 1, &m_sampleState);

		constBuffer = true;
	}

	//
	// Update variables for the first cube
	//
	ConstantBuffer cb1;
	cb1.mWorld = XMMatrixTranspose(g_World1);
	cb1.mView = XMMatrixTranspose(g_View);
	cb1.mProjection = XMMatrixTranspose(g_Projection);
	cb1.mNormal = XMMatrixTranspose(g_Normal1);
	//
	// Update variables for the second cube
	//
	ConstantBuffer cb2;
	cb2.mWorld = XMMatrixTranspose(g_World2);
	cb2.mView = XMMatrixTranspose(g_View);
	cb2.mProjection = XMMatrixTranspose(g_Projection);

	// JPE: variables for PS
	ConstantBufferPS psCb1;
	psCb1.time = t;
	psCb1.vecEye = XMFLOAT3(x, y, z);
	psCb1.bump = bump;
	psCb1.useTexture = useTexture;

	// FIRST PASS
	g_pImmediateContext->RSSetState(m_rasterState);
	g_pImmediateContext->VSSetShader(g_pVertexShader, NULL, 0);
	g_pImmediateContext->PSSetShader(g_pPixelShader, NULL, 0);

	// Render the first cube
	g_pImmediateContext->UpdateSubresource(g_pConstantBuffer, 0, NULL, &cb1, 0, 0);
	g_pImmediateContext->UpdateSubresource(g_pConstantBufferPS, 0, NULL, &psCb1, 0, 0);
	g_pImmediateContext->DrawIndexed( cantIndices, 0, 0 );
	// Render the second cube
	g_pImmediateContext->UpdateSubresource( g_pConstantBuffer, 0, NULL, &cb2, 0, 0 );
	g_pImmediateContext->DrawIndexed(cantIndices, 0, 0);
	
    // SECOND PASS
	if (wireframe)
	{
		g_pImmediateContext->RSSetState(m_rasterStateWF);
		g_pImmediateContext->VSSetShader(g_pVertexShaderWF, NULL, 0);
		g_pImmediateContext->PSSetShader(g_pPixelShaderWF, NULL, 0);

		// Render the first cube
		g_pImmediateContext->UpdateSubresource(g_pConstantBuffer, 0, NULL, &cb1, 0, 0);
		g_pImmediateContext->UpdateSubresource(g_pConstantBufferPS, 0, NULL, &psCb1, 0, 0);
		g_pImmediateContext->DrawIndexed(cantIndices, 0, 0);
		// Render the second cube
		g_pImmediateContext->UpdateSubresource(g_pConstantBuffer, 0, NULL, &cb2, 0, 0);
		g_pImmediateContext->DrawIndexed(cantIndices, 0, 0);
	}

    //
    // Present our back buffer to our front buffer
    //
	// JPE: primer parametro = 1 para Vertical Sync, 0 para Inmediato
	UINT SyncInterval = vsync ? 1: 0;
    g_pSwapChain->Present(SyncInterval, 0 );

	frameCount++;
	
	if (frameCount % frameDelay == 0)
	{
		DWORD tAct = timeGetTime();

		DWORD elapsed = tAct - tAnt;
		long frames = frameCount - frameCountLast;
		float fps = frames / (elapsed / 1000.0f);


		frameDelay = fps / 5;

		if (frameDelay < 10) frameDelay = 10;

		wchar_t text[256];

		swprintf(text, 256, L"FPS = %.1f", fps);

		SetWindowTextW(g_hWnd, text);

		frameCountLast = frameCount;
		tAnt = tAct;
	}
}
Esempio n. 8
0
void D3DAnimation::Update(float dt) {
	if( GetAsyncKeyState('W') & 0x8000 )
		Cam.Walk(10.0f * dt);

	if( GetAsyncKeyState('S') & 0x8000 )
		Cam.Walk(-10.0f * dt);

	if( GetAsyncKeyState('A') & 0x8000 )
		Cam.Strafe(-10.0f * dt);

	if( GetAsyncKeyState('D') & 0x8000 )
		Cam.Strafe(10.0f * dt);
	/*
	for (int i = 0; i < 10; ++i) {
		if (GetAsyncKeyState(VK_F1 + i) & 0x8000 ) {
			if (pointLightsw[i] == true) {
				pointLightsw[i] = false;
			} else {
				pointLightsw[i] = true;
			}
		}
	}
	for (int i = 0; i < 2; ++i) {
		if (GetAsyncKeyState('4' + i) & 0x8000 ) {
			if (SpotLightsw[i] == true) {
				SpotLightsw[i] = false;
			} else {
				SpotLightsw[i] = true;
			}
		}
	}
	for (int i = 0; i < 3; ++i) {
		if ((GetAsyncKeyState('1' + i) & 0x8000) && (!GetKeyState('1' + i) &0x8000)) {
			if (dirLightsw[i] == true) {
				dirLightsw[i] = false;
			} else {
				dirLightsw[i] = true;
			}
		}

	}
	*/
	Object3DInstance* player = list->getPlayer("player");	
		if (GetAsyncKeyState(VK_UP) & 0x8000 ) {
			XMMATRIX world = XMLoadFloat4x4(&(list->getPlayer("player")->mWorld));
			XMMATRIX translation;
			XMFLOAT4X4 offset = { 1.0f, 0.0f, 0.0f, 0.0f,0.0f, 1.0f, 0.0f, 0.0f,0.0f, 0.0f,1.0f, 0.0f,0.0f, 0.0f, -45.0f * dt, 1.0f};
			translation = XMLoadFloat4x4(&offset);
			XMStoreFloat4x4(&list->getPlayer("player")->mWorld, translation * world);
			//list->getPlayer("player")->mWorld._43 -= 2.5f * dt;
			list->Update(dt);
		} else if (GetAsyncKeyState(VK_DOWN) & 0x8000 ) {
			XMMATRIX world = XMLoadFloat4x4(&(list->getPlayer("player")->mWorld));
			XMMATRIX translation;
			XMFLOAT4X4 offset = { 1.0f, 0.0f, 0.0f, 0.0f,0.0f, 1.0f, 0.0f, 0.0f,0.0f, 0.0f,1.0f, 0.0f,0.0f, 0.0f, 45.0f * dt, 1.0f};
			translation = XMLoadFloat4x4(&offset);
			XMStoreFloat4x4(&list->getPlayer("player")->mWorld, translation * world);
			list->Update(-dt);
		} else if (GetAsyncKeyState(VK_LEFT) & 0x8000 ) {
			XMMATRIX world = XMLoadFloat4x4(&(list->getPlayer("player")->mWorld));
			world = XMMatrixRotationY(0.004f * XM_PI) * world;
			XMStoreFloat4x4(&(list->getPlayer("player")->mWorld), world);
			list->Update(dt);
		} else if (GetAsyncKeyState(VK_RIGHT) & 0x8000 ) {
			XMMATRIX world = XMLoadFloat4x4(&(list->getPlayer("player")->mWorld));
			world = XMMatrixRotationY(-0.004f * XM_PI) * world;
			XMStoreFloat4x4(&(list->getPlayer("player")->mWorld), world);
			list->Update(dt);
	} else {
		list->Update(0);
	}
		XMStoreFloat3(&player->mUP, XMVector3Transform(XMLoadFloat3(&player->mUP), XMLoadFloat4x4(&player->mWorld)));
		XMStoreFloat3(&player->mForward, XMVector3Transform(XMLoadFloat3(&player->mForward), XMLoadFloat4x4(&player->mWorld)));
		XMStoreFloat3(&player->mRight, XMVector3Transform(XMLoadFloat3(&player->mRight), XMLoadFloat4x4(&player->mWorld)));	

		Cam.UpdateViewMatrix();


	/*
	XMFLOAT3 eye = Cam.GetPosition();
	XMFLOAT3 focus = Cam.GetLook();
	std::wostringstream outs;
	outs.precision(6);
	outs << mMainWndCaption << L"                                                              " << L"eyeX = " << eye.x << L"  eyeY = " << eye.y << L"    eyeZ = "<<eye.z << L"   focusX = "<<focus.x <<L"   focusY = "<<focus.y <<L"    focusZ = "<< focus.z;
	SetWindowText(mMainWnd, outs.str().c_str());*/
}
Esempio n. 9
0
bool D3DAnimation::Init() {
	if (!D3DBase::Init()) {
		return false;
	}
	
	mLastMousePos.x = 0;
	mLastMousePos.y = 0;

	BOX_DESC box = {1.0f, 1.0f, 1.0f, 3};
	GRID_DESC grid = {20.0f, 30.0f, 60, 40};
	SPHERE_DESC sphere = {0.5f, 20, 20};
	CYLINDER_DESC cylinder = { 0.5f, 0.3f, 3.0f, 20, 20 };

	Material mGridMat;
	Material mBoxMat;
	Material mCylinderMat;
	Material mSphereMat;



	mGridMat.Ambient  = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
	mGridMat.Diffuse  = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
	mGridMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f);

	mCylinderMat.Ambient  = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mCylinderMat.Diffuse  = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mCylinderMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f);

	mSphereMat.Ambient  = XMFLOAT4(0.6f, 0.8f, 0.9f, 1.0f);
	mSphereMat.Diffuse  = XMFLOAT4(0.6f, 0.8f, 0.9f, 1.0f);
	mSphereMat.Specular = XMFLOAT4(0.9f, 0.9f, 0.9f, 16.0f);

	mBoxMat.Ambient  = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mBoxMat.Diffuse  = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mBoxMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f);

	fogenable = true;
	
	XMFLOAT4X4 I;
	XMFLOAT4X4 rotation;
	XMStoreFloat4x4(&rotation, XMMatrixRotationY(XM_PI));
	XMStoreFloat4x4(&I, XMMatrixIdentity());
	//instanceName;translation;rotation;scale;modelName;modelFilename;texturePath;VShaderName;PShaderName;LayoutName; vertexTypeName;
	std::vector<ObjectInstance_M3dModelList_DESC> objlist = {
		{"player", {0.0f, 0.0f, -100.0f}, rotation, {0.05f, 0.05f, -0.05f}, "soldier", ".\\Models\\soldier.m3d", ".\\Textures\\","BasicAnimationVS","FixFunctionLightPS","PosNormalTexTanSkinned","PosNormalTexTanAnimation"}
	};
	std::vector<ObjectInstance_BOXLIST_DESC> boxlist = {
		{ "podium",{0.0f, 0.5f, 0.0f}, I, {3.0f,1.0f,3.0f}, "box", mBoxMat, ".\\Textures\\", "stone.dds", "stones_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan",box} 
	};
	std::vector<ObjectInstance_GRIDLIST_DESC> gridlist = {
		{ "land", {0.0f, 0.0f,0.0f}, I, {1.0f,1.0f,1.0f}, "grid", mGridMat, ".\\Textures\\", "floor.dds", "floor_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan",grid}
	};
	mDirLights[0].Ambient  = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
	mDirLights[0].Diffuse  = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
	mDirLights[0].Specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
	mDirLights[0].Direction = XMFLOAT3(0.57735f, -0.57735f, 0.57735f);
	dirLightsw[0] = true;
	mDirLights[1].Ambient  = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
	mDirLights[1].Diffuse  = XMFLOAT4(0.20f, 0.20f, 0.20f, 1.0f);
	mDirLights[1].Specular = XMFLOAT4(0.25f, 0.25f, 0.25f, 1.0f);
	mDirLights[1].Direction = XMFLOAT3(-0.57735f, -0.57735f, 0.57735f);
	dirLightsw[1] = true;
	mDirLights[2].Ambient  = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
	mDirLights[2].Diffuse  = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
	mDirLights[2].Specular = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
	mDirLights[2].Direction = XMFLOAT3(0.0f, -0.707f, -0.707f);
	dirLightsw[2] = true;
	mSpotLights[0].Ambient = XMFLOAT4(0.2f, 1.0f, 0.2f, 1.0f);
	mSpotLights[0].Diffuse = XMFLOAT4(0.5f, 1.0f, 0.5f, 1.0f);
	mSpotLights[0].Specular = XMFLOAT4(0.5f, 1.0f, 0.5f, 1.0f);
	mSpotLights[0].Position = XMFLOAT3(0.0f, 5.0f, 0.0f);
	mSpotLights[0].Range = 25.0f;
	mSpotLights[0].Att = XMFLOAT3(0.0f, 0.15f, 0.0f);
	XMFLOAT3 dir;
	XMStoreFloat3(&dir, XMVector3Normalize(XMLoadFloat3(&XMFLOAT3(0.0f, -5.0f, -100.0f))));
	mSpotLights[0].Direction = dir;
	mSpotLights[0].Spot = 56.0f;
	SpotLightsw[0] = true;
	mSpotLights[1].Ambient = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mSpotLights[1].Diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mSpotLights[1].Specular = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mSpotLights[1].Position = XMFLOAT3(0.0f, 2.5f, -100.0f);
	mSpotLights[1].Range = 15.0f;
	mSpotLights[1].Att = XMFLOAT3(0.0f, 0.15f, 0.0f);
	mSpotLights[1].Direction = XMFLOAT3(0.0f, 0.0f, -1.0f);
	mSpotLights[1].Spot = 50.0f;
	SpotLightsw[1] = true;
	std::vector<ObjectInstance_SPHERELIST_DESC> spherelist;
	std::vector<ObjectInstance_CYLINDERLIST_DESC> cylinderlist;
	for(int i = 0; i < 5; ++i)
	{
		ObjectInstance_CYLINDERLIST_DESC item1 = { "pillar" + std::to_string(i * 2 + 1), {-5.0f, 1.5f, -10.0f + i*5.0f}, I, {1.0f,1.0f,1.0f}, "cylinder", mCylinderMat, ".\\Textures\\", "bricks.dds", "bricks_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan", cylinder};
		ObjectInstance_CYLINDERLIST_DESC item2 = { "pillar" + std::to_string(i * 2 + 2), {+5.0f, 1.5f, -10.0f + i*5.0f}, I, {1.0f,1.0f,1.0f}, "cylinder", mCylinderMat, ".\\Textures\\", "bricks.dds", "bricks_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan",cylinder};
		cylinderlist.push_back(item1);
		cylinderlist.push_back(item2);
		ObjectInstance_SPHERELIST_DESC item3 = { "ball" + std::to_string(i * 2 + 1), {-5.0f, 3.5f, -10.0f + i*5.0f}, I, {1.0f,1.0f,1.0f}, "sphere", mCylinderMat, ".\\Textures\\", "stone.dds", "stones_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan",sphere};
		ObjectInstance_SPHERELIST_DESC item4 = { "ball" + std::to_string(i * 2 + 2), {+5.0f, 3.5f, -10.0f + i*5.0f}, I, {1.0f,1.0f,1.0f}, "sphere", mCylinderMat, ".\\Textures\\", "stone.dds", "stones_nmap.dds", "BasicVS","FixFunctionLightPS","PosNormTexTan","PosNormalTexTan",sphere};
		spherelist.push_back(item3);
		spherelist.push_back(item4);

		mPointLights[i * 2].Ambient = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f);
		mPointLights[i * 2].Diffuse = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f);
		mPointLights[i * 2].Specular = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f);
		mPointLights[i * 2].Position = XMFLOAT3(-5.0f, 3.5f, -10.0f + i * 5.0f);
		mPointLights[i * 2].Att = XMFLOAT3(0.0f, 0.0f, 0.9f);
		mPointLights[i * 2].Range = 4.0f;
		pointLightsw[i * 2] = true;
		mPointLights[i * 2 + 1].Ambient = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f);
		mPointLights[i * 2 + 1].Diffuse = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f);
		mPointLights[i * 2 + 1].Specular = XMFLOAT4(1.f, 0.9f, 0.3f, 1.0f);
		mPointLights[i * 2 + 1].Position = XMFLOAT3(+5.0f, 3.5f, -10.0f + i * 5.0f);
		mPointLights[i * 2 + 1].Att = XMFLOAT3(0.0f, 0.9f, 0.0f);
		mPointLights[i * 2 + 1].Range = 4.0f;
		pointLightsw[i * 2 + 1] = true;
	}
	list = new Object3DList(this,objlist);
	list->AddBoxist(boxlist);
	list->AddGridList(gridlist);
	list->AddCylinderList(cylinderlist);
	list->AddSphereList(spherelist);
	list->Init();
	Cam.SetLens(0.25f * XM_PI, getAspectRatio(), 1.0f, 1000.0f);
	return true;
}
Esempio n. 10
0
void LevelDisplay::draw( ID3D11DeviceContext* device, ID3DX11Effect* fx, World& world, XMFLOAT4& cameraPos, float blockDimensions )
{
    UINT stride = sizeof(DungeonVertex);
    UINT offset = 0;

    //Update the world matrix
    XMMATRIX worldm = XMMatrixIdentity();

    //Set input layout and topology
    device->IASetInputLayout( mInputLayout );
    device->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

    //Update the world matrix
    device->UpdateSubresource( mWorldCB, 0, 0, &worldm, 0, 0 ); 
    device->VSSetConstantBuffers( 1, 1, &mWorldCB );

    //Set the floor texture
    device->PSSetShaderResources(0, 1, &mFloorTexture );

    //Draw the floor
    device->IASetIndexBuffer( mFloorIB, DXGI_FORMAT_R16_UINT, 0 );
    device->IASetVertexBuffers(0, 1, &mFloorVB, &stride, &offset);
    device->DrawIndexed(6 * mBlockCount, 0, 0);

    //Draw the walls
    device->PSSetShaderResources(0, 1, &mWallTexture );

    device->IASetIndexBuffer( mWallsIB, DXGI_FORMAT_R16_UINT, 0 );
    device->IASetVertexBuffers(0, 1, &mWallsVB, &stride, &offset);
    device->DrawIndexed(6 * mWallCount, 0, 0);

    //Draw the ceiling
    device->PSSetShaderResources(0, 1, &mCeilingTexture );

    device->IASetIndexBuffer( mCeilingIB, DXGI_FORMAT_R16_UINT, 0 );
    device->IASetVertexBuffers(0, 1, &mCeilingVB, &stride, &offset);
    device->DrawIndexed(6 * mBlockCount, 0, 0);

	Level& level = world.getLevel();
    float halfBlockDimension = blockDimensions / 2.0f;

    //Draw light meshes at light locations
    for(ushort i = 0; i < level.getNumLights(); i++){
        Level::Light& l = level.getLight( i );

        float xOffset = 0.0f;
        float zOffset = 0.0f;

        if( l.getType() == Level::Light::Type::Torch ){
            xOffset =   l.getAttachedWall() == Level::Light::AttachedWall::Left ? -halfBlockDimension :
                      ( l.getAttachedWall() == Level::Light::AttachedWall::Back ? halfBlockDimension : 0.0f );
            zOffset =   l.getAttachedWall() == Level::Light::AttachedWall::Right ? halfBlockDimension : 
                      ( l.getAttachedWall() == Level::Light::AttachedWall::Front ? -halfBlockDimension : 0.0f );
        }

        float tx = ( static_cast<float>(l.getI()) * blockDimensions ) + halfBlockDimension + xOffset;
        float ty = l.getHeight();
        float tz = ( static_cast<float>(l.getJ()) * blockDimensions ) + halfBlockDimension + zOffset;

        float dx = (cameraPos.x - tx);
        float dz = (cameraPos.z - tz);

        float d = sqrt( (dx * dx) + (dz * dz) );

        //If we are outside the draw range, skip drawing this one
        if( d > mDrawRange ){
            continue;
        }

        worldm = XMMatrixScaling( mLightScale[ l.getType() ], mLightScale[ l.getType() ], mLightScale[ l.getType() ] ) * 
                 XMMatrixRotationY( static_cast<float>( l.getAttachedWall() ) * PI_OVER_2 ) * 
                 XMMatrixTranslation( tx, ty, tz );

        worldm = XMMatrixTranspose( worldm );

        device->UpdateSubresource( mWorldCB, 0, 0, &worldm, 0, 0 ); 
		device->VSSetConstantBuffers( 1, 1, &mWorldCB );

        mLights[ l.getType() - 1 ].draw( device );
    }

    //Draw furniture meshes
    for(uint i = 0; i < level.getNumFurniture(); i++)
	{
        Level::Furniture& f = level.getFurniture(i);

        float dx = (cameraPos.x - f.getPosition().x);
        float dz = (cameraPos.z - f.getPosition().z);

        float d = sqrt( (dx * dx) + (dz * dz) );

        //If we are outside the draw range, skip drawing this one
        if( d > mDrawRange ){
            continue;
        }

        worldm = XMMatrixScaling( mFurnitureScale[ f.getType() ], 
                                  mFurnitureScale[ f.getType() ], 
                                  mFurnitureScale[ f.getType() ]) * 
                 XMMatrixRotationY( f.getYRotation() ) * 
                 XMMatrixTranslation( f.getPosition().x, f.getPosition().y, f.getPosition().z );

		worldm = XMMatrixTranspose( worldm );

		device->UpdateSubresource( mWorldCB, 0, 0, &worldm, 0, 0 ); 
		device->VSSetConstantBuffers( 1, 1, &mWorldCB );

        mFurniture[ f.getType() - 1 ].draw(device);
	}

    //Draw Containers
    for(uint i = 0; i < level.getNumContainer(); i++)
	{
        Level::Container& f = level.getContainer(i);

        float dx = (cameraPos.x - f.getPosition().x);
        float dz = (cameraPos.z - f.getPosition().z);

        float d = sqrt( (dx * dx) + (dz * dz) );

        //If we are outside the draw range, skip drawing this one
        if( d > mDrawRange ){
            continue;
        }

        worldm = XMMatrixScaling( mContainerScale[ f.getCType() ], 
                                  mContainerScale[ f.getCType() ], 
                                  mContainerScale[ f.getCType() ]) * 
                 XMMatrixRotationY( f.getYRotation() ) * 
                 XMMatrixTranslation( f.getPosition().x, f.getPosition().y, f.getPosition().z );

		worldm = XMMatrixTranspose( worldm );

		device->UpdateSubresource( mWorldCB, 0, 0, &worldm, 0, 0 ); 
		device->VSSetConstantBuffers( 1, 1, &mWorldCB );

        mContainers[ f.getCType() - 1 ].draw(device);
	}

    for(uint i = 0; i < level.getNumDoors(); i++)
	{
        Level::Door& f = level.getDoor(i);

        float dx = (cameraPos.x - f.getPosition().x);
        float dz = (cameraPos.z - f.getPosition().z);

        float d = sqrt( (dx * dx) + (dz * dz) );

        //If we are outside the draw range, skip drawing this one
        if( d > mDrawRange ){
            continue;
        }

        worldm = XMMatrixScaling( mDoorScale, 
                                  mDoorScale, 
                                  mDoorScale) * 
                 XMMatrixRotationY( f.getYRotation() ) * 
                 XMMatrixTranslation( f.getPosition().x, f.getPosition().y, f.getPosition().z );

		worldm = XMMatrixTranspose( worldm );

		device->UpdateSubresource( mWorldCB, 0, 0, &worldm, 0, 0 ); 
		device->VSSetConstantBuffers( 1, 1, &mWorldCB );

        mDoor.draw(device);
	}
}
Esempio n. 11
0
/*--------------------------------------------
	画面の描画処理
--------------------------------------------*/
HRESULT Render(void)
{
	HRESULT hr;

    // 描画ターゲットのクリア
    g_pImmediateContext->ClearRenderTargetView(
                       g_pRenderTargetView, // クリアする描画ターゲット
                       g_ClearColor);         // クリアする値

	// 深度/ステンシルのクリア
	g_pImmediateContext->ClearDepthStencilView(
			g_pDepthStencilView, // クリアする深度/ステンシル・ビュー
			D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL,   // 深度値とステンシル値をクリアする
			1.0f,                // 深度バッファをクリアする値
			0);                  // ステンシル・バッファをクリアする値

	// ***************************************
	// 定数バッファを更新
	// ビュー変換行列
	XMVECTORF32 eyePosition   = { 0.0f, g_fEye, -g_fEye, 1.0f };  // 視点(カメラの位置)
	XMVECTORF32 focusPosition = { 0.0f, 0.0f,  0.0f, 1.0f };  // 注視点
	XMVECTORF32 upDirection   = { 0.0f, 1.0f,  0.0f, 1.0f };  // カメラの上方向
	XMMATRIX mat = XMMatrixLookAtLH(eyePosition, focusPosition, upDirection);
	XMStoreFloat4x4(&g_cbCBuffer.View, XMMatrixTranspose(mat));
	// 点光源座標
	XMVECTOR vec = XMVector3TransformCoord(XMLoadFloat3(&g_vLightPos), mat);
	XMStoreFloat3(&g_cbCBuffer.Light, vec);
	// ワールド変換行列
	XMFLOAT3 center = g_wfObjKuma.GetBoundingSphereCenter();
	XMMATRIX matTrans = XMMatrixTranslation(-center.x, -center.y, -center.z);

	float scale = 1.0f / g_wfObjKuma.GetBoundingSphereRadius();
	XMMATRIX matScale = XMMatrixScaling(scale, scale, scale);

	FLOAT rotate = (FLOAT)(XM_PI * (timeGetTime() % 3000)) / 1500.0f;
	XMMATRIX matY = XMMatrixRotationY(rotate);

	XMStoreFloat4x4(&g_cbCBuffer.World, XMMatrixTranspose(matTrans * matScale * matY));

	// **********************************************************
	// RSにビューポートを設定
	g_pImmediateContext->RSSetViewports(1, g_ViewPort);

	// OMに描画ターゲット ビューと深度/ステンシル・ビューを設定
	g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_pDepthStencilView);

	// VSに定数バッファを設定
	g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pCBuffer);

	// GSに定数バッファを設定
	g_pImmediateContext->GSSetConstantBuffers(0, 1, &g_pCBuffer);

	// PSに定数バッファを設定
	g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pCBuffer);
	// PSにサンプラーを設定
	g_pImmediateContext->PSSetSamplers(0, 1, &g_pTextureSampler);

	// 3Dオブジェクトの描画
	RenderObj();
	// シャドウ・ボリュームの描画
	RenderSV();
	// シャドウの描画
	RenderS();

	// ***************************************
	// バック バッファの表示
	hr = g_pSwapChain->Present(	0,	// 画面を直ぐに更新する
								0);	// 画面を実際に更新する

	return hr;
}
Esempio n. 12
0
/*--------------------------------------------
	画面の描画処理
--------------------------------------------*/
HRESULT Render(void)
{
	HRESULT hr;

    // 描画ターゲットのクリア
    g_pImmediateContext->ClearRenderTargetView(
                       g_pRenderTargetView, // クリアする描画ターゲット
                       g_ClearColor);         // クリアする値

	// 深度/ステンシルのクリア
	g_pImmediateContext->ClearDepthStencilView(
			g_pDepthStencilView, // クリアする深度/ステンシル・ビュー
			D3D11_CLEAR_DEPTH,   // 深度値だけをクリアする
			1.0f,                // 深度バッファをクリアする値
			0);                  // ステンシル・バッファをクリアする値(この場合、無関係)

	// ***************************************
	// 立方体の描画

	// 定数バッファ�Aを更新
	// ビュー変換行列
	XMVECTORF32 eyePosition   = { 0.0f, 5.0f, -5.0f, 1.0f };  // 視点(カメラの位置)
	XMVECTORF32 focusPosition = { 0.0f, 0.0f,  0.0f, 1.0f };  // 注視点
	XMVECTORF32 upDirection   = { 0.0f, 1.0f,  0.0f, 1.0f };  // カメラの上方向
	XMMATRIX mat = XMMatrixLookAtLH(eyePosition, focusPosition, upDirection);
	XMStoreFloat4x4(&g_cbCBuffer.View, XMMatrixTranspose(mat));
	// 点光源座標
	XMVECTOR vec = XMVector3TransformCoord(XMLoadFloat3(&g_vLightPos), mat);
	XMStoreFloat3(&g_cbCBuffer.Light, vec);
	// ワールド変換行列
	XMMATRIX matY, matX;
	FLOAT rotate = (FLOAT)(XM_PI * (timeGetTime() % 3000)) / 1500.0f;
	matY = XMMatrixRotationY(rotate);
	rotate = (FLOAT)(XM_PI * (timeGetTime() % 1500)) / 750.0f;
	matX = XMMatrixRotationX(rotate);
	XMStoreFloat4x4(&g_cbCBuffer.World, XMMatrixTranspose(matY * matX));
	// 定数バッファのマップ取得
	D3D11_MAPPED_SUBRESOURCE MappedResource;
	hr = g_pImmediateContext->Map(
	                  g_pCBuffer,              // マップするリソース
	                  0,                       // サブリソースのインデックス番号
	                  D3D11_MAP_WRITE_DISCARD, // 書き込みアクセス
	                  0,                       //
	                  &MappedResource);        // データの書き込み先ポインタ
	if (FAILED(hr))
		return DXTRACE_ERR(L"InitBackBuffer  g_pImmediateContext->Map", hr);  // 失敗
	// データ書き込み
	CopyMemory(MappedResource.pData, &g_cbCBuffer, sizeof(cbCBuffer));
	// マップ解除
	g_pImmediateContext->Unmap(g_pCBuffer, 0);

	// ***************************************
	// IAに頂点バッファを設定
	// IAに入力レイアウト・オブジェクトを設定(頂点バッファなし)
	g_pImmediateContext->IASetInputLayout(NULL);
	// IAにプリミティブの種類を設定
	g_pImmediateContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	// VSに頂点シェーダを設定
	g_pImmediateContext->VSSetShader(g_pVertexShader, NULL, 0);
	// VSに定数バッファを設定
	g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pCBuffer);

	// GSにジオメトリ・シェーダを設定
	g_pImmediateContext->GSSetShader(g_pGeometryShader, NULL, 0);
	// GSに定数バッファを設定
	g_pImmediateContext->GSSetConstantBuffers(0, 1, &g_pCBuffer);

	// RSにビューポートを設定
	g_pImmediateContext->RSSetViewports(1, g_ViewPort);
	// RSにラスタライザ・ステート・オブジェクトを設定
	g_pImmediateContext->RSSetState(g_pRasterizerState);

	// PSにピクセル・シェーダを設定
	g_pImmediateContext->PSSetShader(g_pPixelShader, NULL, 0);
	// PSに定数バッファを設定
	g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pCBuffer);
	// PSにシェーダ・リソース・ビューを設定
	g_pImmediateContext->PSSetShaderResources(
        0,                // 設定する最初のスロット番号
        1,                // 設定するシェーダ・リソース・ビューの数
        &g_pTextureSRV);  // 設定するシェーダ・リソース・ビューの配列
	// PSにサンプラーを設定
	g_pImmediateContext->PSSetSamplers(0, 1, &g_pTextureSampler);

	// OMに描画ターゲット ビューと深度/ステンシル・ビューを設定
	g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_bDepthMode ? g_pDepthStencilView : NULL);
	// OMにブレンド・ステート・オブジェクトを設定
	FLOAT BlendFactor[4] = {0.0f, 0.0f, 0.0f, 0.0f};
	g_pImmediateContext->OMSetBlendState(g_pBlendState, BlendFactor, 0xffffffff);
	// OMに深度/ステンシル・ステート・オブジェクトを設定
	g_pImmediateContext->OMSetDepthStencilState(g_pDepthStencilState, 0);

	// ***************************************
	// 頂点バッファとインデックス・バッファを使わずに描画する
	g_pImmediateContext->Draw(
			36, // 描画する頂点数
			0); // 最初の頂点ID

	// ***************************************
	// バック バッファの表示
	hr = g_pSwapChain->Present(	0,	// 画面を直ぐに更新する
								0);	// 画面を実際に更新する

	return hr;
}
Esempio n. 13
0
//--------------------------------------------------------------------------------------
// Render a frame
//--------------------------------------------------------------------------------------
void Render()
{
    // Update our time
    static float t = 0.0f;
    if( g_driverType == D3D_DRIVER_TYPE_REFERENCE )
    {
        t += ( float )XM_PI * 0.0125f;
    }
    else
    {
        static DWORD dwTimeStart = 0;
        DWORD dwTimeCur = GetTickCount();
        if( dwTimeStart == 0 )
            dwTimeStart = dwTimeCur;
        t = ( dwTimeCur - dwTimeStart ) / 1000.0f;
    }

    //
    // Apply transforms to the meshes
    //
	g_meshesTransforms[0] = XMMatrixRotationY( t );
	g_meshesTransforms[1] = XMMatrixTranslation(
				  0.3f*t,
				  0.05f*t,
				  0.05f*t
				);

    //
    // Clear the back buffer
    //
    float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; // red,green,blue,alpha
    g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, ClearColor );

	//
    // Clear the depth buffer to 1.0 (max depth)
    //
    g_pImmediateContext->ClearDepthStencilView( g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 );

	int meshesNumber = 2;
	int meshesVertex[2][2] = {{36,0},{36,36}};
	for (int i=meshesNumber-1; i>=0; i--)
	{
		//
		// Update variables
		//
		ConstantBuffer cb;
		cb.mWorld = XMMatrixTranspose( g_meshesTransforms[i] );
		cb.mView = XMMatrixTranspose( g_View );
		cb.mProjection = XMMatrixTranspose( g_Projection );
		g_pImmediateContext->UpdateSubresource( g_pConstantBuffer, 0, NULL, &cb, 0, 0 );

		//
		// Renders a triangle
		//
		g_pImmediateContext->VSSetShader( g_pVertexShader, NULL, 0 );
		g_pImmediateContext->VSSetConstantBuffers( 0, 1, &g_pConstantBuffer );
		g_pImmediateContext->PSSetShader( g_pPixelShader, NULL, 0 );
		g_pImmediateContext->DrawIndexed( meshesVertex[i][0], meshesVertex[i][1], 0 );        // 36 vertices needed for 12 triangles in a triangle list
	}
    //
    // Present our back buffer to our front buffer
    //
    g_pSwapChain->Present( 0, 0 );
}
void Enemies::createEnemy(int model, FLOAT x1, FLOAT y1, FLOAT z1, FLOAT x2, FLOAT y2, FLOAT z2, FLOAT x3, FLOAT y3, FLOAT z3, FLOAT x4, FLOAT y4, FLOAT z4, FLOAT scale, int speed, int collisionstype)
{
	Enemy* newEnemy;

	newEnemy = new Enemy();

	XMMATRIX modelScale = XMMatrixScaling(scale, scale, -scale);
	XMMATRIX modelRot = XMMatrixRotationY(0);
	XMMATRIX modelOffset = XMMatrixTranslation(x1, y1, z1);


	newEnemy->setModelScale(modelScale);
	newEnemy->setModelRot(modelRot);
	newEnemy->setModelOffset(modelOffset);

	newEnemy->SetPositionOne(x1, y1, z1);
	newEnemy->SetPositionTwo(x2, y2, z2);
	newEnemy->SetPositionThree(x3, y3, z3);
	newEnemy->SetPositionFour(x4, y4, z4);



	if (model == simpleEnemy)
	{
		anEnemy = mSimpleEnemy;
	}
	else if (model == tractor)
	{
		anEnemy = mTractor;
	}


	

	newEnemy->setModel(anEnemy);
	newEnemy->setScale(scale);
	newEnemy->setSpeed(speed);
	newEnemy->setcollisiontype(collisionstype);


	BasicModelInstance oneEnemy;


	theEnemy.Model = anEnemy;


	XMStoreFloat4x4(&theEnemy.World, modelScale*modelRot*modelOffset);


	newEnemy->setBasicMInstance(theEnemy);

	oneEnemy = newEnemy->getBasicMInstance();



	addEnemy(theEnemy);

	enemyclass.push_back(newEnemy);


	LevelCollisions.push_back(EnemyBox);

	newEnemy->setWorld(theEnemy.World);





}
Esempio n. 15
0
void GameModel::orientRotateY(float radianAngle){
        // orientationMatrix *= Matrix.CreateRotationY(ry);
		XMStoreFloat4x4(&orientRotateMatrix, XMLoadFloat4x4(&orientRotateMatrix) * XMMatrixRotationY(radianAngle));

}
// Update frame-based values.
void D3D12Multithreading::OnUpdate()
{
	m_timer.Tick(NULL);

	PIXSetMarker(m_commandQueue.Get(), 0, L"Getting last completed fence.");

	// Get current GPU progress against submitted workload. Resources still scheduled 
	// for GPU execution cannot be modified or else undefined behavior will result.
	const UINT64 lastCompletedFence = m_fence->GetCompletedValue();

	// Move to the next frame resource.
	m_currentFrameResourceIndex = (m_currentFrameResourceIndex + 1) % FrameCount;
	m_pCurrentFrameResource = m_frameResources[m_currentFrameResourceIndex];

	// Make sure that this frame resource isn't still in use by the GPU.
	// If it is, wait for it to complete.
	if (m_pCurrentFrameResource->m_fenceValue > lastCompletedFence)
	{
		HANDLE eventHandle = CreateEventEx(nullptr, FALSE, FALSE, EVENT_ALL_ACCESS);
		if (eventHandle == nullptr)
		{
			ThrowIfFailed(HRESULT_FROM_WIN32(GetLastError()));
		}
		ThrowIfFailed(m_fence->SetEventOnCompletion(m_pCurrentFrameResource->m_fenceValue, eventHandle));
		WaitForSingleObject(eventHandle, INFINITE);
	}

	m_cpuTimer.Tick(NULL);
	float frameTime = static_cast<float>(m_timer.GetElapsedSeconds());
	float frameChange = 2.0f * frameTime;

	if (m_keyboardInput.leftArrowPressed)
		m_camera.RotateYaw(-frameChange);
	if (m_keyboardInput.rightArrowPressed)
		m_camera.RotateYaw(frameChange);
	if (m_keyboardInput.upArrowPressed)
		m_camera.RotatePitch(frameChange);
	if (m_keyboardInput.downArrowPressed)
		m_camera.RotatePitch(-frameChange);

	if (m_keyboardInput.animate)
	{
		for (int i = 0; i < NumLights; i++)
		{
			float direction = frameChange * pow(-1.0f, i);
			XMStoreFloat4(&m_lights[i].position, XMVector4Transform(XMLoadFloat4(&m_lights[i].position), XMMatrixRotationY(direction)));

			XMVECTOR eye = XMLoadFloat4(&m_lights[i].position);
			XMVECTOR at = { 0.0f, 8.0f, 0.0f };
			XMStoreFloat4(&m_lights[i].direction, XMVector3Normalize(XMVectorSubtract(at, eye)));
			XMVECTOR up = { 0.0f, 1.0f, 0.0f };
			m_lightCameras[i].Set(eye, at, up);

			m_lightCameras[i].Get3DViewProjMatrices(&m_lights[i].view, &m_lights[i].projection, 90.0f, static_cast<float>(m_width), static_cast<float>(m_height));
		}
	}

	m_pCurrentFrameResource->WriteConstantBuffers(&m_viewport, &m_camera, m_lightCameras, m_lights);
}
Esempio n. 17
0
		void SampleRenderer::Initialize()
		{
			m_RenderQueue = new ::Dispatch::WorkQueue("RenderQueue", ::Concurrency::ThreadPriority::High);
			m_RenderQueue->Loop();
			isInitialized = false;

			float aspectRatio = 1900.f/700;
			float fovAngleY = 70.0f * XM_PI / 180.0f;

			if (aspectRatio < 1.0f)
			{
				fovAngleY *= 2.0f;
			}

			XMMATRIX perspectiveMatrix = XMMatrixPerspectiveFovRH(fovAngleY, aspectRatio, 0.01f, 100.0f);
			XMStoreFloat4x4(&m_MVP.projection, XMMatrixTranspose(perspectiveMatrix));

			static const XMVECTORF32 eye = { 0.0f, 0.7f, 1.5f, 0.0f };
			static const XMVECTORF32 at = { 0.0f, -0.1f, 0.0f, 0.0f };
			static const XMVECTORF32 up = { 0.0f, 1.0f, 0.0f, 0.0f };
			XMStoreFloat4x4(&m_MVP.model, XMMatrixTranspose(XMMatrixRotationY(1.57)));
			XMStoreFloat4x4(&m_MVP.view, XMMatrixTranspose(XMMatrixLookAtRH(eye, at, up)));

			auto d3dDevice = gD3DDevice->GetD3DDevice();


			CD3DX12_ROOT_PARAMETER parameter[3];

			CD3DX12_DESCRIPTOR_RANGE range;
			range.Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0);
			parameter[0].InitAsDescriptorTable(1, &range, D3D12_SHADER_VISIBILITY_VERTEX);

			CD3DX12_DESCRIPTOR_RANGE range2;
			range2.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);
			parameter[1].InitAsDescriptorTable(1, &range2, D3D12_SHADER_VISIBILITY_PIXEL);

			CD3DX12_DESCRIPTOR_RANGE range3;
			range3.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0);
			parameter[2].InitAsDescriptorTable(1, &range3, D3D12_SHADER_VISIBILITY_PIXEL);

			D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags =
				D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
				D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
				D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
				D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
				D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;

			CD3DX12_ROOT_SIGNATURE_DESC descRootSignature;
			descRootSignature.Init(3, parameter, 0, nullptr, rootSignatureFlags);

			PtrBlob pSignature, pError;
			ThrowIfFailed(D3D12SerializeRootSignature(&descRootSignature, D3D_ROOT_SIGNATURE_VERSION_1, pSignature.GetInitReference(), pError.GetInitReference()));
			ThrowIfFailed(d3dDevice->CreateRootSignature(0, pSignature->GetBufferPointer(), pSignature->GetBufferSize(), IID_PPV_ARGS(m_RootSignature.GetInitReference())));
			
			m_CopyQueue = new CopyQueue_tr(d3dDevice);
			m_CopyQueue->StartLoop();


			m_RenderQueue->Queue(::Dispatch::Bind([this, d3dDevice]() {
				m_VS.Load("/Data/Test/Test.vso");
				m_PS.Load("/Data/Test/Test.pso");

				static const D3D12_INPUT_ELEMENT_DESC inputLayout[] =
				{
					{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
					{ "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
				};

				D3D12_GRAPHICS_PIPELINE_STATE_DESC state = {};
				state.InputLayout = { inputLayout, _countof(inputLayout) };
				state.pRootSignature = m_RootSignature;
				state.VS = { m_VS.GetBlob()->GetBufferPointer(), m_VS.GetBlob()->GetBufferSize() };
				state.PS = { m_PS.GetBlob()->GetBufferPointer(), m_PS.GetBlob()->GetBufferSize() };
				state.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
				state.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
				state.DepthStencilState.DepthEnable = FALSE;
				state.DepthStencilState.StencilEnable = FALSE;
				state.SampleMask = UINT_MAX;
				state.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
				state.NumRenderTargets = 1;
				state.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
				state.SampleDesc.Count = 1;

				ThrowIfFailed(d3dDevice->CreateGraphicsPipelineState(&state, IID_PPV_ARGS(m_PipeLineState.GetInitReference())));

				LogUtil::Out("Renderer", ::Concurrency::Thread::GetCurrentThreadName());

			}));

			m_RenderQueue->Queue(::Dispatch::Bind([this, d3dDevice]() {
				ThrowIfFailed(d3dDevice->CreateCommandList(1, D3D12_COMMAND_LIST_TYPE_DIRECT, gD3DDevice->GetCommandAllocator(), m_PipeLineState, IID_PPV_ARGS(m_CmdList.GetInitReference())));

				D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
				heapDesc.NumDescriptors = DeviceManager::GetFrameCount();
				heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
				heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
				ThrowIfFailed(d3dDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(m_CBVHeap.GetInitReference())));
				m_CBVHeap->SetName(L"Constant Buffer Heap");
				
				m_samplerHeap.Create(d3dDevice, D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true);
				D3D12_SAMPLER_DESC samplerDesc = {};
				samplerDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
				samplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
				samplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
				samplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
				samplerDesc.MipLODBias = 0.0f;
				samplerDesc.MaxAnisotropy = 1;
				samplerDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
				samplerDesc.MinLOD = 0;
				samplerDesc.MaxLOD = D3D12_FLOAT32_MAX;
				d3dDevice->CreateSampler(&samplerDesc, m_samplerHeap.hCPU(0));

				m_CubeMesh = new CubeMesh(d3dDevice, m_CmdList);

				this->m_CopyQueue->SubmitTexture(L"\\Data\\Test\\seafloor2bc1.dds", m_CubeMesh);

				m_CBO = new UniformBuffer<ModelViewProjectionConstantBuffer>("ModeViewMatrix", d3dDevice, 1U);
				m_CBO->CreateOnHeap(m_CBVHeap, d3dDevice);

				m_ConstantBuffer = m_CBO->Map();
				ZeroMemory(m_ConstantBuffer, DeviceManager::GetFrameCount() * m_CBO->sAlignedConstantBufferSize);

				ThrowIfFailed(m_CmdList->Close());
				ID3D12CommandList* ppCommandLists[] = { m_CmdList };
				gD3DDevice->GetCommandQueue()->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);
				gD3DDevice->WaitForGPU();

				isInitialized = true; 
			}));
		}
Esempio n. 18
0
int main()
{
	//int avg = 2 * 90 + 3 * 88 + 4 * 87 + 3 * 84 + 4 * 92 + 2 * 93 + 2 * 83 + 2 * 80 + 2 * 95;
	//std::cout << "Avg : " << avg << std::endl;

	SDeviceContextSettings settings;
	settings.MultiSamplingCount = 4;
	settings.MultiSamplingQuality = 32;

	IDevice* device = createDevice(EDT_DIRECT3D11, 800, 600, EWS_NONE, true, settings);
	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();
	IMeshManager* meshManager = driver->getMeshManager();
	IMaterialManager* materialManager = driver->getMaterialManager();

	IResourceGroupManager* resourceGroupManager = driver->getResourceGroupManager();
	resourceGroupManager->init("Resources.cfg");
	resourceGroupManager->loadResourceGroup("General");

	ISimpleMesh* cubeMesh = meshManager->createCubeMesh("cube1");
	IMeshNode* cubeMeshNode = smgr->addMeshNode(cubeMesh, nullptr, nullptr, XMFLOAT3(0, 3.0f, 0));
	cubeMeshNode->setMaterialName("test/material01");
	//cubeMeshNode->remove();

	ISimpleMesh* planeMesh = meshManager->createPlaneMesh("plane1", 10.0, 10.0f, 50, 50, 10.0f, 10.0f);
	IMeshNode* planeMeshNode = smgr->addMeshNode(planeMesh, nullptr);
	planeMeshNode->setMaterialName("test/ground_material");

	IAnimatedMesh* animMesh = meshManager->getAnimatedMesh("lxq.mesh");
	IAnimatedMeshNode* animNode = smgr->addAnimatedMeshNode(animMesh);
	animNode->scale(0.02f, 0.02f, 0.02f);
	IModelMesh* heroMesh = meshManager->getModelMesh("hero.mesh");
	IMeshNode* heroNode = smgr->addModelMeshNode(heroMesh);	
	
	heroNode->scale(0.01f, 0.01f, 0.01f);
	heroNode->translate(2.0f, 0.5f, 0);

	// create sampler state
	SSamplerDesc samplerDesc;
	samplerDesc.Filter = ESF_FILTER_MIN_MAG_MIP_LINEAR;
	samplerDesc.AddressU = EAM_WRAP;
	samplerDesc.AddressV = EAM_WRAP;
	samplerDesc.AddressW = EAM_WRAP;
	ISampler* sampler = driver->getSamplerManager()->create(std::string("sampler1"), samplerDesc);

	IPipeline* pipeline = driver->getPipelineManager()->get("test/pipeline01");
	//pipeline->setSampler(std::string("sampleType"), sampler);

	ILightNode* light = smgr->addLightNode(1);
	light->setType(ELT_POINT);
	light->setAmbient(XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f));
	light->setPosition(2.0f, 5.0f, -3.0f);
	light->setSpecular(XMFLOAT4(1.0f, 1.0f, 1.0f, 32.0f));
	light->setDiffuse(XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f));
	light->setAttenuation(1.0f, 0.0f, 0.0f);
	light->setRange(100.0f);

	materialManager->destroy(std::string("test/material02"));

	//ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 1.0f, -4.0f), XMFLOAT3(0, 1.0f, 0.0f));
	ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 1.0f, -4.0f), XMFLOAT3(0, 1.0f, 0.0f));

	f32 rotx = 0;
	f32 roty = 0;
	f32 rotz = 0;

	char caption[200];

	//FILE* fp = fopen("log.txt", "w");

	ITimer* timer = device->createTimer();
	timer->reset();

	while (device->run())
	{
		const float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f };
		driver->beginScene(true, true, clearColor);

		float dt = timer->tick();
		
		rotx += dt * 2.0f;
		roty += dt * 1.0f;
		rotz += dt * 0.5f;
		if (rotx > XM_2PI) rotx -= XM_2PI;
		if (roty > XM_2PI) roty -= XM_2PI;
		if (rotz > XM_2PI) rotz -= XM_2PI;

		XMMATRIX Mx = XMMatrixRotationX(rotx);
		XMMATRIX My = XMMatrixRotationY(roty);
		XMMATRIX Mz = XMMatrixRotationZ(rotz);
		XMMATRIX rotM = Mx * My * Mz;

		cubeMeshNode->setOrientation(rotM);
	//	heroNode->yaw(dt);
		animNode->addTime(dt * 3000.0f);

		updateCamera(camera, dt);
	//	std::cout << dt << std::endl;

		smgr->drawAll();

		driver->endScene();

		sprintf(caption, "FPS:%f", getFps(dt));
		device->setWindowCaption(caption);
	}

	device->drop();

	return 0;
}
void VolumetricAnimation::PopulateGraphicsCommandList()
{
	HRESULT hr;
	// Command list allocators can only be reset when the associated 
	// command lists have finished execution on the GPU; apps should use 
	// fences to determine GPU execution progress.
	V( m_graphicCmdAllocator->Reset() );

	// However, when ExecuteCommandList() is called on a particular command 
	// list, that command list can then be reset at any time and must be before 
	// re-recording.
	V( m_graphicCmdList->Reset( m_graphicCmdAllocator.Get(), m_pipelineState.Get() ) );

	XMMATRIX view = m_camera.GetViewMatrix();
	XMMATRIX proj = m_camera.GetProjMatrix();

	XMMATRIX world = XMMatrixRotationY( static_cast< float >( m_timer.GetTotalSeconds() ) );
	m_constantBufferData.wvp = XMMatrixMultiply( view, proj );
	//m_constantBufferData.wvp = XMMatrixMultiply( XMMatrixMultiply( world, view ), proj );
	XMStoreFloat4( &m_constantBufferData.viewPos, m_camera.GetEyePt() );
	
	memcpy( m_pCbvDataBegin, &m_constantBufferData, sizeof( m_constantBufferData ) );

	// Set necessary state.
	m_graphicCmdList->SetGraphicsRootSignature( m_graphicsRootSignature.Get() );

	ID3D12DescriptorHeap* ppHeaps[] = { m_cbvsrvuavHeap.Get() };
	m_graphicCmdList->SetDescriptorHeaps( _countof( ppHeaps ), ppHeaps );

	CD3DX12_GPU_DESCRIPTOR_HANDLE cbvHandle( m_cbvsrvuavHeap->GetGPUDescriptorHandleForHeapStart(), RootParameterCBV, m_cbvsrvuavDescriptorSize );
	CD3DX12_GPU_DESCRIPTOR_HANDLE srvHandle( m_cbvsrvuavHeap->GetGPUDescriptorHandleForHeapStart(), RootParameterSRV, m_cbvsrvuavDescriptorSize );

	m_graphicCmdList->SetGraphicsRootDescriptorTable( RootParameterCBV, cbvHandle );
	m_graphicCmdList->SetGraphicsRootDescriptorTable( RootParameterSRV, srvHandle );

	m_graphicCmdList->RSSetViewports( 1, &m_viewport );
	m_graphicCmdList->RSSetScissorRects( 1, &m_scissorRect );

	// Indicate that the back buffer will be used as a render target.
	D3D12_RESOURCE_BARRIER resourceBarriersBefore[] = {
		CD3DX12_RESOURCE_BARRIER::Transition( m_renderTargets[m_frameIndex].Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET ),
		CD3DX12_RESOURCE_BARRIER::Transition( m_volumeBuffer.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE )
	};
	m_graphicCmdList->ResourceBarrier( 2, resourceBarriersBefore );

	CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle( m_rtvHeap->GetCPUDescriptorHandleForHeapStart(), m_frameIndex, m_rtvDescriptorSize );
	m_graphicCmdList->OMSetRenderTargets( 1, &rtvHandle, FALSE, &m_dsvHeap->GetCPUDescriptorHandleForHeapStart() );

	// Record commands.
	const float clearColor[] = { 0.0f, 0.0f, 0.0f, 0.0f };
	m_graphicCmdList->ClearRenderTargetView( rtvHandle, clearColor, 0, nullptr );
	m_graphicCmdList->ClearDepthStencilView( m_dsvHeap->GetCPUDescriptorHandleForHeapStart(), D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr );
	m_graphicCmdList->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
	m_graphicCmdList->IASetVertexBuffers( 0, 1, &m_vertexBufferView );
	m_graphicCmdList->IASetIndexBuffer( &m_indexBufferView );
	m_graphicCmdList->DrawIndexedInstanced( 36, 1, 0, 0, 0 );

	// Indicate that the back buffer will now be used to present.
	D3D12_RESOURCE_BARRIER resourceBarriersAfter[] = {
		CD3DX12_RESOURCE_BARRIER::Transition( m_renderTargets[m_frameIndex].Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT ),
		CD3DX12_RESOURCE_BARRIER::Transition( m_volumeBuffer.Get(), D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS )
	};
	m_graphicCmdList->ResourceBarrier( 2, resourceBarriersAfter );
	V( m_graphicCmdList->Close() );
}
Esempio n. 20
0
void Entity::Update(const Camera& camera, float dt)
{
	if (mSpinning)		{Yaw(dt*movementMult);}
	if (mUpDown)		{GoUpDown(dt);}
	if (mFlipping)		{Pitch(dt*movementMult);}
	if (mRolling)		{Roll(dt*movementMult);}
	if (mSideToSide)	{GoSideToSide(dt);}
	if (mBackAndForth)	{GoBackAndForth(dt);}
	if (mOrbit)			{ Yaw(dt*movementMult); Walk(dt*movementMult*100); }

	XMVECTOR R = XMLoadFloat3(&mRight);
	XMVECTOR U = XMLoadFloat3(&mUp);
	XMVECTOR L = XMLoadFloat3(&mLook);
	XMVECTOR P = XMLoadFloat3(&mPosition);

	
	// Keep axes orthogonal to each other and of unit length.
	L = XMVector3Normalize(L);
	U = XMVector3Normalize(XMVector3Cross(L, R));

	// U, L already ortho-normal, so no need to normalize cross product.
	R = XMVector3Cross(U, L);

	
	// Fill in the world matrix entries.
// 	float x = XMVectorGetX(XMVector3Dot(P, R));
// 	float y = XMVectorGetX(XMVector3Dot(P, U));
// 	float z = XMVectorGetX(XMVector3Dot(P, L));

	float x = XMVectorGetX(P);
	float y = XMVectorGetY(P);
	float z = XMVectorGetZ(P);

	XMStoreFloat3(&mRight, R);
	XMStoreFloat3(&mUp, U);
	XMStoreFloat3(&mLook, L);

	mWorld(0, 0) = mRight.x;
	mWorld(1, 0) = mRight.y;
	mWorld(2, 0) = mRight.z;
	mWorld(3, 0) = x;

	mWorld(0, 1) = mUp.x;
	mWorld(1, 1) = mUp.y;
	mWorld(2, 1) = mUp.z;
	mWorld(3, 1) = y;

	if (reverseLook){
	mWorld(0, 2) = -mLook.x;
	mWorld(1, 2) = -mLook.y;
	mWorld(2, 2) = -mLook.z;
	mWorld(3, 2) = z;}
	else
	{	mWorld(0, 2) = mLook.x;
		mWorld(1, 2) = mLook.y;
		mWorld(2, 2) = mLook.z;
		mWorld(3, 2) = z;}


	mWorld(0, 3) = 0.0f;
	mWorld(1, 3) = 0.0f;
	mWorld(2, 3) = 0.0f;
	mWorld(3, 3) = 1.0f;

	if (hovering)
	{
		XMMATRIX M = XMLoadFloat4x4(&mWorld);
		XMMATRIX scaling = XMMatrixScaling(1.3f, 1.3f, 1.3f);
		XMStoreFloat4x4(&mWorld, scaling * M);
	}


	//GROWING MOVEMENTS
	if (mPulse)	{ Pulse(dt); }
	if (mGrowIn){ GrowIn(dt); }
	if (mGrowOut){ GrowOut(dt); }
	if (mSquishX || mSquishY || mSquishZ){ Squish(dt); 
	if (mSquishX){  ScaleX(currProgress); }
	if (mSquishY){  ScaleY(currProgress); }
	if (mSquishZ){  ScaleZ(currProgress); }}


	if (progressBar)
	{
		ScaleX(currProgress);
	}

	if (billboard)
	{
		XMMATRIX M		= XMLoadFloat4x4(&mWorld);
		XMVECTOR L		= XMVector3Normalize(XMVectorSubtract(camera.GetPositionXM(), GetPositionXM()));
		XMVECTOR Look	= XMLoadFloat3(&mLook);
		XMVECTOR angle	= XMVector3AngleBetweenNormals(L, Look);
		float theAngle	= XMVectorGetY(angle);

		XMMATRIX rotY;
		camera.GetPosition().x < mPosition.x ? rotY = XMMatrixRotationY(-theAngle) : rotY = XMMatrixRotationY(theAngle);

		XMStoreFloat4x4(&mWorld, rotY * M); 
	}

	if (goToPos)
	{
		if (mDistanceLeft <= 0){ goToPos = false; }
	}

	if (mUseAnimation){ mAnim->Update(dt);}

	//update sphere collider
	mSphereCollider.Center	= mPosition;
	if (mUseAAB){ UpdateAAB(); }
	if (mUseAABOnce){ UpdateAAB(); mUseAABOnce = false; }
}
Esempio n. 21
0
bool DEMO::Run()
{

	xTime.Signal();
	static double timer = 0.0;
	static float SPEED = 1.0f / 600.0f;
	timer += xTime.Delta();
	if (timer > ANIMATION_SPEED)
	{
		timer = 0;

		XMMATRIX rotYN = XMMatrixRotationY(XMConvertToRadians(-1.0f));
		star_matrix = rotYN * star_matrix;


		if (scene.percent > 1.0f || scene.percent < 0.0f)
		{
			SPEED = -SPEED;
		}
		scene.percent += SPEED;
		//for (size_t i = 0; i < cubeInstancedData.size(); i++)
		//{
		//	XMMATRIX rotY = XMMatrixRotationY(XMConvertToRadians((float)(i+10))) * XMLoadFloat4x4(&cubeInstancedData[i]);
		//	XMStoreFloat4x4(&cubeInstancedData[i], rotY);
		//}


		//Directional Light Movement
		XMVECTOR DLdir = XMLoadFloat4(&allLights.dLight.lightDirection);
		DLdir = XMVector4Transform(DLdir, XMMatrixRotationX(0.005f));
		XMStoreFloat4(&allLights.dLight.lightDirection, DLdir);


		//Point Light Movement
		XMVECTOR PLpos = XMLoadFloat4(&allLights.pLight.lightPosition);
		PLpos = XMVector4Transform(PLpos, XMMatrixRotationY(0.01f));
		XMStoreFloat4(&allLights.pLight.lightPosition, PLpos);

	}
	if (current_camera)
	{
		SHORT left, right, up, down, shift, w, a, s, d;
		left = GetAsyncKeyState(VK_LEFT);
		a = GetAsyncKeyState('A');
		right = GetAsyncKeyState(VK_RIGHT);
		d = GetAsyncKeyState('D');
		up = GetAsyncKeyState(VK_UP);
		w = GetAsyncKeyState('W');
		down = GetAsyncKeyState(VK_DOWN);
		s = GetAsyncKeyState('S');
		shift = GetAsyncKeyState(VK_SHIFT);
		if (left || a)
		{
			current_camera->Stafe(-(float)xTime.Delta() * 10);
		}


		if (right || d)
		{
			current_camera->Stafe((float)xTime.Delta() * 10);

		}

		if (up || w)
		{
			current_camera->Walk((float)xTime.Delta() * 10);
		}

		if (down || s)
		{
			current_camera->Walk(-(float)xTime.Delta() * 10);
		}

		if (shift && up)
		{
			current_camera->Climb((float)xTime.Delta() * 10);
		}

		if (shift && down)
		{
			current_camera->Climb(-(float)xTime.Delta() * 10);
		}

		GetCursorPos(&CurPos);
		if (/*GetAsyncKeyState(VK_LBUTTON) &&*/ (lastPos.x != CurPos.x || lastPos.y != CurPos.y))
		{
			current_camera->Pitch(0.15f*(CurPos.y - lastPos.y));
			current_camera->RotateY(0.15f*(CurPos.x - lastPos.x));


			RECT rect;
			GetWindowRect(window, &rect);
			if (CurPos.x >= rect.right)
			{
				CurPos.x = rect.left;
			}
			else if (CurPos.x <= rect.left)
			{
				CurPos.x = rect.right;
			}
			else if (CurPos.y <= rect.top)
			{
				CurPos.y = rect.bottom;
			}
			else if (CurPos.y >= rect.bottom - 1)
			{
				CurPos.y = rect.top;
			}
			SetCursorPos(CurPos.x, CurPos.y);
			lastPos.x = CurPos.x;
			lastPos.y = CurPos.y;
		}



		float cube1tocamera = ObjectToCamera(&cubeInstancedData[0], current_camera->GetPosition());
		float cube2tocamera = ObjectToCamera(&cubeInstancedData[1], current_camera->GetPosition());
		float cube3tocamera = ObjectToCamera(&cubeInstancedData[2], current_camera->GetPosition());

		if (cube1tocamera < cube2tocamera)
		{
			swap(cubeInstancedData[0], cubeInstancedData[1]);
			if (cube1tocamera < cube3tocamera)
			{
				swap(cubeInstancedData[1], cubeInstancedData[2]);
			}
		}

		SecureRelease(pCubeInstanceBuffer);
		D3D11_BUFFER_DESC vbd;
		vbd.Usage = D3D11_USAGE_DYNAMIC;
		vbd.ByteWidth = sizeof(XMFLOAT4X4) * (unsigned int)cubeInstancedData.size();
		vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
		vbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		vbd.MiscFlags = 0;
		vbd.StructureByteStride = 0;
		D3D11_SUBRESOURCE_DATA instData;
		ZeroMemory(&instData, sizeof(instData));
		instData.pSysMem = cubeInstancedData.data();
		pDevice->CreateBuffer(&vbd, &instData, &pCubeInstanceBuffer);


	}
	if (GetAsyncKeyState('K') & 0x1)
	{
		current_camera = nullptr;
	}
	if (GetAsyncKeyState('N') & 0x1)
	{
		GetCursorPos(&lastPos);
		current_camera = &another_camera;

	}
	else if (GetAsyncKeyState('O') & 0x1)
	{
		GetCursorPos(&lastPos);
		current_camera = &camera;

	}

	scene._proj = camera.GetProj();
	scene._view = camera.GetView();
	skybox.GO_worldMatrix = XMMatrixScaling(5.0f, 5.0f, 5.0f) * XMMatrixTranslation(camera.GetPosition().x, camera.GetPosition().y, camera.GetPosition().z);


	thread draw = thread(&DEMO::Draw,this);
	draw.join();
	if (pCommandList)
	{
		pDeviceContext->ExecuteCommandList(pCommandList, false);
		pCommandList->Release();
	}

	pSwapchain->Present(0, 0);







	return true;
}
Esempio n. 22
0
    void Camera::Update(float dt)
    {
        if (m_IsMovable)
        {
            float lx, ly, rx, ry;
            g_InputHandler.PollThumbstick(lx, ly, rx, ry);

            bool controller = false;
            if (lx < 0.0f || lx > 0.0f)
            {
                m_moveLeftRight = dt * m_speed * lx;
                controller = true;
            }
            if (ly < 0.0f || ly > 0.0f)
            {
                m_moveBackForward = dt * m_speed * ly;
                controller = true;
            }

            if (rx < 0.0f || rx > 0.0f)
            {
                m_camYaw +=  dt * m_rotateSpeed * rx;
                controller = true;
            }
            if (ry < 0.0f || ry > 0.0f)
            {
                m_camPitch += dt * m_rotateSpeed * ry * -1.0f;
                controller = true;
            }

            if (!controller)
            // Handle Input
            if (g_InputHandler.KeyPressed(Keys::A))
            {
                m_moveLeftRight -= dt * m_speed;
            }
            if (g_InputHandler.KeyPressed(Keys::W))
            {
                m_moveBackForward += dt * m_speed;
            }
            if (g_InputHandler.KeyPressed(Keys::D))
            {
                m_moveLeftRight += dt * m_speed;
            }
            if (g_InputHandler.KeyPressed(Keys::S))
            {
                m_moveBackForward -= dt * m_speed;
            }
            if (g_InputHandler.KeyPressed(Keys::Left_Shift))
            {
                m_moveUpDown += dt * m_speed;
            }
            if (g_InputHandler.KeyPressed(Keys::Left_Ctrl))
            {
                m_moveUpDown -= dt * m_speed;
            }
        }

        m_camRotationMatrix = XMMatrixRotationRollPitchYaw(m_camPitch, m_camYaw, 0);
        m_camTarget = XMVector3TransformCoord(m_defaultForward, m_camRotationMatrix);
        m_camTarget = XMVector3Normalize(m_camTarget);

        XMMATRIX RotateYTempMatrix;
        RotateYTempMatrix = XMMatrixRotationY(m_camYaw);

        m_camRight = XMVector3TransformCoord(m_defaultRight, RotateYTempMatrix);
        // m_camUp = XMVector3TransformCoord(m_camUp, RotateYTempMatrix);
        m_camForward = XMVector3TransformCoord(m_defaultForward, RotateYTempMatrix);

        m_camPosition += m_moveLeftRight*m_camRight;
        m_camPosition += m_moveBackForward*m_camForward;
        m_camPosition += m_moveUpDown*m_camUp;

        m_moveLeftRight = 0.0f;
        m_moveBackForward = 0.0f;
        m_moveUpDown = 0.0f;

        m_camTarget = m_camPosition + m_camTarget;

        m_camView = XMMatrixLookAtLH( m_camPosition, m_camTarget, m_camUp );
    }
Esempio n. 23
0
bool DuckHuntMain::Init()
{
	if (!D3DApp::Init())
		return false;

	// Must init Effects first since InputLayouts depend on shader signatures.
	Effects::InitAll(md3dDevice);
	InputLayouts::InitAll(md3dDevice);
	RenderStates::InitAll(md3dDevice);
	mCrosshair = new Crosshair(md3dDevice);
	mTexMgr.Init(md3dDevice);
	DuckHuntMain::ShowCursors(false);
	mSky = new Sky(md3dDevice, L"Textures/desertcube1024.dds", 5000.0f);
	mSmap = new ShadowMap(md3dDevice, SMapSize, SMapSize);
	Terrain::InitInfo tii;
	tii.HeightMapFilename = L"Textures/myT5.raw";
	tii.LayerMapFilename0 = L"Textures/grass.dds";
	tii.LayerMapFilename1 = L"Textures/darkdirt.dds";
	tii.LayerMapFilename2 = L"Textures/stone.dds";
	tii.LayerMapFilename3 = L"Textures/lightdirt.dds";
	tii.LayerMapFilename4 = L"Textures/snow.dds";
	tii.BlendMapFilename = L"Textures/blend.dds";
	tii.HeightScale = 50.0f;
	tii.HeightmapWidth = 2049;
	tii.HeightmapHeight = 2049;
	tii.CellSpacing = 0.5f;

	mTerrain.Init(md3dDevice, md3dImmediateContext, tii);
	//Sound
	result = FMOD::System_Create(&mSystem);
	result = mSystem->init(32, FMOD_INIT_NORMAL, 0);
	result = mSystem->createSound("Sounds/GunFire.wav", FMOD_DEFAULT, 0, &mGunFire);
	result = mGunFire->setMode(FMOD_LOOP_OFF);






	mCam.SetLens(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);
	mSsao = new Ssao(md3dDevice, md3dImmediateContext, mClientWidth, mClientHeight, mCam.GetFovY(), mCam.GetFarZ());

	BuildScreenQuadGeometryBuffers();

	testModelDuck = new BasicModel(md3dDevice, mTexMgr, "Models\\duck.obj", L"Textures\\DUCK.jpg");



	BasicModelInstance testInstanceDuck;
	BasicModelInstance testInstanceDuck2;
	BasicModelInstance testInstanceDuck3;
	BasicModelInstance testInstanceDuck4;

	testInstanceDuck.Model = testModelDuck;
	testInstanceDuck2.Model = testModelDuck;
	testInstanceDuck3.Model = testModelDuck;
	testInstanceDuck4.Model = testModelDuck;



	//Duck 1
	XMMATRIX modelScale = XMMatrixScaling(1.0f, 1.0f, -1.0f);
	XMMATRIX modelRot = XMMatrixRotationY(0.0f);
	XMMATRIX modelOffset = XMMatrixTranslation(0.0f, 0.0f, 0.0f);
	//Duck 2
	XMMATRIX modelScale2 = XMMatrixScaling(2.0f, 2.0f, -1.0f);
	XMMATRIX modelRot2 = XMMatrixRotationY(-1.0f);
	XMMATRIX modelOffset2 = XMMatrixTranslation(1.0f, 1.0f, -1.0f);
	//Duck3
	XMMATRIX modelScale3 = XMMatrixScaling(1.5f, 1.5f, 1.5f);
	XMMATRIX modelRot3 = XMMatrixRotationY(0.5f);
	XMMATRIX modelOffset3 = XMMatrixTranslation(2.0f, 1.0f, -1.0f);
	//Duck4
	XMMATRIX modelScale4 = XMMatrixScaling(0.5f, 0.5f, -1.0f);
	XMMATRIX modelRot4 = XMMatrixRotationY(1.0f);
	XMMATRIX modelOffset4 = XMMatrixTranslation(0.5f, 1.0f, -1.0f);


	//Duck 1
	XMStoreFloat4x4(&testInstanceDuck.World, modelScale*modelRot*modelOffset);
	mModelInstances.push_back(testInstanceDuck);

	//Duck 2
	XMStoreFloat4x4(&testInstanceDuck2.World, modelScale2*modelRot2*modelOffset2);
	mModelInstances.push_back(testInstanceDuck2);

	//Duck 3
	XMStoreFloat4x4(&testInstanceDuck3.World, modelScale3*modelRot3*modelOffset3);
	mModelInstances.push_back(testInstanceDuck3);

	//Duck 4
	XMStoreFloat4x4(&testInstanceDuck4.World, modelScale4*modelRot4*modelOffset4);
	mModelInstances.push_back(testInstanceDuck4);


	//create collision box
	for (unsigned i = 0; i < mModelInstances.size(); i++)
	{
		mModelInstances[i].Model->CreateCollisionBox(mModelInstances[i].Model->BasicVertices);
	}






	//
	// Compute scene bounding box.
	//

	XMFLOAT3 minPt(+MathHelper::Infinity, +MathHelper::Infinity, +MathHelper::Infinity);
	XMFLOAT3 maxPt(-MathHelper::Infinity, -MathHelper::Infinity, -MathHelper::Infinity);
	for (UINT i = 0; i < mModelInstances.size(); ++i)
	{
		for (UINT j = 0; j < mModelInstances[i].Model->BasicVertices.size(); ++j)
		{
			XMFLOAT3 P = mModelInstances[i].Model->BasicVertices[j].Pos;

			minPt.x = MathHelper::Min(minPt.x, P.x);
			minPt.y = MathHelper::Min(minPt.x, P.x);
			minPt.z = MathHelper::Min(minPt.x, P.x);

			maxPt.x = MathHelper::Max(maxPt.x, P.x);
			maxPt.y = MathHelper::Max(maxPt.x, P.x);
			maxPt.z = MathHelper::Max(maxPt.x, P.x);
		}
	}

	//
	// Derive scene bounding sphere from bounding box.
	//
	mSceneBounds.Center = XMFLOAT3(
		0.5f*(minPt.x + maxPt.x),
		0.5f*(minPt.y + maxPt.y),
		0.5f*(minPt.z + maxPt.z));

	XMFLOAT3 extent(
		0.5f*(maxPt.x - minPt.x),
		0.5f*(maxPt.y - minPt.y),
		0.5f*(maxPt.z - minPt.z));

	mSceneBounds.Radius = sqrtf(extent.x*extent.x + extent.y*extent.y + extent.z*extent.z);

	return true;
}
Esempio n. 24
0
void PrismTexturedModel::InitializeModel(float height, float radius, int nFaces, WCHAR** pTextureFileNames)
{

	/*
	pTextureFileNames is expected to be an array of 3 items
	pTextureFileName[0] is the texture applied to the side faces of the prism
	pTextureFileName[1] is the texture applied to the top end of the prism
	pTextureFileName[2] is the texture applied to the bottom end of the prism
	*/

	int numberOfFaces = nFaces;

	m_textureFileNames = new WCHAR*[NUMBER_OF_TEXTURES]; //file names of 3 face .dds texture files
    for(int i=0; i<NUMBER_OF_TEXTURES; i++){
		m_textureFileNames[i] = pTextureFileNames[i]; //record the file names of the 3 prism face texture files
	}

	//keep number of faces in a reasonable range
	if(numberOfFaces < 3) numberOfFaces = 3;
	if(numberOfFaces > 24) numberOfFaces = 24;
	
	//changing the sign of angle will affect whether the inside or outside of the prism
	//is visible
	float angle = -XM_PI * 2 / nFaces; //slice angle of each face



	//temporary vertices for top and bottom
 	XMFLOAT3* topVertices = new XMFLOAT3[numberOfFaces + 1];
 	XMFLOAT3* bottomVertices = new XMFLOAT3[numberOfFaces + 1];


	
    XMFLOAT3 v0top(radius, height/2, 0); 
    XMFLOAT3 v0bottom(radius, -height/2, 0);

    XMFLOAT3 topCenter(0, height/2, 0);
    XMFLOAT3 bottomCenter(0, -height/2, 0);

    topVertices[0] = v0top;
    topVertices[numberOfFaces] = v0top;
    bottomVertices[0] = v0bottom;
    bottomVertices[numberOfFaces] = v0bottom;


    //define the vertices around the top and bottom of prism

    XMFLOAT4X4 rotationMatrix;
    for (int i = 1; i < numberOfFaces; i++)
    {
		XMStoreFloat4x4(&rotationMatrix, XMMatrixRotationY(angle * i));
	    XMStoreFloat3( &topVertices[i],  XMVector3Transform( XMLoadFloat3(&v0top), XMLoadFloat4x4(&rotationMatrix) ));
	    XMStoreFloat3( &bottomVertices[i],  XMVector3Transform( XMLoadFloat3(&v0bottom), XMLoadFloat4x4(&rotationMatrix) ));

    }

 
	int numberOfFaceVertices = numberOfFaces * 6;
	int numberOfTopVertices = numberOfFaces * 3;
	int numberOfBottomVertices = numberOfFaces * 3;

	m_textureVertices = new TextureVertexType[numberOfFaceVertices];
	m_topTextureVertices = new TextureVertexType[numberOfTopVertices];
	m_bottomTextureVertices = new TextureVertexType[numberOfBottomVertices];

	m_faceTextures = 0; 

	m_indices = new unsigned long[numberOfFaceVertices];
	m_topIndices = new unsigned long[numberOfTopVertices];
	m_bottomIndices = new unsigned long[numberOfBottomVertices];

	//Create the ModelClass object that will be used to deliver these vertices to the graphics pipeline

	m_VertexModelArray = new Model*[NUMBER_OF_TEXTURES]; 

	float faceWidth = 1.0f/numberOfFaces;

	//define the triangle pairs that make up each face
    for (int i = 0; i < numberOfFaces; i++)
    {

           //face vertices -in clockwise render order
 	       m_textureVertices[6*i+0].position = topVertices[i];  //top left
	       m_textureVertices[6*i+0].texture = XMFLOAT2(faceWidth * i, 0.0f);	
	       m_textureVertices[6*i+1].position = topVertices[i+1];   //top right
	       m_textureVertices[6*i+1].texture = XMFLOAT2(faceWidth * (i + 1), 0.0f);
	       m_textureVertices[6*i+2].position = bottomVertices[i];   //bottom left
	       m_textureVertices[6*i+2].texture = XMFLOAT2(faceWidth * i, 1.0f);

		   m_textureVertices[6*i+3].position = bottomVertices[i];  //bottom left
	       m_textureVertices[6*i+3].texture = XMFLOAT2(faceWidth * i, 1.0f);	
	       m_textureVertices[6*i+4].position = topVertices[i + 1];   //top right
	       m_textureVertices[6*i+4].texture = XMFLOAT2(faceWidth * (i + 1), 0.0f);
	       m_textureVertices[6*i+5].position = bottomVertices[i+1];   //bottom right
	       m_textureVertices[6*i+5].texture = XMFLOAT2(faceWidth * (i + 1), 1.0f);

		   //top slice triangle
		   m_topTextureVertices[3*i+0].position = topVertices[i];  
	       m_topTextureVertices[3*i+0].texture = XMFLOAT2((radius + topVertices[i].x)/(2.0f * radius) , (radius - topVertices[i].z)/(2.0f * radius));
	       m_topTextureVertices[3*i+1].position = topCenter;   //center
	       m_topTextureVertices[3*i+1].texture = XMFLOAT2(0.5f , 0.5f);
	       m_topTextureVertices[3*i+2].position = topVertices[i + 1];   
	       m_topTextureVertices[3*i+2].texture = XMFLOAT2((radius + topVertices[i+1].x)/(2.0f * radius), (radius - topVertices[i+1].z)/(2.0f * radius));

		   //bottom slice triangle
		   m_bottomTextureVertices[3*i+0].position = bottomCenter;  //center
	       m_bottomTextureVertices[3*i+0].texture = XMFLOAT2(0.5f , 0.5f);
	       m_bottomTextureVertices[3*i+1].position = bottomVertices[i];  
	       m_bottomTextureVertices[3*i+1].texture = XMFLOAT2((radius + bottomVertices[i].x) /(2.0f * radius) , (radius - bottomVertices[i].z)/(2.0f * radius));
	       m_bottomTextureVertices[3*i+2].position = bottomVertices[i + 1];  
	       m_bottomTextureVertices[3*i+2].texture = XMFLOAT2((radius + bottomVertices[i+1].x)/(2.0f * radius), (radius - bottomVertices[i+1].z)/(2.0f * radius));


     }

	//release memory for temporary arrays
    delete [] topVertices;
 	delete [] bottomVertices;


    //---------------------------------------------
	

	// Load the index array with data.
	// Two triangles per face. The directions are consistent
	// With back-face culling in a left-hand co-ordinate system.
	for(int i=0; i<numberOfFaceVertices; i++)
	     m_indices[i] = i;  // map vertices directly to indices

	for(int i=0; i<numberOfTopVertices; i++)
	     m_topIndices[i] = i;  // map vertices directly to indices

	for(int i=0; i<numberOfBottomVertices; i++)
	     m_bottomIndices[i] = i;  // map vertices directly to indices




	//Create the ModelClass object that will be used to deliver these vertices to the graphics pipeline


    m_VertexModelArray[0] = new Model(
			     m_textureVertices, 
				 numberOfFaceVertices,  //vertex count
				 m_indices, 
				 numberOfFaceVertices, //index count
				 D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	m_VertexModelArray[1] = new Model(
			     m_topTextureVertices, 
				 numberOfTopVertices,  //vertex count
				 m_topIndices, 
				 numberOfTopVertices, //index count
				 D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	m_VertexModelArray[2] = new Model(
			     m_bottomTextureVertices, 
				 numberOfBottomVertices,  //vertex count
				 m_bottomIndices, 
				 numberOfBottomVertices, //index count
				 D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);


}
Esempio n. 25
0
void XM_CALLCONV Camera::RotateY( float angle ) {
	XMMATRIX R = XMMatrixRotationY( angle );
	XMStoreFloat3( &right, XMVector3TransformNormal( XMLoadFloat3( &right ), R ) );
	XMStoreFloat3( &up, XMVector3TransformNormal( XMLoadFloat3( &up ), R ) );
	XMStoreFloat3( &look, XMVector3TransformNormal( XMLoadFloat3( &look ), R ) );
}
Esempio n. 26
0
void AppTest::PopulateCommandListAsync(uint32_t threadID)
{
	CommandAllocatorArray[threadID]->Reset();

	CommandListArray[threadID]->Reset(CommandAllocatorArray[threadID].Get(), PSO.Get());

	Matrix4 view = Matrix4::LookAt(Vector3(0.0f, 6.0f, 2.0f), Vector3(), Vector3(0.0f, 1.0f, 0.0f));
	Matrix4 proj = Matrix4::Perspective(Math::PiOver4, 1280.0f / 720.0f, 0.1f, 1000.0f);

	XMMATRIX viewXM = XMMatrixLookAtRH(XMVectorSet(0.0f, 20.0f, 50.0f, 1.0f), XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f), XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f));
	XMMATRIX projXM = XMMatrixPerspectiveFovRH(Math::PiOver4, 1280.0f / 720.0f, 1.0f, 10000.0f);

	//Update constant buffer
	CBPerObject perObject;

	void* cbUploadPtr = nullptr;

	const unsigned int start = threadID * (BoxCount / ThreadCount);
	const unsigned int end = start + (BoxCount / ThreadCount);

	//Update the constant buffer view transforms for each object
	for (unsigned int i = start; i < end; i++)
	{
		const float scale = 0.04f * static_cast<float>(i);
		const float timeOffset = 1000.0f;
		const float timeMultiplier = 0.001f;

		XMMATRIX world, invTranspose, worldView, worldViewProj;
		world = XMMatrixScaling(scale, scale, scale) * 
			XMMatrixTranslation(static_cast<float>(i), 0.0f, 0.0f) * 
			XMMatrixRotationY(-static_cast<float>((Timer.GetTotalTime() + timeOffset) * static_cast<float>(i)) * timeMultiplier) * 
			XMMatrixScaling(0.01f, 0.01f, 0.01f);

		worldView = world * viewXM;
		worldViewProj = worldView * projXM;

		memcpy_s(&perObject.World, sizeof(perObject.World), &world, sizeof(world));
		memcpy_s(&perObject.WorldViewProj, sizeof(perObject.WorldViewProj), &worldViewProj, sizeof(worldViewProj));

		//Update the constant buffer data for specified object
		cbUploadPtr = PerObjectConstantBuffers.Map(i);
		memcpy_s(cbUploadPtr, sizeof(CBPerObject), &perObject, sizeof(perObject));
		PerObjectConstantBuffers.Unmap(i);
	}

	if (!UseRootLevelCBV)
	{
		ID3D12DescriptorHeap* descriptorHeap = ConstantBufferDescriptorHeap->GetBaseHeap();
		CommandListArray[threadID]->SetDescriptorHeaps(1, &descriptorHeap);
	}

	CommandListArray[threadID]->SetGraphicsRootSignature(RootSignature.Get());

	CommandListArray[threadID]->RSSetViewports(1, &Viewport);
	CommandListArray[threadID]->RSSetScissorRects(1, &RectScissor);

	SetResourceBarrier(CommandListArray[threadID].Get(), RenderTarget.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);

	CommandListArray[threadID]->OMSetRenderTargets(1, &DescriptorHeap->GetCPUDescriptorHandleForHeapStart(), true, &DSVDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
	CommandListArray[threadID]->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	CommandListArray[threadID]->IASetVertexBuffers(0, 1, &DescViewBufVert);
	CommandListArray[threadID]->IASetIndexBuffer(&DescViewBufIndex);

	D3D12_GPU_DESCRIPTOR_HANDLE descriptorHandle;
	
	if (!UseBundles)
	{
		if (UseRootLevelCBV)
		{
			for (unsigned int i = start; i < end; i++)
			{
				CommandListArray[threadID]->SetGraphicsRootConstantBufferView(0, PerObjectConstantBuffers.GetGPUHandle(i));
				CommandListArray[threadID]->DrawIndexedInstanced(IndexCount, 1, 0, 0, 0);
			}
		}
		else
		{
			for (unsigned int i = start; i < end; i++)
			{
				descriptorHandle.ptr = ConstantBufferDescriptorHeap->GetDescriptorGPUHandle(i);
				CommandListArray[threadID]->SetGraphicsRootDescriptorTable(0, descriptorHandle);
				CommandListArray[threadID]->DrawIndexedInstanced(IndexCount, 1, 0, 0, 0);
			}
		}
	}
	else
	{
		const unsigned int bundleStart = (BundleCount / ThreadCount) * threadID;
		const unsigned int bundleEnd = bundleStart + BundleCount / ThreadCount;

		for (unsigned int i = bundleStart; i < bundleEnd; i++)
		{
			CommandListArray[threadID]->ExecuteBundle(CommandBundleArray[i].Get());
		}
	}

	SetResourceBarrier(CommandListArray[threadID].Get(), RenderTarget.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);

	CommandListArray[threadID]->Close();
}
Esempio n. 27
0
bool EndOfDirectX11::LoadContent()
{
	HRESULT result = 0;

	ID3DBlob* buffer = 0;
	ID3DBlob* vsBuffer = 0;
	ID3DBlob* psBuffer = 0;

    bool compileResult = CompileD3DShader( "MultiTexture.fx", 0, "fx_5_0", &buffer );

    if( compileResult == false )
    {
        DXTRACE_MSG( "Error compiling the effect shader!" );
        return false;
    }

	result = D3DX11CreateEffectFromMemory( buffer->GetBufferPointer( ),
        buffer->GetBufferSize( ), 0, d3dDevice_, &effect_ );

	if( FAILED(result) )
	{
		DXTRACE_MSG( "error creating the effect shader" );
		if( buffer )
		{
			buffer->Release();
		}
		return false;
	}

	buffer->Release();

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

	unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout );

	ID3DX11EffectTechnique * colorInvTechnique = 0;
	colorInvTechnique = effect_->GetTechniqueByName( "MultiTexture" );
	ID3DX11EffectPass * effectPass = colorInvTechnique->GetPassByIndex( 0 );

	D3DX11_PASS_SHADER_DESC passDesc;
	D3DX11_EFFECT_SHADER_DESC shaderDesc;
	effectPass->GetVertexShaderDesc( &passDesc );
	passDesc.pShaderVariable->GetShaderDesc( passDesc.ShaderIndex, &shaderDesc );

	result = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements,
		shaderDesc.pBytecode, shaderDesc.BytecodeLength, &inputLayout_ );

	if( FAILED( result ) )
	{
		DXTRACE_MSG( "Error creating the input layout" );
		return false;
	}

	VertexPos vertices[] =
    {
        { XMFLOAT3( -1.0f,  1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3(  1.0f,  1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3(  1.0f,  1.0f,  1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( -1.0f,  1.0f,  1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

        { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3(  1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3(  1.0f, -1.0f,  1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( -1.0f, -1.0f,  1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

        { XMFLOAT3( -1.0f, -1.0f,  1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3( -1.0f,  1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( -1.0f,  1.0f,  1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

        { XMFLOAT3(  1.0f, -1.0f,  1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3(  1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3(  1.0f,  1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3(  1.0f,  1.0f,  1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

        { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3(  1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3(  1.0f,  1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( -1.0f,  1.0f, -1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

        { XMFLOAT3( -1.0f, -1.0f,  1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
        { XMFLOAT3(  1.0f, -1.0f,  1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
        { XMFLOAT3(  1.0f,  1.0f,  1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
        { XMFLOAT3( -1.0f,  1.0f,  1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
    };

    D3D11_BUFFER_DESC vertexDesc;
    ZeroMemory( &vertexDesc, sizeof( vertexDesc ) );
    vertexDesc.Usage = D3D11_USAGE_DEFAULT;
    vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexDesc.ByteWidth = sizeof( VertexPos ) * 24;

    D3D11_SUBRESOURCE_DATA resourceData;
    ZeroMemory( &resourceData, sizeof( resourceData ) );
    resourceData.pSysMem = vertices;

    result = d3dDevice_->CreateBuffer( &vertexDesc, &resourceData, &vertexBuffer_ );

    if( FAILED( result ) )
    {
        DXTRACE_MSG( "Failed to create vertex buffer!" );
        return false;
    }

    WORD indices[] =
    {
        3,   1,  0,  2,  1,  3,
        6,   4,  5,  7,  4,  6,
        11,  9,  8, 10,  9, 11,
        14, 12, 13, 15, 12, 14,
        19, 17, 16, 18, 17, 19,
        22, 20, 21, 23, 20, 22
    };

    D3D11_BUFFER_DESC indexDesc;
    ZeroMemory( &indexDesc, sizeof( indexDesc ) );
    indexDesc.Usage = D3D11_USAGE_DEFAULT;
    indexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexDesc.ByteWidth = sizeof( WORD ) * 36;
    indexDesc.CPUAccessFlags = 0;
    resourceData.pSysMem = indices;

    result = d3dDevice_->CreateBuffer( &indexDesc, &resourceData, &indexBuffer_ );

	if( FAILED( result ) )
	{
		DXTRACE_MSG( "Error in creating index buffer" );
		return false;
	}

	result = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "decal.dds", 0, 0,
		&colorMap_, 0 );

	if( FAILED( result ) )
	{
		DXTRACE_MSG( "Error in creating ShaderResource by decal.dds" );
		return false;
	}

	result = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "decal2.dds", 0, 0,
		&secondMap_, 0 );

	if( FAILED( result ) )
	{
		DXTRACE_MSG( "Error in creating shader resource by decal2.dds" );
		return false;
	}

	D3D11_SAMPLER_DESC colorMapDesc;
	ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) );
	colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
	colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX;

	result = d3dDevice_->CreateSamplerState( &colorMapDesc, &samplerState_ );

	if( FAILED(result) )
	{
		return false;
	}

	D3D11_BUFFER_DESC constDesc;
	ZeroMemory( &constDesc, sizeof( constDesc ) );
	constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	constDesc.ByteWidth = sizeof( XMMATRIX );
	constDesc.Usage = D3D11_USAGE_DEFAULT;

	result = d3dDevice_->CreateBuffer( &constDesc, 0, &worldCB_ );

	if( FAILED( result ) )
	{
		DXTRACE_MSG( "Error in creating world constant buffer" );
		return false;
	}

	result = d3dDevice_->CreateBuffer( &constDesc, 0, &viewCB_ );

	if( FAILED( result ) )
	{
		DXTRACE_MSG( "Error in creating view constant buffer" );
		return false;
	}

	result = d3dDevice_->CreateBuffer( &constDesc, 0, &projCB_ );

	if( FAILED( result ) )
	{
		DXTRACE_MSG( "Error in creating project constant buffer" );
		return false;
	}

	viewMatrix_ = XMMatrixIdentity();
	projMatrix_ = XMMatrixPerspectiveFovLH( XM_PIDIV4, 800.0f / 600.0f, 
		0.01f, 100.0f );

	XMMATRIX rotationMat = XMMatrixRotationY( XM_PIDIV4 * 0.5 );
	XMMATRIX translationMat = XMMatrixTranslation( 0.0f, 0.0f, 6.0f );
	worldMat_ = rotationMat * translationMat;

	return true;
}
	void TransparencyDemo::UpdateDirectionalLight(const GameTime& gameTime)
	{
		static float directionalIntensity = 1.0f;
		float elapsedTime = static_cast<float>(gameTime.ElapsedGameTime().count()) / 1000.0f;

		Library::GamePadComponent* gp = mGame->GetGamePad();

		// Update directional light intensity		
		if (gp->IsButtonDown(GamePadButton::Y) && directionalIntensity < 1.0f)
		{
			directionalIntensity += elapsedTime;
			directionalIntensity = min(directionalIntensity, 1.0f);

			mPixelCBufferPerFrameData.LightColor = XMFLOAT4(directionalIntensity, directionalIntensity, directionalIntensity, 1.0f);
			mDirectionalLight->SetColor(mPixelCBufferPerFrameData.LightColor);
		}
		if (gp->IsButtonDown(GamePadButton::X) && directionalIntensity > 0.0f)
		{
			directionalIntensity -= elapsedTime;
			directionalIntensity = max(directionalIntensity, 0.0f);

			mPixelCBufferPerFrameData.LightColor = XMFLOAT4(directionalIntensity, directionalIntensity, directionalIntensity, 1.0f);
			mDirectionalLight->SetColor(mPixelCBufferPerFrameData.LightColor);
		}


		// Rotate directional light
		XMFLOAT2 rotationAmount = Vector2Helper::Zero;
		if (gp->CurrentState().IsLeftThumbStickRight())
		{
			rotationAmount.x += LightRotationRate.x * elapsedTime;
		}
		if (gp->CurrentState().IsLeftThumbStickLeft())
		{
			rotationAmount.x -= LightRotationRate.x * elapsedTime;
		}
		if (gp->CurrentState().IsLeftThumbStickUp())
		{
			rotationAmount.y += LightRotationRate.y * elapsedTime;
		}
		if (gp->CurrentState().IsLeftThumbStickDown())
		{
			rotationAmount.y -= LightRotationRate.y * elapsedTime;
		}

		XMMATRIX lightRotationMatrix = XMMatrixIdentity();
		if (rotationAmount.x != 0)
		{
			lightRotationMatrix = XMMatrixRotationY(rotationAmount.x);
		}

		if (rotationAmount.y != 0)
		{
			XMMATRIX lightRotationAxisMatrix = XMMatrixRotationAxis(mDirectionalLight->RightVector(), rotationAmount.y);
			lightRotationMatrix *= lightRotationAxisMatrix;
		}

		if (rotationAmount.x != 0.0f || rotationAmount.y != 0.0f)
		{
			mDirectionalLight->ApplyRotation(lightRotationMatrix);
			mProxyModel->ApplyRotation(lightRotationMatrix);

			const XMFLOAT3& lightdirection = mDirectionalLight->Direction();
			mVertexCBufferPerFrameData.LightDirection = XMFLOAT4(lightdirection.x, lightdirection.y, lightdirection.z, 0.0f);
		}
	}
void AnimationController::Interpolate( float dt ) {
	timeSinceStart += dt;
	Anim anim = *anims[currentAnim];
	float animCurrentTime = fmod( timeSinceStart, anim.totalTime );
	for( Bone* bone:anim.boneSet ) {
		XMMATRIX rotMat, scaleMat, translateMat;

		// Interpolate Rotation
		auto rotSetIt = anim.rotChannels.find( bone );
		if( rotSetIt==anim.rotChannels.end() ) {
			rotMat = XMMatrixIdentity();
		} else {
			keySet_t rotKeySet = rotSetIt->second;
			auto itLow = rotKeySet.lower_bound( animCurrentTime );
			if( itLow==rotKeySet.begin() ) {
				itLow = rotKeySet.end();
			}
			--itLow;
			auto itHigh = rotKeySet.upper_bound( animCurrentTime );
			if( itHigh==rotKeySet.end() ) {
				itHigh = rotKeySet.begin();
			}
			float factor = (animCurrentTime-itLow->first)/(itHigh->first-itLow->first);
			XMVECTOR low = XMLoadFloat4( &itLow->second );
			XMVECTOR high = XMLoadFloat4( &itHigh->second );
			XMVECTOR interp = XMQuaternionSlerp( low, high, factor );
			XMVECTOR normalized = XMQuaternionNormalize( interp );
			rotMat = XMMatrixRotationQuaternion( interp );
		}

		// Interpolate Scale
		auto scaleSetIt = anim.scaleChannels.find( bone );
		if( scaleSetIt==anim.scaleChannels.end() ) {
			scaleMat = XMMatrixIdentity();
		} else {
			keySet_t scaleKeySet = scaleSetIt->second;
			auto itLow = scaleKeySet.lower_bound( animCurrentTime );
			if( itLow==scaleKeySet.begin() ) {
				itLow = scaleKeySet.end();
			}
			--itLow;
			auto itHigh = scaleKeySet.upper_bound( animCurrentTime );
			if( itHigh==scaleKeySet.end() ) {
				itHigh = scaleKeySet.begin();
			}
			float factor = (animCurrentTime-itLow->first)/(itHigh->first-itLow->first);
			XMFLOAT4 lowVec = itLow->second;
			XMFLOAT4 highVec = itHigh->second;
			scaleMat = XMMatrixScaling(
				lowVec.x+factor*(highVec.x-lowVec.x),
				lowVec.y+factor*(highVec.y-lowVec.y),
				lowVec.z+factor*(highVec.z-lowVec.z) );
		}

		// Interpolate Position
		auto posSetIt = anim.posChannels.find( bone );
		if( posSetIt==anim.posChannels.end() ) {
			translateMat = XMMatrixIdentity();
		} else {
			keySet_t posKeySet = posSetIt->second;
			auto itLow = posKeySet.lower_bound( animCurrentTime );
			if( itLow==posKeySet.begin() ) {
				itLow = posKeySet.end();
			}
			--itLow;
			auto itHigh = posKeySet.upper_bound( animCurrentTime );
			if( itHigh==posKeySet.end() ) {
				itHigh = posKeySet.begin();
			}
			float factor = (animCurrentTime-itLow->first)/(itHigh->first-itLow->first);
			XMFLOAT4 lowVec = itLow->second;
			XMFLOAT4 highVec = itHigh->second;
			translateMat = XMMatrixTranslation(
				lowVec.x+factor*(highVec.x-lowVec.x),
				lowVec.y+factor*(highVec.y-lowVec.y),
				lowVec.z+factor*(highVec.z-lowVec.z) );
		}

		// Conversion Matrix - this converts imported coords to DirectX
		XMMATRIX reflectX = XMMatrixReflect( XMLoadFloat3( &XMFLOAT3( 1.f, 0.f, 0.f ) ) );
		XMMATRIX reflectY = XMMatrixReflect( XMLoadFloat3( &XMFLOAT3( 0.f, 1.f, 0.f ) ) );
		XMMATRIX reflectZ = XMMatrixReflect( XMLoadFloat3( &XMFLOAT3( 0.f, 0.f, 1.f ) ) );
		XMMATRIX rotX = XMMatrixRotationX( XM_PIDIV2 );
		XMMATRIX rotY = XMMatrixRotationY( XM_PIDIV2 );
		XMMATRIX rotZ = XMMatrixRotationZ( XM_PIDIV2 );
		int foo = 17; //DELETEME
		XMMATRIX flip = XMLoadFloat4x4( &XMFLOAT4X4(
			1.f, 0.f, 0.f, 0.f,
			0.f, 1.f, 0.f, 0.f,
			0.f, 0.f, 1.f, 0.f,
			0.f, 0.f, 0.f, 1.f
			) );

		XMMATRIX finalMat = scaleMat * rotMat * translateMat;
		XMFLOAT4X4 transform;
		XMStoreFloat4x4( &transform, finalMat );
		finalTransform[bone] = transform;
	}
}
Esempio n. 30
0
void DX11::RotateY(float degs)
{
  assert(s_matrixMode == DX11_MODELVIEW_MATRIX);
  g_View = XMMatrixRotationY(DegToRad(degs)) * g_View;
}