Exemplo n.º 1
0
// Pop up a message box with specified title/text
//-----------------------------------------------------------------------------
void CPUT_DX11::DrawLoadingFrame()
{
    // fill first frame with clear values so render order later is ok
    const float srgbClearColor[] = { 0.0993f, 0.0993f, 0.0993f, 1.0f };
    mpContext->ClearRenderTargetView( mpBackBufferRTV, srgbClearColor );
    mpContext->ClearDepthStencilView(mpDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 0.0f, 0);

    // get center
    int x,y,width,height;
    CPUTOSServices::GetOSServices()->GetClientDimensions(&x, &y, &width, &height);

    // draw "loading..." text
    CPUTGuiControllerDX11 *pGUIController = CPUTGuiControllerDX11::GetController();
    CPUTText *pText = NULL;
    pGUIController->CreateText(_L("Just a moment, now loading..."), 999, 0, &pText);
    pGUIController->EnableAutoLayout(false);
    int textWidth, textHeight;
    pText->GetDimensions(textWidth, textHeight);
    pText->SetPosition(width/2-textWidth/2, height/2);

    pGUIController->Draw(mpContext);
    pGUIController->DeleteAllControls();
    pGUIController->EnableAutoLayout(true);
    
    // present loading screen
    mpSwapChain->Present( mSyncInterval, 0 );
}
Exemplo n.º 2
0
// Create a window context
//-----------------------------------------------------------------------------
CPUTResult CPUT_DX11::CPUTCreateWindowAndContext(const cString WindowTitle, CPUTWindowCreationParams windowParams)
{
    CPUTResult result = CPUT_SUCCESS;

    HEAPCHECK;

    // create the window
    result = MakeWindow(WindowTitle, windowParams.windowWidth, windowParams.windowHeight, windowParams.windowPositionX, windowParams.windowPositionY);
    if(CPUTFAILED(result))
    {
        return result;
    }

    HEAPCHECK;

    // create the DX context
    result = CreateDXContext(windowParams.deviceParams);
    if(CPUTFAILED(result))
    {
        return result;
    }

    CPUTModelDX11::CreateModelConstantBuffer();

    HEAPCHECK;
#define ENABLE_GUI
#ifdef ENABLE_GUI
    // initialize the gui controller 
    // Use the ResourceDirectory that was given during the Initialize() function
    // to locate the GUI+font resources
    CPUTGuiControllerDX11 *pGUIController = CPUTGuiControllerDX11::GetController();
    cString ResourceDirectory = GetCPUTResourceDirectory();
    result = pGUIController->Initialize(mpContext, ResourceDirectory);
    if(CPUTFAILED(result))
    {
        return result;
    }
    // register the callback object for GUI events as our sample
    CPUTGuiControllerDX11::GetController()->SetCallback(this);
#endif
    HEAPCHECK;
    DrawLoadingFrame();
    HEAPCHECK;
    
    // warn the user they are using the software rasterizer
    if((D3D_DRIVER_TYPE_REFERENCE == mdriverType) || (D3D_DRIVER_TYPE_WARP == mdriverType))
    {
        CPUTOSServices::GetOSServices()->OpenMessageBox(_L("Performance warning"), _L("Your graphics hardware does not support the DirectX features required by this sample. The sample is now running using the DirectX software rasterizer."));
    }


    // trigger a post-create user callback event
    HEAPCHECK;
    Create();
    HEAPCHECK;

    //
    // Start the timer after everything is initialized and assets have been loaded
    //
    mpTimer->StartTimer();

    // if someone triggers the shutdown routine in on-create, exit
    if(mbShutdown)
    {
        return result;
    }

    // does user want to start in fullscreen mode?
    if(true == windowParams.startFullscreen)
    {
        result = CPUTToggleFullScreenMode();
        if(CPUTFAILED(result))
        {
            return result;
        }
    }

    // fill first frame with clear values so render order later is ok
    const float srgbClearColor[] = { 0.0993f, 0.0993f, 0.0993f, 1.0f };
    mpContext->ClearRenderTargetView( mpBackBufferRTV, srgbClearColor );
    mpContext->ClearDepthStencilView(mpDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 0.0f, 0);

    // trigger a 'resize' event
    int x,y,width,height;
    CPUTOSServices::GetOSServices()->GetClientDimensions(&x, &y, &width, &height);
    ResizeWindow(width,height);

    return result;
}
// Handle keyboard events
//-----------------------------------------------------------------------------
CPUTEventHandledCode MySample::HandleKeyboardEvent(CPUTKey key)
{
    static bool panelToggle = false;
    CPUTEventHandledCode    handled = CPUT_EVENT_UNHANDLED;
    cString fileName;
    CPUTGuiControllerDX11*  pGUI = CPUTGetGuiController();

    switch(key)
    {
    case KEY_F1:
        panelToggle = !panelToggle;
        if(panelToggle)
        {
            pGUI->SetActivePanel(ID_SECONDARY_PANEL);
        }
        else
        {
            pGUI->SetActivePanel(ID_MAIN_PANEL);
        }
        handled = CPUT_EVENT_HANDLED;
        break;
    case KEY_L:
        {
            static int cameraObjectIndex = 0;
            CPUTRenderNode *pCameraList[] = { mpCamera, mpShadowCamera };
            cameraObjectIndex = (++cameraObjectIndex) % (sizeof(pCameraList)/sizeof(*pCameraList));
            CPUTRenderNode *pCamera = pCameraList[cameraObjectIndex];
            mpCameraController->SetCamera( pCamera );
        }
        handled = CPUT_EVENT_HANDLED;
        break;
    case KEY_ESCAPE:
        handled = CPUT_EVENT_HANDLED;
        Shutdown();
        break;

	case KEY_1:
		{
			CPUTToggleFullScreenMode();
			break;
		}
	case KEY_2:
		{
			mEnableCulling = !mEnableCulling;
			CPUTCheckboxState state;
			if(mEnableCulling)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else 
			{
				state = CPUT_CHECKBOX_UNCHECKED;
				memset(mpCPUDepthBuf[mCurrId], 0, SCREENW * SCREENH *4);

				mpOccludersR2DBText->SetText(         _L("\tDepth rasterized models: 0"));
				mpOccluderRasterizedTrisText->SetText(_L("\tDepth rasterized tris: \t0"));
				mpRasterizeTimeText->SetText(         _L("\tDepth rasterizer time: \t0 ms"));

				mpCulledText->SetText(       _L("\tModels culled: \t\t0"));
				mpVisibleText->SetText(      _L("\tModels visible: \t\t0"));
				mpCulledTrisText->SetText(   _L("\tCulled tris: \t\t0"));
				mpVisibleTrisText->SetText(   _L("\tVisible tris: \t\t0"));
				mpDepthTestTimeText->SetText(_L("\tDepth test time: \t0 ms"));
			}
			mpCullingCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_3:
		{
			mEnableFCulling = !mEnableFCulling;
			CPUTCheckboxState state;
			if(mEnableFCulling)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
				mpDBR->ResetInsideFrustum();
				mpAABB->ResetInsideFrustum();
			}
			mpFCullingCheckBox->SetCheckboxState(state);
			break;			
		}
	case KEY_4:
		{
			mViewDepthBuffer = !mViewDepthBuffer;
			CPUTCheckboxState state;
			if(mViewDepthBuffer)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else 
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpDBCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_5:
		{
			mViewBoundingBox = !mViewBoundingBox;
			CPUTCheckboxState state;
			if(mViewBoundingBox)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpBBCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_6:
		{
			TaskCleanUp();
			mEnableTasks = !mEnableTasks;
			CPUTCheckboxState state;
			
			SAFE_DELETE_ARRAY(mpDBR);
			SAFE_DELETE_ARRAY(mpAABB);

			if(mEnableTasks)
			{
				state = CPUT_CHECKBOX_CHECKED;
				mpPipelineCheckBox->SetVisibility(true);
				mpDepthTestTaskSlider->SetVisibility(true);

				wchar_t string[CPUT_MAX_STRING_LENGTH];
				swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Depth Test Task: \t%d"), mNumDepthTestTasks);
				mpDepthTestTaskSlider->SetText(string);
			
				if(mSOCType == SCALAR_TYPE)
				{
					mpDBRScalarMT = new DepthBufferRasterizerScalarMT;
					mpDBR = mpDBRScalarMT;

					mpAABBScalarMT = new AABBoxRasterizerScalarMT;
					mpAABB = mpAABBScalarMT;
				}
				else if(mSOCType == SSE_TYPE)
				{
					mpDBRSSEMT = new DepthBufferRasterizerSSEMT;
					mpDBR = mpDBRSSEMT;
					
					mpAABBSSEMT = new AABBoxRasterizerSSEMT;
					mpAABB = mpAABBSSEMT;
				}
				mpAABB->SetDepthTestTasks(mNumDepthTestTasks);
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
				mpPipelineCheckBox->SetVisibility(false);
				mpDepthTestTaskSlider->SetVisibility(false);
				if(mSOCType == SCALAR_TYPE)
				{
					mpDBRScalarST = new DepthBufferRasterizerScalarST;
					mpDBR = mpDBRScalarST;
	
					mpAABBScalarST = new AABBoxRasterizerScalarST;
					mpAABB = mpAABBScalarST;
				}
				else if(mSOCType == SSE_TYPE)
				{
					mpDBRSSEST = new DepthBufferRasterizerSSEST;
					mpDBR = mpDBRSSEST;
					
					mpAABBSSEST = new AABBoxRasterizerSSEST;
					mpAABB = mpAABBSSEST;
				}	
			}
			mpDBR->CreateTransformedModels(mpAssetSetDBR, OCCLUDER_SETS);		
			mpDBR->SetOccluderSizeThreshold(mOccluderSizeThreshold);
			mpAABB->CreateTransformedAABBoxes(mpAssetSetAABB, OCCLUDEE_SETS);
			mpAABB->SetOccludeeSizeThreshold(mOccludeeSizeThreshold);
			mpTasksCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_7:
		{
			if(mSyncInterval == 1)
			{
				mSyncInterval = 0;
			}
			else 
			{
				mSyncInterval = 1;
			}
			CPUTCheckboxState state;
			if(mSyncInterval == 1)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpVsyncCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_8:
		{
			TaskCleanUp();
			mPipeline = !mPipeline;
			CPUTCheckboxState state;
			if(mPipeline)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpPipelineCheckBox->SetCheckboxState(state);
			break;
		}
    }
	

    // pass it to the camera controller
    if(handled == CPUT_EVENT_UNHANDLED)
    {
        handled = mpCameraController->HandleKeyboardEvent(key);
    }
    return handled;
}
// Handle OnCreation events
//-----------------------------------------------------------------------------
void MySample::Create()
{    
    CPUTAssetLibrary *pAssetLibrary = CPUTAssetLibrary::GetAssetLibrary();

    gLightDir.normalize();

    // TODO: read from cmd line, using these as defaults
    //pAssetLibrary->SetMediaDirectoryName(    _L("Media"));

    CPUTGuiControllerDX11 *pGUI = CPUTGetGuiController();

    // create some controls
	CPUTButton     *pButton = NULL;
    pGUI->CreateButton(_L("Fullscreen"), ID_FULLSCREEN_BUTTON, ID_MAIN_PANEL, &pButton);
	pGUI->CreateDropdown( L"Rasterizer Technique: SCALAR", ID_RASTERIZE_TYPE, ID_MAIN_PANEL, &mpTypeDropDown);
    mpTypeDropDown->AddSelectionItem( L"Rasterizer Technique: SSE" );
   	mpTypeDropDown->SetSelectedItem(mSOCType + 1);
   
	wchar_t string[CPUT_MAX_STRING_LENGTH];
    pGUI->CreateText(    _L("Occluders                                              \t"), ID_OCCLUDERS, ID_MAIN_PANEL, &mpOccludersText);
	
	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of Models: \t%d"), mNumOccluders);
	pGUI->CreateText(string, ID_NUM_OCCLUDERS, ID_MAIN_PANEL, &mpNumOccludersText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tDepth rasterized models: %d"), mNumOccludersR2DB);
	pGUI->CreateText(string, ID_NUM_OCCLUDERS_RASTERIZED_TO_DB, ID_MAIN_PANEL, &mpOccludersR2DBText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of tris: \t\t%f"), mNumOccluderTris);
	pGUI->CreateText(string, ID_NUM_OCCLUDER_TRIS, ID_MAIN_PANEL, &mpOccluderTrisText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tDepth rasterized tris: \t%f"), mNumOccluderRasterizedTris);
	pGUI->CreateText(string, ID_NUM_OCCLUDER_RASTERIZED_TRIS, ID_MAIN_PANEL, &mpOccluderRasterizedTrisText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tDepth raterizer time: \t%f"), mRasterizeTime);
	pGUI->CreateText(string, ID_RASTERIZE_TIME, ID_MAIN_PANEL, &mpRasterizeTimeText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Occluder Size Threshold: %0.4f"), mOccluderSizeThreshold);
	pGUI->CreateSlider(string, ID_OCCLUDER_SIZE, ID_MAIN_PANEL, &mpOccluderSizeSlider);
	mpOccluderSizeSlider->SetScale(0, 5.0, 51);
	mpOccluderSizeSlider->SetValue(mOccluderSizeThreshold);
	mpOccluderSizeSlider->SetTickDrawing(false);
    
	pGUI->CreateText(_L("Occludees                                              \t"), ID_OCCLUDEES, ID_MAIN_PANEL, &mpOccludeesText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of Models: \t%d"), mNumOccludees);
	pGUI->CreateText(string, ID_NUM_OCCLUDEES, ID_MAIN_PANEL, &mpNumOccludeesText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tModels culled: \t%d"), mNumCulled);
	pGUI->CreateText(string, ID_NUM_CULLED, ID_MAIN_PANEL, &mpCulledText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tModels visible: \t%d"), mNumVisible);
	pGUI->CreateText(string, ID_NUM_VISIBLE, ID_MAIN_PANEL, &mpVisibleText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of tris: \t%d"), (int)mNumOccludeeTris);
	pGUI->CreateText(string, ID_NUM_OCCLUDEE_TRIS, ID_MAIN_PANEL, &mpOccludeeTrisText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tCulled Triangles: \t%d"), (int)mNumOccludeeCulledTris);
	pGUI->CreateText(string, ID_NUM_OCCLUDEE_CULLED_TRIS, ID_MAIN_PANEL, &mpCulledTrisText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tVisible Triangles: \t%d"), (int)mNumOccludeeVisibleTris);
	pGUI->CreateText(string, ID_NUM_OCCLUDEE_VISIBLE_TRIS, ID_MAIN_PANEL, &mpVisibleTrisText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tVisible Triangles: \t%0.2f ms"), mDepthTestTime);
	pGUI->CreateText(string, ID_DEPTHTEST_TIME, ID_MAIN_PANEL, &mpDepthTestTimeText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Occludee Size Threshold: %0.4f"), mOccludeeSizeThreshold);
	pGUI->CreateSlider(string, ID_OCCLUDEE_SIZE, ID_MAIN_PANEL, &mpOccludeeSizeSlider);
	mpOccludeeSizeSlider->SetScale(0, 0.1f, 41);
	mpOccludeeSizeSlider->SetValue(mOccludeeSizeThreshold);
	mpOccludeeSizeSlider->SetTickDrawing(false);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Total Cull time: %0.2f"), mTotalCullTime);
	pGUI->CreateText(string, ID_TOTAL_CULL_TIME, ID_MAIN_PANEL, &mpTotalCullTimeText);

	pGUI->CreateCheckbox(_L("Depth Test Culling"),  ID_ENABLE_CULLING, ID_MAIN_PANEL, &mpCullingCheckBox);
	pGUI->CreateCheckbox(_L("Frustum Culling"),  ID_ENABLE_FCULLING, ID_MAIN_PANEL, &mpFCullingCheckBox);
	pGUI->CreateCheckbox(_L("View Depth Buffer"),  ID_DEPTH_BUFFER_VISIBLE, ID_MAIN_PANEL, &mpDBCheckBox);
	pGUI->CreateCheckbox(_L("View Bounding Box"),  ID_BOUNDING_BOX_VISIBLE, ID_MAIN_PANEL, &mpBBCheckBox);
	pGUI->CreateCheckbox(_L("Multi Tasking"), ID_ENABLE_TASKS, ID_MAIN_PANEL, &mpTasksCheckBox);
	pGUI->CreateCheckbox(_L("Vsync"), ID_VSYNC_ON_OFF, ID_MAIN_PANEL, &mpVsyncCheckBox);
	pGUI->CreateCheckbox(_L("Pipeline"), ID_PIPELINE, ID_MAIN_PANEL, &mpPipelineCheckBox);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Number of draw calls: \t%d"), mNumDrawCalls);
	pGUI->CreateText(string, ID_NUM_DRAW_CALLS, ID_MAIN_PANEL, &mpDrawCallsText),
	
	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Depth Test Tasks: \t\t%d"), mNumDepthTestTasks);
    pGUI->CreateSlider(string, ID_DEPTH_TEST_TASKS, ID_MAIN_PANEL, &mpDepthTestTaskSlider);
	mpDepthTestTaskSlider->SetScale(1, (float)NUM_DT_TASKS, 11);
	mpDepthTestTaskSlider->SetValue((float)mNumDepthTestTasks);
	mpDepthTestTaskSlider->SetTickDrawing(false);
	mpAABB->SetDepthTestTasks(mNumDepthTestTasks);

    //
    // Create Static text
    //
    pGUI->CreateText( _L("F1 for Help"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
    pGUI->CreateText( _L("[Escape] to quit application"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
    pGUI->CreateText( _L("A,S,D,F - move camera position"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
    pGUI->CreateText( _L("Q - camera position up"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
    pGUI->CreateText( _L("E - camera position down"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
    pGUI->CreateText( _L("mouse + right click - camera look location"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
	pGUI->CreateText( _L("size thresholds : computed using screen space metris"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);

    pGUI->SetActivePanel(ID_MAIN_PANEL);
    pGUI->DrawFPS(true);

    // Add our programatic (and global) material parameters
    CPUTMaterial::mGlobalProperties.AddValue( _L("cbPerFrameValues"), _L("$cbPerFrameValues") );
    CPUTMaterial::mGlobalProperties.AddValue( _L("cbPerModelValues"), _L("$cbPerModelValues") );
    CPUTMaterial::mGlobalProperties.AddValue( _L("_Shadow"), _L("$shadow_depth") );

	// Creating a render target to view the CPU rasterized depth buffer
	mpCPUDepthBuf[0] = new char[SCREENW*SCREENH*4];
	mpCPUDepthBuf[1] = new char[SCREENW*SCREENH*4];
	mpGPUDepthBuf    = new char[SCREENW*SCREENH*4];

	CD3D11_TEXTURE2D_DESC cpuRenderTargetDescSSE
	(
		DXGI_FORMAT_R8G8B8A8_UNORM,
        SCREENW * 2, // TODO: round up to full tile sizes
        SCREENH / 2,
        1, // Array Size
        1, // MIP Levels
		D3D11_BIND_SHADER_RESOURCE,
        D3D11_USAGE_DEFAULT,
		0
    );
	HRESULT hr;
	hr = mpD3dDevice->CreateTexture2D(&cpuRenderTargetDescSSE, NULL, &mpCPURenderTargetSSE[0]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating render target."));

	hr = mpD3dDevice->CreateTexture2D(&cpuRenderTargetDescSSE, NULL, &mpCPURenderTargetSSE[1]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating render target."));

	hr = mpD3dDevice->CreateShaderResourceView(mpCPURenderTargetSSE[0], NULL, &mpCPUSRVSSE[0]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating shader resource view."));

	hr = mpD3dDevice->CreateShaderResourceView(mpCPURenderTargetSSE[1], NULL, &mpCPUSRVSSE[1]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating shader resource view."));

	// Corresponding texture object
	CPUTTextureDX11 *pDummyTex0 = new CPUTTextureDX11;
	pDummyTex0->SetTextureAndShaderResourceView(mpCPURenderTargetSSE[0], mpCPUSRVSSE[0]);
	pAssetLibrary->AddTexture( _L("$depthbuf_tex_SSE"), pDummyTex0 );
	SAFE_RELEASE(pDummyTex0);

	CPUTTextureDX11 *pDummyTex1 = new CPUTTextureDX11;
	pDummyTex1->SetTextureAndShaderResourceView(mpCPURenderTargetSSE[1], mpCPUSRVSSE[1]);
	pAssetLibrary->AddTexture( _L("$depthbuf_tex_SSE"), pDummyTex1 );
	SAFE_RELEASE(pDummyTex1);

	CD3D11_TEXTURE2D_DESC cpuRenderTargetDescScalar
	(
		DXGI_FORMAT_R8G8B8A8_UNORM,
        SCREENW, // TODO: round up to full tile sizes
        SCREENH,
        1, // Array Size
        1, // MIP Levels
		D3D11_BIND_SHADER_RESOURCE,
        D3D11_USAGE_DEFAULT,
		0
    );
	hr = mpD3dDevice->CreateTexture2D(&cpuRenderTargetDescScalar, NULL, &mpCPURenderTargetScalar[0]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating render target."));

	hr = mpD3dDevice->CreateTexture2D(&cpuRenderTargetDescScalar, NULL, &mpCPURenderTargetScalar[1]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating render target."));

	hr = mpD3dDevice->CreateShaderResourceView(mpCPURenderTargetScalar[0], NULL, &mpCPUSRVScalar[0]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating shader resource view."));

	hr = mpD3dDevice->CreateShaderResourceView(mpCPURenderTargetScalar[1], NULL, &mpCPUSRVScalar[1]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating shader resource view."));

	// Corresponding texture object
	CPUTTextureDX11 *pDummyTex2 = new CPUTTextureDX11;
	pDummyTex2->SetTextureAndShaderResourceView(mpCPURenderTargetScalar[0], mpCPUSRVScalar[0]);
	pAssetLibrary->AddTexture( _L("$depthbuf_tex_Scalar"), pDummyTex2 );
	SAFE_RELEASE(pDummyTex2);

	CPUTTextureDX11 *pDummyTex3 = new CPUTTextureDX11;
	pDummyTex3->SetTextureAndShaderResourceView(mpCPURenderTargetScalar[1], mpCPUSRVScalar[1]);
	pAssetLibrary->AddTexture( _L("$depthbuf_tex_Scalar"), pDummyTex3 );
	SAFE_RELEASE(pDummyTex3);

	// Create default shaders
    CPUTPixelShaderDX11  *pPS       = CPUTPixelShaderDX11::CreatePixelShaderFromMemory(            _L("$DefaultShader"), CPUT_DX11::mpD3dDevice,          _L("PSMain"), _L("ps_4_0"), gpDefaultShaderSource );
    CPUTPixelShaderDX11  *pPSNoTex  = CPUTPixelShaderDX11::CreatePixelShaderFromMemory(   _L("$DefaultShaderNoTexture"), CPUT_DX11::mpD3dDevice, _L("PSMainNoTexture"), _L("ps_4_0"), gpDefaultShaderSource );
    CPUTVertexShaderDX11 *pVS       = CPUTVertexShaderDX11::CreateVertexShaderFromMemory(          _L("$DefaultShader"), CPUT_DX11::mpD3dDevice,          _L("VSMain"), _L("vs_4_0"), gpDefaultShaderSource );
    CPUTVertexShaderDX11 *pVSNoTex  = CPUTVertexShaderDX11::CreateVertexShaderFromMemory( _L("$DefaultShaderNoTexture"), CPUT_DX11::mpD3dDevice, _L("VSMainNoTexture"), _L("vs_4_0"), gpDefaultShaderSource );

    // We just want to create them, which adds them to the library.  We don't need them any more so release them, leaving refCount at 1 (only library owns a ref)
    SAFE_RELEASE(pPS);
    SAFE_RELEASE(pPSNoTex);
    SAFE_RELEASE(pVS);
    SAFE_RELEASE(pVSNoTex);

    // load shadow casting material+sprite object
    cString ExecutableDirectory;
    CPUTOSServices::GetOSServices()->GetExecutableDirectory(&ExecutableDirectory);
    pAssetLibrary->SetMediaDirectoryName(  ExecutableDirectory+_L("..\\..\\Media\\"));

    mpShadowRenderTarget = new CPUTRenderTargetDepth();
    mpShadowRenderTarget->CreateRenderTarget( cString(_L("$shadow_depth")), SHADOW_WIDTH_HEIGHT, SHADOW_WIDTH_HEIGHT, DXGI_FORMAT_D32_FLOAT );

    mpDebugSprite = new CPUTSprite();
    mpDebugSprite->CreateSprite( -1.0f, -1.0f, 0.5f, 0.5f, _L("Sprite") );

	int width, height;
    CPUTOSServices::GetOSServices()->GetClientDimensions(&width, &height);

	// Depth buffer visualization material
	mpShowDepthBufMtrlScalar = (CPUTMaterialDX11*)CPUTAssetLibraryDX11::GetAssetLibrary()->GetMaterial( _L("showDepthBufScalar"));
	mpShowDepthBufMtrlSSE = (CPUTMaterialDX11*)CPUTAssetLibraryDX11::GetAssetLibrary()->GetMaterial( _L("showDepthBufSSE"));
		
	if(mSOCType == SCALAR_TYPE)
	{
		mpCPURenderTarget[0] = mpCPURenderTargetScalar[0];
		mpCPURenderTarget[1] = mpCPURenderTargetScalar[1];
		mpCPUSRV[0]          = mpCPUSRVScalar[0];
		mpCPUSRV[1]          = mpCPUSRVScalar[1];
		mpShowDepthBufMtrl   = mpShowDepthBufMtrlScalar;
		rowPitch			 = SCREENW * 4;
	}
	else
	{
		mpCPURenderTarget[0] = mpCPURenderTargetSSE[0];
		mpCPURenderTarget[1] = mpCPURenderTargetSSE[1];
		mpCPUSRV[0]          = mpCPUSRVSSE[0];
		mpCPUSRV[1]          = mpCPUSRVSSE[1];
		mpShowDepthBufMtrl = mpShowDepthBufMtrlSSE;
		rowPitch			 = 2 * SCREENW * 4;
	}

    // Call ResizeWindow() because it creates some resources that our blur material needs (e.g., the back buffer)
    ResizeWindow(width, height);

    CPUTRenderStateBlockDX11 *pBlock = new CPUTRenderStateBlockDX11();
    CPUTRenderStateDX11 *pStates = pBlock->GetState();

    // Override default sampler desc for our default shadowing sampler
    pStates->SamplerDesc[1].Filter         = D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
    pStates->SamplerDesc[1].AddressU       = D3D11_TEXTURE_ADDRESS_BORDER;
    pStates->SamplerDesc[1].AddressV       = D3D11_TEXTURE_ADDRESS_BORDER;
    pStates->SamplerDesc[1].ComparisonFunc = D3D11_COMPARISON_GREATER;
    pBlock->CreateNativeResources();
    CPUTAssetLibrary::GetAssetLibrary()->AddRenderStateBlock( _L("$DefaultRenderStates"), pBlock );
    pBlock->Release(); // We're done with it.  The library owns it now.

    //
    // Load .set files to load the castle scene
	//
    pAssetLibrary->SetMediaDirectoryName(_L("..\\..\\Media\\Castle\\"));

#ifdef DEBUG
    mpAssetSetDBR[0] = pAssetLibrary->GetAssetSet(_L("castleLargeOccluders"));
	ASSERT(mpAssetSetDBR[0], _L("Failed loading castle."));

	mpAssetSetDBR[1] = pAssetLibrary->GetAssetSet(_L("groundDebug"));
	ASSERT(mpAssetSetDBR[1], _L("Failed loading ground."));

	mpAssetSetAABB[0] = pAssetLibrary->GetAssetSet(_L("marketStallsDebug"));
	ASSERT(mpAssetSetAABB, _L("Failed loading marketStalls"));

	mpAssetSetAABB[1] = pAssetLibrary->GetAssetSet(_L("castleSmallDecorationsDebug"));
	ASSERT(mpAssetSetAABB, _L("Failed loading castleSmallDecorations"));
#else
    mpAssetSetDBR[0] = pAssetLibrary->GetAssetSet(_L("castleLargeOccluders"));
	ASSERT(mpAssetSetDBR[0], _L("Failed loading castle."));

	mpAssetSetDBR[1] = pAssetLibrary->GetAssetSet(_L("ground"));
	ASSERT(mpAssetSetDBR[1], _L("Failed loading ground."));

	mpAssetSetAABB[0] = pAssetLibrary->GetAssetSet(_L("marketStalls"));
	ASSERT(mpAssetSetAABB, _L("Failed loading marketStalls"));

	mpAssetSetAABB[1] = pAssetLibrary->GetAssetSet(_L("castleSmallDecorations"));
	ASSERT(mpAssetSetAABB, _L("Failed loading castleSmallDecorations"));
#endif

	mpAssetSetSky = pAssetLibrary->GetAssetSet(_L("sky"));
	ASSERT(mpAssetSetSky, _L("Failed loading sky"));

	// For every occluder model in the sene create a place holder 
	// for the CPU transformed vertices of the model.   
	mpDBR->CreateTransformedModels(mpAssetSetDBR, OCCLUDER_SETS);
	// Get number of occluders in the scene
	mNumOccluders = mpDBR->GetNumOccluders();
	// Get number of occluder triangles in the scene 
	mNumOccluderTris = mpDBR->GetNumTriangles();


	// For every occludee model in the scene create a place holder
	// for the triangles that make up the model axis aligned bounding box
	mpAssetSetAABB[2] = mpAssetSetDBR[0];
	mpAssetSetAABB[3] = mpAssetSetDBR[1];

	mpAABB->CreateTransformedAABBoxes(mpAssetSetAABB, OCCLUDEE_SETS);
	// Get number of occludees in the scene
	mNumOccludees = mpAABB->GetNumOccludees();
	// Get number of occluddee triangles in the scene
	mNumOccludeeTris = mpAABB->GetNumTriangles();
	
	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of Models: \t%d"), mNumOccluders);
	mpNumOccludersText->SetText(string);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of tris: \t\t%d"), mNumOccluderTris);
	mpOccluderTrisText->SetText(string);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of Model: \t%d"), mNumOccludees);
	mpNumOccludeesText->SetText(string);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of tris: \t\t%d"), mNumOccludeeTris);
	mpOccludeeTrisText->SetText(string);

	CPUTCheckboxState state;
	if(mEnableCulling)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else 
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpCullingCheckBox->SetCheckboxState(state);

	if(mEnableFCulling)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else 
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpFCullingCheckBox->SetCheckboxState(state);
	mpDBR->SetEnableFCulling(mEnableFCulling);
	mpAABB->SetEnableFCulling(mEnableFCulling);

	if(mViewDepthBuffer)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else 
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpDBCheckBox->SetCheckboxState(state);

	if(mEnableTasks)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else 
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpTasksCheckBox->SetCheckboxState(state);

	if(mSyncInterval)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpVsyncCheckBox->SetCheckboxState(state);

	if(mPipeline)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpPipelineCheckBox->SetCheckboxState(state);

	// Setting occluder size threshold in DepthBufferRasterizer
	mpDBR->SetOccluderSizeThreshold(mOccluderSizeThreshold);
	// Setting occludee size threshold in AABBoxRasterizer
	mpAABB->SetOccludeeSizeThreshold(mOccludeeSizeThreshold);
	
	//
	// If no cameras were created from the model sets then create a default simple camera
	// and add it to the camera array.
	//
    if( mpAssetSetDBR[0] && mpAssetSetDBR[0]->GetCameraCount() )
    {
        mpCamera = mpAssetSetDBR[0]->GetFirstCamera();
        mpCamera->AddRef(); 
    } else
    {
        mpCamera = new CPUTCamera();
        CPUTAssetLibraryDX11::GetAssetLibrary()->AddCamera( _L("SampleStart Camera"), mpCamera );

        mpCamera->SetPosition( 0.0f, 0.0f, 5.0f );
        // Set the projection matrix for all of the cameras to match our window.
        // TODO: this should really be a viewport matrix.  Otherwise, all cameras will have the same FOV and aspect ratio, etc instead of just viewport dimensions.
        mpCamera->SetAspectRatio(((float)width)/((float)height));
    }
    mpCamera->SetFov(XMConvertToRadians(60.0f)); // TODO: Fix converter's FOV bug (Maya generates cameras for which fbx reports garbage for fov)
    mpCamera->SetFarPlaneDistance(gFarClipDistance);
	mpCamera->SetPosition(27.0f, 2.0f, 47.0f);
	mpCamera->LookAt(41.0f, 8.0f, -50.0f);
    mpCamera->Update();

    // Set up the shadow camera (a camera that sees what the light sees)
    float3 lookAtPoint(0.0f, 0.0f, 0.0f);
    float3 half(1.0f, 1.0f, 1.0f);
    if( mpAssetSetDBR[0] )
    {
        mpAssetSetDBR[0]->GetBoundingBox( &lookAtPoint, &half );
    }
    float length = half.length();

    mpShadowCamera = new CPUTCamera();
    mpShadowCamera->SetFov(XMConvertToRadians(45));
    mpShadowCamera->SetAspectRatio(1.0f);
    float fov = mpShadowCamera->GetFov();
    float tanHalfFov = tanf(fov * 0.5f);
    float cameraDistance = length/tanHalfFov;
    float nearDistance = cameraDistance * 0.1f;
    mpShadowCamera->SetNearPlaneDistance(nearDistance);
    mpShadowCamera->SetFarPlaneDistance(2.0f * cameraDistance);
    CPUTAssetLibraryDX11::GetAssetLibrary()->AddCamera( _L("ShadowCamera"), mpShadowCamera );
    float3 shadowCameraPosition = lookAtPoint - gLightDir * cameraDistance;
    mpShadowCamera->SetPosition( shadowCameraPosition );
    mpShadowCamera->LookAt( lookAtPoint.x, lookAtPoint.y, lookAtPoint.z );
    mpShadowCamera->Update();

    mpCameraController = new CPUTCameraControllerFPS();
    mpCameraController->SetCamera(mpCamera);
    mpCameraController->SetLookSpeed(0.004f);
    mpCameraController->SetMoveSpeed(2.5f);

	gLightDir = float3(-40.48f, -142.493f, -3.348f);
	gLightDir = gLightDir.normalize();

	QueryPerformanceFrequency(&glFrequency); 
}