void tick() { if(!window_) return; sf::Event e; while(window_->GetEvent(e)) { if(e.Type == sf::Event::Closed) { window_.reset(); return; } } try { glClear(GL_COLOR_BUFFER_BIT); window_->Draw(*this); window_->Display(); boost::this_thread::sleep(boost::posix_time::milliseconds(10)); } catch (...) { CASPAR_LOG_CURRENT_EXCEPTION(); CASPAR_LOG(error) << L"Closing diag window due to error during rendering"; window_.reset(); return; } executor_.begin_invoke([this]{tick();}); }
// 描画 void Player::Draw() { static std::unique_ptr<Mesh> arrow(new Mesh(_T("Mesh/Arrow.x"))); static std::unique_ptr<Texture> redTexture(new Texture(_T("Texture/Red.png"))); D3DXVECTOR3 arrowRota = D3DXVECTOR3(0, 0, atan2(vtx::input->mouse->GetX() - app->wnd->GetWidth() * 0.5f, vtx::input->mouse->GetY() - app->wnd->GetHeight() * 0.5f) + D3DXToRadian(-90)); float distance = pow(pow(vtx::input->mouse->GetX() - app->wnd->GetWidth() * 0.5f, 2) + pow(vtx::input->mouse->GetY() - app->wnd->GetHeight() * 0.5f, 2), 0.5) * 0.03f; D3DXVECTOR3 arrowPos = D3DXVECTOR3(cos(arrowRota.z) * distance, sin(arrowRota.z) * distance, 0); arrow->Draw(&(arrowPos + backPos), &arrowRota, &D3DXVECTOR3(1, 1, 1), redTexture->Get()); // 先端と本体の座標の平均の座標に描画 mesh->Draw(&((frontPos + backPos) * 0.5f), &rota, &scale, nullptr); }
//-------------------------------------------------------------------------------------- void DrawFrustum( const BoundingFrustum& frustum, FXMVECTOR color ) { XMFLOAT3 corners[ BoundingFrustum::CORNER_COUNT ]; frustum.GetCorners( corners ); VertexPositionColor verts[24]; verts[0].position = corners[0]; verts[1].position = corners[1]; verts[2].position = corners[1]; verts[3].position = corners[2]; verts[4].position = corners[2]; verts[5].position = corners[3]; verts[6].position = corners[3]; verts[7].position = corners[0]; verts[8].position = corners[0]; verts[9].position = corners[4]; verts[10].position = corners[1]; verts[11].position = corners[5]; verts[12].position = corners[2]; verts[13].position = corners[6]; verts[14].position = corners[3]; verts[15].position = corners[7]; verts[16].position = corners[4]; verts[17].position = corners[5]; verts[18].position = corners[5]; verts[19].position = corners[6]; verts[20].position = corners[6]; verts[21].position = corners[7]; verts[22].position = corners[7]; verts[23].position = corners[4]; for( size_t j = 0; j < _countof(verts); ++j ) { XMStoreFloat4( &verts[j].color, color ); } auto context = DXUTGetD3D11DeviceContext(); g_BatchEffect->Apply( context ); context->IASetInputLayout( g_pBatchInputLayout ); g_Batch->Begin(); g_Batch->Draw( D3D11_PRIMITIVE_TOPOLOGY_LINELIST, verts, _countof( verts ) ); g_Batch->End(); }
/** Render contents of queue. */ void RenderQueue(const CCamera& camera, const std::vector<PLight>& lights) { for (const auto& task : m_renderQueue) { // Set layer render state. SetRenderState(task, camera); // Set common parameters. m_device->SetLights(lights); // Render mesh. m_device->Draw(); } }
// Draw a teapot at the position g_vfMovableObjectPos. void DrawMovableTeapot(ID3D11DeviceContext* pd3dImmediateContext) { // Setup position/normal effect (constant variables) g_pEffectPositionNormal->SetEmissiveColor(Colors::Black); g_pEffectPositionNormal->SetDiffuseColor(0.6f * Colors::Cornsilk); g_pEffectPositionNormal->SetSpecularColor(0.4f * Colors::White); g_pEffectPositionNormal->SetSpecularPower(100); XMMATRIX scale = XMMatrixScaling(0.5f, 0.5f, 0.5f); XMMATRIX trans = XMMatrixTranslation(g_vfMovableObjectPos.x, g_vfMovableObjectPos.y, g_vfMovableObjectPos.z); XMMATRIX rotations = XMMatrixRotationRollPitchYaw(g_vfRotate.x, g_vfRotate.y, g_vfRotate.z); g_pEffectPositionNormal->SetWorld(rotations * scale * trans); // Draw g_pTeapot->Draw(g_pEffectPositionNormal, g_pInputLayoutPositionNormal); }
//-------------------------------------------------------------------------------------- void DrawRing( FXMVECTOR Origin, FXMVECTOR MajorAxis, FXMVECTOR MinorAxis, CXMVECTOR color ) { static const DWORD dwRingSegments = 32; VertexPositionColor verts[ dwRingSegments + 1 ]; FLOAT fAngleDelta = XM_2PI / ( float )dwRingSegments; // Instead of calling cos/sin for each segment we calculate // the sign of the angle delta and then incrementally calculate sin // and cosine from then on. XMVECTOR cosDelta = XMVectorReplicate( cosf( fAngleDelta ) ); XMVECTOR sinDelta = XMVectorReplicate( sinf( fAngleDelta ) ); XMVECTOR incrementalSin = XMVectorZero(); static const XMVECTOR initialCos = { 1.0f, 1.0f, 1.0f, 1.0f }; XMVECTOR incrementalCos = initialCos; for( DWORD i = 0; i < dwRingSegments; i++ ) { XMVECTOR Pos; Pos = XMVectorMultiplyAdd( MajorAxis, incrementalCos, Origin ); Pos = XMVectorMultiplyAdd( MinorAxis, incrementalSin, Pos ); XMStoreFloat3( &verts[i].position, Pos ); XMStoreFloat4( &verts[i].color, color ); // Standard formula to rotate a vector. XMVECTOR newCos = incrementalCos * cosDelta - incrementalSin * sinDelta; XMVECTOR newSin = incrementalCos * sinDelta + incrementalSin * cosDelta; incrementalCos = newCos; incrementalSin = newSin; } verts[ dwRingSegments ] = verts[0]; // Draw ring auto context = DXUTGetD3D11DeviceContext(); g_BatchEffect->Apply( context ); context->IASetInputLayout( g_pBatchInputLayout ); g_Batch->Begin(); g_Batch->Draw( D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP, verts, dwRingSegments+1 ); g_Batch->End(); }
//-------------------------------------------------------------------------------------- void DrawRay( FXMVECTOR Origin, FXMVECTOR Direction, bool bNormalize, FXMVECTOR color ) { VertexPositionColor verts[3]; XMStoreFloat3( &verts[0].position, Origin ); XMVECTOR NormDirection = XMVector3Normalize( Direction ); XMVECTOR RayDirection = ( bNormalize ) ? NormDirection : Direction; XMVECTOR PerpVector = XMVector3Cross( NormDirection, g_XMIdentityR1 ); if( XMVector3Equal( XMVector3LengthSq( PerpVector ), g_XMZero ) ) { PerpVector = XMVector3Cross( NormDirection, g_XMIdentityR2 ); } PerpVector = XMVector3Normalize( PerpVector ); XMStoreFloat3( &verts[1].position, XMVectorAdd( RayDirection, Origin ) ); PerpVector = XMVectorScale( PerpVector, 0.0625f ); NormDirection = XMVectorScale( NormDirection, -0.25f ); RayDirection = XMVectorAdd( PerpVector, RayDirection ); RayDirection = XMVectorAdd( NormDirection, RayDirection ); XMStoreFloat3( &verts[2].position, XMVectorAdd( RayDirection, Origin ) ); XMStoreFloat4( &verts[0].color, color ); XMStoreFloat4( &verts[1].color, color ); XMStoreFloat4( &verts[2].color, color ); auto context = DXUTGetD3D11DeviceContext(); g_BatchEffect->Apply( context ); context->IASetInputLayout( g_pBatchInputLayout ); g_Batch->Begin(); g_Batch->Draw( D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP, verts, 2 ); g_Batch->End(); }
// Draw several objects randomly positioned in [-0.5f;0.5]³ using DirectXTK geometric primitives. void DrawSomeRandomObjects(ID3D11DeviceContext* pd3dImmediateContext) { // Setup position/normal effect (constant variables) g_pEffectPositionNormal->SetEmissiveColor(Colors::Black); g_pEffectPositionNormal->SetSpecularColor(0.4f * Colors::White); g_pEffectPositionNormal->SetSpecularPower(100); std::mt19937 eng; std::uniform_real_distribution<float> randCol( 0.0f, 1.0f); std::uniform_real_distribution<float> randPos(-0.5f, 0.5f); for (int i=0; i<g_iNumSpheres; i++) { // Setup position/normal effect (per object variables) g_pEffectPositionNormal->SetDiffuseColor(0.6f * XMColorHSVToRGB(XMVectorSet(randCol(eng), 1, 1, 0))); XMMATRIX scale = XMMatrixScaling(g_fSphereSize, g_fSphereSize, g_fSphereSize); XMMATRIX trans = XMMatrixTranslation(randPos(eng),randPos(eng),randPos(eng)); g_pEffectPositionNormal->SetWorld(scale * trans * g_camera.GetWorldMatrix()); // Draw // NOTE: The following generates one draw call per object, so performance will be bad for n>>1000 or so g_pSphere->Draw(g_pEffectPositionNormal, g_pInputLayoutPositionNormal); } }
//-------------------------------------------------------------------------------------- void DrawTriangle( FXMVECTOR PointA, FXMVECTOR PointB, FXMVECTOR PointC, CXMVECTOR color ) { VertexPositionColor verts[4]; XMStoreFloat3( &verts[0].position, PointA ); XMStoreFloat3( &verts[1].position, PointB ); XMStoreFloat3( &verts[2].position, PointC ); XMStoreFloat3( &verts[3].position, PointA ); XMStoreFloat4( &verts[0].color, color ); XMStoreFloat4( &verts[1].color, color ); XMStoreFloat4( &verts[2].color, color ); XMStoreFloat4( &verts[3].color, color ); auto context = DXUTGetD3D11DeviceContext(); g_BatchEffect->Apply( context ); context->IASetInputLayout( g_pBatchInputLayout ); g_Batch->Begin(); g_Batch->Draw( D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP, verts, 4 ); g_Batch->End(); }
void write_plot( const std::unique_ptr<TH1D>& HISTO, const std::unique_ptr<TH1D>& HISTO_MC, const std::string OUTPUT_NAME, const int REBIN = 10, const std::string AXIS_TITLE = "", const double MED_CUT = -100, const double TIGHT_CUT = -100, const double START_X = -1, const double END_X = -1 ) { // Make a canvas to control writing of the pdf file TCanvas canvas("canvas", "canvas", 500, 500); canvas.cd(); if (AXIS_TITLE != "") { HISTO->GetXaxis()->SetTitle(AXIS_TITLE.c_str()); } HISTO->GetYaxis()->SetTitle("Normalized Counts"); const double MARKER_SIZE = 1.; const double DATA_AREA = HISTO->Integral(0, HISTO->GetNbinsX()-1); HISTO->Scale(1. / DATA_AREA); const double MC_AREA = HISTO_MC->Integral(0, HISTO_MC->GetNbinsX()-1); HISTO_MC->Scale(1. / MC_AREA); //HISTO->GetYaxis()->SetNdivisions(7, 5, 0); // Set 10 major ticks, 0 minor //HISTO->GetXaxis()->SetNdivisions(7, 5, 0); // Set 10 major ticks, 0 minor HISTO->GetYaxis()->SetTickLength(0.02); // Make the ticks smaller HISTO->GetXaxis()->SetTickLength(0.02); HISTO->GetYaxis()->SetTitleOffset(1.8); const int FORWARD_HATCH = 3004; const int BACKWARD_HATCH = 3005; HISTO->SetMarkerColor(kBlue); HISTO->SetLineColor(kBlue); HISTO->SetLineWidth(2); HISTO->SetFillColor(kBlue); HISTO->SetFillStyle(FORWARD_HATCH); HISTO->SetMarkerStyle(kFullTriangleDown); HISTO->SetMarkerSize(MARKER_SIZE); HISTO->Rebin(REBIN); HISTO_MC->SetMarkerColor(kRed); HISTO_MC->SetLineColor(kRed); HISTO_MC->SetLineWidth(2); HISTO_MC->SetFillColor(kRed); HISTO_MC->SetFillStyle(BACKWARD_HATCH); HISTO_MC->SetMarkerStyle(kFullTriangleUp); HISTO_MC->SetMarkerSize(MARKER_SIZE); HISTO_MC->Rebin(REBIN); // Set the Y max const double Y_MAX = std::max(HISTO->GetMaximum(), HISTO_MC->GetMaximum()) * 1.2; HISTO->SetMaximum(Y_MAX); //HISTO->SetMinimum(0.001); //canvas.SetLogy(); // Set the X Axis range if (START_X != -1 && END_X != -1) { HISTO->GetXaxis()->SetRangeUser(START_X, END_X); } // Cut Line TLine* cut_line_0p = nullptr; TLine* cut_line_0m = nullptr; if (MED_CUT != -100) { const double X1 = MED_CUT; const double X2 = X1; const double Y1 = 0; const double Y2 = Y_MAX; cut_line_0p = new TLine(X1, Y1, X2, Y2); cut_line_0p->SetLineStyle(kDotted); cut_line_0p->SetLineWidth(3); cut_line_0m = new TLine(-X1, Y1, -X2, Y2); cut_line_0m->SetLineStyle(kDotted); cut_line_0m->SetLineWidth(3); } TLine* cut_line_1p = nullptr; TLine* cut_line_1m = nullptr; if (TIGHT_CUT != -100) { const double X1 = TIGHT_CUT; const double X2 = X1; const double Y1 = 0; const double Y2 = Y_MAX; cut_line_1p = new TLine(X1, Y1, X2, Y2); cut_line_1p->SetLineStyle(kDashed); cut_line_1p->SetLineWidth(2); cut_line_1m = new TLine(-X1, Y1, -X2, Y2); cut_line_1m->SetLineStyle(kDashed); cut_line_1m->SetLineWidth(2); } // Add CMS text inside the plot on the top left const std::string CMS_STRING = "CMS Preliminary"; const double TOP_EDGE = 0.95; const double LEFT_EDGE = 0.12; TLatex* cms_latex = new TLatex(LEFT_EDGE + 0.0, TOP_EDGE + 0.01, CMS_STRING.c_str()); cms_latex->SetNDC(kTRUE); // Use pad coordinates, not Axis cms_latex->SetTextSize(0.035); // Add luminosity text outside the plot on the top right const std::string LUMI_STRING = "19.7 fb^{-1} (8 TeV)"; const double RIGHT_EDGE = 0.90; TLatex* lumi_latex = new TLatex(RIGHT_EDGE - 0.165, TOP_EDGE + 0.01, LUMI_STRING.c_str()); lumi_latex->SetNDC(kTRUE); // Use pad coordinates, not Axis lumi_latex->SetTextSize(0.035); // Set up the legend using the plot edges to set its location const double LEG_HEIGHT = 0.15; const double LEG_LENGTH = 0.40; TLegend legend( RIGHT_EDGE + 0.06 - LEG_LENGTH, TOP_EDGE - LEG_HEIGHT, // 0.025 offset to avoid ticks RIGHT_EDGE + 0.06, TOP_EDGE // 0.025 offset to avoid the ticks ); legend.SetFillColor(kWhite); legend.AddEntry(HISTO.get(), "Minimum-bias Electrons", "f"); legend.AddEntry(HISTO_MC.get(), "Signal MC", "f"); legend.SetBorderSize(1); // Remove drop shadow and border //legend.SetFillStyle(0); // Transparent HISTO->Draw("HIST"); HISTO_MC->Draw("HIST SAME"); HISTO->Draw("HIST SAME"); if (cut_line_0p != nullptr) { legend.AddEntry(cut_line_0p, "Medium Requirement", "l"); cut_line_0p->Draw("SAME"); cut_line_0m->Draw("SAME"); } if (cut_line_1p != nullptr) { // If no other cut, both are at the same place if (MED_CUT == -100) { legend.AddEntry(cut_line_1p, "Selection Requirement", "l"); } else { legend.AddEntry(cut_line_1p, "Tight Requirement", "l"); } cut_line_1p->Draw("SAME"); cut_line_1m->Draw("SAME"); } cms_latex->Draw(); lumi_latex->Draw(); canvas.cd(); redraw_border(); legend.Draw(); const std::string FINAL_NAME = "e_reco_var_" + OUTPUT_NAME; canvas.Print(FINAL_NAME.c_str(), "pdf"); // Clean up if (cut_line_0p != nullptr) { delete cut_line_0p; delete cut_line_0m; } if (cut_line_1p != nullptr) { delete cut_line_1p; delete cut_line_1m; } }
//-------------------------------------------------------------------------------------- // Render a frame //-------------------------------------------------------------------------------------- void Render() { // Update our time static float t = 0.0f; static float dt = 0.f; if( g_driverType == D3D_DRIVER_TYPE_REFERENCE ) { t += ( float )XM_PI * 0.0125f; } else { static uint64_t dwTimeStart = 0; static uint64_t dwTimeLast = 0; uint64_t dwTimeCur = GetTickCount64(); if( dwTimeStart == 0 ) dwTimeStart = dwTimeCur; t = ( dwTimeCur - dwTimeStart ) / 1000.0f; dt = ( dwTimeCur - dwTimeLast ) / 1000.0f; dwTimeLast = dwTimeCur; } // Rotate cube around the origin g_World = XMMatrixRotationY( t ); #ifdef DXTK_AUDIO g_audioTimerAcc -= dt; if ( g_audioTimerAcc < 0 ) { g_audioTimerAcc = 4.f; g_waveBank->Play( g_audioEvent++ ); if ( g_audioEvent >= 11 ) g_audioEvent = 0; } if ( !g_audEngine->Update() ) { // Error cases are handled by the message loop } #endif // DXTK_AUDIO // // Clear the back buffer // g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, Colors::MidnightBlue ); // // Clear the depth buffer to 1.0 (max depth) // g_pImmediateContext->ClearDepthStencilView( g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 ); // Draw procedurally generated dynamic grid //const XMVECTORF32 xaxis = { 20.f, 0.f, 0.f }; //const XMVECTORF32 yaxis = { 0.f, 0.f, 20.f }; //DrawGrid( *g_Batch, xaxis, yaxis, g_XMZero, 20, 20, Colors::Gray ); // Draw 3D object XMMATRIX localForShape1 = XMMatrixMultiply(g_World, XMMatrixTranslation(2.f, 0.f, 0.f)); g_Shape->Draw(localForShape1, g_View, g_Projection, Colors::White, g_pTextureRV1); localForShape1 = XMMatrixMultiply(g_World, XMMatrixTranslation(-2.f, 0.f, 0.f)); g_Shape2->Draw(localForShape1, g_View, g_Projection, Colors::White, g_pTextureRV2); XMVECTOR qid = XMQuaternionIdentity(); const XMVECTORF32 scale = { 0.20f, 0.20f, 0.20f }; const XMVECTORF32 translate = { 0.f, -6.f, 30.f }; XMVECTOR rotate = XMQuaternionRotationRollPitchYaw(0, XM_PI / 2.f, 0); localForShape1 = XMMatrixMultiply(g_World, XMMatrixTransformation(g_XMZero, qid, scale, g_XMZero, rotate, translate)); g_Model->Draw(g_pImmediateContext, *g_States, localForShape1, g_View, g_Projection); // Present our back buffer to our front buffer g_pSwapChain->Present( 0, 0 ); }
void CALLBACK OnD3D11FrameRender(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext) { pd3dImmediateContext->ClearRenderTargetView(DXUTGetD3D11RenderTargetView(), Colors::Black); pd3dImmediateContext->ClearDepthStencilView(DXUTGetD3D11DepthStencilView(), D3D11_CLEAR_DEPTH, 1.0, 0); XMMATRIX mworld = g_camera.GetWorldMatrix(); XMMATRIX mview = g_camera.GetViewMatrix(); XMMATRIX mproj = g_camera.GetProjMatrix(); g_BatchEffect->SetView(mview); g_BatchEffect->SetProjection(mproj); // Draw Grids const XMVECTORF32 xaxis = { 50.f, 0.f, 0.f }; const XMVECTORF32 yaxis = { 0.f, 0.f, 50.f }; DrawGrid(xaxis, yaxis, g_XMZero, 50, 50, Colors::Azure); // Draw Font g_dwtext->Render(L"га╥╧юс = ", DXUTGetFPS(), 10, 10); XMVECTOR worldPos; XMVECTOR worldDir; //g_input->getMousePosWorld(worldPos, worldDir, mview, mproj, TRUE); g_input->Pick(worldPos, worldDir, mworld, mview, mproj); /* POSITION */ WCHAR strformat[256] = {}; XMFLOAT3 pos; XMStoreFloat3(&pos, worldPos); swprintf(strformat, L"pos = %f , %f , %f", pos.x, pos.y, pos.z); g_dwtext->Render(strformat, 0, 10, 30); /* DIRECTION */ XMFLOAT3 dir; XMStoreFloat3(&dir, worldDir); swprintf(strformat, L"dir = %f , %f , %f", dir.x, dir.y, dir.z); g_dwtext->Render(strformat, 0, 10, 50); /* CURSOR POSITION */ POINT pt = g_input->getMousePos(); swprintf(strformat, L"cursor = %d , %d", pt.x, pt.y ); g_dwtext->Render(strformat, 0, 10, 70); XMVECTOR eye = g_camera.GetEyePt(); XMFLOAT3 feye; XMStoreFloat3(&feye, eye); swprintf(strformat, L"eye = %f , %f , %f", feye.x, feye.y, feye.z); g_dwtext->Render(strformat, 0, 10, 90); XMVECTOR lookat = g_camera.GetLookAtPt(); XMFLOAT3 flookat; XMStoreFloat3(&flookat, lookat); swprintf(strformat, L"lookat = %f , %f , %f", flookat.x, flookat.y, flookat.z); g_dwtext->Render(strformat, 0, 10, 110); XMVECTOR axis1 = XMVectorSet( pos.x, pos.y, pos.z, 0.0f); XMVECTOR axis2 = XMVectorSet(dir.x, dir.y, dir.z, 0.0f); DrawCenterGrid(axis1, axis2); XMMATRIX wpos = XMMatrixTranslation(pos.x, pos.y, pos.z); g_ShapePos->Draw(wpos, mview, mproj, Colors::LawnGreen); XMMATRIX wdir = XMMatrixTranslation(dir.x, dir.y, dir.z); g_ShapeDir->Draw(wdir, mview, mproj, Colors::OrangeRed); }
int main(int argc, char* argv[]) { std::cout << "VoxelAO by Kevin Ortegren, 2015" << std::endl; bool running = true; //Setup SDL window SDL_SysWMinfo info; HWND handle; if (SDL_Init(SDL_INIT_TIMER) != 0) { std::cerr << "SDL_Init failed: " << SDL_GetError() << std::endl; } window = SDL_CreateWindow("VoxelAO", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE ); //Must init info struct with SDL version info, see documentation for explanation SDL_VERSION(&info.version); //If succeeded, init d3d11 and other things if (SDL_GetWindowWMInfo(window, &info)) { handle = info.info.win.window; } else { std::cerr << "Failed to get WMInfo: " << SDL_GetError() << std::endl; running = false; } InitD3D(handle); SetupAntTweakBar(); timer = new D3D11Timer(device, context); { ID3DBlob* vsblob,* psblob, *gsblob; ID3DBlob* errblob = nullptr; UINT flags = 0; #ifndef _DEBUG // IF NOT DEBUG flags |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif //Create shaders CHECKDX(D3DCompileFromFile(L"../../Assets/Shaders/simple.vertex", nullptr, nullptr, "main", "vs_5_0", flags, 0, &vsblob, nullptr)); CHECKDX(D3DCompileFromFile(L"../../Assets/Shaders/simple.pixel", nullptr, nullptr, "main", "ps_5_0", flags, 0, &psblob, nullptr)); CHECKDX(device->CreateVertexShader(vsblob->GetBufferPointer(), vsblob->GetBufferSize(), nullptr, &VS)); CHECKDX(device->CreatePixelShader(psblob->GetBufferPointer(), psblob->GetBufferSize(), nullptr, &PS)); D3D11_INPUT_ELEMENT_DESC ied[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; CHECKDX(device->CreateInputLayout(ied, 3, vsblob->GetBufferPointer(), vsblob->GetBufferSize(), &layout)); //Full screen quad shader CHECKDX(D3DCompileFromFile(L"../../Assets/Shaders/fsq.vertex", nullptr, nullptr, "main", "vs_5_0", flags, 0, &vsblob, nullptr)); CHECKDX(D3DCompileFromFile(L"../../Assets/Shaders/fsq.pixel", nullptr, nullptr, "main", "ps_5_0", flags, 0, &psblob, &errblob)); CHECKDX(device->CreateVertexShader(vsblob->GetBufferPointer(), vsblob->GetBufferSize(), nullptr, &fsqVS)); CHECKDX(device->CreatePixelShader(psblob->GetBufferPointer(), psblob->GetBufferSize(), nullptr, &fsqPS)); CHECKDX(D3DCompileFromFile(L"../../Assets/Shaders/fsq_only_AO.pixel", nullptr, nullptr, "main", "ps_5_0", flags, 0, &psblob, &errblob)); CHECKDX(device->CreatePixelShader(psblob->GetBufferPointer(), psblob->GetBufferSize(), nullptr, &fsqOcclusionPS)); CHECKDX(D3DCompileFromFile(L"../../Assets/Shaders/fsq_no_AO.pixel", nullptr, nullptr, "main", "ps_5_0", flags, 0, &psblob, &errblob)); CHECKDX(device->CreatePixelShader(psblob->GetBufferPointer(), psblob->GetBufferSize(), nullptr, &fsqNOOcclusionPS)); D3D11_INPUT_ELEMENT_DESC iedfsq[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; CHECKDX(device->CreateInputLayout(iedfsq, 1, vsblob->GetBufferPointer(), vsblob->GetBufferSize(), &fsqlayout)); //Create voxelizer shaders CHECKDX(D3DCompileFromFile(L"../../Assets/Shaders/voxelizing.vertex", nullptr, nullptr, "main", "vs_5_0", flags, 0, &vsblob, &errblob)); CHECKDX(D3DCompileFromFile(L"../../Assets/Shaders/voxelizing.geometry", nullptr, nullptr, "main", "gs_5_0", flags, 0, &gsblob, &errblob)); CHECKDX(D3DCompileFromFile(L"../../Assets/Shaders/voxelizing.pixel", nullptr, nullptr, "main", "ps_5_0", flags, 0, &psblob, &errblob)); CHECKDX(device->CreateVertexShader(vsblob->GetBufferPointer(), vsblob->GetBufferSize(), nullptr, &voxelVS)); CHECKDX(device->CreateGeometryShader(gsblob->GetBufferPointer(), gsblob->GetBufferSize(), nullptr, &voxelGS)); CHECKDX(device->CreatePixelShader(psblob->GetBufferPointer(), psblob->GetBufferSize(), nullptr, &voxelPS)); D3D11_INPUT_ELEMENT_DESC iedvox[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; CHECKDX(device->CreateInputLayout(ied, 3, vsblob->GetBufferPointer(), vsblob->GetBufferSize(), &voxelLayout)); vsblob->Release(); gsblob->Release(); psblob->Release(); } { OBJLoader objLoader; mesh = objLoader.LoadBIN("../../Assets/Models/sponza.bin"); } //Camera camera.SetLens((float)M_PI_4, NEARZ, FARZ, WINDOW_WIDTH, WINDOW_HEIGHT); { //Init primitive spritebatch from DirectXTK primitiveBatch = new DirectX::PrimitiveBatch<DirectX::VertexPositionColor>(context, 65536, (size_t)(65536/3)); basicEffect = new DirectX::BasicEffect(device); basicEffect->SetProjection(XMLoadFloat4x4(&camera.GetCamData().projMat)); basicEffect->SetVertexColorEnabled(true); void const* shaderByteCode; size_t byteCodeLength; basicEffect->GetVertexShaderBytecode(&shaderByteCode, &byteCodeLength); CHECKDX(device->CreateInputLayout(DirectX::VertexPositionColor::InputElements, DirectX::VertexPositionColor::InputElementCount, shaderByteCode, byteCodeLength, &basicInputLayout)); D3D11_BUFFER_DESC cbDesc; cbDesc.ByteWidth = sizeof(CameraData); cbDesc.Usage = D3D11_USAGE_DYNAMIC; cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; cbDesc.StructureByteStride = 0; CHECKDX(device->CreateBuffer(&cbDesc, nullptr, &camConstBuffer)); D3D11_BUFFER_DESC cbkernelDesc; cbkernelDesc.ByteWidth = sizeof(SampleKernelOptions); cbkernelDesc.Usage = D3D11_USAGE_DYNAMIC; cbkernelDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbkernelDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; cbkernelDesc.MiscFlags = 0; cbkernelDesc.StructureByteStride = 0; CHECKDX(device->CreateBuffer(&cbkernelDesc, nullptr, &sampleConstBuffer)); D3D11_BUFFER_DESC cbvoxelDesc; cbvoxelDesc.ByteWidth = sizeof(VoxelOptions); cbvoxelDesc.Usage = D3D11_USAGE_DYNAMIC; cbvoxelDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbvoxelDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; cbvoxelDesc.MiscFlags = 0; cbvoxelDesc.StructureByteStride = 0; CHECKDX(device->CreateBuffer(&cbvoxelDesc, nullptr, &voxelOptionConstBuffer)); //Set up sampler state D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; CHECKDX(device->CreateSamplerState(&samplerDesc, &linearSamplerState)); //Rasterizer state D3D11_RASTERIZER_DESC RSdesc; ZeroMemory(&RSdesc, sizeof(RSdesc)); RSdesc.FillMode = D3D11_FILL_SOLID; RSdesc.CullMode = D3D11_CULL_NONE; RSdesc.DepthClipEnable = TRUE; CHECKDX(device->CreateRasterizerState(&RSdesc, &RSStateSolid)); RSdesc.FillMode = D3D11_FILL_WIREFRAME; CHECKDX(device->CreateRasterizerState(&RSdesc, &RSStateWireframe)); } //Init voxel structure and GPU resources { voxelMatrix = Matrix::CreateOrthographic(VOXEL_STRUCTURE_WIDTH, VOXEL_STRUCTURE_WIDTH, 0.0f, VOXEL_STRUCTURE_WIDTH); voxelViewProjMatrix[0] = Matrix::CreateLookAt(Vector3(-VOXEL_STRUCTURE_WIDTH/2, 0, 0), Vector3(0, 0, 0), Vector3(0, 1, 0)) * voxelMatrix; voxelViewProjMatrix[1] = Matrix::CreateLookAt(Vector3(0, -VOXEL_STRUCTURE_WIDTH / 2, 0), Vector3(0, 0, 0), Vector3(1, 0, 0)) * voxelMatrix; voxelViewProjMatrix[2] = Matrix::CreateLookAt(Vector3(0, 0, -VOXEL_STRUCTURE_WIDTH / 2), Vector3(0, 0, 0), Vector3(0, 1, 0)) * voxelMatrix; D3D11_BUFFER_DESC voxmatbuffdesc; voxmatbuffdesc.ByteWidth = 3 * sizeof(Matrix); voxmatbuffdesc.Usage = D3D11_USAGE_IMMUTABLE; voxmatbuffdesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; voxmatbuffdesc.CPUAccessFlags = 0; voxmatbuffdesc.MiscFlags = 0; voxmatbuffdesc.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA voxmatdata; voxmatdata.pSysMem = &voxelViewProjMatrix[0]; voxmatdata.SysMemPitch = 3 * sizeof(Matrix); voxmatdata.SysMemSlicePitch = 0; CHECKDX(device->CreateBuffer(&voxmatbuffdesc, &voxmatdata, &voxelMatBuffer)); // CreateVoxelBuffers(); D3D11_BLEND_DESC blendDesc = { 0 }; CHECKDX(device->CreateBlendState(&blendDesc, &voxelBlendState)); } RebuildKernel(); //RenderTarget clear color float clearColor[] = { 1.0f, 1.0f, 0.0f, 1.0f }; //Timer uint32 oldTime, currentTime; float dt; uint32 frames = 0; float collectedTime = 0.0f; float collectedAOTime = 0.0f; float collectedVoxelTime = 0.0f; currentTime = SDL_GetTicks(); while (running) { oldTime = currentTime; currentTime = SDL_GetTicks(); dt = (currentTime - oldTime) / 1000.0f; collectedTime += dt; ++frames; if (collectedTime >= 1.0f) { collectedTime -= 1.0f; FPS = frames; AOTime = collectedAOTime / (float)frames; voxelTime = collectedVoxelTime / (float)frames; collectedAOTime = 0.0f; collectedVoxelTime = 0.0f; frames = 0; } running = HandleEvents(); const Uint8* keystate = SDL_GetKeyboardState(NULL); //Check keys and move camera if (keystate[SDL_SCANCODE_A]) camera.StrafeLeft(dt); if (keystate[SDL_SCANCODE_D]) camera.StrafeRight(dt); if (keystate[SDL_SCANCODE_W]) camera.MoveForward(dt); if (keystate[SDL_SCANCODE_S]) camera.MoveBackward(dt); if (keystate[SDL_SCANCODE_LSHIFT]) camera.MoveDown(dt); if (keystate[SDL_SCANCODE_SPACE]) camera.MoveUp(dt); camera.Update(); D3D11_MAPPED_SUBRESOURCE camResource; CHECKDX(context->Map(camConstBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &camResource)); memcpy(camResource.pData, &camera.GetCamData(), sizeof(CameraData)); context->Unmap(camConstBuffer, 0); if (sampleOptions.sizeX != prevSampleOptions.sizeX || sampleOptions.sizeY != prevSampleOptions.sizeY) { prevSampleOptions.sizeX = sampleOptions.sizeX; prevSampleOptions.sizeY = sampleOptions.sizeY; RebuildKernel(); } D3D11_MAPPED_SUBRESOURCE kernelResource; CHECKDX(context->Map(sampleConstBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &kernelResource)); memcpy(kernelResource.pData, &sampleOptions, sizeof(SampleKernelOptions)); context->Unmap(sampleConstBuffer, 0); if (voxelRes != prevVoxelRes) { prevVoxelRes = voxelRes; switch (voxelRes) { case _64: numVoxels = 64; break; case _128: numVoxels = 128; break; case _256: numVoxels = 256; break; case _512: numVoxels = 512; break; case _1024: numVoxels = 1024; break; default: break; } voxelOptions.count = numVoxels; voxelOptions.width = VOXEL_STRUCTURE_WIDTH / (float)numVoxels; voxelElementCount = numVoxels * numVoxels * (numVoxels / 32); #ifdef ENABLE_VOXELDRAW delete[] voxelCPUstructure; voxelCPUstructure = new uint32[voxelElementCount]; #endif CreateVoxelBuffers(); D3D11_MAPPED_SUBRESOURCE voxelResource; CHECKDX(context->Map(voxelOptionConstBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &voxelResource)); memcpy(voxelResource.pData, &voxelOptions, sizeof(VoxelOptions)); context->Unmap(voxelOptionConstBuffer, 0); } /////////////////////// //Voxelize step /////////////////////// ID3D11RenderTargetView* RT = voxelVoidRT.GetRenderTargetView(); context->OMSetRenderTargetsAndUnorderedAccessViews(1, &RT, 0, 1, 1, &voxelUAV, nullptr); context->OMSetBlendState(voxelBlendState, nullptr, 0xffffffff); context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); //Copy a null buffer to clear voxel structure. Needs to be done if having dynamic geometry //context->CopyResource(voxelStructure, voxelClearBuffer); D3D11_VIEWPORT voxviewPort; ZeroMemory(&voxviewPort, sizeof(D3D11_VIEWPORT)); voxviewPort.TopLeftX = 0; voxviewPort.TopLeftY = 0; voxviewPort.MinDepth = 0.0f; voxviewPort.MaxDepth = 1.0f; voxviewPort.Width = (float)numVoxels; voxviewPort.Height = (float)numVoxels; context->RSSetViewports(1, &voxviewPort); context->VSSetShader(voxelVS, 0, 0); context->GSSetShader(voxelGS, 0, 0); context->PSSetShader(voxelPS, 0, 0); context->PSSetConstantBuffers(1, 1, &voxelOptionConstBuffer); context->IASetInputLayout(voxelLayout); context->GSSetConstantBuffers(0, 1, &voxelMatBuffer); context->GSSetConstantBuffers(1, 1, &voxelOptionConstBuffer); context->RSSetState(RSStateSolid); timer->Start(); mesh->Apply(); mesh->Draw(); timer->Stop(); collectedVoxelTime += (float)timer->GetTime(); #ifdef ENABLE_VOXELDRAW if (enableDebugDraw) { context->CopyResource(voxelStagingStructure, voxelStructure); D3D11_MAPPED_SUBRESOURCE mapData; if (context->Map(voxelStagingStructure, 0, D3D11_MAP_READ, 0, &mapData) == S_OK) { memcpy(voxelCPUstructure, mapData.pData, voxelElementCount * sizeof(uint32)); context->Unmap(voxelStagingStructure, 0); } } #endif ///////////////////////////// //G-buffer pass ///////////////////////////// //Clear RTs before drawing colorRT.Clear(); normalRT.Clear(); positionRT.Clear(); context->ClearRenderTargetView(backBuffer, clearColor); context->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); //Set Gbuffer RTs ID3D11RenderTargetView* RTs[] = { colorRT.GetRenderTargetView(), normalRT.GetRenderTargetView(), positionRT.GetRenderTargetView() }; ID3D11RenderTargetView* RTzero[] = { 0, 0, 0 }; context->OMSetRenderTargets(3, RTs, depthStencilView); context->OMSetBlendState(nullptr, nullptr, 0xffffffff); //Set shaders D3D11_VIEWPORT viewPort; ZeroMemory(&viewPort, sizeof(D3D11_VIEWPORT)); viewPort.TopLeftX = 0; viewPort.TopLeftY = 0; viewPort.MinDepth = 0.0f; viewPort.MaxDepth = 1.0f; viewPort.Width = WINDOW_WIDTH; viewPort.Height = WINDOW_HEIGHT; context->RSSetViewports(1, &viewPort); context->VSSetShader(VS, 0, 0); context->GSSetShader(nullptr, 0, 0); context->PSSetShader(PS, 0, 0); context->IASetInputLayout(layout); context->PSSetSamplers(0, 1, &linearSamplerState); context->VSSetConstantBuffers(0, 1, &camConstBuffer); context->RSSetState(RSStateSolid); //Draw geometry mesh->Apply(); mesh->DrawIndexed(); context->OMSetRenderTargets(3, RTzero, 0); ///////////////////////////// //Draw to backbuffer, AO pass ///////////////////////////// context->OMSetRenderTargets(1, &backBuffer, 0); context->VSSetShader(fsqVS, 0, 0); switch (drawMode) { case DRAW_NORMAL: context->PSSetShader(fsqPS, 0, 0); break; case DRAW_NO_AO: context->PSSetShader(fsqNOOcclusionPS, 0, 0); break; case DRAW_AO_ONLY: context->PSSetShader(fsqOcclusionPS, 0, 0); break; default: break; } context->IASetInputLayout(fsqlayout); colorRT.PSSetSRV(0); normalRT.PSSetSRV(1); positionRT.PSSetSRV(2); context->PSSetShaderResources(3, 1, &depthBufferView); context->PSSetShaderResources(4, 1, &voxelSRV); context->PSSetConstantBuffers(0, 1, &voxelSampleKernel); context->PSSetConstantBuffers(1, 1, &sampleConstBuffer); context->PSSetConstantBuffers(2, 1, &voxelOptionConstBuffer); context->RSSetState(RSStateSolid); timer->Start(); context->DrawInstanced(3, 1, 0, 0); timer->Stop(); collectedAOTime += (float)timer->GetTime(); //Unbind depth from input ID3D11ShaderResourceView* SRVzero[] = { 0 }; context->PSSetShaderResources(3, 1, SRVzero); //Set up some things for DXTK, to draw some lines or other primitives context->OMSetRenderTargets(1, &backBuffer, depthStencilView); basicEffect->SetView(XMLoadFloat4x4(&camera.GetCamData().viewMat)); basicEffect->Apply(context); context->IASetInputLayout(basicInputLayout); voxelCounter = 0; if(enableDebugDraw) DrawVoxels(primitiveBatch); if(enableDrawKernel) DrawKernel(primitiveBatch); TwRefreshBar(antbar); TwDraw(); swapChain->Present(0, 0); //Unbind all resources context->PSSetShaderResources(0, 1, SRVzero); context->PSSetShaderResources(1, 1, SRVzero); context->PSSetShaderResources(2, 1, SRVzero); context->PSSetShaderResources(3, 1, SRVzero); context->PSSetShaderResources(4, 1, SRVzero); } std::cout << "Exiting program!" << std::endl; //Cleanup delete primitiveBatch; delete basicEffect; delete timer; #ifdef ENABLE_VOXELDRAW delete[] voxelCPUstructure; #endif depthStencilView->Release(); RSStateSolid->Release(); RSStateWireframe->Release(); voxelBlendState->Release(); voxelStagingStructure->Release(); voxelSampleKernel->Release(); voxelClearBuffer->Release(); voxelSRV->Release(); fsqVS->Release(); fsqPS->Release(); fsqOcclusionPS->Release(); fsqNOOcclusionPS->Release(); camConstBuffer->Release(); sampleConstBuffer->Release(); voxelOptionConstBuffer->Release(); depthBufferView->Release(); layout->Release(); fsqlayout->Release(); voxelLayout->Release(); linearSamplerState->Release(); VS->Release(); PS->Release(); voxelVS->Release(); voxelGS->Release(); voxelPS->Release(); voxelStructure->Release(); voxelUAV->Release(); voxelMatBuffer->Release(); swapChain->Release(); backBuffer->Release(); device->Release(); context->Release(); basicInputLayout->Release(); SDL_DestroyWindow(window); return 0; }
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: разместите код здесь. MSG msg; HACCEL hAccelTable; // »нициализаци¤ глобальных строк LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_WIN32PROJECT3, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // ¬ыполнить инициализацию приложени¤: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32PROJECT3)); try { // create gl.reset(new shell::Ogl()); game.reset(new mech::Game()); // init gl->Bind(hWnd); menu = game->GetInterface(); // timer & rng Timer timer; std::srand((unsigned int)timer.GetCounter()); timer.Start(); // main & message loop: auto last_turn = game->GetTurn(); bool run = true; while (!game->IsFinished() && run) { auto current_turn = game->GetTurn(); if (last_turn != current_turn) { timer.Start(); last_turn = current_turn; } gl->Draw(*game, timer.GetCounter()); // windows dispatcher while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) != 0) { run &= (GetMessage(&msg, NULL, 0, 0) == TRUE); if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } } } catch (std::runtime_error &exc) { wchar_t message[1025]; MultiByteToWideChar(CP_ACP, 0, exc.what(), -1, message, 1024); MessageBox(NULL, message, NULL, NULL); } return (int) msg.wParam; }