void Camera::rotateX(float amount) { XMMATRIX mRotate = XMMatrixRotationAxis(XMLoadFloat4(&v_Right), amount); XMVECTOR new_y = XMVector4Transform(XMLoadFloat4(&v_Up), mRotate); XMVECTOR new_z = XMVector4Transform(XMLoadFloat4(&v_Look), mRotate); XMStoreFloat4(&v_Up, new_y); XMStoreFloat4(&v_Look, new_z); update(); }
void Camera::rotateZ(float amount) { XMMATRIX mRotate = XMMatrixRotationZ(amount); XMVECTOR new_x = XMVector4Transform(XMLoadFloat4(&v_Right), mRotate); XMVECTOR new_z = XMVector4Transform(XMLoadFloat4(&v_Look), mRotate); XMStoreFloat4(&v_Right, new_x); XMStoreFloat4(&v_Look, new_z); update(); }
void Direct3D::update(float dt) { static float rotDT = 0.f; rotDT = dt; XMMATRIX rot = XMMatrixRotationAxis(XMVectorSet(0.f, 0.f, 1.f, 0.f), rotDT); for(int i = 0; i < NROFLIGHTS; i++) { XMVECTOR vLightPos = XMLoadFloat4(&m_lightList[i].pos); vLightPos = XMVector4Transform(vLightPos, rot); XMStoreFloat4(&m_lightList[i].pos, vLightPos); } m_pCamera->update(); //m_fps = 1/dt; m_time += dt; static int frameCnt = 0; static float t_base = 0.f; frameCnt++; if(m_time - t_base >= 1.f) { frameCnt /= 1; m_fps = (float)frameCnt; frameCnt = 0; t_base += 1.f; } updateConstantBuffers(); }
void Player::UpdateAcceleration(float fElapsedTime) { XMVECTOR vGamePadRightThumb = g_XMZero; XMVECTOR vGamePadLeftThumb = g_XMZero; XMVECTOR vMouseDelta = g_XMZero; XMVECTOR vKeyboardDirection = XMVectorSet(m_vKeyboardDirection.x, 0.f, m_vKeyboardDirection.z, 0.f); if (m_bUseGamepad) { vGamePadRightThumb = XMVectorSet(m_vGamePadRightThumb.x, -m_vGamePadRightThumb.z, 0, 0); vGamePadRightThumb *= XMVectorAbs(vGamePadRightThumb); vGamePadLeftThumb = XMVectorSet(m_vGamePadLeftThumb.x, 0, m_vGamePadLeftThumb.z, 0); } if (m_bUseMouse) { vMouseDelta = m_vMouseDelta; } XMVECTOR vRotVelocity = vMouseDelta * m_fRotationScaler + vGamePadRightThumb * 0.01f; XMVECTOR vAccel = XMVector3Normalize(vKeyboardDirection + vGamePadLeftThumb) * m_fMoveScaler; vAccel = XMVector4Transform(vAccel, GetWorld()); m_vRotVelocity = vRotVelocity; mAcceleration += vAccel * fElapsedTime; }
// Update frame-based values. void D3D12Multithreading::OnUpdate() { m_timer.Tick(NULL); PIXSetMarker(m_commandQueue.Get(), 0, L"Getting last completed fence."); // Get current GPU progress against submitted workload. Resources still scheduled // for GPU execution cannot be modified or else undefined behavior will result. const UINT64 lastCompletedFence = m_fence->GetCompletedValue(); // Move to the next frame resource. m_currentFrameResourceIndex = (m_currentFrameResourceIndex + 1) % FrameCount; m_pCurrentFrameResource = m_frameResources[m_currentFrameResourceIndex]; // Make sure that this frame resource isn't still in use by the GPU. // If it is, wait for it to complete. if (m_pCurrentFrameResource->m_fenceValue > lastCompletedFence) { HANDLE eventHandle = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (eventHandle == nullptr) { ThrowIfFailed(HRESULT_FROM_WIN32(GetLastError())); } ThrowIfFailed(m_fence->SetEventOnCompletion(m_pCurrentFrameResource->m_fenceValue, eventHandle)); WaitForSingleObject(eventHandle, INFINITE); CloseHandle(eventHandle); } m_cpuTimer.Tick(NULL); float frameTime = static_cast<float>(m_timer.GetElapsedSeconds()); float frameChange = 2.0f * frameTime; if (m_keyboardInput.leftArrowPressed) m_camera.RotateYaw(-frameChange); if (m_keyboardInput.rightArrowPressed) m_camera.RotateYaw(frameChange); if (m_keyboardInput.upArrowPressed) m_camera.RotatePitch(frameChange); if (m_keyboardInput.downArrowPressed) m_camera.RotatePitch(-frameChange); if (m_keyboardInput.animate) { for (int i = 0; i < NumLights; i++) { float direction = frameChange * pow(-1.0f, i); XMStoreFloat4(&m_lights[i].position, XMVector4Transform(XMLoadFloat4(&m_lights[i].position), XMMatrixRotationY(direction))); XMVECTOR eye = XMLoadFloat4(&m_lights[i].position); XMVECTOR at = { 0.0f, 8.0f, 0.0f }; XMStoreFloat4(&m_lights[i].direction, XMVector3Normalize(XMVectorSubtract(at, eye))); XMVECTOR up = { 0.0f, 1.0f, 0.0f }; m_lightCameras[i].Set(eye, at, up); m_lightCameras[i].Get3DViewProjMatrices(&m_lights[i].view, &m_lights[i].projection, 90.0f, static_cast<float>(m_width), static_cast<float>(m_height)); } } m_pCurrentFrameResource->WriteConstantBuffers(&m_viewport, &m_camera, m_lightCameras, m_lights); }
XMFLOAT3 EliteEnemyShip::getPosition() { XMFLOAT4 pos; XMFLOAT4 orig = XMFLOAT4(0,0,0,1); XMFLOAT4X4 mat = *(body->getWorldMatrix()); XMStoreFloat4(&pos, XMVector4Transform(XMLoadFloat4(&orig), XMLoadFloat4x4(&mat))); return (XMFLOAT3(pos.x, pos.y, pos.z)); }
void CCamera::Bouger(float tempsEcoule) { // Pour les mouvements, nous utilisons le gestionnaire de saisie CMoteurWindows& rMoteur = CMoteurWindows::GetInstance(); CDIManipulateur& rGestionnaireDeSaisie = rMoteur.GetGestionnaireDeSaisie(); // Vérifier l'état de la touche gauche if (rGestionnaireDeSaisie.ToucheAppuyee(DIK_LEFT)) { // orientationCamera += qq chose; // direction = directionOriginale * matricerotationZ( orientationCamera) orientationCamera += ( 2.0f * XM_PI / 10.0f ) * tempsEcoule; direction = XMVector4Transform(directionOriginale , XMMatrixRotationZ(orientationCamera)); } // Vérifier l'état de la touche droite if (rGestionnaireDeSaisie.ToucheAppuyee(DIK_RIGHT)) { orientationCamera -= (2.0f * XM_PI / 10.0f) * tempsEcoule; direction = XMVector4Transform(directionOriginale, XMMatrixRotationZ(orientationCamera)); } // Vérifier l'état de la touche gauche if (rGestionnaireDeSaisie.ToucheAppuyee(DIK_UP)) { position = position + direction * 5.0f /*vitesse*/ * tempsEcoule; } // Vérifier l'état de la touche droite if (rGestionnaireDeSaisie.ToucheAppuyee(DIK_DOWN)) { position = position - direction * 5.0f /*vitesse*/ * tempsEcoule; } Update(); }
/** * Transforms a four component vector by the current matrix. * * @param vVec The vector to transform. * @return The resulting vector. */ CFVec4 CFMat4x4::TransformVec4( CFVec4Arg vVec ) { CFVec4 v4Return; const XMMATRIX& matA = *reinterpret_cast<const XMMATRIX*>( this ); const XMVECTOR& vArg = *reinterpret_cast<const XMVECTOR*>( &vVec ); XMVECTOR& vResult = *reinterpret_cast<XMVECTOR*>( &v4Return ); //Transform vArg by the matrix: vResult = XMVector4Transform( vArg, matA ); return v4Return; }
void CALLBACK OnD3D11FrameRender(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext) { pd3dImmediateContext->ClearRenderTargetView(DXUTGetD3D11RenderTargetView(), Colors::DeepSkyBlue); pd3dImmediateContext->ClearDepthStencilView(DXUTGetD3D11DepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0); CONSTANTBUFFER cb; ZeroMemory(&cb, sizeof(CONSTANTBUFFER)); XMMATRIX mat = XMLoadFloat4x4(&(g_mesh->getWorld())); XMStoreFloat4x4(&cb.world, XMMatrixTranspose(mat)); //cb.world = g_mesh->getWorld(); XMStoreFloat4x4(&cb.view, XMMatrixTranspose(g_camera.GetViewMatrix())); XMStoreFloat4x4(&cb.projection, XMMatrixTranspose(g_camera.GetProjMatrix())); /* 1 0 0 0 Side (Right) 0 1 0 0 Up 0 0 1 0 Foward x y z 1 Position */ //1. XMMATRIX -> FLOAT4X4 XMVECTOR v = XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f); XMVECTOR litpos = XMVector4Transform(v, g_matLight); litpos = XMVector4Normalize(litpos); XMStoreFloat4(&cb.litDir, litpos); cb.litCol = XMFLOAT4(0.7f, 0.7f, 0.6f, 1.0f); g_shader->RenderPrepare(&cb); g_mesh->Render(); // mat = XMLoadFloat4x4(&(g_meshLight->getWorld())); XMStoreFloat4x4(&cb.world, XMMatrixTranspose(mat)); g_shader->RenderPrepare(&cb); g_meshLight->Render(); }
//-------------------------------------------------------------------------------------- // Render a frame //-------------------------------------------------------------------------------------- void Render() { // Update our time static float t = 0.0f; float delta_t = 0.0f; { static DWORD dwTimeStart = 0; DWORD dwTimeCur = GetTickCount(); if( dwTimeStart == 0 ) dwTimeStart = dwTimeCur; float old_t = t; t = ( dwTimeCur - dwTimeStart ) / 1000.0f; delta_t = t-old_t; } { sphParticle particles[32]; for(size_t i=0; i<_countof(particles); ++i) { particles[i].position = ist::simdvec4_set(GenRand()*0.5f, GenRand()*0.5f, GenRand()*0.5f-7.5f, 1.0f); particles[i].velocity = _mm_set1_ps(0.0f); } g_sphgrid.addParticles(particles, _countof(particles)); } { static PerformanceCounter s_timer; static float s_prev = 0.0f; PerformanceCounter timer; g_sphgrid.update(1.0f); g_pImmediateContext->UpdateSubresource( g_pCubeInstanceBuffer, 0, NULL, &g_sphgrid.particles, 0, 0 ); if(s_timer.getElapsedMillisecond() - s_prev > 1000.0f) { char buf[128]; _snprintf(buf, _countof(buf), " SPH update: %d particles %.3fms\n", g_sphgrid.num_active_particles, timer.getElapsedMillisecond()); OutputDebugStringA(buf); ::SetWindowTextA(g_hWnd, buf); s_prev = s_timer.getElapsedMillisecond(); } } { CBChangesEveryFrame cb; XMVECTOR eye = g_camera.getEye(); { XMMATRIX rot = XMMatrixRotationZ(XMConvertToRadians(0.1f)); eye = XMVector4Transform(eye, rot); } g_camera.setEye(eye); g_camera.updateMatrix(); XMMATRIX vp = g_camera.getViewProjectionMatrix(); cb.ViewProjection = XMMatrixTranspose( vp ); cb.CameraPos = (FLOAT*)&eye; cb.LightPos = XMFLOAT4(10.0f, 10.0f, -10.0f, 1.0f); cb.LightColor = XMFLOAT4(0.9f, 0.9f, 0.9f, 1.0f); cb.MeshShininess = 200.0f; g_pImmediateContext->UpdateSubresource( g_pCBChangesEveryFrame, 0, NULL, &cb, 0, 0 ); } float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; // red, green, blue, alpha g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, ClearColor ); g_pImmediateContext->ClearDepthStencilView( g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 ); { ID3D11Buffer *buffers[] = {g_pCubeVertexBuffer, g_pCubeInstanceBuffer}; UINT strides[] = {sizeof(SimpleVertex), sizeof(sphParticle), }; UINT offsets[] = {0, 0}; g_pImmediateContext->IASetVertexBuffers( 0, ARRAYSIZE(buffers), buffers, strides, offsets ); } g_pImmediateContext->IASetInputLayout( g_pCubeVertexLayout ); g_pImmediateContext->IASetIndexBuffer( g_pCubeIndexBuffer, DXGI_FORMAT_R16_UINT, 0 ); g_pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); // Render the cube g_pImmediateContext->VSSetShader( g_pCubeVertexShader, NULL, 0 ); g_pImmediateContext->VSSetConstantBuffers( 0, 1, &g_pCBChangesEveryFrame ); g_pImmediateContext->PSSetShader( g_pCubePixelShader, NULL, 0 ); g_pImmediateContext->PSSetConstantBuffers( 0, 1, &g_pCBChangesEveryFrame ); g_pImmediateContext->DrawIndexedInstanced( 36, (UINT)g_sphgrid.num_active_particles, 0, 0, 0 ); // Present our back buffer to our front buffer g_pSwapChain->Present( 1, 0 ); // vsync on //g_pSwapChain->Present( 0, 0 ); // vsync off }
//------------------------------------------- // とりあえずIK void BoneModel::VMDIkAnimation() { //XMStoreFloat4() //XMLoadFloat4() if (mBone.empty())return; if (mMotion.empty())return; DWORD mBoneNum = mBone.size(); DWORD mIkNum = mIk.size(); // IK計算 for (DWORD i = 0; i < mIkNum; i++){ //{ // int i = 0; Ik& ik = mIk[i]; UINT tg_idx = ik.target_bone_index; UINT ik_idx = ik.bone_index; for (UINT ite = 0; ite<ik.iterations; ++ite){ for (UINT chn = 0; chn<ik.chain_length; ++chn){ UINT link_idx = ik.child_bone_index[chn];// if (link_idx >= mBoneNum)continue; Bone& link_bone = mBone[link_idx]; //UINT link_pidx = link_bone.mIkBoneIdx; UINT link_pidx = link_bone.mHierarchy.mIdxParent; //if (link_bone.mIkBoneIdx != 0){ // continue; //} if (link_pidx >= mBoneNum)continue; Bone& link_parent = mBone[link_pidx]; Bone& tg_bone = mBone[tg_idx]; (void)tg_bone; Bone& ik_bone = mBone[ik_idx]; (void)ik_bone; XMVECTOR target_wpos = mBone[tg_idx].mMtxPose.r[3]; XMVECTOR ik_wpos = mBone[ik_idx].mMtxPose.r[3]; XMVECTOR lp_wpos = link_parent.mMtxPose.r[3]; //Linkボーンのローカル空間に変換 XMVECTOR Determinant; XMMATRIX inv_mtx = XMMatrixInverse(&Determinant, link_bone.mMtxPose); XMVECTOR tg_pos = XMVector4Transform(target_wpos, inv_mtx); XMVECTOR ik_pos = XMVector4Transform(ik_wpos, inv_mtx); XMVECTOR lp_pos = XMVector4Transform(lp_wpos, inv_mtx); // 回転軸と角度 XMVECTOR rot_axis = XMVectorSet(1, 0, 0, 0); float ang = 0.0f; bool same_dir = false; if (!RotDir(tg_pos, ik_pos, ik.control_weight, &rot_axis, &ang)){ same_dir = true; } if (!same_dir){ //tg_dirをik_dirに一致させるための回転 XMVECTOR rot = XMQuaternionRotationAxis(rot_axis, ang); XMVECTOR lrot = FloatToVector(link_bone.mRot); XMVECTOR bone_rot_before = lrot; link_bone.mRot = VectorToFloat(XMQuaternionMultiply(rot, lrot)); float dist_tg = XMVectorGetX(XMVector3Length(tg_pos)); float dist_ik = XMVectorGetX(XMVector3Length(ik_pos)); (void)dist_ik; float dist_lp = XMVectorGetX(XMVector3Length(lp_pos)); (void)dist_lp; float dist_pltg = XMVectorGetX(XMVector3Length(lp_pos - tg_pos)); float dist_plik = XMVectorGetX(XMVector3Length(lp_pos - ik_pos)); float dot_tgik = XMVectorGetX(XMVector3Dot(XMVector3Normalize(tg_pos), XMVector3Normalize(ik_pos))); (void)dot_tgik; // 回転制限 if (/*link.bLimit*/ 1){ XMVECTOR rotmax, rotmin; //114.5916 = 2 float a = 2;// XM_PI / 180.0f * 57.25f; rotmax = XMVectorSet(a, a, a, 0);//link.vMax; rotmin = XMVectorSet(-a, -a, -a, 0);//link.vMin; //名前に"ひざ"があったら回転制限 if (std::string::npos != link_bone.mStrName.find("ひざ")){ rotmax = XMVectorSet(-XM_PI / 180.0f*0.5f, 0, 0, 0); rotmin = XMVectorSet(-XM_PI, 0, 0, 0); } struct IkLink{ XMFLOAT4 mMax; XMFLOAT4 mMin; }; IkLink link = { VectorToFloat(rotmax), VectorToFloat(rotmin) }; //Bone& link = link_bone; link_bone.mRot = VectorToFloat(LimitAngle(FloatToVector(link_bone.mRot), rotmin, rotmax)); XMVECTOR angxyz = GetAngle(rot); //膝を曲げるための仮処理 かなりてきとう if (XMVectorGetX(angxyz) >= 0 && //0.9f < dot_tgik && //dist_tg > dist_ik && dist_pltg > dist_plik && link.mMax.x < 0 && link.mMax.y == link.mMin.y && link.mMax.z == link.mMin.z){ //親リンクの回転接平面(できるだけこの平面に近づけたほうがよりIK目標に近づける) XMVECTOR lp_nor = XMVector3Normalize(-lp_pos);//平面の法線 //lp_norとの内積が0になる位置を目標にする //2つあるので回転制限後の|内積|が小さいほう XMVECTOR tng = XMVector3Cross(XMVectorSet(1, 0, 0, 0), lp_nor); //+tngと-tngの2つ XMVECTOR rot_axis0, rot_axis1; float ang0 = 0, ang1 = 0; // 回転軸をXに限定 rot_axis1 = rot_axis0 = XMVectorSet(1, 0, 0, 0); XMVECTOR tdir = XMVector3Normalize(XMVectorSetX(tg_pos, 0)); tng = XMVector3Normalize(XMVectorSetX(tng, 0)); RotDir(tdir, tng, ik.control_weight, &rot_axis0, &ang0); RotDir(tdir, -tng, ik.control_weight, &rot_axis1, &ang1); if (XMVectorGetX(rot_axis0) < 0.0f)ang0 = -ang0; if (XMVectorGetX(rot_axis1) < 0.0f)ang1 = -ang1; //これは絶対違う ぴくぴく対策 float coef = (dist_pltg - dist_plik) / dist_tg; if (coef > 1)coef = 1; ang0 *= coef; ang1 *= coef; //ang0,1は現在の位置からの相対角度 // 回転制限を考慮した相対角度に float angx_b = XMVectorGetX(GetAngle(bone_rot_before)); float angx_a0 = angx_b + ang0; float angx_a1 = angx_b + ang1; if (angx_a0 < link.mMin.x) angx_a0 = link.mMin.x; if (angx_a0 > link.mMax.x) angx_a0 = link.mMax.x; if (angx_a1 < link.mMin.x) angx_a1 = link.mMin.x; if (angx_a1 > link.mMax.x) angx_a1 = link.mMax.x; ang0 = angx_a0 - angx_b; ang1 = angx_a1 - angx_b; XMVECTOR rot0 = XMQuaternionRotationRollPitchYaw(ang0, 0, 0); XMVECTOR rot1 = XMQuaternionRotationRollPitchYaw(ang1, 0, 0); XMVECTOR tdir0 = XMVector3TransformCoord(tdir, XMMatrixRotationQuaternion(rot0)); XMVECTOR tdir1 = XMVector3TransformCoord(tdir, XMMatrixRotationQuaternion(rot1)); float d0 = XMVectorGetX(XMVectorAbs(XMVector3Dot(tdir0, lp_nor))); float d1 = XMVectorGetX(XMVectorAbs(XMVector3Dot(tdir1, lp_nor))); if (d0 < d1){ link_bone.mRot = VectorToFloat(XMQuaternionMultiply(rot0, bone_rot_before)); } else{ link_bone.mRot = VectorToFloat(XMQuaternionMultiply(rot1, bone_rot_before)); } } } } //ワールド行列更新 link_bone.mMtxPose = SQTMatrix(FloatToVector(link_bone.mScale), FloatToVector(link_bone.mRot), FloatToVector(link_bone.mPos)); if (link_bone.mHierarchy.mIdxParent < mBoneNum){ link_bone.mMtxPose = XMMatrixMultiply(link_bone.mMtxPose, mBone[link_bone.mHierarchy.mIdxParent].mMtxPose); } // 子階層のリンク再計算 for (int lidown = chn - 1; lidown >= 0; --lidown){ UINT idx = ik.child_bone_index[lidown]; if (idx >= mBoneNum)continue; Bone& linkb = mBone[idx]; linkb.mMtxPose = SQTMatrix(FloatToVector(linkb.mScale), FloatToVector(linkb.mRot), FloatToVector(linkb.mPos)); if (linkb.mHierarchy.mIdxParent < mBoneNum){ linkb.mMtxPose = XMMatrixMultiply(linkb.mMtxPose, mBone[linkb.mHierarchy.mIdxParent].mMtxPose); } } mBone[tg_idx].mMtxPose = SQTMatrix(FloatToVector(mBone[tg_idx].mScale), FloatToVector(mBone[tg_idx].mRot), FloatToVector(mBone[tg_idx].mPos)); if (mBone[tg_idx].mHierarchy.mIdxParent < mBoneNum){ mBone[tg_idx].mMtxPose = XMMatrixMultiply(mBone[tg_idx].mMtxPose, mBone[mBone[tg_idx].mHierarchy.mIdxParent].mMtxPose); } } } //Bone& b = mBone[tg_idx]; //Bone& b2 = mBone[mBone[tg_idx].mHierarchy.mIdxParent]; //Bone& b3 = mBone[b2.mHierarchy.mIdxParent]; //int sa = 1; //IKの計算結果を子階層に反映 //UpdatePose(); } UpdatePose(); }
Vector4 transform(const Vector4& v) const { return Vector4(XMVector4Transform(v, *this)); }
bool DEMO::Run() { xTime.Signal(); static double timer = 0.0; static float SPEED = 1.0f / 600.0f; timer += xTime.Delta(); if (timer > ANIMATION_SPEED) { timer = 0; XMMATRIX rotYN = XMMatrixRotationY(XMConvertToRadians(-1.0f)); star_matrix = rotYN * star_matrix; if (scene.percent > 1.0f || scene.percent < 0.0f) { SPEED = -SPEED; } scene.percent += SPEED; //for (size_t i = 0; i < cubeInstancedData.size(); i++) //{ // XMMATRIX rotY = XMMatrixRotationY(XMConvertToRadians((float)(i+10))) * XMLoadFloat4x4(&cubeInstancedData[i]); // XMStoreFloat4x4(&cubeInstancedData[i], rotY); //} //Directional Light Movement XMVECTOR DLdir = XMLoadFloat4(&allLights.dLight.lightDirection); DLdir = XMVector4Transform(DLdir, XMMatrixRotationX(0.005f)); XMStoreFloat4(&allLights.dLight.lightDirection, DLdir); //Point Light Movement XMVECTOR PLpos = XMLoadFloat4(&allLights.pLight.lightPosition); PLpos = XMVector4Transform(PLpos, XMMatrixRotationY(0.01f)); XMStoreFloat4(&allLights.pLight.lightPosition, PLpos); } if (current_camera) { SHORT left, right, up, down, shift, w, a, s, d; left = GetAsyncKeyState(VK_LEFT); a = GetAsyncKeyState('A'); right = GetAsyncKeyState(VK_RIGHT); d = GetAsyncKeyState('D'); up = GetAsyncKeyState(VK_UP); w = GetAsyncKeyState('W'); down = GetAsyncKeyState(VK_DOWN); s = GetAsyncKeyState('S'); shift = GetAsyncKeyState(VK_SHIFT); if (left || a) { current_camera->Stafe(-(float)xTime.Delta() * 10); } if (right || d) { current_camera->Stafe((float)xTime.Delta() * 10); } if (up || w) { current_camera->Walk((float)xTime.Delta() * 10); } if (down || s) { current_camera->Walk(-(float)xTime.Delta() * 10); } if (shift && up) { current_camera->Climb((float)xTime.Delta() * 10); } if (shift && down) { current_camera->Climb(-(float)xTime.Delta() * 10); } GetCursorPos(&CurPos); if (/*GetAsyncKeyState(VK_LBUTTON) &&*/ (lastPos.x != CurPos.x || lastPos.y != CurPos.y)) { current_camera->Pitch(0.15f*(CurPos.y - lastPos.y)); current_camera->RotateY(0.15f*(CurPos.x - lastPos.x)); RECT rect; GetWindowRect(window, &rect); if (CurPos.x >= rect.right) { CurPos.x = rect.left; } else if (CurPos.x <= rect.left) { CurPos.x = rect.right; } else if (CurPos.y <= rect.top) { CurPos.y = rect.bottom; } else if (CurPos.y >= rect.bottom - 1) { CurPos.y = rect.top; } SetCursorPos(CurPos.x, CurPos.y); lastPos.x = CurPos.x; lastPos.y = CurPos.y; } float cube1tocamera = ObjectToCamera(&cubeInstancedData[0], current_camera->GetPosition()); float cube2tocamera = ObjectToCamera(&cubeInstancedData[1], current_camera->GetPosition()); float cube3tocamera = ObjectToCamera(&cubeInstancedData[2], current_camera->GetPosition()); if (cube1tocamera < cube2tocamera) { swap(cubeInstancedData[0], cubeInstancedData[1]); if (cube1tocamera < cube3tocamera) { swap(cubeInstancedData[1], cubeInstancedData[2]); } } SecureRelease(pCubeInstanceBuffer); D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_DYNAMIC; vbd.ByteWidth = sizeof(XMFLOAT4X4) * (unsigned int)cubeInstancedData.size(); vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; vbd.MiscFlags = 0; vbd.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA instData; ZeroMemory(&instData, sizeof(instData)); instData.pSysMem = cubeInstancedData.data(); pDevice->CreateBuffer(&vbd, &instData, &pCubeInstanceBuffer); } if (GetAsyncKeyState('K') & 0x1) { current_camera = nullptr; } if (GetAsyncKeyState('N') & 0x1) { GetCursorPos(&lastPos); current_camera = &another_camera; } else if (GetAsyncKeyState('O') & 0x1) { GetCursorPos(&lastPos); current_camera = &camera; } scene._proj = camera.GetProj(); scene._view = camera.GetView(); skybox.GO_worldMatrix = XMMatrixScaling(5.0f, 5.0f, 5.0f) * XMMatrixTranslation(camera.GetPosition().x, camera.GetPosition().y, camera.GetPosition().z); thread draw = thread(&DEMO::Draw,this); draw.join(); if (pCommandList) { pDeviceContext->ExecuteCommandList(pCommandList, false); pCommandList->Release(); } pSwapchain->Present(0, 0); return true; }
bool MyRender::Draw() { static float dfi = 0.02f; static float fi = 0.0f; static float radius = 30.0f; float dz = radius * (cos(fi + dfi) - cos(fi)); float dx = radius * (sin(fi + dfi) - sin(fi)); m_car->RotateY(dfi); m_car->Translate(dx, 0, dz); fi += dfi; if (fi > XM_2PI) fi -= XM_2PI; ConstantBuffer cb; m_camera->Update(); XMMATRIX view = XMLoadFloat4x4(&(m_camera->GetViewMatrix())); // add all projectors info to constant buffer for (size_t i = 0, lightIndex = 0; i < m_scene->GetObjectsNumber(); i++) { MyObject *object = m_scene->GetObjectAt(i); for (size_t j = 0; j < object->GetProjectorLightsNumber(); j++, lightIndex++) { ProjectorLight *projector = object->GetProjectorAt(j); XMMATRIX projectorWorldMatrix = (XMLoadFloat4x4(&(object->GetWorldMatrix()))); XMMATRIX projectorRotationMatrix = (XMLoadFloat4x4(&(object->GetRotationMatrix()))); XMVECTOR tempPos = XMLoadFloat4(&(XMFLOAT4(projector->Pos.x, projector->Pos.y, projector->Pos.z, 1))); XMVECTOR tempDir = XMLoadFloat4(&(XMFLOAT4(projector->Direction.x, projector->Direction.y, projector->Direction.z, 1))); XMVECTOR projectorPos = XMVector4Transform(tempPos, projectorWorldMatrix); XMVECTOR projectorDir = XMVector4Transform(tempDir, projectorRotationMatrix); XMStoreFloat4(cb.vLightPos + lightIndex, projectorPos); XMStoreFloat4(cb.vLightDir + lightIndex, projectorDir); cb.vLightColor[lightIndex] = projector->Color; } } // add all point lights info to constant buffer for (size_t i = 0, lightIndex = 0; i < m_scene->GetObjectsNumber(); i++) { MyObject *object = m_scene->GetObjectAt(i); for (size_t j = 0; j < object->GetPointLightsNumber(); j++, lightIndex++) { SimpleLight *bulb = object->GetPointLightAt(j); XMMATRIX bulbWorldMatrix = (XMLoadFloat4x4(&(object->GetWorldMatrix()))); XMVECTOR tempPos = XMLoadFloat4(&(XMFLOAT4(bulb->Pos.x, bulb->Pos.y, bulb->Pos.z, 1))); XMVECTOR bulbPos = XMVector4Transform(tempPos, bulbWorldMatrix); XMStoreFloat4(cb.vBulbLightPos + lightIndex, bulbPos); cb.vBulbLightColor[lightIndex] = bulb->Color; } } // add all directed lights info to constant buffer for (size_t i = 0, lightIndex = 0; i < m_scene->GetObjectsNumber(); i++) { MyObject *object = m_scene->GetObjectAt(i); for (size_t j = 0; j < object->GetDirectedLightsNumber(); j++, lightIndex++) { DirectedLight *dirLight = object->GetDirectedLightAt(j); XMMATRIX dirRotationMatrix = (XMLoadFloat4x4(&(object->GetRotationMatrix()))); XMVECTOR tempDir = XMLoadFloat4(&(XMFLOAT4(dirLight->Dir.x, dirLight->Dir.y, dirLight->Dir.z, 1))); XMVECTOR bulbPos = XMVector4Transform(tempDir, dirRotationMatrix); XMStoreFloat4(cb.vDirectedLightDir + lightIndex, bulbPos); cb.vDirectedLightColor[lightIndex] = dirLight->Color; } } cb.isLightEnabled[0] = m_enableProjectorLight; cb.isLightEnabled[1] = m_enablePointLight; cb.isLightEnabled[2] = m_enableDirectedLight; cb.isLightEnabled[3] = 0; for (size_t idx = 0; idx < m_scene->GetObjectsNumber(); idx++) { MyObject *object = m_scene->GetObjectAt(idx); /****************************************************/ D3D11_BUFFER_DESC bd; RtlZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(SimpleVertex) * object->GetVerticesNumber(); bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA data; RtlZeroMemory(&data, sizeof(data)); data.pSysMem = object->GetVertices(); HRESULT hr = m_pd3dDevice->CreateBuffer(&bd, &data, &m_pVertexBuffer); if (FAILED(hr)) { Log::Get()->Err("CreateBuffer error for vertex buffer."); return false; } UINT stride = sizeof(SimpleVertex); UINT offset = 0; m_pImmediateContext->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &stride, &offset); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(UINT) * object->GetIndicesNumber(); bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; data.pSysMem = object->GetIndices(); hr = m_pd3dDevice->CreateBuffer(&bd, &data, &m_pIndexBuffer); if(FAILED(hr)) { Log::Get()->Err("CreateBuffer error for torus."); return false; } m_pImmediateContext->IASetIndexBuffer(m_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0); m_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); /****************************************************/ XMMATRIX world = XMLoadFloat4x4(&(object->GetWorldMatrix())); cb.mWorld = XMMatrixTranspose(world); cb.mView = XMMatrixTranspose(view); cb.mProjection = XMMatrixTranspose(m_Projection); cb.vOutputColor = XMFLOAT4(0, 0, 0, 0); m_pImmediateContext->UpdateSubresource(m_pConstantBuffer, 0, NULL, &cb, 0, 0); m_pImmediateContext->VSSetShader(m_pVertexShader, NULL, 0); m_pImmediateContext->VSSetConstantBuffers( 0, 1, &m_pConstantBuffer); if (object == m_sun) // absolutely black body m_pImmediateContext->PSSetShader(m_pPixelShaderSolid, NULL, 0); else m_pImmediateContext->PSSetShader(m_pPixelShader, NULL, 0); m_pImmediateContext->PSSetConstantBuffers( 0, 1, &m_pConstantBuffer); m_pImmediateContext->DrawIndexed(object->GetIndicesNumber(), 0, 0); _RELEASE(m_pVertexBuffer); _RELEASE(m_pIndexBuffer); } return true; }