//-------------------------------------------------------------------------------------- // Create any D3D10 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10CreateDevice(ID3D10Device* pDev10, const DXGI_SURFACE_DESC *pBackBufferSurfaceDesc, void* pUserContext) { HRESULT hr; g_pSkyBox = new S3UTSkybox(); //g_pEnvMap = new HDRCubeTexture; V_RETURN(DXUTSetMediaSearchPath(L"..\\Source\\SoftShadows")); V_RETURN(g_DialogResourceManager.OnD3D10CreateDevice(pDev10)); V_RETURN(g_D3DSettingsDlg.OnD3D10CreateDevice(pDev10)); V_RETURN(D3DX10CreateFont(pDev10, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFont10)); g_SampleUI.GetSlider(IDC_LIGHT_SIZE)->SetValue((int)(g_fFilterSize * 200.0)); g_SampleUI.GetComboBox(IDC_SHADOW_ALGORITHM)->SetSelectedByIndex(ssmap.bAccurateShadow == true ? 0 : 1); switch( ShadowAlgorithm ) { case STANDARD_BP: g_ABP.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); break; case BP_MSSM_KERNEL: g_BPMSSMKernel.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); break; case STD_VSM: g_StdVSM.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); break; case MIP_VSM: g_MipVSM.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); break; case HIR_BP: g_HBP.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); break; case BP_GI: g_BPGI.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); break; case STD_PCSS: g_PCSS.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); break; default: break; } g_NoShadow.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_Final.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_GBuffer.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_ScrQuadRender.OnD3D10CreateDevice(g_ABP.m_pEffect,pDev10,pBackBufferSurfaceDesc,pUserContext); ssmap.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_Widget.OnD3D10CreateDevice( pDev10,pBackBufferSurfaceDesc,pUserContext ); g_Blender.OnD3D10CreateDevice( pDev10,pBackBufferSurfaceDesc,pUserContext ); V_RETURN(D3DX10CreateSprite(pDev10, 512, &g_pSprite10)); {//must be after g_ABP create a device,because they uses the members of g_ABP static const D3D10_INPUT_ELEMENT_DESC scenemeshlayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; if (g_MeshLight.Create(pDev10, L"arrow.x", (D3D10_INPUT_ELEMENT_DESC*)scenemeshlayout, 3) != S_OK) { MessageBox(DXUTGetHWND(), L"Could not load geometry from arrow.x", L"Error", MB_OK); exit(0); } D3D10_PASS_DESC PassDesc; V_RETURN(g_NoShadow.m_pEffect->GetTechniqueByName("RenderAcc")->GetPassByIndex(0)->GetDesc(&PassDesc)); V_RETURN(pDev10->CreateInputLayout(scenemeshlayout, 3, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pMaxLayout)); } LoadNewModel(); //V_RETURN( DXUTFindDXSDKMediaFileCch( g_EnvMapFilePath, MAX_PATH_STR, g_DefaultEnvMapName[0] ) ); //g_pEnvMap->OnCreateDevice(pDev10, g_EnvMapFilePath, DXGI_FORMAT_R8G8B8A8_UNORM); g_pSkyBox->OnCreateDevice( pDev10 ); // g_pSkyBox->SetTexture( g_pEnvMap->m_TextureRV ); g_pFloatBufferSurfaceDesc.SampleDesc.Count = pBackBufferSurfaceDesc->SampleDesc.Count; g_pFloatBufferSurfaceDesc.SampleDesc.Quality = pBackBufferSurfaceDesc->SampleDesc.Quality; D3DXVECTOR3 vTmp = D3DXVECTOR3(1, 2, 3); D3DXVec3Normalize(&g_vLightDir, &vTmp); SAFE_RELEASE(g_pRenderState); D3D10_RASTERIZER_DESC RasterizerState; RasterizerState.FillMode = D3D10_FILL_SOLID; RasterizerState.CullMode = D3D10_CULL_FRONT; RasterizerState.FrontCounterClockwise = true; RasterizerState.DepthBias = false; RasterizerState.DepthBiasClamp = 0.1; RasterizerState.SlopeScaledDepthBias = 0; RasterizerState.DepthClipEnable = true; RasterizerState.ScissorEnable = false; RasterizerState.MultisampleEnable = false; RasterizerState.AntialiasedLineEnable = false; V(pDev10->CreateRasterizerState(&RasterizerState, &g_pRenderState)); SAFE_RELEASE(g_pDSState); D3D10_DEPTH_STENCIL_DESC DSState; ZeroMemory(&DSState, sizeof(DSState)); DSState.DepthEnable = true; DSState.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL; DSState.DepthFunc = D3D10_COMPARISON_LESS_EQUAL; V(pDev10->CreateDepthStencilState(&DSState, &g_pDSState)); //light management for( int light_idx = 0; light_idx < NUM_LIGHT; ++light_idx ) { g_pLightLumiBuffer[light_idx] = new RenderObject( "RenderScreenPixelPos" ); g_pLightLumiBuffer[light_idx] ->OnD3D10CreateDevice( NULL,pDev10, pBackBufferSurfaceDesc, pUserContext); } g_pBlendBuffer = new RenderObject( "RenderScreenPixelPos" ); g_pBlendBuffer->OnD3D10CreateDevice( NULL,pDev10, pBackBufferSurfaceDesc, pUserContext); g_pWidgetBuffer = new RenderObject( "RenderScreenPixelPos" );//fake tech name,we dont want to use it. We only want to utilize its buffers g_pWidgetBuffer->OnD3D10CreateDevice( NULL,pDev10, pBackBufferSurfaceDesc, pUserContext); //-------------------------------------------------------------------------------------------------------- return S_OK; }
static void TrVertexFunc_TransformByModelviewAndNormalize( const GLfloat *vertex, float *output ) { D3DXVec3TransformCoord((D3DXVECTOR3*)output, (D3DXVECTOR3*)vertex, D3DGlobal.modelviewMatrixStack->top()); D3DXVec3Normalize((D3DXVECTOR3*)output, (D3DXVECTOR3*)output); }
//플레이어를 로컬 x-축, y-축, z-축을 중심으로 회전한다. void CObject_Player::Rotate(float x, float y, float z) { D3DXMATRIX mtxRotate; DWORD nCurrentCameraMode = m_pCamera->GetMode(); //1인칭 카메라 또는 3인칭 카메라의 경우 플레이어의 회전은 약간의 제약이 따른다. if ((nCurrentCameraMode == FIRST_PERSON_CAMERA) || (nCurrentCameraMode == THIRD_PERSON_CAMERA)) { /*로컬 x-축을 중심으로 회전하는 것은 고개를 앞뒤로 숙이는 동작에 해당한다. 그러므로 x-축을 중심으로 회전하는 각도는 -89.0~+89.0도 사이로 제한한다. x는 현재의 m_fPitch에서 실제 회전하는 각도이므로 x만큼 회전한 다음 Pitch가 +89도 보다 크거나 -89도 보다 작으면 m_fPitch가 +89도 또는 -89도가 되도록 회전각도(x)를 수정한다.*/ if (x != 0.0f) { m_fPitch += x; if (m_fPitch > +89.0f) { x -= (m_fPitch - 89.0f); m_fPitch = +89.0f; } if (m_fPitch < -89.0f) { x -= (m_fPitch + 89.0f); m_fPitch = -89.0f; } } //로컬 y-축을 중심으로 회전하는 것은 몸통을 돌리는 것이므로 회전 각도의 제한이 없다. if (y != 0.0f) { m_fYaw += y; if (m_fYaw > 360.0f) m_fYaw -= 360.0f; if (m_fYaw < 0.0f) m_fYaw += 360.0f; } /*로컬 z-축을 중심으로 회전하는 것은 몸통을 좌우로 기울이는 것이므로 회전 각도는 -20.0~+20.0도 사이로 제한된다. z는 현재의 m_fRoll에서 실제 회전하는 각도이므로 z만큼 회전한 다음 m_fRoll이 +20도 보다 크거나 -20도보다 작으면 m_fRoll이 +20도 또는 -20도가 되도록 회전각도(z)를 수정한다.*/ if (z != 0.0f) { m_fRoll += z; if (m_fRoll > +20.0f) { z -= (m_fRoll - 20.0f); m_fRoll = +20.0f; } if (m_fRoll < -20.0f) { z -= (m_fRoll + 20.0f); m_fRoll = -20.0f; } } //카메라를 x, y, z 만큼 회전한다. 플레이어를 회전하면 카메라가 회전하게 된다. m_pCamera->Rotate(x, y, z); /*플레이어를 회전한다. 1인칭 카메라 또는 3인칭 카메라에서 플레이어의 회전은 로컬 y-축에서만 일어난다. 플레이어의 로컬 y-축(Up 벡터)을 기준으로 로컬 z-축(Look 벡터)와 로컬 x-축(Right 벡터)을 회전시킨다. 기본적으로 Up 벡터를 기준으로 회전하는 것은 플레이어가 똑바로 서있는 것을 가정한다는 의미이다.*/ if (y != 0.0f) { D3DXMatrixRotationAxis(&mtxRotate, &m_d3dxvUp, (float)D3DXToRadian(y)); D3DXVec3TransformNormal(&m_d3dxvLook, &m_d3dxvLook, &mtxRotate); D3DXVec3TransformNormal(&m_d3dxvRight, &m_d3dxvRight, &mtxRotate); } } else if (nCurrentCameraMode == SPACESHIP_CAMERA) { /*스페이스-쉽 카메라에서 플레이어의 회전은 회전 각도의 제한이 없다. 그리고 모든 축을 중심으로 회전을 할 수 있다.*/ m_pCamera->Rotate(x, y, z); if (x != 0.0f) { D3DXMatrixRotationAxis(&mtxRotate, &m_d3dxvRight, (float)D3DXToRadian(x)); D3DXVec3TransformNormal(&m_d3dxvLook, &m_d3dxvLook, &mtxRotate); D3DXVec3TransformNormal(&m_d3dxvUp, &m_d3dxvUp, &mtxRotate); } if (y != 0.0f) { D3DXMatrixRotationAxis(&mtxRotate, &m_d3dxvUp, (float)D3DXToRadian(y)); D3DXVec3TransformNormal(&m_d3dxvLook, &m_d3dxvLook, &mtxRotate); D3DXVec3TransformNormal(&m_d3dxvRight, &m_d3dxvRight, &mtxRotate); } if (z != 0.0f) { D3DXMatrixRotationAxis(&mtxRotate, &m_d3dxvLook, (float)D3DXToRadian(z)); D3DXVec3TransformNormal(&m_d3dxvUp, &m_d3dxvUp, &mtxRotate); D3DXVec3TransformNormal(&m_d3dxvRight, &m_d3dxvRight, &mtxRotate); } } /*회전으로 인해 플레이어의 로컬 x-축, y-축, z-축이 서로 직교하지 않을 수 있으므로 z-축(LookAt 벡터)을 기준으로 하여 서로 직교하고 단위벡터가 되도록 한다.*/ D3DXVec3Normalize(&m_d3dxvLook, &m_d3dxvLook); D3DXVec3Cross(&m_d3dxvRight, &m_d3dxvUp, &m_d3dxvLook); D3DXVec3Normalize(&m_d3dxvRight, &m_d3dxvRight); D3DXVec3Cross(&m_d3dxvUp, &m_d3dxvLook, &m_d3dxvRight); D3DXVec3Normalize(&m_d3dxvUp, &m_d3dxvUp); }
void Minion::ProcessState() { D3DXVECTOR3 pos = position; D3DXVECTOR3 direction; D3DXVECTOR3 right; D3DXVECTOR3 up = D3DXVECTOR3(0, 1, 0); float toPlayerRotationAngle; D3DXMatrixRotationY(&rotation, rotationAngle); D3DXVECTOR3 forward = D3DXVECTOR3(rotation._31, rotation._32, rotation._33); if (target) { direction = *target - position; D3DXVec3Normalize(&direction, &direction); D3DXVec3Cross(&right, &up, &direction); toPlayerRotationAngle = atan2f(direction.x,direction.z); } else direction = forward; switch (currentState) { case CharacterState::CHARACTER_IDLE: { float tick = GameManager::GetTick(); idleTime += tick; if (hm->GetHeight(pos.y, pos.x, pos.z) != false) { } SelectPatrolPosition(); if (!player->GetIsDead()) { ChangeCharacterState(CharacterState::CHARACTER_PATROL); } else { if (idleTime < (float)rand() / RAND_MAX * 2) { ChangeCharacterState(CharacterState::CHARACTER_PATROL); } } }break; case CharacterState::CHARACTER_PATROL: { if (hm->GetHeight(pos.y, pos.x, pos.z) != false) { if (player) { if (Collision::IsSphereToSphere(sight_wide, player->GetBoundingSphereValue())) { D3DXVECTOR3 toPlayer = player->GetPosition() - position; D3DXVec3Normalize(&toPlayer, &toPlayer); //cos60°ú ºñ±³¸¦ Çؼ ³»Àû°ªÀÌ ¾È¿¡ ÀÖÀ¸¸é ¦i¾Æ°¨ //Áß°£¿¡ ¾î´ÀÂÊÀ¸·Î µ¹¾Æ¾ß ÇÒÁö ¿ø·¡ ȸÀü°¢¿¡ 90À» ´õÇؼ ºÎÈ£°¡ ¹Ù²î´ÂÁö ÆÇÁ¤ÇÑ´Ù. DX±âº» ȸÀüÀº CWÀÌ´Ù. if (D3DXVec3Dot(&forward, &toPlayer) > cosf(D3DX_PI*0.33f)) { if (D3DXVec3Dot(&toPlayer, &D3DXVECTOR3(cosf(rotationAngle + D3DX_PI*0.5f), 0, sinf(rotationAngle + D3DX_PI*0.5f))) > 0) { rotateCW = true; } else rotateCW = false; target = player->GetPositionAddress(); ChangeCharacterState(CharacterState::CHARACTER_TRACE); } else { //½Ã¾ß°¢ ¹Û¿¡ ÀÖ´Ù. //Á¼Àº ¿ø ¾È¿¡ µé¾î¿À¸é ÆÇÁ¤À» ÇÔ. µÑ´Ù ¾Æ´Ï¸é °¡´ø ±æÀ» °£´Ù. if (Collision::IsSphereToSphere(sight_narrow, player->GetBoundingSphereValue())) { if (D3DXVec3Dot(&toPlayer, &D3DXVECTOR3(cosf(rotationAngle + D3DX_PI*0.5f), 0, sinf(rotationAngle + D3DX_PI*0.5f))) > 0) { rotateCW = true; } else rotateCW = false; target = player->GetPositionAddress(); if (player->GetIsDead()) { } else { ChangeCharacterState(CharacterState::CHARACTER_TRACE); } } } } } if (isHit) { hp -= inDamage; if (hp > 0) { ChangeCharacterState(CharacterState::CHARACTER_HIT); } else ChangeCharacterState(CharacterState::CHARACTER_DEAD); } } }break; case CharacterState::CHARACTER_ATTACK: { float tick = (float)GameManager::GetTick(); currentAnimationTime += tick; attackSphere.center = meshCenter+position + direction*0.5f; if (currentAnimationTime >= selectedAnimationLength) { ChangeCharacterState(CharacterState::CHARACTER_TRACE); } else { bool playerInivisible = player->GetInvisible(); bool playerHit = player->GetIsHit(); bool playerDead = player->GetIsDead(); if (!playerInivisible && !playerHit&&!playerDead&&!attackHit) { if(Collision::IsSphereToSphere(attackSphere, player->GetBoundingSphereValue())) { if (Collision::IsBoxToSphere(player->GetBoundingBoxValue(), attackSphere)) { DealDamage(player, ATTACK_DAMAGE); attackHit = true; } } } if (isHit) { hp -= inDamage; if (hp > 0) { ChangeCharacterState(CharacterState::CHARACTER_HIT); } else ChangeCharacterState(CharacterState::CHARACTER_DEAD); } } } break; case CharacterState::CHARACTER_DODGE: { } break; case CharacterState::CHARACTER_HIT: { float tick = (float)GameManager::GetTick(); currentAnimationTime += tick; animController->SetTrackSpeed(0, 0.2f); if (currentAnimationTime >= selectedAnimationLength*5.0f) { isHit = false; ChangeCharacterState(CharacterState::CHARACTER_TRACE); } } break; case CharacterState::CHARACTER_TRACE: { if (hm->GetHeight(pos, pos.x, pos.z) != false) { float tick = (float)GameManager::GetTick(); bool move = false; D3DXVECTOR3 collisionDirection; if (CollisionMonsters(&collisionDirection)) { direction += collisionDirection; D3DXVec3Normalize(&direction, &direction); } if (Collision::IsSphereToSphere(player->GetBoundingSphereValue(), boundingSphere)) { attackHit = false; ChangeCharacterState(CharacterState::CHARACTER_ATTACK); } else { pos -= (-direction * moveSpeed * tick); forwardBoundingSphere.center = pos; } rotationAngle = toPlayerRotationAngle; } if (isHit) { hp -= inDamage; if (hp > 0) { ChangeCharacterState(CharacterState::CHARACTER_HIT); } else ChangeCharacterState(CharacterState::CHARACTER_DEAD); } if (player->GetIsDead()) { ChangeCharacterState(CharacterState::CHARACTER_PATROL); } } break; case CharacterState::CHARACTER_RETURN: { } break; case CharacterState::CHARACTER_DEAD: { float tick = (float)GameManager::GetTick(); currentAnimationTime += tick; if (currentAnimationTime >= selectedAnimationLength) { ChangeCharacterState(CharacterState::CHARACTER_DIED); } } break; case CharacterState::CHARACTER_DIED: { float tick=GameManager::GetTick(); animController->SetTrackSpeed(0, 0.0f); currentAnimationTime += tick; if (pos.y > -10.0) { pos.y -= tick; } else { isDead = true; } } break; } position = pos; }
void SunLight::Render() { D3DXVec3Normalize((D3DXVECTOR3*)&mD3DLight.Direction, &Node::GetFrontVector()); Light::Render(); }
//-------------------------------------------------------------------------------------- // FillGrid_WithNormals_Indexed // Creates a regular grid of indexed triangles, including normals. // // Parameters: // // IN // pd3dDevice: The D3D device // dwWidth, dwLength: Number of grid vertices in X and Z direction // fGridSizeX, fGridSizeZ: Grid extents in local space units // // OUT // lplpVB: A pointer to the vertex buffer containing grid vertices // lplpIB: A pointer to the index buffer containing grid indices //-------------------------------------------------------------------------------------- void FillGrid_WithNormals_Indexed( ID3D11Device* pd3dDevice, DWORD dwWidth, DWORD dwLength, float fGridSizeX, float fGridSizeZ, ID3D11Buffer** lplpVB, ID3D11Buffer** lplpIB ) { HRESULT hr; DWORD nNumVertex = ( dwWidth + 1 ) * ( dwLength + 1 ); DWORD nNumIndex = 3 * 2 * dwWidth * dwLength; float fStepX = fGridSizeX / dwWidth; float fStepZ = fGridSizeZ / dwLength; // Allocate memory for buffer of vertices in system memory EXTENDEDVERTEX* pVertexBuffer = new EXTENDEDVERTEX[nNumVertex]; EXTENDEDVERTEX* pVertex = &pVertexBuffer[0]; // Fill vertex buffer for ( DWORD i=0; i<=dwLength; ++i ) { for ( DWORD j=0; j<=dwWidth; ++j ) { pVertex->x = -fGridSizeX/2.0f + j*fStepX; pVertex->y = 0.0f; pVertex->z = fGridSizeZ/2.0f - i*fStepZ; pVertex->nx = 0.0f; pVertex->ny = 0.0f; pVertex->nz = 0.0f; pVertex->u = 0.0f + ( (float)j / dwWidth ); pVertex->v = 0.0f + ( (float)i / dwLength ); pVertex++; } } // Allocate memory for buffer of indices in system memory WORD* pIndexBuffer = new WORD [nNumIndex]; WORD* pIndex = &pIndexBuffer[0]; // Fill index buffer for ( DWORD i=0; i<dwLength; ++i ) { for ( DWORD j=0; j<dwWidth; ++j ) { *pIndex++ = (WORD)( i * ( dwWidth+1 ) + j ); *pIndex++ = (WORD)( i * ( dwWidth+1 ) + j + 1 ); *pIndex++ = (WORD)( ( i+1 ) * ( dwWidth+1 ) + j ); *pIndex++ = (WORD)( ( i+1 ) * (dwWidth+1) + j ); *pIndex++ = (WORD)( i * (dwWidth+1) + j + 1 ); *pIndex++ = (WORD)( ( i+1 ) * (dwWidth+1) + j + 1 ); } } // Set initial data info D3D11_SUBRESOURCE_DATA InitData; InitData.pSysMem = pIndexBuffer; // Fill DX11 index buffer description D3D11_BUFFER_DESC bd; bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( WORD ) * nNumIndex; bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; // Create DX11 index buffer specifying initial data hr = pd3dDevice->CreateBuffer( &bd, &InitData, lplpIB ); if( FAILED( hr ) ) { OutputDebugString( L"FillGrid_WithNormals_Indexed: Failed to create index buffer.\n" ); return; } DXUT_SetDebugName( *lplpIB, "FillGrid IB Nrmls" ); // Write normals into vertex buffer pVertex = &pVertexBuffer[0]; // Loop through all indices for ( DWORD i=0; i<nNumIndex/3; ++i ) { WORD i1 = pIndexBuffer[3*i + 0]; WORD i2 = pIndexBuffer[3*i + 1]; WORD i3 = pIndexBuffer[3*i + 2]; D3DXVECTOR3 Normal = CalculateTriangleNormal( (D3DXVECTOR3 *)&pVertexBuffer[i1].x, (D3DXVECTOR3 *)&pVertexBuffer[i2].x, (D3DXVECTOR3 *)&pVertexBuffer[i3].x ); // Add normal to each vertex for this triangle *( (D3DXVECTOR3 *)&pVertexBuffer[i1].nx ) += Normal; *( (D3DXVECTOR3 *)&pVertexBuffer[i2].nx ) += Normal; *( (D3DXVECTOR3 *)&pVertexBuffer[i3].nx ) += Normal; } // Final normalization pass for ( DWORD i=0; i<nNumVertex; ++i ) { D3DXVec3Normalize( (D3DXVECTOR3 *)&pVertexBuffer[i].nx, (D3DXVECTOR3 *)&pVertexBuffer[i].nx ); } // Set initial data info InitData.pSysMem = pVertexBuffer; // Fill DX11 vertex buffer description bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( EXTENDEDVERTEX ) * nNumVertex; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; // Create DX11 vertex buffer specifying initial data hr = pd3dDevice->CreateBuffer( &bd, &InitData, lplpVB ); if( FAILED( hr ) ) { OutputDebugString( L"FillGrid_WithNormals_Indexed: Failed to create vertex buffer.\n" ); return; } DXUT_SetDebugName( *lplpVB, "FillGrid VB Nrmls Idx" ); // Release host memory index buffer delete [] pIndexBuffer; // Release host memory vertex buffer delete [] pVertexBuffer; }
//============================================================================= // 更新処理 //============================================================================= void UpdateEnemy(float fTimeSpeed) { CAMERA *pCamera = GetCamera(); PLAYER *pPlayer = GetPlayer(); int nCountAlive = 0; //PrintDebugProc("enemy mark %d\n", g_enemy[0].nSeePFrame); for(int nCntEnemy = 0; nCntEnemy < MAX_ENEMY; nCntEnemy++) { if(g_enemy[nCntEnemy].bUse) { nCountAlive++; {//プレイヤーに気づく判断処理 if( !HitCheckMeshWall( g_enemy[nCntEnemy].pos, pCamera->posV, NULL, NULL) && pPlayer->bAlive && //壁に遮られたか //HitCheckBall( g_enemy[nCntEnemy].pos, 1000.0f, pCamera->posV, 20.0f) && //一定の距離以内 HitCheckViewArea( g_enemy[nCntEnemy].pos, pCamera->posV, g_enemy[nCntEnemy].rot, D3DXToRadian( 90.0f) ) && //後ろには見えない !IsDebugMode()) //デバッグモードのときに、当たり判定はなし { if( g_enemy[nCntEnemy].nSeePFrame <= 1000) g_enemy[nCntEnemy].nSeePFrame++; if( g_enemy[nCntEnemy].nSeePFrame >= 50) { g_enemy[nCntEnemy].bSeePlayer = true; //プレイヤーを見た時の情報を保存 if( g_enemy[nCntEnemy].bPatrol) { //びっくりマークを設定 SetFlashMessage(MSG_EXCLAMATION); g_enemy[nCntEnemy].bPatrol = false; g_enemy[nCntEnemy].posPatrol = g_enemy[nCntEnemy].pos; g_enemy[nCntEnemy].rotPatrol = g_enemy[nCntEnemy].rotTarget; } } } else if( HitCheckBall( g_enemy[nCntEnemy].pos, 120.0f, pCamera->posV, 20.0f) ) //一定の距離以内 { if( g_enemy[nCntEnemy].nSeePFrame <= 65535) g_enemy[nCntEnemy].nSeePFrame++; if( g_enemy[nCntEnemy].nSeePFrame >= 50) { g_enemy[nCntEnemy].bSeePlayer = true; //プレイヤーを見た時の情報を保存 if( g_enemy[nCntEnemy].bPatrol) { g_enemy[nCntEnemy].bPatrol = false; g_enemy[nCntEnemy].posPatrol = g_enemy[nCntEnemy].pos; g_enemy[nCntEnemy].rotPatrol = g_enemy[nCntEnemy].rotTarget; } } } else { if( g_enemy[nCntEnemy].nSeePFrame > 0) { g_enemy[nCntEnemy].nSeePFrame--; } g_enemy[nCntEnemy].bSeePlayer = false; } } //CoolDown if( g_enemy[nCntEnemy].nCoolDown > 0) { g_enemy[nCntEnemy].nCoolDown -= 1 * fTimeSpeed; if(g_enemy[nCntEnemy].nCoolDown <= 0) { g_enemy[nCntEnemy].nCoolDown = -1; g_enemy[nCntEnemy].bShot = false; } } //プレイヤーに気づいたら、行動処理 if( g_enemy[nCntEnemy].bSeePlayer || g_enemy[nCntEnemy].nSeePFrame >= 50) { if( !g_enemy[nCntEnemy].bEscaping) { //向き g_enemy[nCntEnemy].rotTarget = GetRotationAngle( g_enemy[nCntEnemy].pos, pCamera->posV, g_enemy[nCntEnemy].rot); } //弾を発射 if(!g_enemy[nCntEnemy].bShot) { //向き g_enemy[nCntEnemy].rot = GetRotationAngle( g_enemy[nCntEnemy].pos, pCamera->posV, g_enemy[nCntEnemy].rot); if(g_enemy[nCntEnemy].type == ENEMY_RED) { for(int cnt = 0; cnt < 3; cnt++) { SetEnemyBullet( g_enemy[nCntEnemy].pos, pCamera->posV + D3DXVECTOR3( rand() % 60 - 30, rand() % 40 - 20, rand() % 60 - 30)); } g_enemy[nCntEnemy].bShot = true; g_enemy[nCntEnemy].nCoolDown = COOLDOWN + rand() % 60; PlaySound(SOUND_LABEL_SE_ESHOT); } else if(g_enemy[nCntEnemy].type == ENEMY_BLUE) { SetEnemyBullet( g_enemy[nCntEnemy].pos, pCamera->posV); g_enemy[nCntEnemy].bShot = true; g_enemy[nCntEnemy].nCoolDown = COOLDOWN/2 + rand() % 60; PlaySound(SOUND_LABEL_SE_ESHOT); } else { SetEnemyBullet( g_enemy[nCntEnemy].pos, pCamera->posV); g_enemy[nCntEnemy].bShot = true; g_enemy[nCntEnemy].nCoolDown = COOLDOWN + rand() % 60; PlaySound(SOUND_LABEL_SE_ESHOT); } } } else { if( g_enemy[nCntEnemy].bPatrol) { //nothing } else { //パトロールに戻る g_enemy[nCntEnemy].rotTarget = GetRotationAngle( g_enemy[nCntEnemy].pos, g_enemy[nCntEnemy].posPatrol, g_enemy[nCntEnemy].rot); D3DXVECTOR3 vec = g_enemy[nCntEnemy].pos - g_enemy[nCntEnemy].posPatrol; if( D3DXVec3Length( &vec) < VALUE_MOVE) { g_enemy[nCntEnemy].bPatrol = true; g_enemy[nCntEnemy].pos = g_enemy[nCntEnemy].posPatrol; g_enemy[nCntEnemy].rotTarget = g_enemy[nCntEnemy].rotPatrol; } } } //弾キレ、逃げる処理 //if( g_enemy[nCntEnemy].bShot && !g_enemy[nCntEnemy].bEscaping) //{ // float movRot = rand() % 180 - 90; // g_enemy[nCntEnemy].rotTarget.y = g_enemy[nCntEnemy].rot.y + D3DXToRadian(movRot); // if( g_enemy[nCntEnemy].rotTarget.y > D3DX_PI) // { // g_enemy[nCntEnemy].rotTarget.y -= D3DX_PI * 2.0f; // } // g_enemy[nCntEnemy].bEscaping = true; //} bool bMove = true; //プレイヤーに近づき過ぎないように D3DXVECTOR3 vec = g_enemy[nCntEnemy].pos - pPlayer->pos; if( (D3DXVec3Length(&vec) < 200.0f) && g_enemy[nCntEnemy].bSeePlayer) { bMove = false; } {//移動処理 if( bMove) { //移動慣性の初期化 g_enemy[nCntEnemy].move.x = VALUE_MOVE; g_enemy[nCntEnemy].move.z = VALUE_MOVE; if(g_enemy[nCntEnemy].type == ENEMY_BLUE) { g_enemy[nCntEnemy].move.x = 0; g_enemy[nCntEnemy].move.z = 0; } } //時計回り、または逆時計回りを決める g_enemy[nCntEnemy].rotAngle = Get2VecRotAngle( g_enemy[nCntEnemy].rot, g_enemy[nCntEnemy].rotTarget, DIVIDE_ROTATE, -1); //回転慣性 g_enemy[nCntEnemy].rotAngle += (-g_enemy[nCntEnemy].rotAngle) * 0.001f; //モデルY軸角度修正 if(g_enemy[nCntEnemy].rot.y > D3DX_PI) { g_enemy[nCntEnemy].rot.y = g_enemy[nCntEnemy].rot.y - D3DX_PI*2; } else if(g_enemy[nCntEnemy].rot.y < 0.0f - D3DX_PI) { g_enemy[nCntEnemy].rot.y = g_enemy[nCntEnemy].rot.y + D3DX_PI*2; } //次の回転位置に到着したら if( fabs(g_enemy[nCntEnemy].rot.y - g_enemy[nCntEnemy].rotTarget.y) < VALUE_ROTATE && fabs(g_enemy[nCntEnemy].rot.x - g_enemy[nCntEnemy].rotTarget.x) < VALUE_ROTATE && fabs(g_enemy[nCntEnemy].rot.z - g_enemy[nCntEnemy].rotTarget.z) < VALUE_ROTATE ) { g_enemy[nCntEnemy].rot = g_enemy[nCntEnemy].rotTarget; g_enemy[nCntEnemy].rotAngle = D3DXVECTOR3( 0, 0, 0); } else //次の回転位置にまだ到着してない { g_enemy[nCntEnemy].rot += g_enemy[nCntEnemy].rotAngle * fTimeSpeed; } //回転していない時 if(g_enemy[nCntEnemy].rotAngle == D3DXVECTOR3( 0, 0, 0)) { //慣性処理 g_enemy[nCntEnemy].move.x -= g_enemy[nCntEnemy].move.x * 0.05f; g_enemy[nCntEnemy].move.z -= g_enemy[nCntEnemy].move.z * 0.05f; D3DXVECTOR3 tNextPos = g_enemy[nCntEnemy].pos; tNextPos.x += g_enemy[nCntEnemy].move.x * sinf(g_enemy[nCntEnemy].rot.y); tNextPos.z += g_enemy[nCntEnemy].move.z * cosf(g_enemy[nCntEnemy].rot.y); D3DXVECTOR3 tSphere = D3DXVECTOR3( 0, 0, 0); D3DXVECTOR3 front = tNextPos - g_enemy[nCntEnemy].pos; D3DXVec3Normalize( &tSphere, &front); tSphere *= MODEL_SPHERE; //壁の法線ベクトルを取得変数の初期化 D3DXVECTOR3 wall_nor = D3DXVECTOR3(0,0,0); //Side g_enemy[nCntEnemy].posLSide.x = g_enemy[nCntEnemy].pos.x + 15.0f * sinf(g_enemy[nCntEnemy].rotTarget.y + D3DXToRadian(-90.0f)); g_enemy[nCntEnemy].posLSide.z = g_enemy[nCntEnemy].pos.z + 15.0f * cosf(g_enemy[nCntEnemy].rotTarget.y + D3DXToRadian(-90.0f)); g_enemy[nCntEnemy].posRSide.x = g_enemy[nCntEnemy].pos.x + 15.0f * sinf(g_enemy[nCntEnemy].rotTarget.y + D3DXToRadian(90.0f)); g_enemy[nCntEnemy].posRSide.z = g_enemy[nCntEnemy].pos.z + 15.0f * cosf(g_enemy[nCntEnemy].rotTarget.y + D3DXToRadian(90.0f)); //壁に当たったら if( HitCheckMeshWall( g_enemy[nCntEnemy].posLSide, g_enemy[nCntEnemy].posLSide + tSphere, &wall_nor, NULL) || HitCheckMeshWall( g_enemy[nCntEnemy].posRSide, g_enemy[nCntEnemy].posRSide + tSphere, &wall_nor, NULL) ) { if( g_enemy[nCntEnemy].bSeePlayer || !g_enemy[nCntEnemy].bPatrol) { //壁ずり処理:移動ベクトルを修正 GetWallScratchVector( &front, front, wall_nor); D3DXVec3Normalize( &tSphere, &front); tSphere *= MODEL_SPHERE; if( !HitCheckMeshWall( g_enemy[nCntEnemy].pos, g_enemy[nCntEnemy].pos + tSphere, &wall_nor, NULL) ) { //移動処理 g_enemy[nCntEnemy].pos += front; } } if( g_enemy[nCntEnemy].bPatrol) { //180反転 g_enemy[nCntEnemy].rotTarget.y = g_enemy[nCntEnemy].rot.y + D3DXToRadian(180.0f); if( g_enemy[nCntEnemy].rotTarget.y > D3DX_PI) { g_enemy[nCntEnemy].rotTarget.y -= D3DX_PI * 2.0f; } } } else { //移動処理 g_enemy[nCntEnemy].pos += front * fTimeSpeed; } } } //shadow SetPositionShadow( g_enemy[nCntEnemy].nIdxShadow, g_enemy[nCntEnemy].pos); } } if( nCountAlive == 0) { PlaySound( SOUND_LABEL_SE_CLEAR); SetGameStep(STEP_CLEAR); } //PrintDebugProc("\n敵の位置:(X:%f, Y:%f, Z:%f)\n", g_enemy[0].pos.x, g_enemy[0].pos.y, g_enemy[0].pos.z); //PrintDebugProc("敵の向き :(X:%f, Y:%f, Z:%f)\n", g_enemy[0].rot.x, D3DXToDegree(g_enemy[0].rot.y), g_enemy[0].rot.z); //if( g_enemy[0].bSeePlayer) PrintDebugProc("see Player\n"); //if( g_enemy[0].bPatrol)PrintDebugProc("patral\n"); }
void Enemy::update(float dt) { //No keyboard input, just preset patterns gameTime += dt; elapsed += dt; bool moving = false; bool sprinting = false; switch(aiMode) { case RANDOM: //Check if first time through. If so, select random waypoint within bounds //if(aiPath.size() == 0) { // /*float xRange; // float zRange; // float tempX1, tempX2, xOffset; // float tempZ1, tempZ2, zOffset; // // if(xBounds.x < 0) {tempX1 = - xBounds.x;} else {tempX1 = xBounds.x;} // if(xBounds.y < 0) {tempX2 = - xBounds.y;} else {tempX2 = xBounds.y;} // if(zBounds.x < 0) {tempZ1 = - zBounds.x;} else {tempZ1 = zBounds.x;} // if(zBounds.y < 0) {tempZ2 = - zBounds.y;} else {tempZ2 = zBounds.y;} // xRange = tempX1 + tempX2; // zRange = tempZ1 + tempZ2;*/ // float xRand, zRand; // std::random_device rseed; // std::mt19937 rng(rseed()); // std::uniform_int<int> dist1(xBounds.x,xBounds.y); // xRand = dist1(rng); // std::uniform_int<int> dist2(zBounds.x,zBounds.y); // zRand = dist2(rng); // aiPath.push_back(Vector3(xRand, position.y, zRand)); // direction = aiPath[0] - position; // D3DXVec3Normalize(&direction, &direction); //} ////Check if close to destination //// If so, calculate and set new destination //if(((position.x < (aiPath[pathIndex].x + 1.0f)) && (position.x > (aiPath[pathIndex].x - 1.0f))) //&&((position.z < (aiPath[pathIndex].z + 1.0f)) && (position.z > (aiPath[pathIndex].z - 1.0f)))) //{ // float xRand, zRand; // std::random_device rseed; // std::mt19937 rng(rseed()); // std::uniform_int<int> dist1(xBounds.x, xBounds.y); // xRand = dist1(rng); // std::uniform_int<int> dist2(zBounds.x, zBounds.y); // zRand = dist2(rng); // aiPath[0] = Vector3(xRand, position.y, zRand); // direction = aiPath[0] - position; // D3DXVec3Normalize(&direction, &direction); // elapsed = 0; //} ////Move toward waypoint, updating both position and direction //if(pathIndex == 0) // OutputDebugString(L"0\n"); //else // OutputDebugString(L"1\n"); //position += direction * speed * dt; //moving = true; break; case PATH: //Check if close to waypoint // If so, calculate and set new waypoint if(((position.x < (aiPath[pathIndex].x + 1.0f)) && (position.x > (aiPath[pathIndex].x - 1.0f))) &&((position.z < (aiPath[pathIndex].z + 1.0f)) && (position.z > (aiPath[pathIndex].z - 1.0f)))) { if(pathIndex == aiPath.size() - 1) { pathDir = -1; } if (pathIndex == 0) { pathDir = 1; } pathIndex += pathDir; if (pathIndex > aiPath.size() - 1) pathIndex = aiPath.size() - 1; direction = aiPath[pathIndex] - position; D3DXVec3Normalize(&direction, &direction); elapsed = 0; } //Move toward waypoint, updating position direction = aiPath[pathIndex] - position; if (aiPath.size() == 1) { direction = Vector3(0.0f, 0.0f, 1.0f); speed = 0; } D3DXVec3Normalize(&direction, &direction); position += direction * speed * dt; moving = true; break; } //direction.x = sinf(dirTheta); //direction.z = cosf(dirTheta); torso->setDirection(direction); torso->setPosition(Vector3(position.x, position.y + height * 0.5f, position.z)); spotLight->pos = position + Vector3(0.0f, head->getPosition().y, 0.0f) + torso->getDirection() * depth; Vector3 lightTarget = position + direction * 20; Vector3 lightLookAt = lightTarget - spotLight->pos; //spotLight->pos.y += 10.0f; //Vector3 normalizedDir = (torso->getDirection()*12)-torso->getPosition(); D3DXVec3Normalize(&spotLight->dir, &(lightLookAt)); // leg movement float normPos = 175; float legRot = sin(elapsed * limbSpeed); float phase = 0; float shinRot = sin(elapsed * limbSpeed + phase); float legRange = 0; float legOffset = 0; float shinRange = 0; float shinOffset = 10; if (moving && !sprinting) // set the leg position variables { //swing legs back and forth if moving normPos = 175; legRot = sin(elapsed * limbSpeed); phase = 1.414f; shinRot = sin(elapsed * limbSpeed + phase); legRange = 20; legOffset = 0; shinRange = 25; shinOffset = 15; } else if (moving && sprinting) { normPos = 175; legRot = sin(elapsed * limbSpeed); phase = 1.414f; shinRot = sin(elapsed * limbSpeed + phase); legRange = 90; legOffset = -45; shinRange = 80; shinOffset = 55; } // set the leg positions rightLeg->setRotX(ToRadian(normPos + (-legRot * legRange + legOffset))); leftLeg->setRotX(ToRadian(normPos + (legRot * legRange + legOffset))); rightShin->setRotX(ToRadian(shinRot * shinRange + shinOffset)); leftShin->setRotX(ToRadian(-shinRot * shinRange + shinOffset)); //if (keyPressed(PlayerJumpKey)) //{ // torso->reduceScaleByFactor(1.01f); //} // arm movement // rotate arms down rightArm->setRotX(ToRadian(180)); leftArm->setRotX(ToRadian(180)); if (moving && !sprinting) { //swing arms back and forth if moving float normPos = 180; float armRot = sin(elapsed * limbSpeed); float armRange = 10; rightArm->setRotX(ToRadian(normPos + (armRot * armRange))); leftArm->setRotX(ToRadian(normPos + (-armRot * armRange))); } else if (moving && sprinting) { float normPos = 180; float armRot = sin(elapsed * limbSpeed); float armRange = 30; float armOffset = 10; rightArm->setRotX(ToRadian(normPos + (armRot * armRange) + armOffset)); leftArm->setRotX(ToRadian(normPos + (-armRot * armRange) + armOffset)); } else { //move arms by side if not moving rightArm->setRotX(ToRadian(180)); leftArm->setRotX(ToRadian(180)); } //Update the bodyparts head->update(dt); rightArm->update(dt); leftArm->update(dt); rightLeg->update(dt); leftLeg->update(dt); rightShin->update(dt); leftShin->update(dt); torso->update(dt); }
bool XProc_DeleteCharacter::Process( void ) { if(g_pTitleFlashObject) g_pTitleFlashObject->PlayTimerFire(); g_MessageBox.Process(); g_IMEWindow.Process(); m_WindowManager.Process(); if( m_CameraMoving ) { FLOAT fFrameSpeed = 0.0f; FLOAT distance = _XMeshMath_DistanceBetweenTwoPoint( m_CameraMovingTarget, g_LodTerrain.m_3PCamera.m_TargetPosition ); FLOAT maxdistance = _XMeshMath_DistanceBetweenTwoPoint( D3DXVECTOR3( 0.125f, 0.495f, 0.0f ), D3DXVECTOR3( 0.125f, 0.895f, 0.0f ) ); if( maxdistance - distance < 0.08f ) fFrameSpeed = g_fElapsedFrameMilisecondTime / 4.0f; else if( maxdistance - distance < 0.18f ) fFrameSpeed = g_fElapsedFrameMilisecondTime / 1.2f; else { if( distance < 0.08f ) fFrameSpeed = g_fElapsedFrameMilisecondTime / 2.0f; else if( distance < 0.18f ) fFrameSpeed = g_fElapsedFrameMilisecondTime; else fFrameSpeed = g_fElapsedFrameMilisecondTime * 2.5f; } BOOL zooming = TRUE; if( m_CameraMovingTargetDistance > g_LodTerrain.m_3PCamera.GetDistance() ) { g_LodTerrain.m_3PCamera.SetDistance( g_LodTerrain.m_3PCamera.GetDistance() + fFrameSpeed * 5.0f ); if( m_CameraMovingTargetDistance < g_LodTerrain.m_3PCamera.GetDistance() ) { g_LodTerrain.m_3PCamera.SetDistance( m_CameraMovingTargetDistance ); zooming = FALSE; } } else if( m_CameraMovingTargetDistance < g_LodTerrain.m_3PCamera.GetDistance() ) { g_LodTerrain.m_3PCamera.SetDistance( g_LodTerrain.m_3PCamera.GetDistance() - fFrameSpeed * 5.0f ); if( m_CameraMovingTargetDistance > g_LodTerrain.m_3PCamera.GetDistance() ) { g_LodTerrain.m_3PCamera.SetDistance( m_CameraMovingTargetDistance ); zooming = FALSE; } } else { zooming = FALSE; } if( distance < EPSILON3 ) { g_LodTerrain.m_3PCamera.m_TargetPosition = m_CameraMovingTarget; g_LodTerrain.m_3PCamera.UpdateViewMatrix(); g_LodTerrain.m_3PCamera.UpdateProjMatrix(); if( !zooming ) m_CameraMoving = FALSE; } else { D3DXVECTOR3 direction = m_CameraMovingTarget - g_LodTerrain.m_3PCamera.m_TargetPosition; D3DXVec3Normalize( &direction, &direction ); D3DXVECTOR3 prevPosition = g_LodTerrain.m_3PCamera.m_TargetPosition; g_LodTerrain.m_3PCamera.m_TargetPosition += direction * fFrameSpeed * 1.68f; FLOAT prevdistance = _XMeshMath_DistanceBetweenTwoPoint( prevPosition, m_CameraMovingTarget ); FLOAT newdistance = _XMeshMath_DistanceBetweenTwoPoint( m_CameraMovingTarget, g_LodTerrain.m_3PCamera.m_TargetPosition ); if( prevdistance < newdistance ) { g_LodTerrain.m_3PCamera.m_TargetPosition = m_CameraMovingTarget; if( !zooming ) m_CameraMoving = FALSE; } g_LodTerrain.m_3PCamera.UpdateViewMatrix(); g_LodTerrain.m_3PCamera.UpdateProjMatrix(); } } return true; }
void HeightMap::Initialize(char* mapFileName, char* textureFileName, int bitNum/*= 8*/) { D3DXMatrixIdentity(&world); texture = TextureManager::GetTexture(textureFileName); ZeroMemory(&material, sizeof(D3DMATERIAL9)); material.Ambient = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f); material.Diffuse = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f); material.Specular = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f); char fullPath[256]; strcpy_s(fullPath, HEIGHTMAP_DIRECTORY); strcat_s(fullPath, mapFileName); FILE* fp = nullptr; fopen_s(&fp, fullPath, "rb"); if (fp != nullptr) { fseek(fp, 0, SEEK_END); vertexCount = ftell(fp); fseek(fp, 0, SEEK_SET); //총 픽셀 개수 보정 vertexSizeCount = vertexCount / (bitNum / 8); mapSize = (int)(sqrt(vertexSizeCount)); assert(vertexSizeCount == mapSize*mapSize && "가로세로길이가 동일해야 합니다."); std::vector<unsigned char> fileData; fileData.resize(vertexSizeCount); if ( bitNum == 24 ) { int d[3]; for ( int i = 0; i < vertexSizeCount; ++i ) { d[0] = fgetc(fp); d[1] = fgetc(fp) << 8; d[2] = fgetc(fp) << 16; int a = d[0] | d[1] | d[2]; fileData[i] = a; } } else if ( bitNum == 16 ) { int d[2]; for ( int i = 0; i < vertexSizeCount; ++i ) { d[0] = fgetc(fp); d[1] = fgetc(fp) << 8; int a = d[0] | d[1]; fileData[i] = a; } } else { for ( int i = 0; i < vertexSizeCount; ++i ) { fileData[i] = fgetc(fp); } } fclose(fp); tileCount = mapSize - 1; std::vector<FVF_PositionNormalTexture> fvfVertex; fvfVertex.resize(vertexSizeCount); vertex.resize(vertexSizeCount); for (int z = 0; z < mapSize; ++z) { for (int x = 0; x < mapSize; ++x) { int index = z * mapSize + x; FVF_PositionNormalTexture v; v.pos = D3DXVECTOR3((float)x, fileData[index] * 0.2f, (float)-z); v.normal = D3DXVECTOR3(0,1,0); v.tex = D3DXVECTOR2(x / (float)tileCount, z / (float)tileCount); fvfVertex[index] = v; vertex[index] = v.pos; } } //노말값들 갱신 //필요한건 벡터 4개 //왼쪽, 오른쪽, 위쪽, 아래쪽 for (int z = 1; z < tileCount; ++z) { for (int x = 1; x < tileCount; ++x) { int index = z * mapSize + x; D3DXVECTOR3 left = vertex[index - 1]; D3DXVECTOR3 right = vertex[index + 1]; D3DXVECTOR3 front = vertex[index - mapSize]; D3DXVECTOR3 rear = vertex[index + mapSize]; D3DXVECTOR3 leftToRight = right - left; D3DXVECTOR3 frontToRear = rear - front; D3DXVECTOR3 normal; D3DXVec3Cross(&normal, &leftToRight, &frontToRear); D3DXVec3Normalize(&normal, &normal); fvfVertex[index].normal = normal; } } //버벡스 버퍼, 인덱스 버퍼 만들기 std::vector<DWORD> indexData; triangleCount = tileCount * tileCount * 2; indexData.resize(triangleCount * 3); for (int z = 0; z < tileCount; ++z) { for (int x = 0, k = 0; x < tileCount; ++x, ++k) { int _0 = (x + 0) + (z + 0) * mapSize; int _1 = (x + 1) + (z + 0) * mapSize; int _2 = (x + 0) + (z + 1) * mapSize; int _3 = (x + 1) + (z + 1) * mapSize; indexData[z * (6 * tileCount) + k] = (_0); indexData[z * (6 * tileCount) + ++k] = (_1); indexData[z * (6 * tileCount) + ++k] = (_2); indexData[z * (6 * tileCount) + ++k] = (_3); indexData[z * (6 * tileCount) + ++k] = (_2); indexData[z * (6 * tileCount) + ++k] = (_1); } } int bufferSize = fvfVertex.size() * sizeof(FVF_PositionNormalTexture); GameManager::GetDevice()->CreateVertexBuffer( bufferSize, 0, FVF_PositionNormalTexture::FVF, D3DPOOL_MANAGED, &vertexBuffer, nullptr); LPVOID pV; vertexBuffer->Lock(0, 0, &pV, 0); memcpy_s(pV, bufferSize, &fvfVertex[0], bufferSize); vertexBuffer->Unlock(); bufferSize = indexData.size() * sizeof(DWORD); GameManager::GetDevice()->CreateIndexBuffer( bufferSize, 0, D3DFMT_INDEX32, D3DPOOL_MANAGED, &indexBuffer, nullptr); LPVOID pI; indexBuffer->Lock(0, 0, &pI, 0); memcpy_s(pI, bufferSize, &indexData[0], bufferSize); indexBuffer->Unlock(); } }
RobotArmDemo::RobotArmDemo(HINSTANCE hInstance, std::string winCaption, D3DDEVTYPE devType, DWORD requestedVP) : D3DApp(hInstance, winCaption, devType, requestedVP) { if(!checkDeviceCaps()) { MessageBox(0, "checkDeviceCaps() Failed", 0, 0); PostQuitMessage(0); } InitAllVertexDeclarations(); mGfxStats = new GfxStats(); // Initialize Camera Settings mCameraRadius = 9.0f; mCameraRotationY = 1.5f * D3DX_PI; mCameraHeight = 0.0f; // Setup a directional light. mLight.dirW = D3DXVECTOR3(0.0f, 1.0f, 2.0f); D3DXVec3Normalize(&mLight.dirW, &mLight.dirW); mLight.ambient = D3DXCOLOR(0.8f, 0.8f, 0.8f, 1.0f); mLight.diffuse = D3DXCOLOR(0.8f, 0.8f, 0.8f, 1.0f); mLight.spec = D3DXCOLOR(0.8f, 0.8f, 0.8f, 1.0f); // Load the bone .X file mesh. LoadXFile("bone.x", &mBoneMesh, mMtrl, mTex); D3DXMatrixIdentity(&mWorld); // Create the white dummy texture. HR(D3DXCreateTextureFromFile(gd3dDevice, "whitetex.dds", &mWhiteTex)); // Initialize the bones relative to their parent frame. // The root is special--its parent frame is the world space. // As such, its position and angle are ignored--its // toWorldXForm should be set explicitly (that is, the world // transform of the entire skeleton). // // *------*------*------*------ // 0 1 2 3 for(int i = 1; i < NUM_BONES; ++i) // Ignore root. { // Describe each bone frame relative to its parent frame. mBones[i].pos = D3DXVECTOR3(2.0f, 0.0f, 0.0f); mBones[i].zAngle = 0.0f; } // Root frame at center of world. mBones[0].pos = D3DXVECTOR3(0.0f, 0.0f, 0.0f); mBones[0].zAngle = 0.0f; // Start off with the last (leaf) bone: mBoneSelected = NUM_BONES-1; mGfxStats->addVertices(mBoneMesh->GetNumVertices() * NUM_BONES); mGfxStats->addTriangles(mBoneMesh->GetNumFaces() * NUM_BONES); buildFX(); onResetDevice(); }
HRESULT APPLICATION::Init(HINSTANCE hInstance, int width, int height, bool windowed) { debug.Print("Application initiated"); //Create Window Class WNDCLASS wc; memset(&wc, 0, sizeof(WNDCLASS)); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)::DefWindowProc; wc.hInstance = hInstance; wc.lpszClassName = "D3DWND"; //Register Class and Create new Window RegisterClass(&wc); m_mainWindow = CreateWindow("D3DWND", "Example 12.7: Constructing Buildings", WS_EX_TOPMOST, 0, 0, width, height, 0, 0, hInstance, 0); SetCursor(NULL); ShowWindow(m_mainWindow, SW_SHOW); UpdateWindow(m_mainWindow); //Create IDirect3D9 Interface IDirect3D9* d3d9 = Direct3DCreate9(D3D_SDK_VERSION); if(d3d9 == NULL) { debug.Print("Direct3DCreate9() - FAILED"); return E_FAIL; } //Check that the Device supports what we need from it D3DCAPS9 caps; d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps); //Hardware Vertex Processing or not? int vp = 0; if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) vp = D3DCREATE_HARDWARE_VERTEXPROCESSING; else vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING; //Check vertex & pixelshader versions if(caps.VertexShaderVersion < D3DVS_VERSION(2, 0) || caps.PixelShaderVersion < D3DPS_VERSION(2, 0)) { debug.Print("Warning - Your graphic card does not support vertex and pixelshaders version 2.0"); } //Set D3DPRESENT_PARAMETERS D3DPRESENT_PARAMETERS d3dpp; d3dpp.BackBufferWidth = width; d3dpp.BackBufferHeight = height; d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; d3dpp.BackBufferCount = 1; d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; d3dpp.MultiSampleQuality = 0; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow = m_mainWindow; d3dpp.Windowed = windowed; d3dpp.EnableAutoDepthStencil = true; d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; d3dpp.Flags = 0; d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; //Create the IDirect3DDevice9 if(FAILED(d3d9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_mainWindow, vp, &d3dpp, &m_pDevice))) { debug.Print("Failed to create IDirect3DDevice9"); return E_FAIL; } //Release IDirect3D9 interface d3d9->Release(); // Create m_light ::ZeroMemory(&m_light, sizeof(m_light)); m_light.Type = D3DLIGHT_DIRECTIONAL; m_light.Ambient = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f); m_light.Diffuse = D3DXCOLOR(0.9f, 0.9f, 0.9f, 1.0f); m_light.Specular = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f); D3DXVECTOR3 dir = D3DXVECTOR3(-1.0f, -1.0f, 0.0f); D3DXVec3Normalize(&dir, &dir); m_light.Direction = dir; m_pDevice->SetLight(0, &m_light); m_pDevice->LightEnable(0, true); //Set sampler state for(int i=0;i<4;i++) { m_pDevice->SetSamplerState(i, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); m_pDevice->SetSamplerState(i, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); m_pDevice->SetSamplerState(i, D3DSAMP_MIPFILTER, D3DTEXF_POINT); } m_build1.Load("meshes/townhall_b.x", m_pDevice); m_build2.Load("meshes/townhall.x", m_pDevice); m_buildPrc = 0.0f; return S_OK; }
void Player::update(float _dt) { //do nothing if dead if (bIsDead) { gStateMachine->transitionState(STATE_LOSE); return; } Pawn::update(_dt); //facing controls if (gDInput->keyDown(DIK_Q)) { gCameraMain->setAngleOffset(1.0f * _dt); } if (gDInput->keyDown(DIK_E)) { gCameraMain->setAngleOffset(-1.0f * _dt); } //face towards mouse position float a = (float)gWindowWidth / 2.0f - gDInput->mCursorPos2D.x; float b = (float)gWindowHeight / 2.0f - gDInput->mCursorPos2D.y; float angle = atan2f(b, a) + D3DX_PI / 2.0f + gCameraMain->getAngleOffset(); mRotation.y = angle; //direction controls bIsMoving = false; mVelocity = D3DXVECTOR3(0.0f, 0.0f, 0.0f); if (gDInput->keyDown(DIK_W)) { mVelocity += D3DXVECTOR3(0.0f, 0.0f, mSpeed); bIsMoving = true; } if (gDInput->keyDown(DIK_S)) { mVelocity += D3DXVECTOR3(0.0f, 0.0f, -mSpeed); bIsMoving = true; } if (gDInput->keyDown(DIK_A)) { mVelocity += D3DXVECTOR3(-mSpeed, 0.0f, 0.0f); bIsMoving = true; } if (gDInput->keyDown(DIK_D)) { mVelocity += D3DXVECTOR3(mSpeed, 0.0f, 0.0f); bIsMoving = true; } if (mVelocity != D3DXVECTOR3(0.0f, 0.0f, 0.0f)) { //face direction that the buttons indicate we're going D3DXVec3Normalize(&mVelocity, &mVelocity); float a = (float)gWindowWidth * 0.5f - mVelocity.x; float b = (float)gWindowHeight * 0.5f - mVelocity.z; float angle = atan2f(b, a) + /*D3DX_PI * 1.795f + */5.6391588f + gCameraMain->getAngleOffset(); //build rotation matrix D3DXMATRIX rot; D3DXMatrixRotationY(&rot, angle); //transform direction by rot matrix D3DXVECTOR4 transform; D3DXVec3Transform(&transform, &mVelocity, &rot); mVelocity = D3DXVECTOR3(transform.x, transform.y, transform.z); D3DXVec3Normalize(&mVelocity, &mVelocity); mVelocity *= mSpeed; } //did we collide with any level geometry? bool colliding = false; //for each colliding mesh in level // SAM: TODO: Hack, this is for testing // mLastPosition = mPosition; // mPosition += (mVelocity * _dt); for (Mesh* M : gCurrentLevel->getWorldGeometry()) { //for each bounding box in mesh /* for (AxisAlignedBoundingBox2D* AABB : M->getAABBs()) { colliding = collides(*AABB, BoundingSphere2D(D3DXVECTOR2(mPosition.x, mPosition.z), mRadius)); if (colliding) break; } if (colliding) break;*/ // SAM for (UINT i = 0; i < M->getBoundsBoxList().size(); ++i) { colliding = collides(AxisAlignedBoundingBox(M->getBoundsBoxList()[i]), BoundingSphere(D3DXVECTOR3(mPosition.x, mPosition.y, mPosition.z), mRadius)); if (colliding) break; } if (colliding) break; } //move if (!colliding) {//if not colliding, update position and rotation as normal mLastPosition = mPosition; mPosition += (mVelocity * _dt); } else//if colliding, only update rotation, push position back { mPosition = mLastPosition; } mMesh->setPosRot(mPosition, mRotation); //attacks mAttackTime += _dt; //if time to attack and if didn't just click the upper right UI buttons this frame if (mAttackTime > mAttackDelay && ( (gDInput->mCursorPos2D.x < (0.9f * (float)gWindowWidth)) || (gDInput->mCursorPos2D.y > (0.3f * (float)gWindowHeight)) ) ) { ePAttack attackType; //check if button is pressed if (gDInput->mouseButtonDown(0)) attackType = mLeftAttack; else if (gDInput->mouseButtonDown(1)) attackType = mRightAttack; else attackType = A_NONE; bool attacked = false; if (attackType != A_NONE) { Attack* attack; bool canAttack = true; switch (attackType) { case A_MELEE: attack = new Attack(L"", 20.0f, 400.0f, 0.1f, true); gSound->getSystem()->playSound(FMOD_CHANNEL_FREE,playerAttackMelee, false, 0); attacked = true; break; case A_SEED: if (mAmmoSeeds > 0) { --mAmmoSeeds; attack = new Attack(L"Content/Models/ball.x", 15.0f, 600.0f, 8.0f, true, 10.0f, D3DXVECTOR3(4.0f, 4.0f, 4.0f)); attack->setTextures(L"Content/Textures/tex_seed.dds", L"Content/Textures/tex_seed_n.dds"); gSound->getSystem()->playSound(FMOD_CHANNEL_FREE,playerAttackSeed, false, 0); attacked = true; } break; case A_FIRE: if (mAmmoFire > 0) { --mAmmoFire; attack = new Attack(L"Content/Models/ball.x", 30.0f, 500.0f, 8.0f, true, 10.0f, D3DXVECTOR3(4.0f, 4.0f, 4.0f)); attack->setTextures(L"Content/Textures/tex_fire.dds", L"Content/Textures/tex_fire_n.dds"); gSound->getSystem()->playSound(FMOD_CHANNEL_FREE,playerAttackFire, false, 0); attacked = true; } break; } if (attacked) { attack->moveFacingDirection(); gCurrentLevel->getAttackManager()->addAttack(attack); } mAttackTime = 0.0f; } } }
void Follower::update(float _dt) { //do nothing if dead if (bIsDead) {//will add a more elaborate lose screen later gStateMachine->transitionState(STATE_LOSE); return; } Pawn::update(_dt); mLastPathFound += _dt; static float aiCheck = 0.0f; aiCheck += _dt; if (aiCheck >= RUN_AI)//only run the AI every so many frames //inside this conditional you should use aiCheck where you'd normally use _dt { float distanceToPlayerSq; bIsMoving = true; switch (mState) { case PSTATE_PURSUE: distanceToPlayerSq = D3DXVec3LengthSq(&(gPlayer->getPosition() - mPosition)); if (distanceToPlayerSq > FOLLOW_DISTANCE_SQ) { if (!followPath() || mLastPathFound > MIN_PATH_TIME) setPathPlayer(); } else if (distanceToPlayerSq > FOLLOW_DISTANCE_STOP_SQ) { mVelocity = gPlayer->getPosition() - mPosition; D3DXVec3Normalize(&mVelocity, &mVelocity);//normalize to 1 unit length vector mVelocity *= mSpeed;//multiply by speed } else { stop(); bIsMoving = false; } break; case PSTATE_AFRAID: //how long has it been afraid mAfraidTime += _dt; if (mAfraidTime >= mAfraidMax) {//don't let the follower be afraid indefinitely, else the task of getting them //to the goal might become impossible bAfraid = false; mAfraidTime = 0.0f; mState = PSTATE_PURSUE; break; } //if no longer afraid if (!bAfraid) { mState = PSTATE_PURSUE; break; } else//flee randomly in panic { if (mLastPathFound >= MIN_PATH_TIME || !followPath(1.0f)) { setPathFlee(); } //gSound->getSystem()->playSound(NULL, followerCry, false, 0); } break; } mPosition += (mVelocity * aiCheck);//set position based on speed detectCollision();//let the player push the follower, but not into walls pointForward(aiCheck);//set rotation based on direction mMesh->setPosRot(mPosition, mRotation);//set position and rotation of mesh aiCheck = 0.0f; } }
bool ZEffectBillboardList::Draw() { if(!m_pVB) return false; if( size()==0 ) return true; BeginState(); HRESULT hr; DWORD dwRemainNum = (DWORD)size(); iterator itr=begin(); while(dwRemainNum) { if(m_dwBase >= EFFECTBASE_DISCARD_COUNT) m_dwBase = 0; // 갯수가 BILLBOARD_FLUSH_COUNT 를 넘어가면 BILLBOARD_FLUSH_COUNT 씩 찍는다 DWORD dwThisNum = min( dwRemainNum , BILLBOARD_FLUSH_COUNT ); // 버퍼의 크기를 넘어가면 개수를 줄여서 크기만큼만 찍는다 dwThisNum = min( dwThisNum , EFFECTBASE_DISCARD_COUNT - m_dwBase ); BYTE *pVertices; if( FAILED( hr = m_pVB->Lock( m_dwBase * sizeof(ZEFFECTCUSTOMVERTEX) * 4, dwThisNum * sizeof(ZEFFECTCUSTOMVERTEX) * 4, (VOID**)&pVertices, m_dwBase ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD ) ) ) { return false; } BYTE *pInd; if( FAILED( hr = m_pIB->Lock( m_dwBase * sizeof(WORD) * 6, dwThisNum * sizeof(WORD) * 6, (VOID**)&pInd, m_dwBase ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD ) ) ) { return false; } for(DWORD j=0;j<dwThisNum;j++) { ZEFFECTBILLBOARDITEM *p = (ZEFFECTBILLBOARDITEM*)*itr; // Transform rmatrix matTranslation; rmatrix matScaling; rmatrix matWorld; rvector dir = p->normal; rvector up=p->up; rvector right; if(IS_EQ(dir.z,1.f)) up=rvector(1,0,0); D3DXVec3Cross(&right, &up, &dir); D3DXVec3Normalize(&right, &right); D3DXVec3Cross(&up, &right, &dir); D3DXVec3Normalize(&up, &up); rmatrix mat; D3DXMatrixIdentity(&mat); mat._11=right.x;mat._12=right.y;mat._13=right.z; mat._21=up.x;mat._22=up.y;mat._23=up.z; mat._31=dir.x;mat._32=dir.y;mat._33=dir.z; rvector pos=p->position; // float fScale=p->fStartSize * p->fOpacity + p->fEndSize * (1.f - p->fOpacity); float fInt = min(1,max(0,(p->fLifeTime - p->fElapsedTime)/p->fLifeTime)); float fScale=p->fStartSize * fInt + p->fEndSize * (1.f - fInt); if( p->bUseTrainSmoke ) { float fRatio = GetLifeRatio(p); float fAddScale = (p->fEndSize - p->fStartSize) / p->fLifeTime; if(fRatio < 0.1f ) { fAddScale *= 0.001f; } else if(fRatio < 0.4) { fAddScale *= 0.02f; } else { fAddScale *= 0.05f; } p->fCurScale += fAddScale; if(p->fCurScale > p->fEndSize) p->fCurScale = p->fEndSize; fScale = p->fCurScale; } D3DXMatrixScaling(&matScaling,fScale*m_Scale.x,fScale*m_Scale.y,fScale*m_Scale.z); D3DXMatrixTranslation(&matTranslation, pos.x, pos.y, pos.z); D3DXMatrixMultiply(&matWorld, &matScaling, &mat); D3DXMatrixMultiply(&matWorld, &matWorld, &matTranslation); // D3DXMatrixMultiply(&matWorld, &mat, &matTranslation); DWORD color = ((DWORD)(p->fOpacity * 255))<<24 | p->dwColor; static ZEFFECTCUSTOMVERTEX v[] = { {-1, -1, 0, 0xFFFFFFFF, 1, 0}, {-1, 1, 0, 0xFFFFFFFF, 1, 1}, { 1, 1, 0, 0xFFFFFFFF, 0, 1}, { 1, -1, 0, 0xFFFFFFFF, 0, 0}, }; static rvector sv[4] = { rvector(-1,-1,0) , rvector(-1,1,0) , rvector(1,1,0) , rvector(1,-1,0) }; // 좋은코드는 아니지만 버텍스 카피를 줄이기위해 타입캐스팅했다. D3DXVec3TransformCoord((D3DXVECTOR3*)&v[0].x,sv+0,&matWorld); D3DXVec3TransformCoord((D3DXVECTOR3*)&v[1].x,sv+1,&matWorld); D3DXVec3TransformCoord((D3DXVECTOR3*)&v[2].x,sv+2,&matWorld); D3DXVec3TransformCoord((D3DXVECTOR3*)&v[3].x,sv+3,&matWorld); v[0].color=v[1].color=v[2].color=v[3].color=color; memcpy(pVertices,v,sizeof(ZEFFECTCUSTOMVERTEX)*4); pVertices+=sizeof(ZEFFECTCUSTOMVERTEX)*4; WORD inds[] = { 0,1,2,0,2,3 }; for(int k=0;k<6;k++) { inds[k]+=(m_dwBase+j)*4; } memcpy(pInd,inds,sizeof(inds)); pInd+=sizeof(inds); itr++; } m_pVB->Unlock(); m_pIB->Unlock(); if(FAILED( hr = RGetDevice()->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,m_dwBase*4,dwThisNum*4,m_dwBase*6,dwThisNum*2) )) return false; m_dwBase+=dwThisNum; dwRemainNum-=dwThisNum; } RGetDevice()->SetStreamSource( 0, NULL , 0,0 ); RGetDevice()->SetIndices(NULL); EndState(); return true; }
////////////////////////////////////////////////////////////////////////// // satisfyConstraints ////////////////////////////////////////////////////////////////////////// void ZClothEmblem::satisfyConstraints() { sConstraint* c; rvector* x1; rvector* x2; rvector delta; float deltaLegth; float diff; int i,j; // if( mbIsInFrustrum ) { for( i = 0 ; i < m_nCntIter; ++i ) { // 캐릭터와 충돌 체크 for (ZCharacterManager::iterator itor = ZGetCharacterManager()->begin(); itor != ZGetCharacterManager()->end(); ++itor) { ZCharacter* pCharacter = (*itor).second; // 현재 화면에 보이는 캐릭터만 대상으로 체크.. 뷰프러스텀 컬링 if( !isInViewFrustum( pCharacter->GetPosition(), CHARACTER_RADIUS + 10, RGetViewFrustum() ) ) { continue; } if( pCharacter->IsDie() && pCharacter->m_dwStatusBitPackingValue.Ref().m_bBlastDrop && !pCharacter->IsVisible() ) { continue; } for( j = 0 ; j < m_nCntP; ++j ) { rvector pos = pCharacter->GetPosition(); rvector myPos = m_pX[j]; if( pos.z + 190 < myPos.z || pos.z > myPos.z ) { continue; } pos.z = 0; myPos.z = 0; rvector dir = myPos - pos; float lengthsq = D3DXVec3LengthSq( &dir ); if( lengthsq > CHARACTER_RADIUS*CHARACTER_RADIUS ) { continue; } D3DXVec3Normalize( &dir, &dir ); myPos = pos + dir * ( CHARACTER_RADIUS ); m_pX[j].x = myPos.x; m_pX[j].y = myPos.y; //break; } } } // Restriction for( list<sRestriction*>::iterator itor = mRestrictionList.begin(); itor != mRestrictionList.end(); ++itor ) { for( int j = 0 ; j < m_nCntP; ++j ) { float* p = (float*)&m_pX[j]; sRestriction* r = *itor; p += (int)r->axis; // 축결정 if( r->compare == COMPARE_GREATER) { if( *p > r->position ) { *p = r->position; } } else { if( *p < r->position -3) { *p = r->position; } } } } // Relaxation for( j = 0 ; j < m_nCntC; ++j ) { c = &m_pConst[j]; x1 = &m_pX[ c->refA ]; x2 = &m_pX[ c->refB ]; delta = *x2 - *x1; deltaLegth = D3DXVec3Length( &delta ); diff = (float) ( ( deltaLegth - c->restLength ) / (deltaLegth )); *x1 += delta * diff * 0.5; *x2 -= delta * diff * 0.5; } } for( i = 0 ; i < m_nCntP; ++i ) { if( m_pHolds[i] & CLOTH_HOLD ) { m_pX[i] = m_pOldX[i]; } } }
bool ZEffectBillboardTexAniList::Draw() { if(!m_pVB) return false; if( size()==0 ) return true; BeginState(); RSetFog(FALSE); HRESULT hr; DWORD dwRemainNum = (DWORD)size(); iterator itr = begin(); while(dwRemainNum) { if(m_dwBase >= EFFECTBASE_DISCARD_COUNT) m_dwBase = 0; DWORD dwThisNum = min( dwRemainNum , BILLBOARD_FLUSH_COUNT ); dwThisNum = min( dwThisNum , EFFECTBASE_DISCARD_COUNT - m_dwBase ); BYTE *pVertices; if( FAILED( hr = m_pVB->Lock( m_dwBase * sizeof(ZEFFECTCUSTOMVERTEX) * 4, dwThisNum * sizeof(ZEFFECTCUSTOMVERTEX) * 4, (VOID**)&pVertices, m_dwBase ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD ) ) ) { return false; } BYTE *pInd; if( FAILED( hr = m_pIB->Lock( m_dwBase * sizeof(WORD) * 6, dwThisNum * sizeof(WORD) * 6, (VOID**)&pInd, m_dwBase ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD ) ) ) { return false; } int nRenderCnt = 0; ZCharacter* pChar = NULL; for(DWORD j=0;j<dwThisNum;j++) { ZEFFECTBILLBOARDTEXANIITEM *p = (ZEFFECTBILLBOARDTEXANIITEM*)*itr; if(p->fElapsedTime < p->fAddTime ) { itr++; continue; } pChar = ZGetCharacterManager()->Find(p->CharUID); if( pChar ) { if( pChar->m_pVMesh ) { if( pChar->m_pVMesh->m_bIsRender==false) {//부모가 안그려졌으면 skip... itr++; continue; } } } nRenderCnt++; // Transform rmatrix matTranslation; rmatrix matScaling; rmatrix matWorld; rvector dir = p->normal; rvector up=p->up; rvector right; if(IS_EQ(dir.z,1.f)) up=rvector(1,0,0); D3DXVec3Cross(&right, &up, &dir); D3DXVec3Normalize(&right, &right); D3DXVec3Cross(&up, &right, &dir); D3DXVec3Normalize(&up, &up); rmatrix mat; D3DXMatrixIdentity(&mat); mat._11=right.x;mat._12=right.y;mat._13=right.z; mat._21=up.x;mat._22=up.y;mat._23=up.z; mat._31=dir.x;mat._32=dir.y;mat._33=dir.z; rvector pos=p->position; // float fScale=p->fStartSize * p->fOpacity + p->fEndSize * (1.f - p->fOpacity); float fInt = min(1,max(0,(p->fLifeTime - p->fElapsedTime)/p->fLifeTime)); float fScale=p->fStartSize * fInt + p->fEndSize * (1.f - fInt); D3DXMatrixScaling(&matScaling,fScale*m_Scale.x,fScale*m_Scale.y,fScale*m_Scale.z); D3DXMatrixTranslation(&matTranslation, pos.x, pos.y, pos.z); D3DXMatrixMultiply(&matWorld, &matScaling, &mat); D3DXMatrixMultiply(&matWorld, &matWorld, &matTranslation); DWORD color = ((DWORD)(p->fOpacity * 255))<<24 | p->dwColor; static ZEFFECTCUSTOMVERTEX v[] = { {-1, -1, 0, 0xFFFFFFFF, 1, 0}, {-1, 1, 0, 0xFFFFFFFF, 1, 1}, { 1, 1, 0, 0xFFFFFFFF, 0, 1}, { 1, -1, 0, 0xFFFFFFFF, 0, 0}, }; static rvector sv[4] = { rvector(-1,-1,0) , rvector(-1,1,0) , rvector(1,1,0) , rvector(1,-1,0) }; GetFrameUV( min( p->frame,m_nMaxFrame-1) ); v[0].tu = m_fUV[0]; v[0].tv = m_fUV[1]; v[1].tu = m_fUV[2]; v[1].tv = m_fUV[3]; v[2].tu = m_fUV[4]; v[2].tv = m_fUV[5]; v[3].tu = m_fUV[6]; v[3].tv = m_fUV[7]; // 좋은코드는 아니지만 버텍스 카피를 줄이기위해 타입캐스팅했다. D3DXVec3TransformCoord((D3DXVECTOR3*)&v[0].x,sv+0,&matWorld); D3DXVec3TransformCoord((D3DXVECTOR3*)&v[1].x,sv+1,&matWorld); D3DXVec3TransformCoord((D3DXVECTOR3*)&v[2].x,sv+2,&matWorld); D3DXVec3TransformCoord((D3DXVECTOR3*)&v[3].x,sv+3,&matWorld); v[0].color=v[1].color=v[2].color=v[3].color=color; memcpy(pVertices,v,sizeof(ZEFFECTCUSTOMVERTEX)*4); pVertices+=sizeof(ZEFFECTCUSTOMVERTEX)*4; WORD inds[] = { 0,1,2,0,2,3 }; for(int k=0;k<6;k++) { inds[k]+=(m_dwBase+j)*4; } memcpy(pInd,inds,sizeof(inds)); pInd+=sizeof(inds); itr++; } m_pVB->Unlock(); m_pIB->Unlock(); if(FAILED( hr = RGetDevice()->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,m_dwBase*4,nRenderCnt*4,m_dwBase*6,nRenderCnt*2) )) return false; m_dwBase+=dwThisNum; dwRemainNum-=dwThisNum; } RGetDevice()->SetStreamSource( 0, NULL , 0,0 ); RGetDevice()->SetIndices(NULL); if(ZGetWorld()) { ZGetWorld()->SetFog(true);// 게임 설정에 따라서 } EndState(); return true; }
//----------------------------------------------------------------------------- // Updates the player object. //----------------------------------------------------------------------------- void PlayerObject::Update( float elapsed, bool addVelocity ) { // Allow the base animated object to update. AnimatedObject::Update( elapsed, addVelocity ); // Override the object's forward vector to take the view tilt into account. // This will allow the forward vector to move up and down as well instead // of just remaining horizontal. This is not important for movement since // the player can not fly, but for things like shooting it is. m_forward.x = (float)sin( GetRotation().y ); m_forward.y = (float)-tan( m_viewTilt ); m_forward.z = (float)cos( GetRotation().y ); D3DXVec3Normalize( &m_forward, &m_forward ); // Set the player's view point. This is done every frame because as the // mesh is animated, the reference point in the mesh may move. This // will allow the view point to move with the mesh's animations. m_viewPoint = GetMesh()->GetReferencePoint( "rp_view_point" )->GetTranslation(); // Ensure that the view movement is relative to the rotation. D3DXVec3TransformCoord( &m_viewPoint, &m_viewPoint, GetRotationMatrix() ); // Only calculate the correct view matrix if it is being used. if( m_isViewing == true ) { // Create the x axis rotation matrix. D3DXMATRIX rotationXMatrix; D3DXMatrixRotationX( &rotationXMatrix, m_viewTilt ); // Create the combined rotation matrix (i.e. y axis rotation from the // scene object plus the x axis rotation from the player object). D3DXMATRIX combinedRotation; D3DXMatrixMultiply( &combinedRotation, &rotationXMatrix, GetRotationMatrix() ); // Build a translation matrix that represents the final view point. D3DXMATRIX viewPointTranslationMatrix; D3DXVECTOR3 finalViewPointTranslation = GetTranslation() + m_viewPoint; D3DXMatrixTranslation( &viewPointTranslationMatrix, finalViewPointTranslation.x, finalViewPointTranslation.y, finalViewPointTranslation.z ); // Override the object's view matrix using the combined rotation and // the position of the final view point translation. D3DXMatrixMultiply( &m_viewMatrix, &combinedRotation, &viewPointTranslationMatrix ); D3DXMatrixInverse( &m_viewMatrix, NULL, &m_viewMatrix ); } // Ignore the rest if the player is dying (or dead) if( m_dying == true ) return; // Drive and strafe the player accordingly. if( m_drive != 0.0f ) Drive( m_drive * 8000.0f * elapsed ); if( m_strafe != 0.0f ) Strafe( m_strafe * 4000.0f * elapsed ); // Update the step audio paths. m_leftStepAudioPath->SetPosition( GetTranslation() + GetMesh()->GetReferencePoint( "rp_left_foot" )->GetTranslation() ); m_leftStepAudioPath->SetVelocity( GetVelocity() ); m_rightStepAudioPath->SetPosition( GetTranslation() + GetMesh()->GetReferencePoint( "rp_right_foot" )->GetTranslation() ); m_rightStepAudioPath->SetVelocity( GetVelocity() ); // Check if the player is changing their weapon (local player only). static float move = 0.0f; if( m_changingWeapon > 0.0f ) { m_changingWeapon -= elapsed; if( m_changingWeapon > 1.0f ) { // Lower the old weapon. move -= 100.0f * elapsed; m_weapons[m_oldWeapon]->RaiseLowerWeapon( elapsed, this, move ); } else if( m_changingWeapon < 0.0f ) { // The new weapon is in place. m_changingWeapon = 0.0f; move = 0.0f; // Send a message to inform the other players the weapon is ready. PlayerWeaponChangeMsg pwcm; pwcm.msgid = MSGID_PLAYER_WEAPON_CHANGE; pwcm.dpnid = g_engine->GetNetwork()->GetLocalID(); pwcm.weapon = m_currentWeapon; g_engine->GetNetwork()->Send( &pwcm, sizeof( PlayerWeaponChangeMsg ), DPNID_ALL_PLAYERS_GROUP, DPNSEND_NOLOOPBACK ); } else { // Raise the new weapon. move += 100.0f * elapsed; m_weapons[m_currentWeapon]->RaiseLowerWeapon( elapsed, this, move ); } } else { // Update the player's current weapon, when not changing weapons. if( m_weaponChanging == false ) m_weapons[m_currentWeapon]->Update( elapsed, m_fire, this, m_viewPoint.y ); } }
//-------------------------------------------------------------------------------------- // Render the scene using the D3D10 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { // Clear the render target float ClearColor[4] = { 0.9569f, 0.9569f, 1.0f, 0.0f }; ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView(); pd3dDevice->ClearRenderTargetView( pRTV, ClearColor ); ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView(); pd3dDevice->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 ); // Make sure we only grow the tree the first time we go to render. // If we recreated the same tree every frame, we would definitely waste time. static bool bFirst = true; if( bFirst ) { //----------------------------------------------------------------------------------------- // o/__ <-- BreakdancinBob NOTE: Give the grow algorithm access to the random buffer // | (\ //----------------------------------------------------------------------------------------- g_pRandomBuf->SetResource( g_pRandomBufferRV ); // Grow the branches one step at a time for( UINT i = 0; i < g_NumGrowthSpurts; i++ ) { GrowBranches( pd3dDevice ); } bFirst = false; } // Render the result D3DXMATRIX mWorld; D3DXMATRIX mView; D3DXMATRIX mProj; D3DXMATRIX mWorldViewProj; D3DXMATRIX mWorldView; mWorld = *g_Camera.GetWorldMatrix(); mProj = *g_Camera.GetProjMatrix(); mView = *g_Camera.GetViewMatrix(); mWorldView = mWorld * mView; mWorldViewProj = mWorldView * mProj; // Set variables g_pmWorldViewProj->SetMatrix( ( float* )&mWorldViewProj ); g_pmWorld->SetMatrix( ( float* )&mWorld ); g_pmWorldView->SetMatrix( ( float* )&mWorldView ); g_pDiffuseTex->SetResource( g_pMeshTexRV ); D3DXVECTOR3 lightDir( -1,1,-1 ); D3DXVECTOR3 viewLightDir; D3DXVec3TransformNormal( &viewLightDir, &lightDir, &mView ); D3DXVec3Normalize( &viewLightDir, &viewLightDir ); g_pViewSpaceLightDir->SetFloatVector( ( float* )&viewLightDir ); // Set Input Assembler params ID3D10Buffer* pBuffers[1]; pBuffers[0] = g_pDrawFrom; UINT stride = g_VertStride; UINT offset = 0; pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); pd3dDevice->IASetVertexBuffers( 0, 1, pBuffers, &stride, &offset ); // Render using the technique g_pRenderTextured D3D10_TECHNIQUE_DESC techDesc; g_pRenderTextured->GetDesc( &techDesc ); for( UINT p = 0; p < techDesc.Passes; p++ ) { g_pRenderTextured->GetPassByIndex( p )->Apply( 0 ); pd3dDevice->DrawAuto(); } }
void CSmashBot::TakeDamage(IBaseObject* _pIn) { if(_pIn->GetID() == OBJ_POOL) { SetHealth(GetHealth() - ((CMoltenPool*)_pIn)->GetDamage()); SetWasHit(true); return; } else if (_pIn->GetID() == OBJ_TURRET) { SetHealth(GetHealth() - ((CTurret*)_pIn)->GetDamage()); SetWasHit(true); return; } if( _pIn->GetID() == OBJ_BULLET_EXP ) { if(((CBullet*)_pIn)->GetType() == SPECIALBULLET) SetHealth(0.0f); else SetHealth(GetHealth() - ((CBullet*)_pIn)->GetDamage()); SetWasHit(true); return; } if( m_bIsSmashing ) { SetHealth(GetHealth() - ((CBullet*)_pIn)->GetDamage()); SetWasHit(true); } else { if( _pIn->GetID() == OBJ_BULLET_BEAM || _pIn->GetID() == OBJ_BULLET_TESLA ) { SetHealth(GetHealth() - ((CBullet*)_pIn)->GetDamage()*.5f); SetWasHit(true); return; } D3DXVECTOR3 d3dMyZ(GetMatrix()._31, GetMatrix()._32, GetMatrix()._33); D3DXVECTOR3 d3dIn(_pIn->GetMatrix()._41, _pIn->GetMatrix()._42, _pIn->GetMatrix()._43); D3DXVECTOR3 d3dToTarget = d3dIn - D3DXVECTOR3(GetMatrix()._41, GetMatrix()._42, GetMatrix()._43); float fDot = D3DXVec3Dot(&d3dMyZ, &d3dToTarget); if( fDot < 0.0f) { SetHealth(GetHealth() - ((CBullet*)_pIn)->GetDamage()); SetWasHit(true); CGameplayState::GetInstance()->GetFX()->CreateEffect(EFFECT_BULLETHIT,_pIn->GetMatrix()); } else { float fSafe = GetSphere().m_Radius * GetSphere().m_Radius + ((CBullet*)_pIn)->GetSphere().m_Radius * ((CBullet*)_pIn)->GetSphere().m_Radius + .5f; D3DXVECTOR3 d3dFinal = *(D3DXVECTOR3*)&_pIn->GetMatrix()[12], d3dToBullet = *(D3DXVECTOR3*)&_pIn->GetMatrix()[12] - *(D3DXVECTOR3*)&GetMatrix()[12]; if( D3DXVec3LengthSq(&d3dToBullet) > fSafe ) { D3DXVECTOR3 d3dDir; D3DXVec3Normalize(&d3dDir, &d3dToBullet); d3dDir *= GetSphere().m_Radius; d3dFinal = *(D3DXVECTOR3*)&GetMatrix()[12] + d3dDir; } D3DXMATRIX d3dMat = GetMatrix(); d3dMat[12]=d3dFinal.x; d3dMat[13]=d3dFinal.y; d3dMat[14]=d3dFinal.z; CGameplayState::GetInstance()->GetFX()->CreateEffect(EFFECT_INVULSPARK,d3dMat); } } }
SolarSysDemo::SolarSysDemo(HINSTANCE hInstance, std::string winCaption, D3DDEVTYPE devType, DWORD requestedVP) : D3DApp(hInstance, winCaption, devType, requestedVP) { if(!checkDeviceCaps()) { MessageBox(0, "checkDeviceCaps() Failed", 0, 0); PostQuitMessage(0); } InitAllVertexDeclarations(); mGfxStats = new GfxStats(); // Initialize Camera Settings mCameraRadius = 25.0f; mCameraRotationY = 1.2f * D3DX_PI; mCameraHeight = 10.0f; // Setup a directional light. mLight.dirW = D3DXVECTOR3(0.0f, 1.0f, 2.0f); D3DXVec3Normalize(&mLight.dirW, &mLight.dirW); mLight.ambient = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); mLight.diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); mLight.spec = D3DXCOLOR(0.6f, 0.6f, 0.6f, 1.0f); // Create a sphere to represent a solar object. HR(D3DXCreateSphere(gd3dDevice, 1.0f, 30, 30, &mSphere, 0)); genSphericalTexCoords(); D3DXMatrixIdentity(&mWorld); // Create the textures. HR(D3DXCreateTextureFromFile(gd3dDevice, "sun.dds", &mSunTex)); HR(D3DXCreateTextureFromFile(gd3dDevice, "planet1.dds", &mPlanet1Tex)); HR(D3DXCreateTextureFromFile(gd3dDevice, "planet2.dds", &mPlanet2Tex)); HR(D3DXCreateTextureFromFile(gd3dDevice, "planet3.dds", &mPlanet3Tex)); HR(D3DXCreateTextureFromFile(gd3dDevice, "moon.dds", &mMoonTex)); // Initialize default white material. mWhiteMtrl.ambient = WHITE; mWhiteMtrl.diffuse = WHITE; mWhiteMtrl.spec = WHITE * 0.5f; mWhiteMtrl.specPower = 48.0f; //================================================== // Specify how the solar object frames are related. D3DXVECTOR3 pos[NUM_OBJECTS] = { D3DXVECTOR3(0.0f, 0.0f, 0.0f), D3DXVECTOR3(7.0f, 0.0f, 7.0f), D3DXVECTOR3(-9.0f, 0.0f, 0.0f), D3DXVECTOR3(7.0f, 0.0f, -6.0f), D3DXVECTOR3(5.0f, 0.0f, 0.0f), D3DXVECTOR3(-5.0f, 0.0f, 0.0f), D3DXVECTOR3(3.0f, 0.0f, 0.0f), D3DXVECTOR3(2.0f, 0.0f, -2.0f), D3DXVECTOR3(-2.0f, 0.0f, 0.0f), D3DXVECTOR3(0.0f, 0.0f, 2.0f) }; mObject[0].set(SUN, pos[0], 0.0f, -1, 2.5f, mSunTex); // Sun mObject[1].set(PLANET, pos[1], 0.0f, 0, 1.5f, mPlanet1Tex);// P1 mObject[2].set(PLANET, pos[2], 0.0f, 0, 1.2f, mPlanet2Tex);// P2 mObject[3].set(PLANET, pos[3], 0.0f, 0, 0.8f, mPlanet3Tex);// P3 mObject[4].set(MOON, pos[4], 0.0f, 1, 0.5f, mMoonTex); // M1P1 mObject[5].set(MOON, pos[5], 0.0f, 1, 0.5f, mMoonTex); // M2P1 mObject[6].set(MOON, pos[6], 0.0f, 2, 0.4f, mMoonTex); // M1P2 mObject[7].set(MOON, pos[7], 0.0f, 3, 0.3f, mMoonTex); // M1P3 mObject[8].set(MOON, pos[8], 0.0f, 3, 0.3f, mMoonTex); // M2P3 mObject[9].set(MOON, pos[9], 0.0f, 3, 0.3f, mMoonTex); // M3P3 //================================================== mGfxStats->addVertices(mSphere->GetNumVertices() * NUM_OBJECTS); mGfxStats->addTriangles(mSphere->GetNumFaces() * NUM_OBJECTS); buildFX(); onResetDevice(); }
void _X3PCamera::UpdateViewMatrix( _XLodTerrain* terrainobject, BOOL setexternproperties ) { if(!g_QuestScriptManager.GetQuestCameraMode()) { FindCameraPosition2D(); if( terrainobject ) { POINT pt; S_WATER* curwater; _XLODTILE* curtile; FLOAT height = terrainobject->GetTerrainHeight( m_CameraPosition ); curtile = terrainobject->GetTerrainTile( m_CameraPosition, &pt ); curwater = terrainobject->m_pWaterObjectManager->GetWaterObject( pt.y + (pt.x * g_LodTerrain.m_TileCount) ); if( curwater && curwater->enabled ) { if( height < curwater->height ) { height = curwater->height; } } height += _XDEF_BASEHEIGHTOFTERRAIN / 1.5f; if( height > m_CameraPosition.y ) m_CameraPosition.y = height; // Check OBB D3DXVECTOR3 LastCollidePoint; FLOAT collidedist = 9999.0f; D3DXVECTOR3 camerainvviewvector; BOOL bCollide = FALSE; camerainvviewvector = m_CameraPosition - m_TargetPosition; D3DXVec3Normalize( &camerainvviewvector, &camerainvviewvector ); camerainvviewvector *= (m_TargetDistance * 2.0f); if( !g_FreeMoveMode && curtile ) { if( !curtile->svObbList.empty() ) { _XOBBData* pOBBData; svdef_OBBData::iterator it; for (it = curtile->svObbList.begin(); it != curtile->svObbList.end(); ++ it) { pOBBData = (*it); D3DXVECTOR3 CollidePoint; if( pOBBData->InterOBBvsRay( m_TargetPosition, camerainvviewvector, CollidePoint ) ) { D3DXVECTOR3 localcollidepoint; localcollidepoint = CollidePoint - m_TargetPosition; FLOAT dist = D3DXVec3LengthSq( &localcollidepoint ); if( dist < collidedist ) { if( dist < m_TargetDistance*m_TargetDistance ) { collidedist = dist; LastCollidePoint = CollidePoint; bCollide = TRUE; } } } } } } if( !g_FreeMoveMode && !bCollide ) { if( g_LodTerrain.m_FunctionalObjectManager.m_countFunctionalObject != 0 ) { for( int i = 0; i < g_LodTerrain.m_FunctionalObjectManager.m_countFunctionalObject; i++ ) { if( g_LodTerrain.m_FunctionalObjectManager.m_pFunctionalOBBDataArray[i].m_bCollidable )// 충돌 가능할 때만 충돌 처리를 한다. ( 문이 부서지면 충돌처리를 하지 않는다.) { D3DXVECTOR3 CollidePoint; if( g_LodTerrain.m_FunctionalObjectManager.m_pFunctionalOBBDataArray[i].InterOBBvsRay( m_TargetPosition, camerainvviewvector, CollidePoint ) ) { D3DXVECTOR3 localcollidepoint; localcollidepoint = CollidePoint - m_TargetPosition; FLOAT dist = D3DXVec3LengthSq( &localcollidepoint ); if( dist < collidedist ) { if( dist < m_TargetDistance*m_TargetDistance ) { collidedist = dist; LastCollidePoint = CollidePoint; bCollide = TRUE; } } } } } } } if( bCollide ) { if( collidedist < m_MinDistance ) { camerainvviewvector = LastCollidePoint - m_TargetPosition; D3DXVec3Normalize( &camerainvviewvector, &camerainvviewvector ); m_CameraPosition = m_TargetPosition + (camerainvviewvector * m_MinDistance); } else { m_CameraPosition = LastCollidePoint; } } } } D3DXVECTOR3 distvector = m_CameraPosition - m_TargetPosition; //distvector.y = 1.0f; m_CurrentTargetDistance = D3DXVec3Length( &distvector ); // 카메라가 너무 가까이 붙었으면 타켓을 높이 설정해 하늘을 볼 수 있도록 설정. D3DXVECTOR3 targetposition = m_TargetPosition; if( !g_FreeMoveMode && m_EnableFirstPersonView ) { if( m_CurrentTargetDistance < m_MinDistance+m_AdditionalHeightMinDistance ) { targetposition.y += 0.1f; } } m_LookVector = targetposition - m_CameraPosition; D3DXVec3Normalize( &m_LookVector, &m_LookVector ); D3DXVec3Cross(&m_RightVector, &D3DXVECTOR3(0.0f, 1.0f, 0.0f), &m_LookVector); D3DXVec3Normalize(&m_RightVector, &m_RightVector); D3DXVECTOR3 newCamPos, newTargetPos; newCamPos = m_CameraPosition; newTargetPos= targetposition; newCamPos.x += m_CameraShakeFactor.x; newCamPos.y += m_CameraShakeFactor.y; newCamPos.z += m_CameraShakeFactor.z; newTargetPos.x += m_CameraShakeFactor.x; newTargetPos.y += m_CameraShakeFactor.y; newTargetPos.z += m_CameraShakeFactor.z; D3DXMatrixLookAtLH( &mp_view_matrix, &newCamPos, &newTargetPos, &D3DXVECTOR3(0.0, 1.0, 0.0) ); // Copy core view matrix if( setexternproperties ) { g_ViewMatrix = mp_view_matrix; #ifdef _XUSEFMOD #ifdef _XDWDEBUG extern BOOL g_3DSoundTargettype; if( g_3DSoundTargettype ) { g_FMODWrapper.SetListenerAttribute( m_CameraPosition, m_LookVector, m_UpVector ); } else { g_FMODWrapper.SetListenerAttribute( m_TargetPosition, m_LookVector, m_UpVector ); } #else g_FMODWrapper.SetListenerAttribute( m_CameraPosition, m_LookVector, m_UpVector ); //g_FMODWrapper.SetListenerAttribute( m_TargetPosition, m_LookVector, m_UpVector ); #endif #else AUDIOVECTOR newposition; newposition.x = m_CameraPosition.x; newposition.y = m_CameraPosition.y; newposition.z = m_CameraPosition.z; /*newposition.x = g_pLocalUser->m_Position.x; newposition.y = g_pLocalUser->m_Position.y; newposition.z = g_pLocalUser->m_Position.z;*/ g_XAudioSystem.m_pListener->SetPosition( newposition ); g_XAudioSystem.m_pListener->SetOrientation( m_LookVector, m_UpVector ); #endif if(g_pLocalUser) g_pLocalUser->m_ModelDescriptor.m_CameraDistance = m_CurrentTargetDistance; } }
// ------------------------------------- void TCam::Update( ) { D3DXVECTOR3 vDirection; bool computed = false; // solve moving // get normalized direction vector D3DXVec3Normalize(&vDirection,&(m_lookAt - m_pos)); // forward if( m_pInput->isKeyPressed(DIK_W)) { m_pos += vDirection * m_speed; m_lookAt += vDirection * m_speed; } // backward if( m_pInput->isKeyPressed(DIK_S)) { m_pos -= vDirection * m_speed; m_lookAt -= vDirection * m_speed; } // left if( m_pInput->isKeyPressed(DIK_A)) { // compute cross product of direction and up vector D3DXVec3Cross(&vDirection,&vDirection,&m_up); D3DXVec3Normalize(&vDirection,&vDirection); computed = true; m_pos += vDirection * m_speed; m_lookAt += vDirection * m_speed; } // right if( m_pInput->isKeyPressed(DIK_D)) { if( ! computed) { D3DXVec3Cross(&vDirection,&vDirection,&m_up); D3DXVec3Normalize(&vDirection,&vDirection); computed = true; } m_pos -= vDirection * m_speed; m_lookAt -= vDirection * m_speed; } // solve looking D3DXVECTOR3 rotAxis; // axis used for horizontal rotation D3DXMATRIX matRotAxis, matRotZ; D3DXVec3Normalize(&vDirection,&(m_lookAt - m_pos)); D3DXVec3Cross(&rotAxis,&vDirection,&m_up); D3DXVec3Normalize(&rotAxis,&rotAxis); D3DXMatrixRotationAxis(&matRotAxis,&rotAxis, (float)m_pInput->getYChange( ) / -360); D3DXMatrixRotationY(&matRotZ, (float)m_pInput->getXChange( ) / 360); // transform vectors D3DXVec3TransformCoord(&vDirection,&vDirection,&(matRotAxis * matRotZ)); D3DXVec3TransformCoord(&m_up,&m_up,&(matRotAxis * matRotZ)); // update look at vector m_lookAt = vDirection + m_pos; // Update the view matrix D3DXMATRIX mView; D3DXMatrixLookAtLH( &mView, &m_pos, &m_lookAt, &m_up ); // set the device m_pDevice->SetTransform(D3DTS_VIEW,&mView); }
void Outlines::GetFaceNormals(ID3DXMesh* mesh, ID3DXBuffer* adj, D3DXVECTOR3* currentfacenormal, D3DXVECTOR3 adjfacenormals[3], DWORD faceindex) { MeshVertex* v = 0; mesh->LockVertexBuffer(0, (void**)&v); WORD* in = 0; mesh->LockIndexBuffer(0, (void**)&in); DWORD* a = (DWORD*)adj->GetBufferPointer(); // // Get the face normal. GetFaceNormal(mesh, faceindex, currentfacenormal); // // Get adjacent face indices WORD faceindexA = WORD(a[faceindex * 3]); WORD faceindexB = WORD(a[faceindex * 3 + 1]); WORD faceindexC = WORD(a[faceindex * 3 + 2]); // // Get adjacent face normals, if there is no adjacent face, // then set the adjacent face normal to the opposite of the // "currentFaceNormal". Recall we do this because edges that // don't have an adjacent triangle are automatically considered // silhouette edges. And in order to make that happen, we need // the current face normal and adjacent face normal to point // in the opposite direction. Also, recall that an entry // in the adjacency buffer equal to -1 denotes that the edge // doesn't have an adjacent triangle. D3DXVECTOR3 facenormalA, facenormalB, facenormalC; if( faceindexA != USHRT_MAX ) // is there an adjacent triangle? { WORD iA = in[faceindexA * 3]; WORD iB = in[faceindexA * 3 + 1]; WORD iC = in[faceindexA * 3 + 2]; D3DXVECTOR3 vA = v[iA].pos; D3DXVECTOR3 vB = v[iB].pos; D3DXVECTOR3 vC = v[iC].pos; D3DXVECTOR3 edgeA = vB - vA; D3DXVECTOR3 edgeB = vC - vA; D3DXVec3Cross(&facenormalA, &edgeA, &edgeB); D3DXVec3Normalize(&facenormalA, &facenormalA); } else { facenormalA = -(*currentfacenormal); } if( faceindexB != USHRT_MAX ) // is there an adjacent triangle? { WORD iA = in[faceindexB * 3]; WORD iB = in[faceindexB * 3 + 1]; WORD iC = in[faceindexB * 3 + 2]; D3DXVECTOR3 vA = v[iA].pos; D3DXVECTOR3 vB = v[iB].pos; D3DXVECTOR3 vC = v[iC].pos; D3DXVECTOR3 edgeA = vB - vA; D3DXVECTOR3 edgeB = vC - vA; D3DXVec3Cross(&facenormalB, &edgeA, &edgeB); D3DXVec3Normalize(&facenormalB, &facenormalB); } else { facenormalB = -(*currentfacenormal); } if( faceindexC != USHRT_MAX ) // is there an adjacent triangle? { WORD iA = in[faceindexC * 3]; WORD iB = in[faceindexC * 3 + 1]; WORD iC = in[faceindexC * 3 + 2]; D3DXVECTOR3 vA = v[iA].pos; D3DXVECTOR3 vB = v[iB].pos; D3DXVECTOR3 vC = v[iC].pos; D3DXVECTOR3 edgeA = vB - vA; D3DXVECTOR3 edgeB = vC - vA; D3DXVec3Cross(&facenormalC, &edgeA, &edgeB); D3DXVec3Normalize(&facenormalC, &facenormalC); } else { facenormalC = -(*currentfacenormal); } // save adjacent face normals adjfacenormals[0] = facenormalA; adjfacenormals[1] = facenormalB; adjfacenormals[2] = facenormalC; mesh->UnlockVertexBuffer(); mesh->UnlockIndexBuffer(); }
//-------------------------------------------------------------------------------------- HRESULT CTerrain::CreateGrass() { HRESULT hr = S_OK; float fTileSize = m_fWorldScale / ( float )m_SqrtNumTiles; fTileSize /= 2.0f; float fGrassWidth = m_fGrassWidth / 2.0f; float fGrassHeight = m_fGrassHeight; D3DXVECTOR3* pGrassCenters = new D3DXVECTOR3[ m_NumGrassBlades ]; if( !pGrassCenters ) return E_OUTOFMEMORY; for( UINT i = 0; i < m_NumGrassBlades; i++ ) { pGrassCenters[i].x = RPercent() * fTileSize; pGrassCenters[i].y = 0.0f; pGrassCenters[i].z = RPercent() * fTileSize; } GRASS_VERTEX* pVertices = NULL; D3D10_BUFFER_DESC BufferDesc; if( m_pDev10 ) { BufferDesc.ByteWidth = m_NumGrassBlades * 4 * sizeof( GRASS_VERTEX ); BufferDesc.Usage = D3D10_USAGE_IMMUTABLE; BufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; BufferDesc.CPUAccessFlags = 0; BufferDesc.MiscFlags = 0; pVertices = new GRASS_VERTEX[ m_NumGrassBlades * 4 ]; if( !pVertices ) return E_OUTOFMEMORY; } else { V_RETURN( m_pDev->CreateVertexBuffer( m_NumGrassBlades * 4 * sizeof( GRASS_VERTEX ), D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, &m_pGrassVB, NULL ) ); V_RETURN( m_pGrassVB->Lock( 0, 0, ( void** )&pVertices, 0 ) ); } UINT vIndex = 0; for( UINT i = 0; i < m_NumGrassBlades; i++ ) { D3DXVECTOR3 vRandRight( RPercent(), 0, RPercent() ); D3DXVec3Normalize( &vRandRight, &vRandRight ); pVertices[vIndex ].pos = pGrassCenters[i] - vRandRight * fGrassWidth; pVertices[vIndex ].uv = D3DXVECTOR2( 0, 1 ); pVertices[vIndex + 1].pos = pGrassCenters[i] + vRandRight * fGrassWidth; pVertices[vIndex + 1].uv = D3DXVECTOR2( 1, 1 ); pVertices[vIndex + 2].pos = pVertices[vIndex + 1].pos + D3DXVECTOR3( 0, fGrassHeight, 0 ); pVertices[vIndex + 2].uv = D3DXVECTOR2( 1, 0 ); pVertices[vIndex + 3].pos = pVertices[vIndex ].pos + D3DXVECTOR3( 0, fGrassHeight, 0 ); pVertices[vIndex + 3].uv = D3DXVECTOR2( 0, 0 ); vIndex += 4; } if( m_pDev10 ) { D3D10_SUBRESOURCE_DATA InitData; InitData.pSysMem = pVertices; V_RETURN( m_pDev10->CreateBuffer( &BufferDesc, &InitData, &m_pGrassVB10 ) ); SAFE_DELETE_ARRAY( pVertices ); } else { m_pGrassVB->Unlock(); } // Alloc indices and distances SHORT* pGrassIndices = new SHORT[ m_NumGrassBlades ]; if( !pGrassIndices ) return E_OUTOFMEMORY; float* pGrassDistances = new float[ m_NumGrassBlades ]; if( !pGrassDistances ) return E_OUTOFMEMORY; m_NumDirections = 16; if( m_pDev10 ) { m_ppGrassIB10 = new ID3D10Buffer*[ m_NumDirections ]; if( !m_ppGrassIB10 ) return E_OUTOFMEMORY; } else { m_ppGrassIB = new LPDIRECT3DINDEXBUFFER9[ m_NumDirections ]; if( !m_ppGrassIB ) return E_OUTOFMEMORY; } m_pDirections = new D3DXVECTOR3[ m_NumDirections ]; if( !m_pDirections ) return E_OUTOFMEMORY; D3DXVECTOR3 vStartDir( -1,0,0 ); float fAngleDelta = ( D3DX_PI * 2.0f ) / ( float )( m_NumDirections ); for( UINT i = 0; i < m_NumDirections; i++ ) { D3DXMATRIX mRot; D3DXMatrixRotationY( &mRot, i * fAngleDelta ); D3DXVec3TransformNormal( &m_pDirections[i], &vStartDir, &mRot ); // init indices and distances for( UINT g = 0; g < m_NumGrassBlades; g++ ) { pGrassIndices[g] = ( SHORT )g; pGrassDistances[g] = -D3DXVec3Dot( &m_pDirections[i], &pGrassCenters[g] ); } // sort indices QuickDepthSort( pGrassIndices, pGrassDistances, 0, m_NumGrassBlades - 1 ); SHORT* pIndices = NULL; if( m_pDev10 ) { BufferDesc.ByteWidth = m_NumGrassBlades * 6 * sizeof( SHORT ); BufferDesc.Usage = D3D10_USAGE_IMMUTABLE; BufferDesc.BindFlags = D3D10_BIND_INDEX_BUFFER; BufferDesc.CPUAccessFlags = 0; BufferDesc.MiscFlags = 0; pIndices = new SHORT[ m_NumGrassBlades * 6 ]; if( !pIndices ) return E_OUTOFMEMORY; } else { V_RETURN( m_pDev->CreateIndexBuffer( m_NumGrassBlades * 6 * sizeof( SHORT ), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_ppGrassIB[i], NULL ) ); V_RETURN( m_ppGrassIB[i]->Lock( 0, 0, ( void** )&pIndices, 0 ) ); } UINT iIndex = 0; for( UINT g = 0; g < m_NumGrassBlades; g++ ) { //Starting vert SHORT GrassIndex = pGrassIndices[g] * 4; //Tri1 pIndices[iIndex ] = GrassIndex; pIndices[iIndex + 1] = GrassIndex + 3; pIndices[iIndex + 2] = GrassIndex + 1; //Tri2 pIndices[iIndex + 3] = GrassIndex + 1; pIndices[iIndex + 4] = GrassIndex + 3; pIndices[iIndex + 5] = GrassIndex + 2; iIndex += 6; } if( m_pDev10 ) { D3D10_SUBRESOURCE_DATA InitData; InitData.pSysMem = pIndices; V_RETURN( m_pDev10->CreateBuffer( &BufferDesc, &InitData, &m_ppGrassIB10[i] ) ); SAFE_DELETE_ARRAY( pIndices ); } else { m_ppGrassIB[i]->Unlock(); } } SAFE_DELETE_ARRAY( pGrassIndices ); SAFE_DELETE_ARRAY( pGrassDistances ); SAFE_DELETE_ARRAY( pGrassCenters ); return hr; }
bool KLightning::Create(const D3DXVECTOR3& StartPoint, const D3DXVECTOR3& EndPoint, float LengthOfNode, float WidthOfNode) { m_StartPoint = StartPoint; m_EndPoint = EndPoint; m_LengthOfNode = LengthOfNode; m_WidthOfNode = WidthOfNode; D3DXVECTOR3 DirOfLightning = m_EndPoint - m_StartPoint; // 闪电总体走向 float LengthOfLightning = ModelSFX::GetVec3Len(DirOfLightning); // 闪电总体长度 D3DXVec3Normalize(&DirOfLightning, &DirOfLightning); D3DXVECTOR3 verAxis(0.f, 1.f, 0.f); // The up axis D3DXVECTOR3 horAxis; D3DXVec3Cross(&horAxis, &DirOfLightning, &verAxis); // The horizontal axis D3DXVec3Normalize(&horAxis, &horAxis); D3DXVECTOR3 Vertex0, Vertex1; // The first two vertices in the current node; used in the following loop Vertex0 = m_StartPoint; D3DXVECTOR3 CurrentDir = DirOfLightning; // The direction of the current node; used in the following loop KLightningVertex* pLVBuffer = 0; // The vertex buffer m_pVB->Lock(0, 0, (void**)&pLVBuffer, 0); // 先处理头两个顶点 KLightningNode* pLNFirst = m_pNodes; // The 1st node KLightningVertex* pLVFirst = pLNFirst->GetVertex(pLVBuffer, 0); // The 1st vertex pLVFirst->x = m_StartPoint.x; pLVFirst->y = m_StartPoint.y; pLVFirst->z = m_StartPoint.z; KLightningVertex* pLVSecond = pLNFirst->GetVertex(pLVBuffer, 1); // The 2nd vertex Vertex1 = Vertex0 + horAxis * m_WidthOfNode; pLVSecond->x = Vertex1.x; pLVSecond->y = Vertex1.y; pLVSecond->z = Vertex1.z; float RemainingLengthOfLightning = LengthOfLightning; // The remaining length m_CurrentNumOfNodes = 0; KLightningVertex* pLV2 = 0; KLightningVertex* pLV3 = 0; while(m_CurrentNumOfNodes < m_MaxNumOfNodes) // If the remaining length is longer than length of a node { KLightningNode* pLN = m_pNodes + m_CurrentNumOfNodes; // The current node in legend; 传说中的当前结点 D3DXVECTOR3 Vertex2 = Vertex0 + CurrentDir * m_LengthOfNode; // The 2nd vertex in the current node D3DXVECTOR3 Vertex3 = Vertex1 + CurrentDir * m_LengthOfNode; // The 3rd vertex in the current node // Then rotate the two vertices float Angle = ModelSFX::GetRandom(-45, 45) * PI / 180; // The rotation angle around the up axis; the range of value is from -PI/2 to PI/2 if(Angle > 0) // Stretch the vertex to refine the corner { Vertex0 = Vertex0 + CurrentDir * m_WidthOfNode; KLightningVertex* pLV0 = pLN->GetVertex(pLVBuffer, 0); pLV0->x = Vertex0.x; pLV0->y = Vertex0.y; pLV0->z = Vertex0.z; } else if(Angle < 0) // Stretch the vertex to refine the corner { Vertex1 = Vertex1 + CurrentDir * m_WidthOfNode; KLightningVertex* pLV1 = pLN->GetVertex(pLVBuffer, 1); pLV1->x = Vertex1.x; pLV1->y = Vertex1.y; pLV1->z = Vertex1.z; } D3DXMATRIX mtx; // The rotation matrix //D3DXMATRIX matTransInv; //D3DXMATRIX matTrans; //D3DXMatrixTranslation(&matTransInv, -Vertex0.x, -Vertex0.y, -Vertex0.z); //D3DXMatrixTranslation(&matTrans, Vertex0.x, Vertex0.y, Vertex0.z); D3DXMatrixRotationAxis(&mtx, &verAxis, Angle); // The rotation matrix //D3DXMatrixMultiply(&mtx, &matTransInv, &mtx); //D3DXMatrixMultiply(&mtx, &mtx, &matTrans); Vertex2 -= -Vertex0; D3DXVECTOR4 vec4Temp; D3DXVec3Transform(&vec4Temp, &Vertex2, &mtx); Vertex2.x = vec4Temp.x / vec4Temp.w; Vertex2.y = vec4Temp.y / vec4Temp.w; Vertex2.z = vec4Temp.z / vec4Temp.w; Vertex2 += Vertex0; Vertex3 -= -Vertex0; D3DXVec3Transform(&vec4Temp, &Vertex3, &mtx); Vertex3.x = vec4Temp.x / vec4Temp.w; Vertex3.y = vec4Temp.y / vec4Temp.w; Vertex3.z = vec4Temp.z / vec4Temp.w; Vertex3 += Vertex0; // Update the vertices pLV2 = pLN->GetVertex(pLVBuffer, 2); pLV2->x = Vertex2.x; pLV2->y = Vertex2.y; pLV2->z = Vertex2.z; pLV3 = pLN->GetVertex(pLVBuffer, 3); pLV3->x = Vertex3.x; pLV3->y = Vertex3.y; pLV3->z = Vertex3.z; // Update some variables for the next loop Vertex0 = Vertex2; Vertex1 = Vertex3; //CurrentDir = CurrentDir * mtx; RemainingLengthOfLightning -= m_LengthOfNode; ++m_CurrentNumOfNodes; } pLV2->x = m_EndPoint.x; pLV2->y = m_EndPoint.y; pLV2->z = m_EndPoint.z; pLV3->x = m_EndPoint.x; pLV3->y = m_EndPoint.y; pLV3->z = m_EndPoint.z; m_pVB->Unlock(); return true; }
VehiclePose* VehicleController::getVehiclePose() { if(m_poseGiven) return m_vehiclePose; m_poseGiven = true; Mat backup; Vec3 wheelPos; NxWheelContactData dest; NxShape* cont; float contactPos; Vec3 suspensionTravel; /*CHASSIS*/ Mat rot; worldMat(&m_vehiclePose->matChassis, Vec3(m_actor->getGlobalPosition().x, m_actor->getGlobalPosition().y, m_actor->getGlobalPosition().z), Vec3(0, 0, 0)); D3DXMatrixRotationQuaternion(&rot, &D3DXQUATERNION(m_actor->getGlobalOrientationQuat().x, m_actor->getGlobalOrientationQuat().y, m_actor->getGlobalOrientationQuat().z, m_actor->getGlobalOrientationQuat().w)); Vec3 cross; Mat chassisRot; D3DXVec3Cross(&cross, &Vec3(1, 0, 0), &m_vehicleParams->vecChassisForward); D3DXMatrixRotationAxis(&chassisRot, &cross, acos(D3DXVec3Dot(&Vec3(1, 0, 0), &m_vehicleParams->vecChassisForward))); m_vehiclePose->matChassis = chassisRot * rot * m_vehiclePose->matChassis; D3DXVec3TransformCoord(&m_forward, &Vec3(1, 0, 0), &rot); D3DXVec3TransformCoord(&m_left, &Vec3(0, 0, -1), &rot); D3DXVec3Normalize(&m_forward, &m_forward); D3DXVec3Normalize(&m_left, &m_left); ShapeUserData* sud; //Wheels //Front Left wheel Mat wheelRot; D3DXMatrixRotationYawPitchRoll(&wheelRot, m_vehicleParams->vecFrontLeftWheelRotation.y, m_vehicleParams->vecFrontLeftWheelRotation.x, m_vehicleParams->vecFrontLeftWheelRotation.z); sud = (ShapeUserData*)(m_wheelFrontLeft->userData); sud->wheelShapePose.getColumnMajor44((NxF32*)&m_vehiclePose->matFrontLeftWheel); m_vehiclePose->matFrontLeftWheel = wheelRot * m_vehiclePose->matFrontLeftWheel; wheelPos = getVehicleParams()->posFrontLeftWheel; D3DXVec3TransformCoord(&wheelPos, &wheelPos, &m_vehiclePose->matChassis); cont = m_wheelFrontLeft->getContact(dest); backup = m_vehiclePose->matChassis; backup._41 = 0; backup._42 = 0; backup._43 = 0; contactPos = dest.contactPosition; if(!cont) contactPos = m_wheelFrontLeft->getSuspensionTravel(); else contactPos -= m_wheelFrontLeft->getRadius(); suspensionTravel = Vec3(0, contactPos, 0); D3DXVec3TransformCoord(&suspensionTravel, &suspensionTravel, &backup); //if(dest.contactForce) wheelPos -= suspensionTravel; m_vehiclePose->matFrontLeftWheel._41 = wheelPos.x; m_vehiclePose->matFrontLeftWheel._42 = wheelPos.y; m_vehiclePose->matFrontLeftWheel._43 = wheelPos.z; //Front Right wheel D3DXMatrixRotationYawPitchRoll(&wheelRot, m_vehicleParams->vecFrontRightWheelRotation.y, m_vehicleParams->vecFrontRightWheelRotation.x, m_vehicleParams->vecFrontRightWheelRotation.z); sud = (ShapeUserData*)(m_wheelFrontRight->userData); sud->wheelShapePose.getColumnMajor44((NxF32*)&m_vehiclePose->matFrontRightWheel); m_vehiclePose->matFrontRightWheel = wheelRot * m_vehiclePose->matFrontRightWheel; wheelPos = getVehicleParams()->posFrontRightWheel; D3DXVec3TransformCoord(&wheelPos, &wheelPos, &m_vehiclePose->matChassis); cont = m_wheelFrontRight->getContact(dest); backup = m_vehiclePose->matChassis; backup._41 = 0; backup._42 = 0; backup._43 = 0; contactPos = dest.contactPosition; if(!cont) contactPos = m_wheelFrontRight->getSuspensionTravel(); else contactPos -= m_wheelFrontRight->getRadius(); suspensionTravel = Vec3(0, contactPos, 0); D3DXVec3TransformCoord(&suspensionTravel, &suspensionTravel, &backup); //if(dest.contactForce) wheelPos -= suspensionTravel; m_vehiclePose->matFrontRightWheel._41 = wheelPos.x; m_vehiclePose->matFrontRightWheel._42 = wheelPos.y; m_vehiclePose->matFrontRightWheel._43 = wheelPos.z; //Rear Left wheel D3DXMatrixRotationYawPitchRoll(&wheelRot, m_vehicleParams->vecRearLeftWheelRotation.y, m_vehicleParams->vecRearLeftWheelRotation.x, m_vehicleParams->vecRearLeftWheelRotation.z); sud = (ShapeUserData*)(m_wheelRearLeft->userData); sud->wheelShapePose.getColumnMajor44((NxF32*)&m_vehiclePose->matRearLeftWheel); m_vehiclePose->matRearLeftWheel = wheelRot * m_vehiclePose->matRearLeftWheel; wheelPos = getVehicleParams()->posRearLeftWheel; D3DXVec3TransformCoord(&wheelPos, &wheelPos, &m_vehiclePose->matChassis); cont = m_wheelRearLeft->getContact(dest); backup = m_vehiclePose->matChassis; backup._41 = 0; backup._42 = 0; backup._43 = 0; contactPos = dest.contactPosition; if(!cont) contactPos = m_wheelRearLeft->getSuspensionTravel(); else contactPos -= m_wheelRearLeft->getRadius(); suspensionTravel = Vec3(0, contactPos, 0); D3DXVec3TransformCoord(&suspensionTravel, &suspensionTravel, &backup); //if(dest.contactForce) wheelPos -= suspensionTravel; m_vehiclePose->matRearLeftWheel._41 = wheelPos.x; m_vehiclePose->matRearLeftWheel._42 = wheelPos.y; m_vehiclePose->matRearLeftWheel._43 = wheelPos.z; //Rear Right wheel D3DXMatrixRotationYawPitchRoll(&wheelRot, m_vehicleParams->vecRearRightWheelRotation.y, m_vehicleParams->vecRearRightWheelRotation.x, m_vehicleParams->vecRearRightWheelRotation.z); sud = (ShapeUserData*)(m_wheelRearRight->userData); sud->wheelShapePose.getColumnMajor44((NxF32*)&m_vehiclePose->matRearRightWheel); m_vehiclePose->matRearRightWheel = wheelRot * m_vehiclePose->matRearRightWheel; wheelPos = getVehicleParams()->posRearRightWheel; D3DXVec3TransformCoord(&wheelPos, &wheelPos, &m_vehiclePose->matChassis); cont = m_wheelRearRight->getContact(dest); backup = m_vehiclePose->matChassis; backup._41 = 0; backup._42 = 0; backup._43 = 0; contactPos = dest.contactPosition; if(!cont) contactPos = m_wheelRearRight->getSuspensionTravel(); else contactPos -= m_wheelRearRight->getRadius(); suspensionTravel = Vec3(0, contactPos, 0); D3DXVec3TransformCoord(&suspensionTravel, &suspensionTravel, &backup); //if(dest.contactForce) wheelPos -= suspensionTravel; m_vehiclePose->matRearRightWheel._41 = wheelPos.x; m_vehiclePose->matRearRightWheel._42 = wheelPos.y; m_vehiclePose->matRearRightWheel._43 = wheelPos.z; return m_vehiclePose; }
int CObjectRightView::SetupLights() { float max = 1; // Set up a white, directional light, with an oscillating direction. // Note that many lights may be active at a time (but each one slows down // the rendering of our scene). However, here we are just using one. Also, // we need to set the D3DRS_LIGHTING renderstate to enable lighting D3DXVECTOR3 vecDir; D3DLIGHT9 light; ZeroMemory(&light, sizeof(D3DLIGHT9)); light.Type = D3DLIGHT_DIRECTIONAL; light.Diffuse.r = 3.4f; light.Diffuse.g = 3.4f; light.Diffuse.b = 3.4f; light.Diffuse.a = 3.4f; light.Specular.r = 0.1f; light.Specular.g = 0.1f; light.Specular.b = 0.1f; light.Specular.a = 0.5f; light.Ambient.r = 0.5f; light.Ambient.g = 0.5f; light.Ambient.b = 0.5f; light.Ambient.a = 1.0f; light.Position.x = (float) -2.0f; light.Position.y = (float) -2.0f; light.Position.z = (float) -2.0f; vecDir.x = -2.0f; vecDir.y = -6.0f; vecDir.z = -1.0f; D3DXVec3Normalize((D3DXVECTOR3*)&light.Direction, &vecDir); light.Range = 5.0f; if (FAILED(g_pd3dDevice->SetLight(0, &light))) { DirectXStatus = -1; return 1; } if (FAILED(g_pd3dDevice->LightEnable(0, TRUE))) { DirectXStatus = -1; return 1; } D3DLIGHT9 light1; ZeroMemory(&light1, sizeof(D3DLIGHT9)); light1.Type = D3DLIGHT_DIRECTIONAL; light1.Diffuse.r = 3.4f; light1.Diffuse.g = 3.4f; light1.Diffuse.b = 3.4f; light1.Diffuse.a = 3.4f; light1.Specular.r = 0.1f; light1.Specular.g = 0.1f; light1.Specular.b = 0.1f; light1.Specular.a = 0.5f; light1.Ambient.r = 0.5f; light1.Ambient.g = 0.5f; light1.Ambient.b = 0.5f; light1.Ambient.a = 1.0f; light1.Position.x = (float) 2.0f; light1.Position.y = (float) 2.0f; light1.Position.z = (float) 2.0f; vecDir.x = 2.0f; vecDir.y = 6.0f; vecDir.z = 1.0f; D3DXVec3Normalize((D3DXVECTOR3*)&light1.Direction, &vecDir); light1.Range = 5.0f; if (FAILED(g_pd3dDevice->SetLight(1, &light1))) { DirectXStatus = -1; return 1; } if (FAILED(g_pd3dDevice->LightEnable(1, TRUE))) { DirectXStatus = -1; return 1; } if (FAILED(g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, TRUE))) { DirectXStatus = -1; return 1; } // Finally, turn on some ambient light. g_pd3dDevice->SetRenderState(D3DRS_AMBIENT, 0x00707070); return 0; }
void SpherePopup::Update() { D3DXVECTOR3 t; auto vp = GraphicsEngine::GetViewport(); viewport.Width = vp.Width; viewport.Height = vp.Height; D3DXVec3Project(&t, &worldPos, &viewport, &projection, &view, &world); windowWP.x = t.x; windowWP.y = t.y; D3DXVECTOR4 t4; t = worldPos; t.y = 0; D3DXVec3Normalize(&t, &t); D3DXVec3Transform(&t4, &t, &world); if (animationState > .99f && t4.z <= .5f) { animationMultiplier = -1; } if (animationState < 0) isDead = true; if (animationState < 0.3333f) { if (windowPos.x < Window::GetWidth() / 2)//line should go to the right top corner animationState += animationMultiplier * .3333f * 10 / D3DXVec2Length(&(windowWP - windowPos2)); else animationState += animationMultiplier * .3333f * 10 / D3DXVec2Length(&(windowWP - windowPos)); } else if (animationState < 0.6666f) { animationState += animationMultiplier * .3333f * 10 / 192; } else { animationState += animationMultiplier * .3333f * 10 / 128; if (animationState > 1) { animationState = 1; animationMultiplier = 0; } } float s1 = animationState * 3, s2 = animationState * 3 - 1, s3 = animationState * 3 - 2; vLines[0] = windowWP.x; vLines[1] = windowWP.y; vLines[3] = lerp(windowWP.y, windowPos.y, s1); vLines[5] = vLines[7] = vLines[9] = vLines[19] = vWindow[1] = vWindow[5] = windowPos.y; vLines[11] = vLines[13] = vLines[15] = vLines[17] = vWindow[3] = vWindow[7] = lerp(windowPos.y, windowPos2.y, s3); if (windowPos.x < Window::GetWidth() / 2)//line should go to the right top corner { vLines[2] = lerp(windowWP.x, windowPos2.x, s1); vLines[4] = vLines[14] = vLines[16] = vLines[18] = vWindow[4] = vWindow[6] = windowPos2.x; vLines[6] = vLines[8] = vLines[10] = vLines[12] = vWindow[0] = vWindow[2] = lerp(windowPos2.x, windowPos.x, s2); } else { vLines[2] = lerp(windowWP.x, windowPos.x, s1); vLines[4] = vLines[14] = vLines[16] = vLines[18] = vWindow[0] = vWindow[2] = windowPos.x; vLines[6] = vLines[8] = vLines[10] = vLines[12] = vWindow[4] = vWindow[6] = lerp(windowPos.x, windowPos2.x, s2); } if (s3 > 0) { vWindow[3]--; vWindow[4]--; vWindow[6]--; vWindow[7]--; } meshLines->SetRawData(vLines, 20, 20 * sizeof(float), 2 * sizeof(float)); meshWindow->SetRawData(vWindow, 8, 8 * sizeof(float), 2 * sizeof(float)); }
//============================================================================================================= void CGodRayRenderer9::Draw() { if( !BackBuffer || !CanBeApplied() ) return; viewdir.x = View._13; viewdir.y = View._23; viewdir.z = View._33; D3DXVec3Normalize(&lightdir, &Sun); float exposure = CHelper::Clamp<float>(D3DXVec3Dot(&lightdir, &viewdir), 0, 1); if( exposure > 0.0f ) { D3DXVECTOR3 sun = Eye + Sun; D3DXVec3Transform(&lightpos, &sun, &ViewProj); lightpos.x = (1.0f + lightpos.x / lightpos.w) * 0.5f; lightpos.y = (1.0f - lightpos.y / lightpos.w) * 0.5f; manager->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); manager->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); effect->SetTechnique("godray"); effect->SetFloat("exposure", exposure); effect->SetVector("lightPos", (D3DXVECTOR4*)&lightpos); world._11 = size.x * 0.25f; world._22 = size.y * 0.25f; game->Graphics->SetRenderTarget(0, surfaces[0]); manager->SetTexture(0, rendertargets[1]); effect->Begin(NULL, 0); effect->BeginPass(0); { game->DrawImage(world); } effect->EndPass(); effect->End(); // blur effect->SetTechnique("blur"); game->Graphics->SetRenderTarget(0, surfaces[1]); manager->SetTexture(0, rendertargets[2]); effect->Begin(NULL, 0); effect->BeginPass(0); { game->DrawImage(world); } effect->EndPass(); effect->End(); // final effect->SetTechnique("final"); world._11 = size.x; world._22 = size.y; game->Graphics->SetRenderTarget(0, BackBuffer); manager->SetTexture(0, rendertargets[0]); manager->SetTexture(1, rendertargets[3]); effect->Begin(NULL, 0); effect->BeginPass(0); { game->DrawImage(world); } effect->EndPass(); effect->End(); manager->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); manager->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); } else { effect->SetTechnique("nothing"); world._11 = size.x; world._22 = size.y; game->Graphics->SetRenderTarget(0, BackBuffer); manager->SetTexture(0, rendertargets[0]); effect->Begin(NULL, 0); effect->BeginPass(0); { game->DrawImage(world); } effect->EndPass(); effect->End(); } }