void AlliedGetCloseState::Enter(Agent * agent) { //assumes that 0 is player, allies start with 1 and so on, also max 3 allies Vector3 dest = WORLD->getPlayerAgent()->GetPosition(); int ally_id = agent->getID(); if (ally_id == 1) { Quaternion q; q.FromAngleAxis(Radian(Math::PI / 2), Vector3::UNIT_Y); dest += WORLD->getPlayerAgent()->GetDirection() * q * Vector3::UNIT_Z * AIConsts::PlayerCloseDistance; } else if (ally_id == 2) { Quaternion q; q.FromAngleAxis(Radian(Math::PI / 2), Vector3::UNIT_Y); dest += WORLD->getPlayerAgent()->GetDirection() * q * Vector3::NEGATIVE_UNIT_Z * AIConsts::PlayerCloseDistance; } else if (ally_id == 3) { Quaternion q; q.FromAngleAxis(Radian(Math::PI / 1), Vector3::UNIT_Y); dest += WORLD->getPlayerAgent()->GetDirection() * q * Vector3::UNIT_Z * AIConsts::PlayerCloseDistance; } agent->orderGoTo(dest); }
Vector3 Vector3::RandomDeviant( Radian angle, Vector3 up ) { Vector3 newUp; if (up == Vector3::ZERO) { // Generate an up vector newUp = this->Perpendicular; } else { newUp = up; } // Rotate up vector by random amount around this Quaternion q; q.FromAngleAxis( Radian(Math::UnitRandom() * Math::TWO_PI), *this ); newUp = q * newUp; // Finally rotate this by given angle around randomised up q.FromAngleAxis( angle, newUp ); return q * (*this); }
Quaternion Vector3::GetRotationTo(Vector3 dest, Vector3 fallbackAxis) { // Based on Stan Melax's article in Game Programming Gems Quaternion q; // Copy, since cannot modify local Vector3 v0 = *this; Vector3 v1 = dest; v0.Normalise(); v1.Normalise(); Real d = v0.DotProduct(v1); // If dot == 1, vectors are the same if (d >= 1.0f) { return Quaternion::IDENTITY; } // sometimes the dot product yields -1.0000001 // floating point math does that to you if (d < -1.0f) d = -1.0f; Real s = Math::Sqrt( (1+d)*2 ); if (s < 1e-6f) { if (fallbackAxis != Vector3::ZERO) { // rotate 180 degrees about the fallback axis q.FromAngleAxis(Radian(Math::PI), fallbackAxis); } else { // Generate an axis Vector3 axis = Vector3::UNIT_X.CrossProduct(*this); if (axis.IsZeroLength) // pick another if colinear axis = Vector3::UNIT_Y.CrossProduct(*this); axis.Normalise(); q.FromAngleAxis(Radian(Math::PI), axis); } } else { Real invs = 1 / s; Vector3 c = v0.CrossProduct(v1); q.x = c.x * invs; q.y = c.y * invs; q.z = c.z * invs; q.w = s * 0.5; q.Normalise(); } return q; }
//------------------------------------------------------------------------------------- Quaternion SceneLoader::getXMLRotation(rapidxml::xml_node<>* node) { Quaternion rotation = Quaternion::IDENTITY; Vector3 components = getXMLVector(node, ROTATION_X_STRING, ROTATION_Y_STRING, ROTATION_Z_STRING); rotation.FromAngleAxis(Ogre::Degree(components.x), Vector3::UNIT_X); rotation.FromAngleAxis(Ogre::Degree(components.y), Vector3::UNIT_Y); rotation.FromAngleAxis(Ogre::Degree(components.z), Vector3::UNIT_Z); return rotation; }
Ogre::Quaternion CameraManager::getOrientation() { Quaternion ident; Radian angle; Vector3 vector; mPitchNode->getOrientation().ToAngleAxis(angle,vector); ident.FromAngleAxis(-angle,vector); Quaternion tmp; mYawNode->getOrientation().ToAngleAxis(angle,vector); tmp.FromAngleAxis(-angle,vector); ident = ident * tmp; return ident; }
ParaEngine::Quaternion Vector3::getRotationTo(const Vector3& dest, const Vector3& fallbackAxis /*= Vector3::ZERO*/) const { // Based on Stan Melax's article in Game Programming Gems Quaternion q; // Copy, since cannot modify local Vector3 v0 = *this; Vector3 v1 = dest; v0.normalise(); v1.normalise(); float d = v0.dotProduct(v1); // If dot == 1, vectors are the same if (d >= 1.0f) { return Quaternion::IDENTITY; } if (d < (1e-6f - 1.0f)) { if (fallbackAxis != Vector3::ZERO) { // rotate 180 degrees about the fallback axis q.FromAngleAxis(Radian(Math::PI), fallbackAxis); } else { // Generate an axis Vector3 axis = Vector3::UNIT_X.crossProduct(*this); if (axis.isZeroLength()) // pick another if colinear axis = Vector3::UNIT_Y.crossProduct(*this); axis.normalise(); q.FromAngleAxis(Radian(Math::PI), axis); } } else { float s = Math::Sqrt((1 + d) * 2); float invs = 1 / s; Vector3 c = v0.crossProduct(v1); q.x = c.x * invs; q.y = c.y * invs; q.z = c.z * invs; q.w = s * 0.5f; q.normalise(); } return q; }
bool WaitingForYou::update(u32 current, u32 delta) { // if (NULL == _modules) { return false; } if (!isActive()) { return true; } if (_camera) { _camera->update(); } // rotate static Quaternion sQ; static float sT; //sT = current * 0.001f; sQ.FromAngleAxis(sT, Vec3::UNIT_Y); // _modelMatrix.makeTransform(Vec3::ZERO, Vec3::UNIT_SCALE * 1.0f, sQ); _modelMatrix_skybox.makeTransform(Vec3::ZERO, Vec3::UNIT_SCALE * (_mapWidth / 2.0) * 20.0f, sQ); float c = Euler::Basic::Cos(current * 0.0001f); _water_matrix.makeTrans(Vec2(c, c)); // return true; }
void TransformationComponent::SetDirection( Vec3& i_oDirection ) { if (i_oDirection == Vec3::ZERO) return; i_oDirection.normalise(); Vec3 oXAxe; Vec3 oYAxe; Vec3 oZAxe; m_oOrientation.ToAxes(oXAxe, oYAxe, oZAxe); Quaternion rotQuat; if ( (oZAxe + i_oDirection).squaredLength() < 0.0f) { // Oops, a 180 degree turn (infinite possible rotation axes) // Default to yaw i.e. use current UP rotQuat.FromAngleAxis(Ogre::Radian(Ogre::Math::PI), oYAxe); } else { // Derive shortest arc to new direction rotQuat = oZAxe.getRotationTo(i_oDirection); } m_oOrientation = rotQuat * m_oOrientation; }
// Rotate selected void SplineRoad::RotateSel(Real relA, Vector3 axis, int addYawRoll) { if (vSel.empty()) return; Vector3 pos0 = getPos0(); Quaternion q; q.FromAngleAxis(Degree(relA), axis); Matrix3 m; q.ToRotationMatrix(m); // rotate 2d yaw around center for (std::set<int>::const_iterator it = vSel.begin(); it != vSel.end(); ++it) { Vector3 pos = getPos(*it) - pos0; Vector3 npos = pos * m + pos0; pos = npos; if (mP[*it].onTer) pos.y = (mTerrain ? mTerrain->getHeightAtWorldPosition(pos.x, 0, pos.z) : 0.f) + fHeight; setPos(*it, pos); if (addYawRoll==1) // todo: get from axis? mP[*it].mYaw -= relA; // rot point yaw else if (addYawRoll==2) // todo: * mul by cos of yaw ?.. mP[*it].mRoll -= relA; // rot point roll vMarkNodes[*it]->setPosition(pos); //Move1(*it, npos); } bSelChng = true; }
bool pathDrawerState::keyPressed(const OIS::KeyEvent& e) { if (e.key == OIS::KC_ESCAPE) _exitGame = true; if (e.key == OIS::KC_F2) guardarRuta(); if (e.key == OIS::KC_F4) cargarRutaCheckPoint("rutasIA.xml"); //cargarRuta("rutasIA.xml"); if (e.key == OIS::KC_F9) borrarTodasLasMarcas(); if (e.key == OIS::KC_U && _nodoSelector && _nodoSelector->getName().substr(0,_nodoSelector->getName().find("_")-1) != _checkPointInfo.nombreNodo) { Quaternion q = Quaternion::IDENTITY; q.FromAngleAxis(Ogre::Degree(-90),Vector3::UNIT_Y); _nodoSelector->setOrientation(q); } return true; }
void CameraControllerThirdPerson::onMouseMove( u16 x,u16 y ) { if(m_bLButtonDown) { float angleX = (float)(x - m_ptOrigin.x) * 0.1f; float angleY = (float)(y - m_ptOrigin.y) * 0.1f; Quaternion qy(angleX, Vec3::UNIT_Y); Mat4 mtxWorld(qy); m_mtxWorld = m_mtxWorld * mtxWorld; Mat4 mi = m_mtxWorld.inverse(); Vec3 v = m_pCamera->getRight(); v = mi * v; Quaternion q; q.FromAngleAxis(angleY, v); m_mtxWorld = m_mtxWorld * q; } else if(m_bMButtonDown) { m_pCamera->moveRelative(Vec3((-x + m_ptOrigin.x) / 4.0f,0,0)); m_pCamera->moveRelative(Vec3(0,(y - m_ptOrigin.y) / 4.0f,0)); } m_ptOrigin.x = x; m_ptOrigin.y = y; }
LRESULT Canvas::OnLeftButtonDown( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled ) { // int x = GET_X_LPARAM(lParam); int y = GET_Y_LPARAM(lParam); //_cameraController.onLeftButtonDown(x,y); bHandled = false; //拾取射线 Ray r = _camera.getCameraToViewportRay(x, y); //与xz平面的交点 Real t = -r._origin.y / r._direction.y; Vec3 p = r.getPoint(t); Vec3 ap = _getActorPosition(); p -= ap; Real len = p.length(); _positionSpeed = 0.010f / len; //目标点 _setActorPosition(p); //调整主角方向 Quaternion q; Radian angle = Euler::Basic::ATan2(p.x, p.z); q.FromAngleAxis(angle, Vec3::UNIT_Y); _angleSpeed = 0.01f; _setActorAngle(q); return 0; }
Quaternion DotSceneLoader::parseQuaternion(TiXmlElement *XMLNode) { //! @todo Fix this crap! Quaternion orientation; if(XMLNode->Attribute("qx")) { orientation.x = StringConverter::parseReal(XMLNode->Attribute("qx")); orientation.y = StringConverter::parseReal(XMLNode->Attribute("qy")); orientation.z = StringConverter::parseReal(XMLNode->Attribute("qz")); orientation.w = StringConverter::parseReal(XMLNode->Attribute("qw")); } else if(XMLNode->Attribute("axisX")) { Vector3 axis; axis.x = StringConverter::parseReal(XMLNode->Attribute("axisX")); axis.y = StringConverter::parseReal(XMLNode->Attribute("axisY")); axis.z = StringConverter::parseReal(XMLNode->Attribute("axisZ")); Real angle = StringConverter::parseReal(XMLNode->Attribute("angle"));; orientation.FromAngleAxis(Ogre::Angle(angle), axis); } else if(XMLNode->Attribute("angleX")) { Vector3 axis; axis.x = StringConverter::parseReal(XMLNode->Attribute("angleX")); axis.y = StringConverter::parseReal(XMLNode->Attribute("angleY")); axis.z = StringConverter::parseReal(XMLNode->Attribute("angleZ")); //orientation.FromAxes(&axis); //orientation.F } return orientation; }
bool WaitingForYou::update(u32 current, u32 delta) { // if (NULL == _modules) { return false; } if (!isActive()) { return true; } if (_camera) { _camera->update(); } // rotate static Quaternion sQ; static float sT; //sT = current * 0.001f; sQ.FromAngleAxis(sT, Vec3::UNIT_Y); // _modelMatrix.makeTransform(Vec3::ZERO, Vec3::UNIT_SCALE, sQ); // return true; }
void Transforms::rotate(const Vector3& axis, const Radian& angle, tTransformSpace relativeTo) { Quaternion q; q.FromAngleAxis(angle,axis); rotate(q, relativeTo); }
//----------------------------------------------------------------------- void Lathe::_latheBodyImpl(TriangleBuffer& buffer, const Shape* shapeToExtrude) const { int numSegShape = shapeToExtrude->getSegCount(); assert(numSegShape>1 && "Shape must contain at least two points"); int offset =0; //int numSeg = mClosed?mNumSeg+1:mNumSeg; int numSeg = mNumSeg+1; buffer.rebaseOffset(); buffer.estimateIndexCount(numSeg*numSegShape*6); buffer.estimateVertexCount((numSegShape+1)*(numSeg+1)); Radian angleEnd(mAngleEnd); if (mAngleBegin>mAngleEnd) angleEnd+=(Radian)Math::TWO_PI; for (int i=0;i<numSeg;i++) { Radian angle; if (mClosed) angle = i/(Real)mNumSeg*Math::TWO_PI; else angle = mAngleBegin + i/(Real)mNumSeg*(angleEnd-mAngleBegin); Quaternion q; q.FromAngleAxis(angle,Vector3::UNIT_Y); for (int j=0;j<=numSegShape;j++) { const Vector2& v0 = shapeToExtrude->getPoint(j); Vector3 vp(v0.x,v0.y,0); const Vector2& vp2direction = shapeToExtrude->getAvgDirection(j); Vector2 vp2normal = vp2direction.perpendicular(); Vector3 normal(vp2normal.x, vp2normal.y, 0); normal.normalise(); if (shapeToExtrude->getOutSide() == SIDE_RIGHT) normal = -normal; addPoint(buffer, q*vp, q*normal, Vector2(i/(Real)mNumSeg, j/(Real)numSegShape)); if (j <numSegShape && i <numSeg-1) { if (shapeToExtrude->getOutSide() == SIDE_RIGHT) { buffer.triangle(offset + numSegShape + 2, offset, offset + numSegShape + 1); buffer.triangle(offset + numSegShape + 2, offset + 1, offset); } else { buffer.triangle(offset + numSegShape + 2, offset + numSegShape + 1, offset); buffer.triangle(offset + numSegShape + 2, offset, offset + 1); } } offset ++; } } }
void AlliedLookAroundState::Enter(Agent * agent) { Quaternion mq = agent->GetRotation(); float some = Math::fDeg2Rad * Math::RangeRandom(-90, 90); Quaternion aq; aq.FromAngleAxis(Radian(some), Vector3::UNIT_Y); agent->SetDirection(mq * aq); //exit immidiately agent->setWaitTime(0); }
//----------------------------------------------------------------------- void BspSceneManager::setWorldGeometry(const String& filename) { mLevel.setNull(); // Check extension is .bsp char extension[6]; size_t pos = filename.find_last_of("."); if( pos == String::npos ) OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Unable to load world geometry. Invalid extension (must be .bsp).", "BspSceneManager::setWorldGeometry"); strncpy(extension, filename.substr(pos + 1, filename.length() - pos).c_str(), 5); extension[5] = 0; if (stricmp(extension, "bsp")) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Unable to load world geometry. Invalid extension (must be .bsp).", "BspSceneManager::setWorldGeometry"); // Load using resource manager mLevel = BspResourceManager::getSingleton().load(filename, ResourceGroupManager::getSingleton().getWorldResourceGroupName()); if (mLevel->isSkyEnabled()) { // Quake3 is always aligned with Z upwards Quaternion q; q.FromAngleAxis(Radian(Math::HALF_PI), Vector3::UNIT_X); // Also draw last, and make close to camera (far clip plane is shorter) setSkyDome(true, mLevel->getSkyMaterialName(), mLevel->getSkyCurvature(), 12, 2000, false, q); } else { setSkyDome(false, StringUtil::BLANK); } // Init static render operation mRenderOp.vertexData = mLevel->mVertexData; // index data is per-frame mRenderOp.indexData = OGRE_NEW IndexData(); mRenderOp.indexData->indexStart = 0; mRenderOp.indexData->indexCount = 0; // Create enough index space to render whole level mRenderOp.indexData->indexBuffer = HardwareBufferManager::getSingleton() .createIndexBuffer( HardwareIndexBuffer::IT_32BIT, // always 32-bit mLevel->mNumIndexes, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, false); mRenderOp.operationType = RenderOperation::OT_TRIANGLE_LIST; mRenderOp.useIndexes = true; }
Agent * EnemyPatrolIdlingState::Enter(Agent* agent) { agent->setWaitTime(0); //turn around randomly Quaternion mq = agent->GetRotation(); float some = Math::fDeg2Rad * Math::RangeRandom(-90, 90); Quaternion aq; aq.FromAngleAxis(Radian(some), Vector3::UNIT_Y); agent->SetDirection(mq * aq); return nullptr; }
void CStaticObject::setRotation(const Radian& r) { m_rotation = r; //if( m_loaded ) //{ Quaternion q; q.FromAngleAxis(getRotation(),Vector3::UNIT_Y); CObject::setOrientation(q); //} updateGeometry(); };
Wall::Wall(Vector3 from, Vector3 to, bool leftnormal) { this->From = from; this->To = to; //find normal this->Normal = (to - from); Quaternion q; if (leftnormal) { q.FromAngleAxis(Radian(Math::fDeg2Rad * 90), Vector3::UNIT_Y); } else { q.FromAngleAxis(Radian(Math::fDeg2Rad * -90), Vector3::UNIT_Y); } this->Normal = q * this->Normal; this->Normal.y = 0; this->Normal.normalise(); //mark mark = GSYS->GetSceneMgr()->createManualObject(); mark->setCastShadows(false); MaterialPtr markMaterial = MaterialManager::getSingleton().create("markMaterial","General"); markMaterial->setReceiveShadows(false); markMaterial->getTechnique(0)->setLightingEnabled(false); mark->clear(); mark->begin("markMaterial", RenderOperation::OT_LINE_LIST); mark->position(from); mark->colour(0,0,1); mark->position(to); mark->colour(0,0,1); mark->position(from.midPoint(to)); mark->colour(1,1,1); mark->position(from.midPoint(to)+Normal); mark->colour(1,1,1); mark->end(); GSYS->GetSceneMgr()->getRootSceneNode()->attachObject(mark); }
bool OgreApp::mouseMoved(const OIS::MouseEvent &evt) { if (pause) { // Move the camera when paused Vector2 dmove = Vector2(evt.state.X.rel, evt.state.Y.rel); Vector3 right = player->getCamRight(true); Vector3 up = player->getCamUpward(true); Quaternion yawRot; Quaternion pitchRot; yawRot.FromAngleAxis(Degree(-dmove.x) / 4, up); pitchRot.FromAngleAxis(Degree(-dmove.y) / 4, right); Quaternion curRot = player->getCamRot(); curRot = pitchRot * yawRot * curRot; player->setCamRot(curRot); curRot = player->getCombinedRotAndRoll(); OgreFramework::getSingletonPtr()->m_pCameraMain->setOrientation(curRot); player->setMousePos(Vector2(evt.state.X.abs, evt.state.Y.abs)); } else { //if (player->getMouseLeft()) { player->checkCursorMove(evt.state.X.rel, evt.state.Y.rel); if (player->checkPerformLeftMove(false)) { activatePerformLeftMove(); player->setCursorMoved(); } else if (player->checkPerformRightMove(false)) { activatePerformRightMove(); player->setCursorMoved(); } } } return true; }
void EngineStage::mouseMoved(const OIS::MouseEvent &evt) { if (stageState == STAGE_STATE_PAUSE) { // Move the camera when paused Vector2 dmove = Vector2(evt.state.X.rel, evt.state.Y.rel); Vector3 right = player->getCamRight(true); Vector3 up = player->getCamUpward(true); Quaternion yawRot; Quaternion pitchRot; yawRot.FromAngleAxis(Degree(-dmove.x) / 4, up); pitchRot.FromAngleAxis(Degree(-dmove.y) / 4, right); Quaternion curRot = player->getCamRot(); curRot = pitchRot * yawRot * curRot; player->setCamRot(curRot); curRot = player->getCombinedRotAndRoll(); OgreFramework::getSingletonPtr()->m_pCameraMain->setOrientation(curRot); player->setMousePos(Vector2(evt.state.X.abs, evt.state.Y.abs)); } }
ParaEngine::Vector3 Vector3::randomDeviant(const Radian& angle, const Vector3& up /*= Vector3::ZERO */) const { Vector3 newUp; if (up == Vector3::ZERO) { // Generate an up vector newUp = this->perpendicular(); } else { newUp = up; } // Rotate up vector by random amount around this Quaternion q; q.FromAngleAxis(Radian(Math::UnitRandom() * Math::TWO_PI), *this); newUp = q * newUp; // Finally rotate this by given angle around randomized up q.FromAngleAxis(angle, newUp); return q * (*this); }
void ParaEngine::CPainter::LoadBillboardMatrix() { Matrix4 mat; Math::CreateBillboardMatrix(&mat, NULL, NULL, true); // to rotate 180 degrees for ease of composing. Quaternion q; q.FromAngleAxis(Radian(Math::PI), Vector3::UNIT_Y); Matrix4 matRot; q.ToRotationMatrix(matRot, Vector3::ZERO); mat = matRot * mat; MultiplyMatrix(mat); }
// Sky Dome //------------------------------------------------------------------------------------- void CScene::CreateSkyDome(String sMater, Vector3 sc, float yaw) { ManualObject* m = app->mSceneMgr->createManualObject(); m->begin(sMater, RenderOperation::OT_TRIANGLE_LIST); // divisions- quality int ia = 32*2, ib = 24,iB = 24 +1/*below_*/, i=0; //int ia = 4, ib = 4, i=0; // angles, max float a,b; const float B = PI_d/2.f, A = 2.f*PI_d; float bb = B/ib, aa = A/ia; // add ia += 1; // up/dn y ) for (b = 0.f; b <= B+bb/*1*/*iB; b += bb) { float cb = sinf(b), sb = cosf(b); float y = sb; // circle xz o for (a = 0.f; a <= A; a += aa, ++i) { float x = cosf(a)*cb, z = sinf(a)*cb; m->position(x,y,z); m->textureCoord(a/A, b/B); if (a > 0.f && b > 0.f) // rect 2tri { m->index(i-1); m->index(i); m->index(i-ia); m->index(i-1); m->index(i-ia); m->index(i-ia-1); } } } m->end(); AxisAlignedBox aab; aab.setInfinite(); m->setBoundingBox(aab); // always visible m->setRenderQueueGroup(RQG_Sky); m->setCastShadows(false); #ifdef SR_EDITOR m->setVisibilityFlags(RV_Sky); // hide on minimap #endif app->ndSky = app->mSceneMgr->getRootSceneNode()->createChildSceneNode(); app->ndSky->attachObject(m); app->ndSky->setScale(sc); Quaternion q; q.FromAngleAxis(Degree(-yaw), Vector3::UNIT_Y); app->ndSky->setOrientation(q); }
//----------------------------------------------------------------------- void TerrainCircleLineList::build( TerrainManager* terrainMgr , Vec3 center, Flt radius, Flt gap ) { Flt girth = 2 * 3.14 * radius; UInt sectorCount = girth / gap; UInt maxSectorCount = 100; if ( sectorCount > maxSectorCount ) sectorCount = maxSectorCount; if ( sectorCount < 6 ) sectorCount = 6; Vector3 dir = Vector3( 0, 0, radius ); Flt onceRadianValue = 2 * 3.14 / sectorCount; Radian onceRadian = Radian( onceRadianValue ); ////////////////////////////////////////////////////// Ogre::Quaternion baseQua; Flt delta = MGTimeOp::getCurrTick() - mLastBuildTime; mLastBuildTime = MGTimeOp::getCurrTick(); Flt speed = 0.003; mBaseRadian += delta * speed * onceRadianValue; if ( mBaseRadian > 2 * 3.14 ) mBaseRadian = 0; baseQua.FromAngleAxis( Radian(mBaseRadian), Vector3::UNIT_Y); dir = baseQua * dir; ////////////////////////////////////////////////////// Quaternion q; q.FromAngleAxis( onceRadian, Vector3::UNIT_Y); ////////////////////////////////////////////////////// mCircleLine.clear(); Vec3 pos; for ( UInt i=0; i<sectorCount; i++ ) { pos = center + Vec3(dir.x,dir.y,dir.z); ////////////////////////////////////////////////////////////////// terrainMgr->getStickHeight( Vec2(pos.x, pos.z), pos.y ); ////////////////////////////////////////////////////////////////// mCircleLine.push_back( pos ); dir = q * dir; } }
Quaternion OpenGLSceneViewCore::rotationFromPoint(NSPoint point, Vector3D &lastPosition) { _delegate->makeCurrentContext(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadMatrixf(_camera->GetViewMatrix()); Quaternion quaternion; Vector3D position; float angle; unsigned int selectedIndex = _currentManipulator->selectedIndex; position = this->positionFromPlaneAxis((PlaneAxis)(selectedIndex + 3), point); position -= _manipulated->selectionCenter(); switch ((Axis)selectedIndex) { case Axis::X: angle = atan2f(position.y, position.z) - atan2f(lastPosition.y, lastPosition.z); quaternion.FromAngleAxis(-angle, Vector3D(1, 0, 0)); break; case Axis::Y: angle = atan2f(position.x, position.z) - atan2f(lastPosition.x, lastPosition.z); quaternion.FromAngleAxis(angle, Vector3D(0, 1, 0)); break; case Axis::Z: angle = atan2f(position.x, position.y) - atan2f(lastPosition.x, lastPosition.y); quaternion.FromAngleAxis(-angle, Vector3D(0, 0, 1)); break; default: break; } lastPosition = position; return quaternion; }
void Lathe::addToTriangleBuffer(TriangleBuffer& buffer) const { assert( mShapeToExtrude && "Shape must not be null!"); int numSegShape = mShapeToExtrude->getSegCount(); assert(numSegShape>1 && "Shape must contain at least two points"); int offset =0; buffer.rebaseOffset(); buffer.estimateIndexCount(mNumSeg*numSegShape*6); buffer.estimateVertexCount((numSegShape+1)*(mNumSeg+1)); for (int i=0;i<=mNumSeg;i++) { Real angle = i/(Real)mNumSeg*Math::TWO_PI; Quaternion q; q.FromAngleAxis((Radian)angle,Vector3::UNIT_Y); for (int j=0;j<=numSegShape;j++) { Vector2 v0 = mShapeToExtrude->getPoint(j); Vector3 vp(v0.x,v0.y,0); Vector2 vp2direction = mShapeToExtrude->getAvgDirection(j); Vector2 vp2normal = vp2direction.perpendicular(); Vector3 normal(vp2normal.x, vp2normal.y, 0); normal.normalise(); if (mShapeToExtrude->getOutSide() == SIDE_LEFT) { normal = -normal; } addPoint(buffer, q*vp, q*normal, Vector2(i/(Real)mNumSeg, j/(Real)numSegShape)); if (j <numSegShape && i <mNumSeg) { buffer.index(offset + numSegShape + 2); buffer.index(offset); buffer.index(offset + numSegShape + 1); buffer.index(offset + numSegShape + 2); buffer.index(offset + 1); buffer.index(offset); } offset ++; } } }
void Enemy::decidePatrol(bool search) { delete m_path; m_path = new Spline(); Vector3 prev = m_pos; prev.y = 0.f; path_len = 0.f; path_pos = 0.001f; m_path->addPoint(prev); if (search) { prev = playerPos; prev.y = 0; m_path->addPoint(prev); prev += (playerPos - m_pos); m_path->addPoint(prev); } float speed_factor = playerPos.distance(m_pos); speed_factor /= 100.f; speed_factor = std::max(speed_factor, 1.f); for (int i = 0; i < 6; ++i) { Vector3 pdir = playerPos - m_pos; pdir.y = 0; pdir.normalize(); Quaternion q; q.FromAngleAxis(Rand::get().genFloat(-1.0, 1.0), Vector3::UNIT_Y); pdir = q * pdir; //pdir.randomDeviant(0.75f, Vector3::UNIT_Y); pdir.y = 0; pdir.normalize(); pdir *= Rand::get().genFloat(30.f, 50.f) * speed_factor; m_patrol.push_back(prev + pdir); //m_patrol.push_back(prev + Vector3(Rand::get().genFloat(-50.f, 50.f), // 0.f, Rand::get().genFloat(-50.f, 50.f))); path_len += prev.distance(m_patrol.back()); prev = m_patrol.back(); m_path->addPoint(m_patrol.back()); } m_path->recalc(); //std::cout<<"Path len: "<<path_len<<"\n"; }