//-------------------------------------------------------------------------------------- // Updates the position and velocity of the entity associated to this movement manager // using the accumulated sum of all forces impacting the entity. // Param1: The time in seconds passed since the last frame. // Param2: The maximal speed of the entity. // Param3: The maximal size of the accumulated forces. // Param4: The handicap to use if the entity is currently being handicapped. //-------------------------------------------------------------------------------------- void EntityMovementManager::UpdatePosition(float deltaTime, float maxSpeed, float maxForce, float handicap) { // Truncate steering force to not be greater than the maximal allowed force float magnitude = 0.0f; XMStoreFloat(&magnitude, XMVector2Length(XMLoadFloat2(&m_steeringForce))); if(magnitude > maxForce) { // Truncate the vector to be of the magnitude corresponding to the maximal allowed force XMStoreFloat2(&m_steeringForce, XMVector2Normalize(XMLoadFloat2(&m_steeringForce)) * maxForce); } // Calculate the new velocity for the entity XMFLOAT2 newVelocity; XMStoreFloat2(&newVelocity, XMLoadFloat2(&m_velocity) + XMLoadFloat2(&m_steeringForce)); // Truncate the velocity if it is greater than the maximally allowed velocity for the entity XMStoreFloat(&magnitude, XMVector2Length(XMLoadFloat2(&newVelocity))); if(magnitude > maxSpeed) { // Truncate the vector to be of the magnitude corresponding to the maximal allowed velocity XMStoreFloat2(&newVelocity, XMVector2Normalize(XMLoadFloat2(&newVelocity)) * maxSpeed); } // Set the new velocity and position on the entity m_velocity = newVelocity; XMFLOAT2 newPosition; if(m_pEntity->IsHandicapped()) { XMStoreFloat2(&newPosition, XMLoadFloat2(&m_pEntity->GetPosition()) + XMLoadFloat2(&newVelocity) * deltaTime * handicap); }else { XMStoreFloat2(&newPosition, XMLoadFloat2(&m_pEntity->GetPosition()) + XMLoadFloat2(&newVelocity) * deltaTime); } m_pEntity->SetPosition(newPosition); m_pEntity->UpdateColliderPosition(newPosition); // Update the rotation to make the entity face the direction, in which it is moving if(!(newVelocity.x == 0.0f && newVelocity.y == 0.0f)) { XMFLOAT2 lookAtPoint(0.0f, 0.0f); XMStoreFloat2(&lookAtPoint, XMLoadFloat2(&m_pEntity->GetPosition()) + XMLoadFloat2(&newVelocity)); LookAt(lookAtPoint); } // Reset the steering force for the next frame m_steeringForce.x = 0.0f; m_steeringForce.y = 0.0f; }
//-------------------------------------------------------------------------------------- // Calculate the collision avoidance force and add it to the total force. This force // is used to avoid collisions of an entity with static obstacles in the environment and // other entities. // Param1: Obstacles and entities within this distance in front of the entity will be avoided. // Param2: The maximal size of this force. //-------------------------------------------------------------------------------------- void EntityMovementManager::AvoidCollisions(float seeAheadDistance, float maximalForce) { if(m_velocity.x == 0.0f && m_velocity.y == 0.0f) { return; } std::multimap<float, CollidableObject*> nearbyObjects; m_pEnvironment->GetNearbyObjects(m_pEntity->GetPosition(), seeAheadDistance, GroupAllSoldiersAndObstacles, nearbyObjects); // One element is entity itself -> Check if there are more than one if(nearbyObjects.size() > 1) { XMFLOAT2 lineEndPoint(0.0f, 0.0f); XMStoreFloat2(&lineEndPoint, XMLoadFloat2(&m_pEntity->GetPosition()) + XMVector2Normalize(XMLoadFloat2(&m_pEntity->GetViewDirection())) * seeAheadDistance); for(std::multimap<float, CollidableObject*>::iterator it = nearbyObjects.begin(); it != nearbyObjects.end(); ++it) { if((it->second->GetId() != m_pEntity->GetId()) && reinterpret_cast<CollidableObject*>(it->second)->GetCollider()->CheckLineCollision(m_pEntity->GetPosition(), lineEndPoint)) { // Determine whether the other entity is left or right of this entity XMFLOAT2 entityToObject(0.0f, 0.0f); XMStoreFloat2(&entityToObject, XMLoadFloat2(&it->second->GetPosition()) - XMLoadFloat2(&m_pEntity->GetPosition())); float dot = m_pEntity->GetViewDirection().x * (-entityToObject.y) + m_pEntity->GetViewDirection().y * entityToObject.x; XMFLOAT2 avoidanceVector = m_pEntity->GetViewDirection(); if(dot > 0) { // Object is right of entity, steer left to avoid avoidanceVector.x = -m_pEntity->GetViewDirection().y; avoidanceVector.y = m_pEntity->GetViewDirection().x; }else { // Object is left of entity, steer right to avoid avoidanceVector.x = m_pEntity->GetViewDirection().y; avoidanceVector.y = -m_pEntity->GetViewDirection().x; } XMStoreFloat2(&m_steeringForce, XMLoadFloat2(&m_steeringForce) + XMVector2Normalize(XMLoadFloat2(&avoidanceVector)) * maximalForce); // Bail out of the function as soon as the first collision is found (the nearby entities are already sorted // by their distance from the original entity, thus the first collision found is the closest one) return; } } } }
//-------------------------------------------------------------------------------------- // Calculate the separation force and add it to the total force. // Param1: The entity will try to move away from entities that are at this distance or closer. // Param2: The maximal size of this force. //-------------------------------------------------------------------------------------- void EntityMovementManager::Separate(float separationRadius, float maximalForce) { XMVECTOR separationVector = XMVectorZero(); // The separation force to prevent overlapping of moving entities // Find the moving entities that are in close proximity to this one (check both teams) std::multimap<float, CollidableObject*> nearbySoldiers; m_pEnvironment->GetNearbyObjects(m_pEntity->GetPosition(), separationRadius, GroupAllSoldiers, nearbySoldiers); // The entity itself will be included in the list of soldiers -> check if there are others as well if(nearbySoldiers.size() > 1) { for(std::multimap<float, CollidableObject*>::const_iterator it = nearbySoldiers.begin(); it != nearbySoldiers.end(); ++it) { if(it->second->GetId() != m_pEntity->GetId()) { // Scale the force according to the proximity of the nearby entity. Thus the push from close objects will be // stronger than that from objects that are farther away. // Avoid possible division by zero float proximity = (it->first != 0) ? it->first : 0.01f; separationVector += (XMLoadFloat2(&m_pEntity->GetPosition()) - XMLoadFloat2(&it->second->GetPosition())) / proximity; } } // Truncate the force according to the maximally allowed separation force. separationVector = XMVector2Normalize(separationVector) * maximalForce; // Add the separation force to the accumulated steering force XMStoreFloat2(&m_steeringForce, XMLoadFloat2(&m_steeringForce) + separationVector); } }
//-------------------------------------------------------------------------------------- // Calculate the wall avoidance force and add it to the total force. This force // is used to push the entity away from walls (objects) that it is getting too close to. // Param1: Obstacles within this radius around the entity will be avoided. // Param2: The maximal size of this force. //-------------------------------------------------------------------------------------- void EntityMovementManager::StayAwayFromWalls(float avoidWallsRadius, float maximalForce) { // Get nearby obstacles std::multimap<float, CollidableObject*> nearbyObjects; m_pEnvironment->GetNearbyObjects(m_pEntity->GetPosition(), avoidWallsRadius, GroupObstacles, nearbyObjects); if(!nearbyObjects.empty()) { XMVECTOR avoidanceForce = XMVectorZero(); for(std::multimap<float, CollidableObject*>::iterator it = nearbyObjects.begin(); it != nearbyObjects.end(); ++it) { // Scale the force according to the proximity of the nearby entity. Thus the push from close objects will be // stronger than that from objects that are farther away. avoidanceForce += (XMLoadFloat2(&m_pEntity->GetPosition()) - XMLoadFloat2(&(it->second->GetPosition()))) / it->first; } // Truncate the force according to the maximally allowed wall avoidance force. avoidanceForce = XMVector2Normalize(avoidanceForce) * maximalForce; // Add the collision avoidance force to the accumulated steering force XMStoreFloat2(&m_steeringForce, XMLoadFloat2(&m_steeringForce) + avoidanceForce); } }
//-------------------------------------------------------------------------------------- // Move the entity to a specified target position. // Param1: The target position of the entity. // Param2: The radius around the target position from which the target counts as reached. // Param3: The speed, at which the entity should seek the target. // Returns true if the target was reached, false if there is still way to go. //-------------------------------------------------------------------------------------- bool EntityMovementManager::Seek(const XMFLOAT2& targetPosition, float targetReachedRadius, float speed) { XMFLOAT2 desiredVelocity; XMStoreFloat2(&desiredVelocity, XMLoadFloat2(&targetPosition) - XMLoadFloat2(&m_pEntity->GetPosition())); // Get the distance from the current position of the entity to the target float distance; XMStoreFloat(&distance, XMVector2Length(XMLoadFloat2(&desiredVelocity))); // Normalise the desired velocity XMStoreFloat2(&desiredVelocity, XMVector2Normalize(XMLoadFloat2(&desiredVelocity))); XMStoreFloat2(&desiredVelocity, XMLoadFloat2(&desiredVelocity) * speed); bool targetReached = false; // Target reached if(distance <= targetReachedRadius) { desiredVelocity = XMFLOAT2(0.0f, 0.0f); targetReached = true; } XMFLOAT2 force; XMStoreFloat2(&force, XMLoadFloat2(&desiredVelocity) - XMLoadFloat2(&m_velocity)); // Add the seek force to the accumulated steering force XMStoreFloat2(&m_steeringForce, XMLoadFloat2(&m_steeringForce) + XMLoadFloat2(&force)); return targetReached; }
Vec2 VectorMath::Normalize(const Vec2* vec) { Vec2 retval; XMVECTOR xmVec = XMLoadFloat2((_XMFLOAT2*)vec); xmVec = XMVector2Normalize(xmVec); XMStoreFloat2((XMFLOAT2*)&retval, xmVec); return retval; }
void DirectionSelector::VerifyDirection() { if (_direction.x * _direction.x + _direction.y * _direction.y >= 1.0f || (_direction.x == 0.0f && _direction.y == 0.0f)) { XMVECTOR vec = XMLoadFloat2(&_direction); vec = XMVector2Normalize(vec) * (1.0f - EPSILON); XMStoreFloat2(&_direction, vec); } }
//-------------------------------------------------------------------------------------- // Rotates the entity towards a specific point. // Param1: The position, the entity should look at. //-------------------------------------------------------------------------------------- void EntityMovementManager::LookAt(const XMFLOAT2& lookAtPosition) { XMFLOAT2 newViewDirection(0.0f, 1.0f); XMStoreFloat2(&newViewDirection, XMVector2Normalize(XMLoadFloat2(&lookAtPosition) - XMLoadFloat2(&m_pEntity->GetPosition()))); m_pEntity->SetViewDirection(newViewDirection); float rotation = (atan2(m_pEntity->GetViewDirection().x, m_pEntity->GetViewDirection().y)) * 180 / XM_PI; m_pEntity->SetRotation(rotation); }
XMFLOAT2 HydraManager::getJoystick(int controllerIndex) const { XMFLOAT2 directionVector(0.0f, 0.0f); if (sixenseIsControllerEnabled(controllerIndex)) { XMStoreFloat2(&directionVector, XMVector2Normalize(XMVectorSet(mAcd.controllers[controllerIndex].joystick_x, mAcd.controllers[controllerIndex].joystick_y, 0.0f, 0.0f))); } return directionVector; }
void Small::Chase(float weight) { XMMATRIX rotationmatrix; XMVECTOR playerlocation = Target->Location; XMVECTOR leftvector = {0, 0, 0, 0}; XMVECTOR rightvector = {0, 0, 0, 0}; XMMATRIX rotationmatrixleft = XMMatrixRotationZ(float(M_PI)/2.0f); XMMATRIX rotationmatrixright = XMMatrixRotationZ(float(M_PI)/-2.0f); leftvector = XMVector3Transform(Direction, rotationmatrixleft); rightvector = XMVector3Transform(Direction, rotationmatrixright); Direction = XMVector2Normalize(Direction); XMVECTOR differencevector = playerlocation - Location; differencevector = XMVector2Normalize(differencevector); float radiandifference = XMVectorGetX(XMVector2AngleBetweenNormals(leftvector, differencevector)); float epsilon = XMVectorGetX(XMVector2AngleBetweenNormals(Direction, differencevector)); if (radiandifference <= float(M_PI/2.0f)) { rotationmatrix = XMMatrixRotationZ(weight); if (epsilon <= (1.25f * weight)) { Direction = differencevector; Direction = XMVector2Normalize(Direction); } else { Direction = XMVector3Transform(Direction, rotationmatrix); Direction = XMVector2Normalize(Direction); } } else if (radiandifference > float(M_PI/2.0f)) { rotationmatrix = XMMatrixRotationZ(-weight); if (epsilon <= (1.25f * weight)) { Direction = differencevector; Direction = XMVector2Normalize(Direction); } else { Direction = XMVector3Transform(Direction, rotationmatrix); Direction = XMVector2Normalize(Direction); } } }
//-------------------------------------------------------------------------------------- // Name: Render() // Desc: Renders the gamepad help image and its labelled callouts //-------------------------------------------------------------------------------------- VOID Help::Render( Font* pFont, const HELP_CALLOUT* pTags, DWORD dwNumCallouts ) { #ifdef ALLOW_CALLOUT_EDITTING // Use the shoulder buttons, triggers, and dpad to edit callout positions XINPUT_STATE CurrInputState; static XINPUT_STATE LastInputState = {0}; static DWORD dwCurrCallout = 0; if( XInputGetState( 0, &CurrInputState ) == ERROR_SUCCESS ) { if( ( 0 != (CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_LEFT_SHOULDER) ) && ( 0 == (LastInputState.Gamepad.wButtons&XINPUT_GAMEPAD_LEFT_SHOULDER) ) ) dwCurrCallout = (dwCurrCallout+dwNumCallouts-1) % dwNumCallouts; if( ( 0 != (CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_RIGHT_SHOULDER) ) && ( 0 == (LastInputState.Gamepad.wButtons&XINPUT_GAMEPAD_RIGHT_SHOULDER) ) ) dwCurrCallout = (dwCurrCallout+dwNumCallouts+1) % dwNumCallouts; HELP_CALLOUT_POS* pCallout = &g_pHelpCallouts[pTags[dwCurrCallout].wControl]; XMFLOAT2* pPos1 = &pCallout->Button; XMFLOAT2* pPos2 = &pCallout->Placement[pTags[dwCurrCallout].wPlacement].Line; XMFLOAT2* pPos3 = &pCallout->Placement[pTags[dwCurrCallout].wPlacement].Text; if( CurrInputState.Gamepad.bLeftTrigger ) { pPos1->x -= CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_LEFT ? 1.0f : 0.0f; pPos1->x += CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_RIGHT ? 1.0f : 0.0f; pPos1->y -= CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_UP ? 1.0f : 0.0f; pPos1->y += CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_DOWN ? 1.0f : 0.0f; } else if( CurrInputState.Gamepad.bRightTrigger ) { pPos2->x -= CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_LEFT ? 1.0f : 0.0f; pPos2->x += CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_RIGHT ? 1.0f : 0.0f; pPos2->y -= CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_UP ? 1.0f : 0.0f; pPos2->y += CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_DOWN ? 1.0f : 0.0f; pPos3->x -= CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_LEFT ? 1.0f : 0.0f; pPos3->x += CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_RIGHT ? 1.0f : 0.0f; pPos3->y -= CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_UP ? 1.0f : 0.0f; pPos3->y += CurrInputState.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_DOWN ? 1.0f : 0.0f; } memcpy( &LastInputState, &CurrInputState, sizeof(XINPUT_STATE) ); } #endif // ALLOW_CALLOUT_EDITTING // Calculate a scale factor based on the video mode D3DDISPLAYMODE ModeDesc; XGTEXTURE_DESC TextureDesc; g_pd3dDevice->GetDisplayMode( 0, &ModeDesc ); XGGetTextureDesc( m_pGamepadTexture, 0, &TextureDesc ); FLOAT fScale = ModeDesc.Width / 1280.0f; FLOAT h = fScale * 720 * 0.48f; FLOAT w = TextureDesc.Width * h / TextureDesc.Height; FLOAT x = ( ModeDesc.Width - w ) / 2; FLOAT y = ( ModeDesc.Height - h ) / 2; D3DRECT rcSaved = pFont->m_rcWindow; pFont->SetWindow( 0, 0, ModeDesc.Width, ModeDesc.Height ); // Setup the gamepad vertices struct VERTEX { FLOAT sx, sy; FLOAT tu, tv; }; // Set up state for rendering the gamepad g_pd3dDevice->SetVertexDeclaration( g_pHelpVertexDecl ); g_pd3dDevice->SetVertexShader( g_pHelpVertexShader ); g_pd3dDevice->SetTexture( 0, m_pGamepadTexture ); g_pd3dDevice->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP ); g_pd3dDevice->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP ); g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR ); g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE ); g_pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); g_pd3dDevice->SetRenderState( D3DRS_VIEWPORTENABLE, FALSE ); g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); g_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD ); // Draw the scene-darkening quad { VERTEX GamepadVertices[4] = { { 0.0f, 0.0f, 0.0f, 0.0f }, { 1.0f * ModeDesc.Width, 0.0f, 1.0f, 0.0f }, { 1.0f * ModeDesc.Width, 1.0f * ModeDesc.Height, 1.0f, 1.0f }, { 0.0f, 1.0f * ModeDesc.Height, 0.0f, 1.0f }, }; g_pd3dDevice->SetPixelShader( g_pDarkPixelShader ); g_pd3dDevice->DrawPrimitiveUP( D3DPT_QUADLIST, 1, GamepadVertices, sizeof( GamepadVertices[0] ) ); } // Draw the gamepad image { VERTEX GamepadVertices[4] = { { x, y, 0.0f, 0.0f }, { x + w, y, 1.0f, 0.0f }, { x + w, y + h, 1.0f, 1.0f }, { x, y + h, 0.0f, 1.0f }, }; g_pd3dDevice->SetPixelShader( g_pHelpPixelShader ); g_pd3dDevice->DrawPrimitiveUP( D3DPT_QUADLIST, 1, GamepadVertices, sizeof( GamepadVertices[0] ) ); } // Set state to draw the lines g_pd3dDevice->SetTexture( 0, m_pLineTexture ); g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); for( DWORD i = 0; i < dwNumCallouts; i++ ) { if( pTags[i].wControl >= ARRAYSIZE( g_vHelpCallouts ) ) continue; HELP_CALLOUT_POS* pCallout = &g_pHelpCallouts[pTags[i].wControl]; XMFLOAT2 line1 = pCallout->Button; XMFLOAT2 line2 = pCallout->Placement[pTags[i].wPlacement].Line; line1.x = fScale * ( line1.x - 640 ) + ModeDesc.Width / 2; line1.y = fScale * ( line1.y - 360 ) + ModeDesc.Height / 2; line2.x = fScale * ( line2.x - 640 ) + ModeDesc.Width / 2; line2.y = fScale * ( line2.y - 360 ) + ModeDesc.Height / 2; XMVECTOR vc = XMVector2Normalize( XMVectorSet( line2.y - line1.y, -line2.x + line1.x, 0, 0 ) ); #ifdef ALLOW_CALLOUT_EDITTING if( dwCurrCallout == i ) vc *= 2; #endif // ALLOW_CALLOUT_EDITTING // Initialize the callout line vertices VERTEX LineVertices[4] = { { ( line1.x - 2 * vc.x ), ( line1.y - 2 * vc.y ), 0.0f, 0.0f }, { ( line1.x + 2 * vc.x ), ( line1.y + 2 * vc.y ), 1.0f, 0.0f }, { ( line2.x + 2 * vc.x ), ( line2.y + 2 * vc.y ), 1.0f, 1.0f }, { ( line2.x - 2 * vc.x ), ( line2.y - 2 * vc.y ), 0.0f, 1.0f }, }; g_pd3dDevice->DrawPrimitiveUP( D3DPT_QUADLIST, 1, LineVertices, sizeof( LineVertices[0] ) ); } // Turn the viewport back on g_pd3dDevice->SetRenderState( D3DRS_VIEWPORTENABLE, TRUE ); // Prepare font for rendering pFont->Begin(); static FLOAT fFontXScale = 1.0f; static FLOAT fFontYScale = 1.0f; pFont->SetScaleFactors( fFontXScale * fScale, fFontYScale * fScale ); // Render the callouts for( DWORD i = 0; i < dwNumCallouts; i++ ) { if( pTags[i].wControl >= ARRAYSIZE( g_vHelpCallouts ) ) continue; HELP_CALLOUT_POS* pCallout = &g_pHelpCallouts[pTags[i].wControl]; XMFLOAT2 pos = pCallout->Placement[pTags[i].wPlacement].Text; pos.x = fScale * ( pos.x - 640 ) + ModeDesc.Width / 2; pos.y = fScale * ( pos.y - 360 ) + ModeDesc.Height / 2; // Draw the callout text pFont->DrawText( pos.x, pos.y, 0xffffffff, pTags[i].strText, g_pHelpCallouts[pTags[i].wControl].dwFontFlags ); } // Flush the text drawing pFont->SetScaleFactors( 1.0f, 1.0f ); pFont->End(); pFont->m_rcWindow = rcSaved; }
MyListener::MyListener(AaSceneManager* mSceneMgr, AaPhysicsManager* mPhysicsMgr) { zp=zm=xp=xm = false; cameraMan = new FreeCamera(mSceneMgr->getCamera()); mSceneMgr->getCamera()->setPosition(XMFLOAT3(-1.8f,10,-6)); this->mPhysicsMgr = mPhysicsMgr; this->mSceneMgr = mSceneMgr; continue_rendering = true; AaRenderSystem* rs=mSceneMgr->getRenderSystem(); voxelScene = new AaVoxelScene(mSceneMgr); voxelScene->initScene(128); mShadowMapping = new AaShadowMapping(mSceneMgr); mSceneMgr->loadMaterialFiles(MATERIAL_DIRECTORY); pp = new AaBloomPostProcess(mSceneMgr); AaMaterial* mat=mSceneMgr->getMaterial("Green"); /*ent= mSceneMgr->createEntity("testEnt",mat); ent->setModel("angel"); ent->setScale(XMFLOAT3(10,10,10)); ent->setPosition(0,-15,30); ent= mSceneMgr->createEntity("testEnt22",mat); ent->setModel("angel"); ent->setScale(XMFLOAT3(10,10,10)); ent->setPosition(-15,-15,30); //ent->yaw(-2.0f); AaSceneNode* node= new AaSceneNode(XMFLOAT3(-15,-15,30)); node->attachEntity(ent); ent= mSceneMgr->createEntity("testEnt33",mat); ent->setModel("angel"); ent->setScale(XMFLOAT3(10,10,10)); ent->setPosition(15,-15,30); //ent->yaw(0.7f); ent->pitch(-1.0f); AaSceneNode* node2 = node->createChild(); node2->setPosition(XMFLOAT3(15,-15,30)); node2->attachEntity(ent); node->move(XMFLOAT3(0,10,0)); node->yawPitchRoll(0.4,0.2,0); node->localPitch(1);*/ /*ent= mSceneMgr->createEntity("testEnt2",mat); ent->setModel("teapot.obj"); ent->yaw(0.7f); ent->pitch(-1.7f); ent->yaw(-2.7f); ent->setPosition(3,-1,10);*/ /*PxMaterial* mMaterial; mMaterial = mPhysicsMgr->getPhysics()->createMaterial(0.7f, 1.7f, 0.2f); //static friction, dynamic friction, restitution PxShape* aSphereShape; AaEntity* ent= mSceneMgr->createEntity("testEnt3",mat); ent->setModel("ball24.mesh"); ent->setPosition(0,20,0); ent->setScale(XMFLOAT3(0.4,1.4,1.4)); mPhysicsMgr->createSphereBodyDynamic(ent,0.4);//->setLinearVelocity(physx::PxVec3(1,15,0)); ent= mSceneMgr->createEntity("testEnt6",mat); ent->setModel("ball24.mesh"); ent->setPosition(0,20,0); mPhysicsMgr->createConvexBodyDynamic(ent);//->setLinearVelocity(physx::PxVec3(1,15,0)); ent= mSceneMgr->createEntity("testEnt63",mat); ent->setModel("ball32.mesh"); ent->setPosition(5,35,20); ent->setScale(XMFLOAT3(4,1,4)); ent->yaw(0.5); ent->roll(0.5); mPhysicsMgr->createTreeBodyStatic(ent); ent= mSceneMgr->createEntity("testEnt61",mat); ent->setModel("ball24.mesh"); ent->setPosition(5,25,20); ent->setScale(XMFLOAT3(2,1,2)); ent->roll(0.5); mPhysicsMgr->createConvexBodyDynamic(ent)->setLinearVelocity(physx::PxVec3(1,15,0)); */ Light* l = new Light(); l->color = XMFLOAT3(1,1,1); l->direction = XMFLOAT3(0.0f,-2,1.6); XMStoreFloat3(&l->direction,XMVector2Normalize(XMLoadFloat3(&l->direction))); mSceneMgr->mShadingMgr->directionalLight = l; mPhysicsMgr->createPlane(0); loadScene("test.scene",mSceneMgr,mPhysicsMgr); mRS=rs; setupInputSystem(); debugWindow = new TestGuiWindow(mSceneMgr->getGuiManager()->getContext(),mSceneMgr); }
void Small::Cohesion(float weight) { XMMATRIX rotationmatrix; XMVECTOR flocktotal = {0, 0, 0, 0}; bool isalone = true; for (int i = 0; i < SmallVector->size(); i++) { if (SmallVector->at(i)->ID != this->ID) { if (SmallVector->at(i)->Chasing) { if (Target->ID == SmallVector->at(i)->Target->ID) { flocktotal += SmallVector->at(i)->Location; isalone = false; } } } } if (!isalone) { XMVECTOR flockaverage = flocktotal / SmallVector->size(); XMVECTOR leftvector = {0, 0, 0, 0}; XMVECTOR rightvector = {0, 0, 0, 0}; XMMATRIX rotationmatrixleft = XMMatrixRotationZ(float(M_PI)/2.0f); XMMATRIX rotationmatrixright = XMMatrixRotationZ(float(M_PI)/-2.0f); leftvector = XMVector3Transform(Direction, rotationmatrixleft); rightvector = XMVector3Transform(Direction, rotationmatrixright); Direction = XMVector2Normalize(Direction); XMVECTOR differencevector = flockaverage - Location; differencevector = XMVector2Normalize(differencevector); float radiandifference = XMVectorGetX(XMVector2AngleBetweenNormals(leftvector, differencevector)); float epsilon = XMVectorGetX(XMVector2AngleBetweenNormals(Direction, differencevector)); if (radiandifference <= float(M_PI/2.0f)) { rotationmatrix = XMMatrixRotationZ(weight); if (epsilon <= (1.25f * weight)) { Direction = differencevector; Direction = XMVector2Normalize(Direction); } else { Direction = XMVector3Transform(Direction, rotationmatrix); Direction = XMVector2Normalize(Direction); } } else if (radiandifference > float(M_PI/2.0f)) { rotationmatrix = XMMatrixRotationZ(-weight); if (epsilon <= (1.25f * weight)) { Direction = differencevector; Direction = XMVector2Normalize(Direction); } else { Direction = XMVector3Transform(Direction, rotationmatrix); Direction = XMVector2Normalize(Direction); } } } }
void Small::Separation(float weight) { XMMATRIX rotationmatrix; XMVECTOR closestflockmatedifference = {-1000.0f, -1000.0f, 0, 0}; bool isalone = true; for (int i = 0; i < SmallVector->size(); i++) { if (SmallVector->at(i)->ID != this->ID) { if (SmallVector->at(i)->Chasing) { if (Target->ID == SmallVector->at(i)->Target->ID) { XMVECTOR tempvector = {XMVectorGetX(SmallVector->at(i)->Location), XMVectorGetY(SmallVector->at(i)->Location), 0, 0}; XMVECTOR tempdifference = Location - tempvector; if (XMVectorGetX(XMVector2Length(tempdifference)) < XMVectorGetX(XMVector2Length(closestflockmatedifference))) { closestflockmatedifference = tempdifference; isalone = false; } } } } } if (!isalone) { XMVECTOR leftvector = {0, 0, 0, 0}; XMVECTOR rightvector = {0, 0, 0, 0}; XMMATRIX rotationmatrixleft = XMMatrixRotationZ(float(M_PI)/2.0f); XMMATRIX rotationmatrixright = XMMatrixRotationZ(float(M_PI)/-2.0f); leftvector = XMVector3Transform(Direction, rotationmatrixleft); rightvector = XMVector3Transform(Direction, rotationmatrixright); Direction = XMVector2Normalize(Direction); XMVECTOR differencevector = closestflockmatedifference; differencevector = XMVector2Normalize(differencevector); float radiandifference = XMVectorGetX(XMVector2AngleBetweenNormals(leftvector, differencevector)); float epsilon = XMVectorGetX(XMVector2AngleBetweenNormals(Direction, differencevector)); if (radiandifference <= float(M_PI/2.0f)) { rotationmatrix = XMMatrixRotationZ(weight); if (epsilon <= (1.25f * weight)) { Direction = differencevector; Direction = XMVector2Normalize(Direction); } else { Direction = XMVector3Transform(Direction, rotationmatrix); Direction = XMVector2Normalize(Direction); } } else if (radiandifference > float(M_PI/2.0f)) { rotationmatrix = XMMatrixRotationZ(-weight); if (epsilon <= (1.25f * weight)) { Direction = differencevector; Direction = XMVector2Normalize(Direction); } else { Direction = XMVector3Transform(Direction, rotationmatrix); Direction = XMVector2Normalize(Direction); } } } }
void MovementManagerServer::Update(double p_dt) { // Some debug bools just to test various effects. We'll have these read some other way later bool iceEffect = false; bool fireEffect = false; const size_t length = EntityHandler::GetInstance().GetLastEntityIndex(); int mask = (int)ComponentType::Movement | (int)ComponentType::CharacterController; for(size_t i = 0; i < length; i++) { if(EntityHandler::GetInstance().HasComponents(i, mask)) { /// 1 Get comp MovementComponent* movementComp = EntityHandler::GetInstance().GetComponentFromStorage<MovementComponent>(i); /// 2 Clamp speed // Clamp down XZ movement to maximum movement speed (we don't mess with y due to jump/gravity) XMVECTOR movementXZVec = XMLoadFloat2(&XMFLOAT2(movementComp->movement.x, movementComp->movement.z)); movementXZVec = XMVector2Normalize(movementXZVec) * movementComp->speed * p_dt; // movementXZVec = XMVector2ClampLength(movementXZVec, 0, 0.8f); // Store it back XMFLOAT2 movementXZ; XMStoreFloat2(&movementXZ, movementXZVec); movementComp->movement.x = movementXZ.x; movementComp->movement.z = movementXZ.y; /// 3 Move controller // Perform move bool hitGround = m_sharedContext.GetPhysicsModule().GetCharacterControlManager().MoveController(i, movementComp->movement, p_dt); if(hitGround) { EntityHandler::GetInstance().GetComponentFromStorage<GravityComponent>(i)->travelSpeed = 0; if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::Jump)) // temporary fix { EntityHandler::GetInstance().GetComponentFromStorage<JumpComponent>(i)->active = false; } } /// 4 Fix speed for next iteration // If we're sliding around, only reduce speed, don't entierly reset it if(iceEffect) { float iceSlowdownFactor = 0.99f * (1 - p_dt); movementComp->movement.x *= iceSlowdownFactor; movementComp->movement.z *= iceSlowdownFactor; } // If we're not running on fire (or ice) we can stop else if(!fireEffect) { movementComp->movement = XMFLOAT3(0, 0, 0); } // Always reset y movement. Again, we don't mess with y movementComp->movement.y = 0; // RigidBodyComponent* rigidBody = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(i); // XMFLOAT3 currentVelocity = m_sharedContext.GetPhysicsModule().GetRigidBodyManager().GetBodyVelocity(rigidBody->p_bodyID); // XMVECTOR forward = XMLoadFloat3(&movement->direction); // XMVECTOR up = XMLoadFloat3(&XMFLOAT3(0, 1, 0)); // XMVECTOR right = XMVector3Cross(up, forward); // right *= movement->rightAcceleration; // forward *= movement->forwardAcceleration; // XMVECTOR moveForce = right + forward; // XMVECTOR currentVel = XMLoadFloat3(¤tVelocity); //// moveForce -= (XMVector3Length(currentVel)/movement->maxSpeed) * moveForce ; // XMFLOAT3 force; // XMStoreFloat3(&force, moveForce); // m_sharedContext.GetPhysicsModule().GetRigidBodyManager().AddForceToBody(rigidBody->p_bodyID, force); } } }
void CCutscene::Initialize(std::string szFilename) { m_cCameraController = new CCameraController(this); if (szFilename == "Test") { XMFLOAT4X4 f44World = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 500, 0, 1 }; CCameraFrame* pCameraFrame = new CCameraFrame(5.0f, false, f44World); m_cCameraController->GetFrames().push_back(pCameraFrame); m_fCutsceneTime = 3.0f; } else { //Load from XML TODO std::string szFullFilepath; szFullFilepath = "../Game/Assets/Scripts/Cutscene/" + szFilename; TiXmlDocument Doc; if (Doc.LoadFile(szFullFilepath.c_str(), TiXmlEncoding::TIXML_ENCODING_UTF8)) { TiXmlElement * root = Doc.RootElement(); TiXmlElement * CameraFrameElmt = root->FirstChildElement("CameraFrame"); m_fCutsceneTime = 0.0f; while (CameraFrameElmt != nullptr) { double dLook[3]; double dPos[3]; double dFrameTime; int nShouldInterpolate; CameraFrameElmt->Attribute("lookDirX", &dLook[0]); CameraFrameElmt->Attribute("lookDirY", &dLook[1]); CameraFrameElmt->Attribute("lookDirZ", &dLook[2]); CameraFrameElmt->Attribute("posX", &dPos[0]); CameraFrameElmt->Attribute("posY", &dPos[1]); CameraFrameElmt->Attribute("posZ", &dPos[2]); CameraFrameElmt->Attribute("frameTime", &dFrameTime); CameraFrameElmt->Attribute("shouldInterpolate", &nShouldInterpolate); //Do Look At Algorithm to find Matrix of Frame XMFLOAT4X4 f44WorldMatrix; XMVECTOR vecZAxis = { (float)dLook[0], (float)dLook[1], (float)dLook[2], 0 }; vecZAxis = XMVector3Normalize(vecZAxis); XMVECTOR vecUp = { 0, 1, 0, 0 }; XMVECTOR vecXAxis = XMVector3Cross(vecUp, vecZAxis); vecXAxis = XMVector3Normalize(vecXAxis); XMVECTOR vecYAxis = XMVector3Cross(vecZAxis, vecXAxis); vecYAxis = XMVector2Normalize(vecYAxis); f44WorldMatrix.m[0][0] = vecXAxis.m128_f32[0]; f44WorldMatrix.m[0][1] = vecXAxis.m128_f32[1]; f44WorldMatrix.m[0][2] = vecXAxis.m128_f32[2]; f44WorldMatrix.m[0][3] = 0; f44WorldMatrix.m[1][0] = vecYAxis.m128_f32[0]; f44WorldMatrix.m[1][1] = vecYAxis.m128_f32[1]; f44WorldMatrix.m[1][2] = vecYAxis.m128_f32[2]; f44WorldMatrix.m[1][3] = 0; f44WorldMatrix.m[2][0] = vecZAxis.m128_f32[0]; f44WorldMatrix.m[2][1] = vecZAxis.m128_f32[1]; f44WorldMatrix.m[2][2] = vecZAxis.m128_f32[2]; f44WorldMatrix.m[2][3] = 0; f44WorldMatrix.m[3][0] = (float)dPos[0]; f44WorldMatrix.m[3][1] = (float)dPos[1]; f44WorldMatrix.m[3][2] = (float)dPos[2]; f44WorldMatrix.m[3][3] = 1; CCameraFrame* pCameraFrame = new CCameraFrame((float)dFrameTime, nShouldInterpolate,f44WorldMatrix); m_cCameraController->GetFrames().push_back(pCameraFrame); m_fCutsceneTime += (float)dFrameTime; CameraFrameElmt = CameraFrameElmt->NextSiblingElement("CameraFrame"); } } } }