//---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void MainLoop() { for(;;) { MSG msg; if (PeekMessage (&msg,NULL,0,0,PM_NOREMOVE)) { if( msg.message == WM_QUIT ) { return ; } GetMessage (&msg,NULL,0,0); TranslateMessage(&msg); DispatchMessage(&msg); } else { // フリップを行う g_manager->Flip(); // Updateと再生開始を並行で行う g_wait = false; if( g_timer % 30 == 0 ) { // エフェクトの再生 g_manager->Play( g_effect, rand() % 20 - 10, rand() % 20 - 10, rand() % 20 - 10 ); } // Update完了待ち while( !g_wait ) { Sleep(1); } g_d3d_device->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 ); g_d3d_device->BeginScene(); // エフェクトの描画開始処理を行う。 g_renderer->BeginRendering(); // エフェクトの描画を行う。 g_manager->Draw(); // エフェクトの描画終了処理を行う。 g_renderer->EndRendering(); g_d3d_device->EndScene(); g_timer++; { HRESULT hr; hr = g_d3d_device->Present( NULL, NULL, NULL, NULL ); // デバイスロスト処理 switch ( hr ) { // デバイスロスト case D3DERR_DEVICELOST: while ( FAILED( hr = g_d3d_device->TestCooperativeLevel() ) ) { switch ( hr ) { // デバイスロスト case D3DERR_DEVICELOST: ::SleepEx( 1000, true ); break; // デバイスロスト:リセット可 case D3DERR_DEVICENOTRESET: // デバイスロストの処理を行う前に実行する g_renderer->OnLostDevice(); D3DPRESENT_PARAMETERS d3dp; ZeroMemory(&d3dp, sizeof(d3dp)); d3dp.BackBufferWidth = g_window_width; d3dp.BackBufferHeight = g_window_height; d3dp.BackBufferFormat = D3DFMT_X8R8G8B8; d3dp.BackBufferCount = 1; d3dp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dp.Windowed = TRUE; d3dp.hDeviceWindow = g_window_handle; d3dp.EnableAutoDepthStencil = TRUE; d3dp.AutoDepthStencilFormat = D3DFMT_D16; g_d3d_device->Reset( &d3dp ); // デバイスロストの処理の後に実行する g_renderer->OnResetDevice(); break; } } break; } } } } }
// 使用DirectX 9來繪圖 void RenderFrameDX9(void) { DWORD FogColor = D3DCOLOR_RGBA(128, 128, 128, 255); LPDIRECT3DDEVICE9 device = GutGetGraphicsDeviceDX9(); device->BeginScene(); // 消除畫面 device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, FogColor, 1.0f, 0); // 設定轉換矩陣 Matrix4x4 view_matrix = g_Control.GetViewMatrix(); Matrix4x4 object_matrix = g_Control.GetObjectMatrix(); device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &g_projection_matrix); device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &view_matrix); device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &object_matrix); // 設定霧 device->SetRenderState(D3DRS_FOGENABLE, TRUE); device->SetRenderState(D3DRS_FOGCOLOR, FogColor); switch(g_iFogMode) { case 0: device->SetRenderState(D3DRS_FOGENABLE, FALSE); break; case 1: { // 隨距離線性變濃的霧 float fStart = 0.0f; float fEnd = 10.0f; device->SetRenderState(D3DRS_FOGVERTEXMODE, D3DFOG_LINEAR); device->SetRenderState(D3DRS_FOGSTART, *(DWORD *)(&fStart)); device->SetRenderState(D3DRS_FOGEND, *(DWORD *)(&fEnd)); // 計算公式為 // (fog_end - distance_to_camera) / (fog_end - fog_start) break; } case 2: { // `套用指數函式來變化的霧 ` float fFogDensity = 0.5f; device->SetRenderState(D3DRS_FOGVERTEXMODE, D3DFOG_EXP); device->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)&fFogDensity); // 計算公式為 // power(e, -(fog_density * distance_to_camera)) break; } case 3: { // `套用指數函式來變化的霧 ` float fFogDensity = 0.5f; device->SetRenderState(D3DRS_FOGVERTEXMODE, D3DFOG_EXP2); device->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)&fFogDensity); // 計算公式為 // power(e, -(fog_density * distance_to_camera)^2) break; } } // 畫出模型 g_Model_DX9.Render(); // 宣告所有的繪圖指令都下完了 device->EndScene(); // 把背景backbuffer的畫面呈現出來 device->Present( NULL, NULL, NULL, NULL ); }
VOID Render() { static __int64 _lastFrameTime, currTime, cps; static float _deltaT; static D3DXMATRIX t; D3DXMatrixTranslation(&ObjectAllign, 0.0f, 0.0f, 0); D3DXMatrixRotationYawPitchRoll(&t, 0, 0, D3DX_PI); D3DXMatrixMultiply(&ObjectAllign, &ObjectAllign, &t); pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(100,100,255), 1.0f, 0x0); if( SUCCEEDED( pD3DDevice->BeginScene() ) ) /////////////////////////////////////////////////// { pD3DDevice->SetVertexShader(NULL); // Set properties g_dist_tolerance = GetTolerance(fabs(Position.z)); for(int l = 0; l < LAYER_NUM; ++l) { for(size_t i = 0; i < g_layers[l].Components().size(); ++i) { g_layers[l].Components()[i]->SetProperty(VG::PP_DEFAULT_JOINT, g_joint_style); g_layers[l].Components()[i]->SetProperty(VG::PP_DEFAULT_ENDING, g_ending_style); g_layers[l].Components()[i]->DistanceTolerance() = g_dist_tolerance; } } // Calculate paths size_t triangles = 0; for(int l = 0; l < LAYER_NUM; ++l) { g_layers[l].Recalculate(); triangles += g_layers[l].TriangleCount(); } // Draw layers D3DXMATRIX m; D3DXMatrixRotationYawPitchRoll(&m, CameraRotation.y, CameraRotation.x, CameraRotation.z); D3DXMatrixMultiply(&m, &ObjectAllign, &m); pD3DDevice->SetTransform(D3DTS_WORLD, &m); for(int l = 0; l < LAYER_NUM; ++l) { g_layers[l].Draw(pD3DDevice); } // FPS wchar_t buf[1000]; RECT rect = {0, 0, iWidth, iHeight}; swprintf(buf, 1000, L"FPS: %d \nSec: %f \nTriangles: %d \nDistance: %f \nTolerance: %f", int(1.0f / _deltaT), _deltaT, triangles, fabs(Position.z), g_dist_tolerance); g_font->DrawText(NULL, buf, -1, &rect, DT_TOP | DT_LEFT, 0xff80ff80); pD3DDevice->EndScene();////////////////////////////////////////////////////////// } pD3DDevice->Present(NULL, NULL, NULL, NULL); BOOL ok = QueryPerformanceCounter((LARGE_INTEGER*)&currTime); assert(ok); ok = QueryPerformanceFrequency((LARGE_INTEGER*)&cps); assert(ok); _deltaT = float(currTime - _lastFrameTime) / cps; _lastFrameTime = currTime; }
//-----------------------------------【Direct3D_Render( )函数】------------------------------- // 描述:使用Direct3D进行渲染 //-------------------------------------------------------------------------------------------------- void Direct3D_Render(HWND hwnd) { //-------------------------------------------------------------------------------------- // 【Direct3D渲染五步曲之一】:清屏操作 //-------------------------------------------------------------------------------------- g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0); //定义一个矩形,用于获取主窗口矩形 RECT formatRect; GetClientRect(hwnd, &formatRect); //-------------------------------------------------------------------------------------- // 【Direct3D渲染五步曲之二】:开始绘制 //-------------------------------------------------------------------------------------- g_pd3dDevice->BeginScene(); // 开始绘制 Matrix_Set();//调用封装了四大变换的函数,对Direct3D世界变换,取景变换,投影变换,视口变换进行设置 // 获取键盘消息并给予设置相应的填充模式 if (::GetAsyncKeyState(0x31) & 0x8000f) // 若数字键1被按下,进行实体填充 g_pd3dDevice->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID); if (::GetAsyncKeyState(0x32) & 0x8000f) // 若数字键2被按下,进行线框填充 g_pd3dDevice->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME); //-------------------------------------------------------------------------------------- // 【Direct3D渲染五步曲之三】:正式绘制,利用顶点缓存绘制图形 //-------------------------------------------------------------------------------------- D3DXMatrixRotationY(&R, ::timeGetTime() / 1440.0f); //设置公转的矩阵 // 进行立方体的绘制 D3DXMatrixTranslation(&g_WorldMatrix[0], 3.0f, -3.0f, 0.0f); g_WorldMatrix[0] = g_WorldMatrix[0]*R; g_pd3dDevice->SetTransform(D3DTS_WORLD, &g_WorldMatrix[0]); g_cube->DrawSubset(0); //进行茶壶的绘制 D3DXMatrixTranslation(&g_WorldMatrix[1], -3.0f, -3.0f, 0.0f); g_WorldMatrix[1] = g_WorldMatrix[1]*R; g_pd3dDevice->SetTransform(D3DTS_WORLD, &g_WorldMatrix[1]); g_teapot->DrawSubset(0); // 进行圆环的绘制 D3DXMatrixTranslation(&g_WorldMatrix[2], 3.0f, 3.0f, 0.0f); g_WorldMatrix[2] = g_WorldMatrix[2]*R; g_pd3dDevice->SetTransform(D3DTS_WORLD, &g_WorldMatrix[2]); g_torus->DrawSubset(0); // 进行球面体的绘制 D3DXMatrixTranslation(&g_WorldMatrix[3], -3.0f, 3.0f, 0.0f); g_WorldMatrix[3] = g_WorldMatrix[3]*R; g_pd3dDevice->SetTransform(D3DTS_WORLD, &g_WorldMatrix[3]); g_sphere->DrawSubset(0); //在窗口右上角处,显示每秒帧数 int charCount = swprintf_s(g_strFPS, 20, _T("FPS:%0.3f"), Get_FPS() ); g_pFont->DrawText(NULL, g_strFPS, charCount , &formatRect, DT_TOP | DT_RIGHT, D3DCOLOR_XRGB(255,39,136)); //-------------------------------------------------------------------------------------- // 【Direct3D渲染五步曲之四】:结束绘制 //-------------------------------------------------------------------------------------- g_pd3dDevice->EndScene(); // 结束绘制 //-------------------------------------------------------------------------------------- // 【Direct3D渲染五步曲之五】:显示翻转 //-------------------------------------------------------------------------------------- g_pd3dDevice->Present(NULL, NULL, NULL, NULL); // 翻转与显示 }
//----------------------------------------------------------------------------- // Name: Render() // Desc: Draws the scene //----------------------------------------------------------------------------- VOID Render(HWND hWnd) { // Clear the backbuffer and the zbuffer g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(40,40,40), 1.0f, 0 ); g_pd3dDevice->BeginScene(); g_pd3dDevice->SetRenderState( D3DRS_ZFUNC, D3DCMP_LESSEQUAL ); SetupMatrices(); // Set up the vertex shader constants D3DXMATRIX mat; D3DXMATRIX mat1; D3DXMatrixMultiply( &mat, &g_matWorld, &g_matView ); D3DXMatrixTranspose( &mat1, &mat ); D3DXMatrixMultiply( &mat, &mat, &g_matProj ); D3DXMatrixTranspose( &mat, &mat ); // send the world matrix to the shader into constant register 0 (actually 0 to 3 due to the size of a matrix) g_pd3dDevice->SetVertexShaderConstantF(0, (float*)&mat, 4); // send the camera position to constant register 4 float fCamera[3] = { cameraPos.x , cameraPos.y , cameraPos.z }; g_pd3dDevice->SetVertexShaderConstantF(4, (float*)fCamera,1); // send the light position into constant register 5 float fLightPosition[3] = { lightPos.x , lightPos.y , lightPos.z }; g_pd3dDevice->SetVertexShaderConstantF(5, (float*)fLightPosition,1); // send the light 2 position into constant register 6 float fLightPosition2[3] = { -5.0f , 0.0f , 2.0f }; g_pd3dDevice->SetVertexShaderConstantF(6, (float*)fLightPosition2,1); // send the light 3 position into constant register 7 float fLightPosition3[3] = { 0.0f , 5.0f , -2.0f }; g_pd3dDevice->SetVertexShaderConstantF(7, (float*)fLightPosition3,1); // send the diffuse color into constant register 8 float diffuseColor[4] = { 0.90f, 0.90f, 0.90f, 1.0f }; g_pd3dDevice->SetVertexShaderConstantF(8, (float*)diffuseColor, 1); // send the diffuse color 2 into constant register 9 float diffuseColor2[4] = { 0.95f, 0.20f, 0.10f, 1.0f }; g_pd3dDevice->SetVertexShaderConstantF(9, (float*)diffuseColor2, 1); // send the diffuse color 3 into constant register 10 float diffuseColor3[4] = { 0.10f, 0.20f, 0.95f, 1.0f }; g_pd3dDevice->SetVertexShaderConstantF(10, (float*)diffuseColor3, 1); // send the ambient colour into constant register 11 float fAmbient[4] = {0.1f, 0.1f, 0.1f, 1.0f}; g_pd3dDevice->SetVertexShaderConstantF(11, (float*)fAmbient,1); // send the specular lighting colour into constant register 12 float fSpecularLight[4] = {1.0f, 1.0f, 1.0f, 1.0f}; g_pd3dDevice->SetVertexShaderConstantF(12, (float*)fSpecularLight,1); // send the reflection constant to constant register 13 float fReflection = 10.0f; g_pd3dDevice->SetVertexShaderConstantF(13,&fReflection,1); // send the separation line to constant register 14 float separationLine = 0.0f; g_pd3dDevice->SetVertexShaderConstantF(14,&separationLine,1); // send ambient material to the constant register 15 float ambientMaterial[4] = { 0.25f , 0.25f , 0.25f , 1.0f}; g_pd3dDevice->SetVertexShaderConstantF(15,(float*)ambientMaterial,1); // send diffuse material one to constant register 16 float diffuseMaterial1[4] = { 0.75f , 0.60f , 0.40f , 1.0f}; g_pd3dDevice->SetVertexShaderConstantF(16,(float*)diffuseMaterial1,1); // send diffuse material two to constant register 17 float diffuseMaterial2[4] = { 0.95f , 0.20f , 0.1f , 1.0f }; g_pd3dDevice->SetVertexShaderConstantF(17,(float*)diffuseMaterial2,1); // send specular material to the constant register 18 float specularMaterial[4] = { 1.0f , 1.0f , 1.0f , 1.0f}; g_pd3dDevice->SetVertexShaderConstantF(18,(float*)specularMaterial,1); // Render the vertex buffer contents g_pd3dDevice->SetFVF(D3DFVF_D3DVERTEX ); g_pd3dDevice->SetStreamSource( 0, g_pMeshVB, 0, sizeof(D3DVERTEX) ); g_pd3dDevice->SetIndices( g_pMeshIB); g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); g_pd3dDevice->SetTexture( 0, g_pTexture ); switch ( currentShader ) // activate the appropiate vertex shader { case 1: g_pd3dDevice->SetVertexShader( g_pVertexShader); break; case 2: g_pd3dDevice->SetVertexShader( g_pVertexShader2); break; case 3: g_pd3dDevice->SetVertexShader( g_pVertexShader3); g_pd3dDevice->SetTexture( 0, g_pTexture2 );break; case 4: g_pd3dDevice->SetVertexShader( g_pVertexShader4); break; case 5: g_pd3dDevice->SetVertexShader( g_pVertexShader5); g_pd3dDevice->SetTexture( 0, marbleTexture ); break; case 6: g_pd3dDevice->SetVertexShader( g_pVertexShader6); g_pd3dDevice->SetTexture( 0, backgroundTexture );break; }; g_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST,0, 0, g_dwNumVertices, 0, g_dwNumFaces ); // End the scene. g_pd3dDevice->EndScene(); // Present the backbuffer contents to the display g_pd3dDevice->Present( NULL, NULL, NULL, NULL ); }
// 使用DirectX 9來繪圖 void RenderFrameDX9(void) { LPDIRECT3DDEVICE9 device = GutGetGraphicsDeviceDX9(); Matrix4x4 view_matrix = g_Control.GetViewMatrix(); Matrix4x4 world_matrix = g_Control.GetObjectMatrix(); Matrix4x4 ident_matrix; ident_matrix.Identity(); device->BeginScene(); // 消除畫面 device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, D3DCOLOR_RGBA(30, 30, 30, 255), 1.0f, 0); // light position & orientation Vector4 light_pos(5.0f, 0.0f, 5.0f); Vector4 light_lookat(0.0f, 0.0f, 0.0f); Vector4 light_up(0.0f, 1.0f, 0.0f); // light matrix Matrix4x4 light_view = GutMatrixLookAtRH(light_pos, light_lookat, light_up); Matrix4x4 light_world_view = world_matrix * light_view; Matrix4x4 shadow_matrix; // 建立shadow volume if ( g_bDirectionalLight ) { g_ShadowVolume.BuildShadowVolume_DirectionalLight(light_world_view, 20.0f, true); shadow_matrix = light_view; shadow_matrix.FastInvert(); } else { g_ShadowVolume.BuildShadowVolume_PointLight(light_pos, world_matrix, 20.0f, true); shadow_matrix.Identity(); } // 畫出空間中的茶壼 { device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &g_projection_matrix); device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &view_matrix); device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &world_matrix); g_Model_DX9.Render(); } // 畫出墻壁 { device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &ident_matrix); sModelMaterial_DX9 material; material.m_Material.Diffuse.r = 0.0f; material.m_Material.Diffuse.g = 0.0f; material.m_Material.Diffuse.b = 1.0f; material.m_Material.Diffuse.a = 1.0f; material.Submit(); device->SetFVF(D3DFVF_XYZ); device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_Quad, sizeof(Vertex_VT)); } device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); device->SetRenderState(D3DRS_STENCILENABLE, TRUE); device->SetRenderState(D3DRS_STENCILREF, 0x01); device->SetRenderState(D3DRS_STENCILMASK, 0xff); // 在Stencil Buffer上標示出陰影區域 { sModelMaterial_DX9 material; material.m_bCullFace = false; material.Submit(); // 套用矩陣 device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &shadow_matrix); // 設定頂點資料格式 device->SetFVF(D3DFVF_XYZ); device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE); // cw stencil setting device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS); device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_INCR); // ccw stencil setting device->SetRenderState(D3DRS_CCW_STENCILFUNC, D3DCMP_ALWAYS); device->SetRenderState(D3DRS_CCW_STENCILZFAIL, D3DSTENCILOP_DECR); // disable color write device->SetRenderState(D3DRS_COLORWRITEENABLE, 0); // 畫出Shadow Volume device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, g_ShadowVolume.m_iNumShadowVolumeFaces, g_ShadowVolume.m_pShadowVolume, sizeof(Vector4)); // 恢復更新framebuffer device->SetRenderState(D3DRS_COLORWRITEENABLE, 0xff); device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE); device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP); device->SetRenderState(D3DRS_CCW_STENCILZFAIL, D3DSTENCILOP_KEEP); } // 畫出陰影 { sModelMaterial_DX9 material; material.m_bCullFace = false; material.Submit(); device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TFACTOR); device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG2); // 套用矩陣 device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &ident_matrix); device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &ident_matrix); device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &ident_matrix); // 只更新stencil buffer上值為1的像素 device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_EQUAL); device->SetRenderState(D3DRS_STENCILREF, 0x01); // 使用黑色再畫一次墻壁 device->SetRenderState(D3DRS_TEXTUREFACTOR, D3DCOLOR_RGBA(0, 0, 0,255) ); device->SetFVF(D3DFVF_XYZ); device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_FullScreenQuad, sizeof(Vertex_VT)); } device->SetRenderState(D3DRS_STENCILENABLE, FALSE); // 觀察shadow volume, 除錯用. if ( g_bDrawShadowVolume ) { device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &g_projection_matrix); device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &view_matrix); device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &shadow_matrix); sModelMaterial_DX9 material; material.m_bCullFace = false; material.Submit(); device->SetRenderState(D3DRS_TEXTUREFACTOR, D3DCOLOR_RGBA(255, 255, 255, 255) ); device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, g_ShadowVolume.m_iNumShadowVolumeFaces, g_ShadowVolume.m_pShadowVolume, sizeof(Vector4)); device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); } // 恢復更新zbuffer device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); // 把顏色來源還原為 diffuse * texture device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT); device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); // 宣告所有的繪圖指令都下完了 device->EndScene(); // 把背景backbuffer的畫面呈現出來 device->Present( NULL, NULL, NULL, NULL ); }
void Game() { build_display_array(); if(g_pDevice == NULL) return; g_pDevice->SetRenderState(D3DRS_FILLMODE, (g_bShowWireFrm)?D3DFILL_WIREFRAME:D3DFILL_SOLID); g_pDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 255), 1.0f, 0); SetupCam(); for (int i=0;i<100;++i) for (int j=0;j<100;++j) { int index = (i * 100 + j) * 6; int count = g_pBox[i][j].bSelect; int intensity; if (count == 0) intensity = 0; else if (count == 1) intensity = 127; else { intensity = min(255, 127 + count*16); } intensity = 255 - intensity; int color = D3DCOLOR_ARGB(255, intensity, intensity, 255); g_pVerticesList[index++].color = color; g_pVerticesList[index++].color = color; g_pVerticesList[index++].color = color; g_pVerticesList[index++].color = color; g_pVerticesList[index++].color = color; g_pVerticesList[index++].color = color; } //'장면(Scene) 그리기' 시작 if(SUCCEEDED(g_pDevice->BeginScene())) { g_pDevice->SetFVF(D3DFVF_CUSTOMVERTEX); //버퍼 채우기. VOID* pVertices; if(FAILED(g_pVB->Lock(0, sizeof(g_pVerticesList), (void**)&pVertices, 0 ))) { printf("버텍스버퍼 Locking 오류!!\n"); return; } memcpy(pVertices, g_pVerticesList, sizeof(g_pVerticesList)); g_pVB->Unlock(); g_pDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX)); D3DXMATRIX mTrans; D3DXMatrixIdentity(&mTrans); g_pDevice->SetTransform(D3DTS_WORLD, &mTrans); g_pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 6 * 100 * 100); g_pDevice->EndScene(); } g_pDevice->Present(NULL, NULL, NULL, NULL); }
//************************************************************************************************************* void Render(float alpha, float elapsedtime) { LPDIRECT3DSURFACE9 oldtarget = NULL; D3DXMATRIX vp, inv, tmp1, tmp2; D3DXVECTOR3 axis(0, 1, 0); D3DXVECTOR3 eye(0, 0, -5); D3DXVECTOR3 look(0, 0, 0); D3DXVECTOR3 up(0, 1, 0); D3DXVECTOR2 cangle = cameraangle.smooth(alpha); D3DXVECTOR2 oangle = objectangle.smooth(alpha); float expo = exposure.smooth(alpha); D3DXMatrixRotationYawPitchRoll(&world, cangle.x, cangle.y, 0); D3DXVec3TransformCoord(&eye, &eye, &world); D3DXMatrixLookAtLH(&view, &eye, &look, &up); D3DXMatrixMultiply(&vp, &view, &proj); D3DXMatrixInverse(&inv, NULL, &view); memcpy(&eye, inv.m[3], 3 * sizeof(float)); if( mesh == mesh1 ) { // skullocc D3DXMatrixScaling(&world, 0.4f, 0.4f, 0.4f); world._42 = -1.5f; } else if( mesh == mesh2 ) { // knot D3DXMatrixScaling(&world, 0.8f, 0.8f, 0.8f); } else { // teapot D3DXMatrixScaling(&world, 1.5f, 1.5f, 1.5f); } D3DXMatrixRotationYawPitchRoll(&tmp1, oangle.x, oangle.y, 0); D3DXMatrixMultiply(&world, &world, &tmp1); D3DXMatrixInverse(&inv, NULL, &world); fresnel->SetVector("eyePos", (D3DXVECTOR4*)&eye); fresnel->SetMatrix("matWorld", &world); fresnel->SetMatrix("matWorldInv", &inv); fresnel->SetMatrix("matViewProj", &vp); D3DXMatrixScaling(&world, 20, 20, 20); skyeffect->SetMatrix("matWorld", &world); D3DXMatrixIdentity(&world); skyeffect->SetMatrix("matWorldSky", &world); skyeffect->SetMatrix("matViewProj", &vp); memcpy(tmpvert, quadvertices, 36 * sizeof(float)); if( SUCCEEDED(device->BeginScene()) ) { device->SetRenderState(D3DRS_SRGBWRITEENABLE, false); device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); // STEP 1: render sky device->GetRenderTarget(0, &oldtarget); if( firstframe ) { device->SetRenderTarget(0, aftersurfaces[0]); device->Clear(0, NULL, D3DCLEAR_TARGET, 0, 1.0f, 0); device->SetRenderTarget(0, aftersurfaces[1]); device->Clear(0, NULL, D3DCLEAR_TARGET, 0, 1.0f, 0); device->SetRenderTarget(0, avglumsurfaces[4]); device->Clear(0, NULL, D3DCLEAR_TARGET, 0x11111111, 1.0f, 0); device->SetRenderTarget(0, avglumsurfaces[5]); device->Clear(0, NULL, D3DCLEAR_TARGET, 0x11111111, 1.0f, 0); firstframe = false; } device->SetRenderTarget(0, scenesurface); device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0xff6694ed, 1.0f, 0); device->SetRenderState(D3DRS_ZENABLE, FALSE); device->SetTexture(0, skytexture); skyeffect->Begin(NULL, 0); skyeffect->BeginPass(0); { skymesh->DrawSubset(0); } skyeffect->EndPass(); skyeffect->End(); device->SetRenderState(D3DRS_ZENABLE, TRUE); // STEP 2: render object device->SetTexture(0, texture); device->SetTexture(1, fresneltexture); device->SetTexture(2, skytexture); device->SetTexture(3, roughspecular); fresnel->Begin(NULL, 0); fresnel->BeginPass(0); { mesh->DrawSubset(0); } fresnel->EndPass(); fresnel->End(); device->SetVertexDeclaration(vertexdecl); // STEP 3: measure average luminance MeasureLuminance(); // STEP 4: adapt luminance to eye AdaptLuminance(elapsedtime); // STEP 5: bright pass BrightPass(); // STEP 6: downsample bright pass texture DownSample(); // STEP 7: blur downsampled textures Blur(); // STEP 8: ghost LensFlare(); // STEP 9: star Star(); // STEP 10: final combine hdreffect->SetTechnique("final"); hdreffect->SetFloat("targetluminance", targetluminance); device->SetRenderTarget(0, oldtarget); device->SetTexture(0, scenetarget); // scene device->SetTexture(1, blurtargets[0]); // blur device->SetTexture(2, blurtargets[1]); // star device->SetTexture(3, ghosttargets[0]); // ghost device->SetTexture(4, afterimages[1 - afterimagetex]); device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); device->SetRenderState(D3DRS_SRGBWRITEENABLE, true); oldtarget->Release(); hdreffect->Begin(NULL, 0); hdreffect->BeginPass(0); { device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, sizeof(D3DXVECTOR4) + sizeof(D3DXVECTOR2)); } hdreffect->EndPass(); hdreffect->End(); if( drawhelp ) { // render text device->SetFVF(D3DFVF_XYZRHW|D3DFVF_TEX1); device->SetRenderState(D3DRS_ZENABLE, FALSE); device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); device->SetTexture(0, text); device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, textvertices, 6 * sizeof(float)); device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); device->SetRenderState(D3DRS_ZENABLE, TRUE); } // clean up device->SetTexture(1, NULL); device->SetTexture(2, NULL); device->SetTexture(3, NULL); device->SetTexture(4, NULL); device->SetTexture(5, NULL); device->EndScene(); } device->Present(NULL, NULL, NULL, NULL); }
void Render(float alpha, float elapsedtime) { static float time = 0; LPDIRECT3DSURFACE9 backbuffer = 0; D3DXMATRIX view, proj, viewproj; D3DXMATRIX world, inv; D3DXVECTOR4 texelsize; D3DXVECTOR4 lightpos(-600, 350, 1000, 1); D3DXVECTOR4 refllight; D3DXVECTOR3 eye(0, 0, -5.0f); D3DXVECTOR3 look(0, 1.2f, 0); D3DXVECTOR3 refleye, refllook; D3DXVECTOR3 up(0, 1, 0); D3DXVECTOR2 orient = cameraangle.smooth(alpha); D3DXMatrixRotationYawPitchRoll(&view, orient.x, orient.y, 0); D3DXVec3TransformCoord(&eye, &eye, &view); eye.y += 1.2f; D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI / 2, (float)screenwidth / (float)screenheight, 0.1f, 30); time += elapsedtime; if( SUCCEEDED(device->BeginScene()) ) { device->GetRenderTarget(0, &backbuffer); // STEP 1: render reflection texture device->SetRenderTarget(0, reflectsurf); device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0xff6694ed, 1.0f, 0); D3DXPLANE plane(0, 1, 0, 1); refleye = eye - 2 * D3DXPlaneDotCoord(&plane, &eye) * (D3DXVECTOR3&)plane; refllook = look - 2 * D3DXPlaneDotCoord(&plane, &look) * (D3DXVECTOR3&)plane; refllight = lightpos - 2 * D3DXPlaneDot(&plane, &lightpos) * (D3DXVECTOR4&)plane; refllight.w = 1; D3DXMatrixLookAtLH(&view, &refleye, &refllook, &up); D3DXMatrixMultiply(&viewproj, &view, &proj); D3DXMatrixInverse(&inv, 0, &viewproj); D3DXMatrixTranspose(&inv, &inv); D3DXPlaneTransform(&plane, &plane, &inv); device->SetClipPlane(0, &plane.a); RenderScene(viewproj, refleye, refllight, true); // STEP 2: render scene (later used for refraction) D3DXMatrixLookAtLH(&view, &eye, &look, &up); D3DXMatrixMultiply(&viewproj, &view, &proj); device->SetRenderTarget(0, refractsurf); device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0xff6694ed, 1.0f, 0); RenderScene(viewproj, eye, lightpos, false); // render water surface into alpha channel for masking device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA); D3DXMatrixTranslation(&world, 0, -1, 0); device->SetTransform(D3DTS_WORLD, &world); device->SetTransform(D3DTS_VIEW, &view); device->SetTransform(D3DTS_PROJECTION, &proj); waterplane->DrawSubset(0, DXObject::Opaque); device->SetRenderState(D3DRS_COLORWRITEENABLE, 0x0f); // STEP 3: light shafts quadvertices[6] = quadvertices[24] = quadvertices[30] = (float)screenwidth - 0.5f; quadvertices[13] = quadvertices[19] = quadvertices[31] = (float)screenheight - 0.5f; RenderLightShafts(view, proj, eye, lightpos); // STEP 4: gamma correct device->SetRenderTarget(0, sceneldrsurf); device->SetRenderState(D3DRS_ZENABLE, FALSE); device->SetVertexDeclaration(quaddecl); bloom->SetTechnique("gammacorrect"); bloom->Begin(0, 0); bloom->BeginPass(0); { device->SetTexture(0, refraction); device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float)); } bloom->EndPass(); bloom->End(); device->SetRenderState(D3DRS_ZENABLE, TRUE); // STEP 5: water surface device->SetRenderState(D3DRS_SRGBWRITEENABLE, TRUE); D3DXMatrixTranslation(&world, 0, -1, 0); D3DXMatrixIdentity(&inv); water->SetMatrix("matViewProj", &viewproj); water->SetMatrix("matWorld", &world); water->SetMatrix("matWorldInv", &inv); water->SetVector("eyePos", (D3DXVECTOR4*)&eye); water->SetVector("lightPos", &lightpos); water->SetVector("lightColor", &lightcolor); water->SetFloat("time", time); water->Begin(0, 0); water->BeginPass(0); { device->SetTexture(0, refraction); device->SetTexture(1, reflection); device->SetTexture(2, waves); waterplane->DrawSubset(0, DXObject::Opaque); } water->EndPass(); water->End(); device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE); // STEP 6: downsample & blur quadvertices[6] = quadvertices[24] = quadvertices[30] = (float)screenwidth * 0.5f - 0.5f; quadvertices[13] = quadvertices[19] = quadvertices[31] = (float)screenheight * 0.5f - 0.5f; device->SetRenderTarget(0, bloomsurf1); device->SetRenderState(D3DRS_ZENABLE, FALSE); device->SetVertexDeclaration(quaddecl); texelsize.x = 1.0f / screenwidth; texelsize.y = 1.0f / screenheight; bloom->SetTechnique("downsample"); bloom->SetVector("texelSize", &texelsize); bloom->Begin(0, 0); bloom->BeginPass(0); { device->SetTexture(0, sceneldr); device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float)); } bloom->EndPass(); bloom->End(); device->SetRenderTarget(0, bloomsurf2); texelsize.x = 2.0f / screenwidth; texelsize.y = 2.0f / screenheight; bloom->SetTechnique("blur"); bloom->SetVector("texelSize", &texelsize); bloom->Begin(0, 0); bloom->BeginPass(0); { device->SetTexture(0, bloomtex1); device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float)); } bloom->EndPass(); bloom->End(); // STEP 7: add light shafts quadvertices[6] = quadvertices[24] = quadvertices[30] = (float)screenwidth - 0.5f; quadvertices[13] = quadvertices[19] = quadvertices[31] = (float)screenheight - 0.5f; device->SetRenderTarget(0, backbuffer); godray->SetTechnique("final"); godray->Begin(0, 0); godray->BeginPass(0); { device->SetTexture(0, sceneldr); device->SetTexture(1, occluders); device->SetTexture(2, bloomtex2); device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float)); } godray->EndPass(); godray->End(); backbuffer->Release(); device->SetRenderState(D3DRS_ZENABLE, TRUE); device->EndScene(); } device->Present(NULL, NULL, NULL, NULL); }
//랜더 void Render(int timeDelta) { //화면 청소 if (SUCCEEDED(g_pDevice->Clear( 0, //청소할 영역의 D3DRECT 배열 갯수 ( 전체 클리어 0 ) NULL, //청소할 영역의 D3DRECT 배열 포인터 ( 전체 클리어 NULL ) D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, //청소될 버퍼 플레그 ( D3DCLEAR_TARGET 컬러버퍼, D3DCLEAR_ZBUFFER 깊이버퍼, D3DCLEAR_STENCIL 스텐실버퍼 D3DCOLOR_XRGB(150, 150, 150), //컬러버퍼를 청소하고 채워질 색상( 0xAARRGGBB ) 1.0f, //깊이버퍼를 청소할값 ( 0 ~ 1 0 이 카메라에서 제일가까운 1 이 카메라에서 제일 먼 ) 0 //스텐실 버퍼를 채울값 ))) { //화면 청소가 성공적으로 이루어 졌다면... 랜더링 시작 g_pDevice->BeginScene(); //fps출력 static WORD frameCnt = 0; static DWORD ntimeDelay = 0; static float fps = 0.f; frameCnt++; ntimeDelay += timeDelta; if( ntimeDelay >= 1000 ) { fps = (float)frameCnt; frameCnt = 0; ntimeDelay -= ntimeDelay; } string outputFps = format( "%0.3f", fps ); RECT rc; SetRect( &rc, 150, 100, 0, 0 ); //다이렉트 생성할때의 화면 크기의 좌표로 적용됨 global->font->DrawTextA( NULL, //A : 아스키코드 // "global->font->DrawText", outputFps.c_str(), -1, &rc, DT_NOCLIP, //다 출력하겠다라는 의미(화면 크기 연연하지 않겠다인듯??) D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f) ); //쿼터니언 응용 /* Quaternion quat; quat.SetRotationArc(Vector3(0,1,0),Vector3(0,0,1)); //첫번째 인자방향 기준으로 두번째 인자 방향으로 Matrix44 qt = quat.GetMatrix(); */ static float ftheta = 0.f; ftheta += 0.0005f; const float fradian = ftheta / MATH_PI; if( ftheta >= 360.f ) ftheta = 0.f; Matrix44 mat; mat.SetTranslate(Vector3(5, sin(fradian) * 10.f, -490)); //sin(fradian) : 각도에 따른 +-변화 //10.f 곱하기는 범위 // Matrix44 m = global->localTm * mat; // g_pDevice->SetTransform(D3DTS_WORLD, (D3DXMATRIX*)&m); //마우스 회전 잠금 g_pDevice->SetTransform(D3DTS_WORLD, (D3DXMATRIX*)&mat); global->mesh3DText->DrawSubset( 0 ); Vector3 mainPos(-10, 0, -490); Vector3 targetLook = mat.GetPosition() - mainPos; //대상물체와 메인물체와의 거리 판단 targetLook.Normalize(); Quaternion quat; // mainPos.Normalize(); // quat.SetRotationArc(mainPos, targetLook); //첫번째 인자를 물체의 위치로 하니 회전하는 방향이 생각과는 다르게 표현된다...역시 고정된 방향이어야 되나보다... quat.SetRotationArc(Vector3(1,0,0), targetLook); //양의 x축방향으로 대상물체를 바라본다 Matrix44 qm = quat.GetMatrix(); mat.SetTranslate(mainPos); qm *= mat; g_pDevice->SetTransform(D3DTS_WORLD, (D3DXMATRIX*)&qm); global->mesh3DText->DrawSubset( 0 ); //랜더링 끝 g_pDevice->EndScene(); //랜더링이 끝났으면 랜더링된 내용 화면으로 전송 g_pDevice->Present( NULL, NULL, NULL, NULL ); } }
//============================================================================= // エントリー関数 //============================================================================= int APIENTRY WinMain(HINSTANCE _instanceHandle ,HINSTANCE _instanceHandlePrev, LPSTR _cmdLine, int _cmdShow) { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); UNREFERENCED_PARAMETER(_instanceHandlePrev); UNREFERENCED_PARAMETER(_cmdLine); DWORD execLastTime; DWORD LastTimeFPS; DWORD currentTime; DWORD flameCount; WNDCLASSEX wcex = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0, 0, _instanceHandle, NULL, LoadCursor(NULL, IDC_ARROW), (HBRUSH)(COLOR_WINDOW + 1), NULL, CLASS_NAME, NULL }; HWND windowHandle; MSG msg; // ウィンドウクラスの登録 RegisterClassEx(&wcex); // ウィンドウの作成 windowHandle = CreateWindowEx(0, CLASS_NAME, WINDOW_NAME, WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_THICKFRAME, CW_USEDEFAULT, CW_USEDEFAULT, static_cast<int>(SCREEN_WIDTH + GetSystemMetrics(SM_CXDLGFRAME) * 2), static_cast<int>(SCREEN_HEIGHT + GetSystemMetrics(SM_CXDLGFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION)), NULL, NULL, _instanceHandle, NULL); // フレームカウント初期化 timeBeginPeriod(1); // 分解能を設定 execLastTime = LastTimeFPS = timeGetTime(); currentTime = flameCount = 0; // ウインドウの表示(初期化処理の後に呼ばないと駄目) ShowWindow(windowHandle, _cmdShow); UpdateWindow(windowHandle); #ifndef _DEBUG LoadLibraryA("WiiYourself.dll"); #else LoadLibraryA("WiiYourself_debug.dll"); #endif LPDIRECT3D9 direct3D; // Direct3D9用デバイス LPDIRECT3DDEVICE9 device; // _deviceオブジェクト(描画に必要) D3DDISPLAYMODE displayMode; D3DPRESENT_PARAMETERS presentParameter; // Direct3Dオブジェクトの作成 direct3D = Direct3DCreate9(D3D_SDK_VERSION); direct3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &displayMode); // デバイスのプレゼンテーションパラメータの設定 //-------------------------------------------------------------------- // ワークをゼロクリア ZeroMemory(&presentParameter, sizeof(presentParameter)); // バックバッファの数をセット presentParameter.BackBufferCount = 1; //ゲーム画面サイズ presentParameter.BackBufferWidth = static_cast<int>SCREEN_WIDTH; presentParameter.BackBufferHeight = static_cast<int>SCREEN_HEIGHT; // バックバッファフォーマットはディスプレイモードに合わせて使う presentParameter.BackBufferFormat = displayMode.Format; // 映像信号に同期してフリップする presentParameter.SwapEffect = D3DSWAPEFFECT_DISCARD; // ウィンドウモード presentParameter.Windowed = TRUE; // デプスバッファ(Zバッファ)とステンシルバッファを作成 presentParameter.EnableAutoDepthStencil = TRUE; // デプスバッファの利用方法 // D3DFMT_D16 デプスバッファのみを16bitとして扱う // D3DFMT_D24S8 デプスバッファを24bit ステンシルバッファを8bitとして扱う presentParameter.AutoDepthStencilFormat = D3DFMT_D24S8; // ウィンドウモード presentParameter.FullScreen_RefreshRateInHz = 0; presentParameter.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; //-------------------------------------------------------------------- direct3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, windowHandle, D3DCREATE_HARDWARE_VERTEXPROCESSING, &presentParameter, &device); CDebug* debug = new CDebug(); debug->Init(device); CKeyboard* keyboard = new CKeyboard(); keyboard->Init(_instanceHandle, windowHandle); CMouse* mouse = new CMouse(); mouse->Init(_instanceHandle, windowHandle); CWiiController* wiiController = new CWiiController(); // メッセージループ for (;;) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) { // PostQuitMessage()が呼ばれたらループ終了 break; } else { // メッセージの翻訳とディスパッチ TranslateMessage(&msg); DispatchMessage(&msg); } } else { currentTime = timeGetTime(); if ((currentTime - LastTimeFPS) >= 500) { #ifdef _DEBUG countFPS = flameCount * 1000 / (currentTime - LastTimeFPS); #endif LastTimeFPS = currentTime; flameCount = 0; } if ((currentTime - execLastTime) >= (1000 / 60)) { execLastTime = currentTime ; keyboard->Update(); mouse->Update(); wiiController->update(); { // 本体 { debug->SetDebug("本体の加速度X [%f]\n", wiiController->getAccelerationX()); debug->SetDebug("本体の加速度Y [%f]\n", wiiController->getAccelerationY()); debug->SetDebug("本体の加速度Z [%f]\n", wiiController->getAccelerationZ()); debug->SetDebug("本体の回転角X [%f]\n", wiiController->getRotX()); debug->SetDebug("本体の回転角Y [%f]\n", wiiController->getRotY()); debug->SetDebug("本体の回転角Z [%f]\n", wiiController->getRotZ()); debug->SetDebug("本体の回転角の変異X [%f]\n", wiiController->getChangeRotX()); debug->SetDebug("本体の回転角の変異Y [%f]\n", wiiController->getChangeRotY()); debug->SetDebug("本体の回転角の変異Z [%f]\n", wiiController->getChangeRotZ()); debug->SetDebug("本体の角速度X [%f]\n", wiiController->getRotSpeedX()); debug->SetDebug("本体の角速度Y [%f]\n", wiiController->getRotSpeedY()); debug->SetDebug("本体の角速度Z [%f]\n", wiiController->getRotSpeedZ()); } // ヌンチャク { debug->SetDebug("ヌンチャクの加速度X [%f]\n", wiiController->getAccelerationNX()); debug->SetDebug("ヌンチャクの加速度Y [%f]\n", wiiController->getAccelerationNY()); debug->SetDebug("ヌンチャクの加速度Z [%f]\n", wiiController->getAccelerationNZ()); debug->SetDebug("ヌンチャクの回転角X [%f]\n", wiiController->getRotNX()); debug->SetDebug("ヌンチャクの回転角Y [%f]\n", wiiController->getRotNY()); debug->SetDebug("ヌンチャクの回転角Z [%f]\n", wiiController->getRotNZ()); debug->SetDebug("ヌンチャクの位置X [%f]\n", wiiController->getJoystick().x); debug->SetDebug("ヌンチャクの位置Y [%f]\n", wiiController->getJoystick().y); } // 赤外線 { debug->SetDebug("赤外線X [%f]\n", wiiController->getIR().x); debug->SetDebug("赤外線Y [%f]\n", wiiController->getIR().y); } debug->SetDebug("バッテリー残量[%d%]\n", wiiController->battery()); debug->SetDebug("モーションPlusの接続状態[%d]\n", wiiController->getMotionConnect()); /*if (wiiController->getTrigger(WC_A)) wiiController->rumble(true); if (wiiController->getTrigger(WC_B)) wiiController->rumble(false); if (wiiController->getTrigger(WC_UP)) wiiController->rumble((unsigned int)1000);*/ // Aボタン { if (wiiController->getPress(WC_A)) debug->SetDebug("A [ON]\n"); else debug->SetDebug("A [OFF]\n"); } // Bボタン { if (wiiController->getPress(WC_B)) debug->SetDebug("B [ON]\n"); else debug->SetDebug("B [OFF]\n"); } // Cボタン { if (wiiController->getPress(WC_C)) debug->SetDebug("C [ON]\n"); else debug->SetDebug("C [OFF]\n"); } // Zボタン { if (wiiController->getPress(WC_Z)) debug->SetDebug("Z [ON]\n"); else debug->SetDebug("Z [OFF]\n"); } // ↑ボタン { if (wiiController->getPress(WC_UP)) debug->SetDebug("UP [ON]\n"); else debug->SetDebug("UP [OFF]\n"); } // ↓ボタン { if (wiiController->getPress(WC_DOWN)) debug->SetDebug("DOWN [ON]\n"); else debug->SetDebug("DOWN [OFF]\n"); } // ←ボタン { if (wiiController->getPress(WC_LEFT)) debug->SetDebug("LEFT [ON]\n"); else debug->SetDebug("LEFT [OFF]\n"); } // →ボタン { if (wiiController->getPress(WC_RIGHT)) debug->SetDebug("RIGHT [ON]\n"); else debug->SetDebug("RIGHT [OFF]\n"); } // -ボタン { if (wiiController->getPress(WC_MINUS)) debug->SetDebug("MINUS [ON]\n"); else debug->SetDebug("MINUS [OFF]\n"); if(wiiController->getTrigger(WC_MINUS)) wiiController->rotSpeedCalibration(); } // +ボタン { if (wiiController->getPress(WC_PLUS)) debug->SetDebug("PLUS [ON]\n"); else debug->SetDebug("PLUS [OFF]\n"); if(wiiController->getTrigger(WC_PLUS)) wiiController->rotReset(); } // 1ボタン { if (wiiController->getPress(WC_ONE)) debug->SetDebug("ONE [ON]\n"); else debug->SetDebug("ONE [OFF]\n"); } // 2ボタン { if (wiiController->getPress(WC_TWO)) debug->SetDebug("TWO [ON]\n"); else debug->SetDebug("TWO [OFF]\n"); } // HOMEボタン { if (wiiController->getPress(WC_HOME)) debug->SetDebug("HOME [ON]\n"); else debug->SetDebug("HOME [OFF]\n"); } } // バックバッファ&Zバッファのクリア device->Clear(0, NULL, (D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER), D3DCOLOR_RGBA(255, 255, 255, 255), 1.0f, 0); // Direct3Dによる描画の開始 if (SUCCEEDED(device->BeginScene())) { CDebug::Draw(); // Direct3Dによる描画の終了 device->EndScene(); } // バックバッファとフロントバッファの入れ替える device->Present(NULL, NULL, NULL, NULL); flameCount++; } } } SAFE_DELETE(wiiController); SAFE_DELETE(keyboard); SAFE_DELETE(mouse); SAFE_DELETE(debug); // ウィンドウクラスの登録を解除 UnregisterClass(CLASS_NAME, wcex.hInstance); timeEndPeriod(1); // 分解能を戻す return static_cast<int>(msg.wParam); }
//-----------------------------------【Direct3D_Render( )函数】------------------------------- // 描述:使用Direct3D进行渲染 //-------------------------------------------------------------------------------------------------- void Direct3D_Render(HWND hwnd) { //-------------------------------------------------------------------------------------- // 【Direct3D渲染五步曲之一】:清屏操作 //-------------------------------------------------------------------------------------- g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, D3DCOLOR_XRGB(50, 100, 250), 1.0f, 0); //-------------------------------------------------------------------------------------- // 【Direct3D渲染五步曲之二】:开始绘制 //-------------------------------------------------------------------------------------- g_pd3dDevice->BeginScene(); // 开始绘制 //-------------------------------------------------------------------------------------- // 【Direct3D渲染五步曲之三】:正式绘制 //-------------------------------------------------------------------------------------- g_pd3dDevice->SetTransform(D3DTS_WORLD, &g_matWorld); for (DWORD i = 0; i < g_dwNumMtrls; i++) { g_pd3dDevice->SetMaterial(&g_pMaterials[i]); g_pd3dDevice->SetTexture(0, g_pTextures[i]); g_pMesh->DrawSubset(i); } D3DXMATRIX matWorld; D3DXMatrixTranslation(&matWorld, 0.0f, 0.0f, 0.0f); g_pd3dDevice->SetTransform(D3DTS_WORLD, &matWorld); g_pd3dDevice->SetTexture(0, g_pTexture); g_pd3dDevice->SetStreamSource(0, g_pVertexBuffer, 0, sizeof(CUSTOMVERTEX)); g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX); g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); D3DXMATRIX TransMatrix, RotMatrix, FinalMatrix; D3DXMatrixRotationX(&RotMatrix, -D3DX_PI * 0.5f); g_pd3dDevice->SetMaterial(&g_MaterialCylinder); for (int i = 0; i < 6; i++) { D3DXMatrixTranslation(&TransMatrix, -100.0f, 0.0f, -150.0f + (i * 75.0f)); FinalMatrix = RotMatrix * TransMatrix; g_pd3dDevice->SetTransform(D3DTS_WORLD, &FinalMatrix); g_cylinder->DrawSubset(0); D3DXMatrixTranslation(&TransMatrix, 100.0f, 0.0f, -150.0f + (i * 75.0f)); FinalMatrix = RotMatrix * TransMatrix; g_pd3dDevice->SetTransform(D3DTS_WORLD, &FinalMatrix); g_cylinder->DrawSubset(0); } HelpText_Render(hwnd); //-------------------------------------------------------------------------------------- // 【Direct3D渲染五步曲之四】:结束绘制 //-------------------------------------------------------------------------------------- g_pd3dDevice->EndScene(); // 结束绘制 //-------------------------------------------------------------------------------------- // 【Direct3D渲染五步曲之五】:显示翻转 //-------------------------------------------------------------------------------------- g_pd3dDevice->Present(NULL, NULL, NULL, NULL); // 翻转与显示 }
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Initialize comctl CoInitializeEx(NULL, COINIT_MULTITHREADED); static const wchar_t *class_name = L"ImGui Example"; // Create application window HINSTANCE instance = GetModuleHandle(NULL); HICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1)); WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, instance, icon, NULL, NULL, NULL, class_name, NULL}; RegisterClassEx(&wc); HWND hwnd = CreateWindow(class_name, _T("Open Board Viewer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 1280, 800, NULL, NULL, wc.hInstance, NULL); DragAcceptFiles(hwnd, true); // Initialize Direct3D LPDIRECT3D9 pD3D; if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) { UnregisterClass(class_name, wc.hInstance); MessageBox(hwnd, L"Failed to initialise Direct3D", NULL, 0); return 0; } ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); g_d3dpp.Windowed = TRUE; g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; g_d3dpp.EnableAutoDepthStencil = TRUE; g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Create the D3DDevice if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) { pD3D->Release(); UnregisterClass(class_name, wc.hInstance); MessageBox(hwnd, L"Failed to create Direct3D device", NULL, 0); return 0; } // Setup ImGui binding ImGui_ImplDX9_Init(hwnd, g_pd3dDevice); ImGuiIO &io = ImGui::GetIO(); io.IniFilename = NULL; // Disable imgui.ini // Load Fonts for (auto name : {"Liberation Sans", "DejaVu Sans", "Arial", ""}) { // Empty string = use system default font ImFontConfig font_cfg{}; font_cfg.FontDataOwnedByAtlas = false; const std::vector<char> ttf = load_font(name); if (!ttf.empty()) { io.Fonts->AddFontFromMemoryTTF( const_cast<void *>(reinterpret_cast<const void *>(ttf.data())), ttf.size(), 20.0f, &font_cfg); break; } } io.Fonts->AddFontDefault(); // ImGui fallback font #if 0 // Get current flag int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Turn on leak-checking bit. tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF; // Set flag to the new value. _CrtSetDbgFlag(tmpFlag); #endif BoardView app{}; bool show_test_window = true; bool show_another_window = false; ImVec4 clear_col = ImColor(20, 20, 30); // Main loop MSG msg; ZeroMemory(&msg, sizeof(msg)); ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); continue; } ImGui_ImplDX9_NewFrame(); if (msg.message == WM_DROPFILES) { HDROP hDrop = (HDROP)msg.wParam; TCHAR *lpszFile = new TCHAR[MAX_PATH]; UINT uFile = 0; uFile = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, NULL); if (uFile > 1) { app.ShowError("Multiple files not supported"); } else { lpszFile[0] = '\0'; if (DragQueryFile(hDrop, 0, lpszFile, MAX_PATH)) { char *fileAsChar = new char[MAX_PATH]; wcstombs_s(NULL, fileAsChar, MAX_PATH, lpszFile, wcslen(lpszFile) + 1); app.OpenFile(fileAsChar); } } DragFinish(hDrop); } #if 0 // 1. Show a simple window // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window // automatically called "Debug" { static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", (float *)&clear_col); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } // 2. Show another simple window, this time using an explicit Begin/End pair if (show_another_window) { ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello"); ImGui::End(); } #endif #if 0 // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow() if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver); ImGui::ShowTestWindow(&show_test_window); } #endif app.Update(); if (app.m_wantsQuit) { PostMessage(hwnd, WM_QUIT, 0, 0); } if (app.m_wantsTitleChange) { app.m_wantsTitleChange = false; TCHAR title[MAX_PATH + 100]; TCHAR filename[MAX_PATH + 10]; // Convert character encoding if required, and format the window title mbstowcs_s(NULL, filename, _countof(filename), app.m_lastFileOpenName, strlen(app.m_lastFileOpenName)); _stprintf_s(title, _countof(title), L"%s - Open Board Viewer", filename); SetWindowText(hwnd, title); } // Rendering g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false); D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_col.x * 255.0f), (int)(clear_col.y * 255.0f), (int)(clear_col.z * 255.0f), (int)(clear_col.w * 255.0f)); g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); if (g_pd3dDevice->BeginScene() >= 0) { ImGui::Render(); g_pd3dDevice->EndScene(); } g_pd3dDevice->Present(NULL, NULL, NULL, NULL); } ImGui_ImplDX9_Shutdown(); if (g_pd3dDevice) g_pd3dDevice->Release(); if (pD3D) pD3D->Release(); UnregisterClass(class_name, wc.hInstance); DragAcceptFiles(hwnd, false); return 0; }
//---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void MainLoop() { int time = 0; bool reverse = false; for(;;) { MSG msg; if (PeekMessage (&msg,NULL,0,0,PM_NOREMOVE)) { if( msg.message == WM_QUIT ) { return ; } GetMessage (&msg,NULL,0,0); TranslateMessage(&msg); DispatchMessage(&msg); } else { if( time % 120 == 0 ) { // エフェクトの停止 for( size_t i = 0; i < g_handles.size(); i++ ) { g_manager->StopEffect(g_handles[i]); } g_handles.clear(); // エフェクトの再生 for( int i = 0; i < 3; i++ ) { Effekseer::Handle handle = g_manager->Play( g_effects[i], (i - 1) * 10.0f, 0, 0 ); g_handles.push_back(handle); } reverse = !reverse; } // エフェクトの更新処理を行う g_manager->Update(); g_d3d_device->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 ); g_d3d_device->BeginScene(); // エフェクトの描画開始処理を行う。 g_renderer->BeginRendering(); // 視錐体内に存在するエフェクトを計算する。 // カリングの設定がないエフェクトは常に描画される。 g_manager->CalcCulling( g_renderer->GetCameraProjectionMatrix(), false ); // エフェクトを描画する。 g_manager->Draw(); // エフェクトの描画終了処理を行う。 g_renderer->EndRendering(); g_d3d_device->EndScene(); time++; { HRESULT hr; hr = g_d3d_device->Present( NULL, NULL, NULL, NULL ); // デバイスロスト処理 switch ( hr ) { // デバイスロスト case D3DERR_DEVICELOST: while ( FAILED( hr = g_d3d_device->TestCooperativeLevel() ) ) { switch ( hr ) { // デバイスロスト case D3DERR_DEVICELOST: ::SleepEx( 1000, true ); break; // デバイスロスト:リセット可 case D3DERR_DEVICENOTRESET: // デバイスロストの処理を行う前に実行する g_renderer->OnLostDevice(); D3DPRESENT_PARAMETERS d3dp; ZeroMemory(&d3dp, sizeof(d3dp)); d3dp.BackBufferWidth = g_window_width; d3dp.BackBufferHeight = g_window_height; d3dp.BackBufferFormat = D3DFMT_X8R8G8B8; d3dp.BackBufferCount = 1; d3dp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dp.Windowed = TRUE; d3dp.hDeviceWindow = g_window_handle; d3dp.EnableAutoDepthStencil = TRUE; d3dp.AutoDepthStencilFormat = D3DFMT_D16; g_d3d_device->Reset( &d3dp ); // デバイスロストの処理の後に実行する g_renderer->OnResetDevice(); break; } } break; } } } } }