Ejemplo n.º 1
0
void DynamicBody::CalcExternalForce()
{
    // gravity
    if (!GetFrame()) return;			// no external force if not in a frame
    Body *body = GetFrame()->GetBody();
    if (body && !body->IsType(Object::SPACESTATION)) {	// they ought to have mass though...
        vector3d b1b2 = GetPosition();
        double m1m2 = GetMass() * body->GetMass();
        double invrsqr = 1.0 / b1b2.LengthSqr();
        double force = G*m1m2 * invrsqr;
        m_externalForce = -b1b2 * sqrt(invrsqr) * force;
    }
    else m_externalForce = vector3d(0.0);
    m_gravityForce = m_externalForce;

    // atmospheric drag
    if (body && GetFrame()->IsRotFrame() && body->IsType(Object::PLANET))
    {
        vector3d dragDir = -m_vel.NormalizedSafe();
        vector3d fDrag = CalcAtmosphericForce(m_dragCoeff)*dragDir;

        // make this a bit less daft at high time accel
        // only allow atmosForce to increase by .1g per frame
        vector3d f1g = m_atmosForce + dragDir * GetMass();
        if (fDrag.LengthSqr() > f1g.LengthSqr()) m_atmosForce = f1g;
        else m_atmosForce = fDrag;

        m_externalForce += m_atmosForce;
    }
    else m_atmosForce = vector3d(0.0);

    // centrifugal and coriolis forces for rotating frames
    if (GetFrame()->IsRotFrame()) {
        vector3d angRot(0, GetFrame()->GetAngSpeed(), 0);
        m_externalForce -= m_mass * angRot.Cross(angRot.Cross(GetPosition()));	// centrifugal
        m_externalForce -= 2 * m_mass * angRot.Cross(GetVelocity());			// coriolis
    }
}
Ejemplo n.º 2
0
void ObjectViewerView::OnChangeGeoSphereStyle()
{
	SBody sbody;

	const fixed volatileGas = fixed(65536.0*atof(m_sbodyVolatileGas->GetText().c_str()), 65536);
	const fixed volatileLiquid = fixed(65536.0*atof(m_sbodyVolatileLiquid->GetText().c_str()), 65536);
	const fixed volatileIces = fixed(65536.0*atof(m_sbodyVolatileIces->GetText().c_str()), 65536);
	const fixed life = fixed(65536.0*atof(m_sbodyLife->GetText().c_str()), 65536);
	const fixed volcanicity = fixed(65536.0*atof(m_sbodyVolcanicity->GetText().c_str()), 65536);
	const fixed metallicity = fixed(65536.0*atof(m_sbodyMetallicity->GetText().c_str()), 65536);
	const fixed mass = fixed(65536.0*atof(m_sbodyMass->GetText().c_str()), 65536);
	const fixed radius = fixed(65536.0*atof(m_sbodyRadius->GetText().c_str()), 65536);

	sbody.parent = 0;
	sbody.name = "Test";
	/* These should be the only SBody attributes GeoSphereStyle uses */
	sbody.type = SBody::TYPE_PLANET_TERRESTRIAL;
	sbody.seed = atoi(m_sbodySeed->GetText().c_str());
	sbody.radius = radius;
	sbody.mass = mass;
	sbody.averageTemp = 273;
	sbody.m_metallicity = metallicity;
	sbody.m_volatileGas = volatileGas;
	sbody.m_volatileLiquid = volatileLiquid;
	sbody.m_volatileIces = volatileIces;
	sbody.m_volcanicity = volcanicity;
	sbody.m_life = life;
	sbody.heightMapFilename = 0;

	Body *body = Pi::player->GetNavTarget();
	if (body->IsType(Object::PLANET)) {
		Planet *planet = static_cast<Planet*>(body);
		GeoSphere *gs = planet->GetGeoSphere();
		gs->m_style = GeoSphereStyle(&sbody);
		// force rebuild
		gs->OnChangeDetailLevel();
	}
}
Ejemplo n.º 3
0
Entity* CreateFloor(SimpleTree& _rParentNode)
{
	Entity* pFloor = new Entity;

	// The model
	Plane* pPlane = new Plane(Vector3(0.0f, 1.0f, 0.0f), FLOOR_POSITION);
	pFloor->addComponent(pPlane);
	pPlane->setEntity(pFloor);

	// The visible model
	Cube* pVisibleFloor = new Cube(Vector2(), 500.0f);
	pVisibleFloor->setColour(Vector4(0.0f, 0.5f, 0.0f, 1.0f));
	pFloor->addComponent(pVisibleFloor);
	pVisibleFloor->setEntity(pFloor);

	// The physical body
	Body::Material material;
	material.density = 0.5f;
	material.friction = 0.5f;
	material.restitution = 0.5f;
	Body* pBody = PhysicsFactory::getInstance()->createBody(material, pPlane, FLOOR_POSITION, false);
	pFloor->addComponent(pBody);
	pBody->setEntity(pFloor);

	// The scene
	SimpleTree* pNode = new SimpleTree;
	pNode->setModel(pPlane);
	pBody->setNode(pNode);
	_rParentNode.addChild(pNode);

	SimpleTree* pVisibleNode = new SimpleTree;
	getTranslation3(pVisibleNode->getTransformation()) = FLOOR_POSITION + Vector3(0.0f, -500.0f, -500.0f);
	pVisibleNode->setModel(pVisibleFloor);
	_rParentNode.addChild(pVisibleNode);

	GazEngine::addEntity(pFloor);
	return pFloor;
}
Ejemplo n.º 4
0
bool EditTool::onMousePress( const QPointF& pos_ ) {
    m_selected = scene()->selected();
    Body* b = scene()->activeBody();
    QPointF pos = pos_;
    if (m_selected) {
        if (b) {
            pos = b->toLocal(pos_);
        }
        PrimitiveMarker* marker = m_selected->getMarkerAtPoint(pos);
        if (marker) {
            m_start_pos = marker->position();
            m_offset = marker->getOffset( pos );
            m_selected_marker = marker;
            m_selected_marker->activate();
            m_moved = false;
            return true;
        }
    }
    m_selected_marker = 0;
    pos = pos_;
    Primitive* primitive = scene()->getPrimitiveAtPoint( pos );

    if (primitive) {
        scene()->setSelected( primitive );
        b = scene()->activeBody();
        if (b) {
            pos = b->toLocal(pos_);
        }
        m_start_pos = primitive->position();
        m_offset = m_start_pos - pos;
    } else {
        scene()->clearSelection();
        scene()->setText("");
    }
    m_moved = false;
    m_selected = primitive;
    return true;
}
Ejemplo n.º 5
0
TEST(TestMeiDocument, ElementsByName) {
    Mei *mei = new Mei();
    Music *mus = new Music();
    Body *body = new Body();
    Staff *staff = new Staff();
    Staff *s2 = new Staff();
    Note *n1 = new Note();
    string wantedId = n1->getId();
    Note *n2 = new Note();
    Note *n3 = new Note();
    Note *n4 = new Note();
    
    mei->addChild(mus);
    mus->addChild(body);
    body->addChild(staff);
    body->addChild(s2);
    staff->addChild(n1);
    staff->addChild(n2);
    staff->addChild(n3);
    s2->addChild(n4);
    
    MeiDocument *doc = new MeiDocument();
    doc->setRootElement(mei);
    
    std::vector<MeiElement*> notes = doc->getElementsByName("note");
    ASSERT_EQ(4, notes.size());
    
    std::vector<MeiElement*> rests = doc->getElementsByName("rest");
    ASSERT_EQ(0, rests.size());

    // After adding the root element, making a new element works
    Note *n5 = new Note();
    staff->addChild(n5);
    
    std::vector<MeiElement*> notes_new = doc->getElementsByName("note");
    ASSERT_EQ(5, notes_new.size());
    
}
Ejemplo n.º 6
0
static int test_torus()
{
  printf("making torus\n");
  Body* torus = GeometryModifyTool::instance()->torus(1, .2);
  if(!torus)
  {
    printf("failed to make torus\n");
    return 1;
  }
  CubitBox comp_box(CubitVector(-1.2,-1.2,-0.2), CubitVector(1.2,1.2,0.2));
  CubitBox bnd_box = torus->bounding_box();

  bool identical =  cubit_box_identical(bnd_box, comp_box, GEOMETRY_RESABS*2.0, true);
  if (identical)
    return 0;

  if( bnd_box < comp_box || bnd_box > comp_box*1.09)
  {
    printf("boxes not identical\n");
    return 1;
  }
  return 0;
}
Ejemplo n.º 7
0
/**
* Convenience constructor.
*/
BodyActuator::BodyActuator(const Body& body, 
                           const SimTK::Vec3& point,
                           bool pointIsGlobal,
                           bool spatialForceIsGlobal)
{
    setAuthors("Soha Pouya, Michael Sherman");
    constructInfrastructure();

    updConnector<Body>("body").set_connected_to_name(body.getName());

    set_point(point); // origin
    set_point_is_global(pointIsGlobal);
    set_spatial_force_is_global(spatialForceIsGlobal);
}
	void updateCenterOfMass(double &mass, Vec2D &centerOfMass) {
		if (_state == INTERNAL) {
			double child_mass = 0;
			Vec2D child_com;
			if (_NW != NULL)
				_NW->updateCenterOfMass(child_mass, child_com);
			if (_SW != NULL)
				_SW->updateCenterOfMass(child_mass, child_com);
			if (_NE != NULL)
				_NE->updateCenterOfMass(child_mass, child_com);
			if (_SE != NULL)
				_SE->updateCenterOfMass(child_mass, child_com);
			_mass = child_mass;
			_centerOfMass = child_com/_mass;
			centerOfMass = centerOfMass + child_com*child_mass;
			mass += child_mass;
		} else {
			if (_body != NULL) {
				mass += _body->getMass();
				centerOfMass = centerOfMass+  _body->getPos()*_body->getMass();
			}
		}
	}
Ejemplo n.º 9
0
	int w_Body_applyImpulse(lua_State * L)
	{
		Body * t = luax_checkbody(L, 1);
		float jx = (float)luaL_checknumber(L, 2);
		float jy = (float)luaL_checknumber(L, 3);

		if(lua_gettop(L) == 3)
		{
			t->applyImpulse(jx, jy);
		}
		else if(lua_gettop(L) == 5)
		{
			float rx = (float)luaL_checknumber(L, 4);
			float ry = (float)luaL_checknumber(L, 5);
			t->applyImpulse(jx, jy, rx, ry);
		}
		else
		{
			return luaL_error(L, "Wrong number of parameters.");
		}

		return 0;
	}
Ejemplo n.º 10
0
DrawList::Item::Item(const Body &body, Point pos, Point blur, float cloak, float clip, int swizzle, int step)
	: position{static_cast<float>(pos.X()), static_cast<float>(pos.Y())}, clip(clip), flags(swizzle)
{
	Body::Frame frame = body.GetFrame(step);
	tex0 = frame.first;
	tex1 = frame.second;
	flags |= static_cast<uint32_t>(frame.fade * 256.f) << 8;
	
	double width = body.Width();
	double height = body.Height();
	Point unit = body.Facing().Unit();
	Point uw = unit * width;
	Point uh = unit * height;
	
	if(clip < 1.)
	{
		// "clip" is the fraction of its height that we're clipping the sprite
		// to. We still want it to start at the same spot, though.
		pos -= uh * ((1. - clip) * .5);
		position[0] = static_cast<float>(pos.X());
		position[1] = static_cast<float>(pos.Y());
		uh *= clip;
	}
	
	// (0, -1) means a zero-degree rotation (since negative Y is up).
	transform[0] = -uw.Y();
	transform[1] = uw.X();
	transform[2] = -uh.X();
	transform[3] = -uh.Y();
	
	// Calculate the blur vector, in texture coordinates.
	this->blur[0] = unit.Cross(blur) / (width * 4.);
	this->blur[1] = -unit.Dot(blur) / (height * 4.);

	if(cloak > 0.)
		Cloak(cloak);
}
    void onItemAdded(Item* item)
        {
            MessageView* mv = MessageView::instance();

            if(BodyItem* bodyItem = dynamic_cast<BodyItem*>(item)){
                Body* body = bodyItem->body();
                for(size_t i=0; i < body->numDevices(); ++i){
                    Device* device = body->device(i);
                    if(!camera){
                        camera = dynamic_pointer_cast<Camera>(device);
                        if(camera){
                            mv->putln(format("RTCVisionSensorSamplePlugin: Detected Camera \"%1%\" of %2%.")
                                      % camera->name() % body->name());
                            visionSensorSampleRTC->setCameraLocalT(camera->T_local());
                        }
                    }
                    if(!rangeSensor){
                        rangeSensor = dynamic_pointer_cast<RangeSensor>(device);
                        if(rangeSensor){
                            mv->putln(format("RTCVisionSensorSamplePlugin: Detected RangeSensor \"%1%\" of %2%.")
                                      % rangeSensor->name() % body->name());
                            visionSensorSampleRTC->setRangeSensorLocalT(rangeSensor->T_local());
                        }
                    }
                }
            }else if(PointSetItem* pointSetItem = dynamic_cast<PointSetItem*>(item)){
                if(pointSetItem->name() == "RangeCameraPoints"){
                    pointSetFromRangeCamera = pointSetItem->pointSet();
                    mv->putln("RTCVisionSensorSamplePlugin: Detected PointSetItem \"RangeCameraPoints\"");
                    visionSensorSampleRTC->setPointSetFromRangeCamera(pointSetFromRangeCamera);
                } else if(pointSetItem->name() == "RangeSensorPoints"){
                    pointSetFromRangeSensor = pointSetItem->pointSet();
                    mv->putln("RTCVisionSensorSamplePlugin: Detected PointSetItem \"RangeSensorPoints\"");
                    visionSensorSampleRTC->setPointSetFromRangeSensor(pointSetFromRangeSensor);
                }
            }
        }
Ejemplo n.º 12
0
void BodyItemImpl::doAssign(Item* srcItem)
{
    BodyItem* srcBodyItem = dynamic_cast<BodyItem*>(srcItem);
    if(srcBodyItem){
        // copy the base link property
        Link* baseLink = 0;
        Link* srcBaseLink = srcBodyItem->currentBaseLink();
        if(srcBaseLink){
            baseLink = body->link(srcBaseLink->name());
            if(baseLink){
                setCurrentBaseLink(baseLink);
            }
        }
        // copy the current kinematic state
        Body* srcBody = srcBodyItem->body();
        for(int i=0; i < srcBody->numLinks(); ++i){
            Link* srcLink = srcBody->link(i);
            Link* link = body->link(srcLink->name());
            if(link){
                link->q() = srcLink->q();
            }
        }

        if(baseLink){
            baseLink->p() = srcBaseLink->p();
            baseLink->R() = srcBaseLink->R();
        } else {
            body->rootLink()->p() = srcBody->rootLink()->p();
            body->rootLink()->R() = srcBody->rootLink()->R();
        }
        zmp = srcBodyItem->impl->zmp;

        initialState = srcBodyItem->impl->initialState;
        
        self->notifyKinematicStateChange(true);
    }
}
Ejemplo n.º 13
0
static int l_get_gps(lua_State *l)
{
	Player *player = LuaObject<Player>::CheckFromLua(1);
	vector3d pos = Pi::player->GetPosition();
	double center_dist = pos.Length();
	auto frame = player->GetFrame();
	if(frame) {
		Body *astro = frame->GetBody();
		if(astro && astro->IsType(Object::TERRAINBODY)) {
			TerrainBody* terrain = static_cast<TerrainBody*>(astro);
			if (!frame->IsRotFrame())
				frame = frame->GetRotFrame();
			vector3d surface_pos = pos.Normalized();
			double radius = 0.0;
			if (center_dist <= 3.0 * terrain->GetMaxFeatureRadius()) {
				radius = terrain->GetTerrainHeight(surface_pos);
			}
			double altitude = center_dist - radius;
			vector3d velocity = player->GetVelocity();
			double vspeed = velocity.Dot(surface_pos);
			if (fabs(vspeed) < 0.05) vspeed = 0.0; // Avoid alternating between positive/negative zero

			//			RefreshHeadingPitch();

			if (altitude < 0) altitude = 0;
			LuaPush(l, altitude);
			LuaPush(l, vspeed);
			const float lat = RAD2DEG(asin(surface_pos.y));
			const float lon = RAD2DEG(atan2(surface_pos.x, surface_pos.z));
			LuaPush(l, lat);
			LuaPush(l, lon);
			return 4;
			//				}
		}
	}
	return 0;
}
Ejemplo n.º 14
0
Body* System::processChild(pugi::xml_node tmpRoot, Body* parent)
{
    //Deal with the root node
    xml_node tmpNode;
    std::string tmpName = tmpRoot.child_value("name");
    std::string tmpType = tmpRoot.child_value("type");
    std::string tmpDesc = tmpRoot.child_value("desc");
    int tmpRadius = atoi(tmpRoot.child_value("radius"));
    std::string tmpTexture = tmpRoot.child_value("texture");
    int tmpOrbitRadius = atoi(tmpRoot.child_value("orbit_radius"));
    f32 tmpOrbitSpeed = atof(tmpRoot.child_value("orbit_speed"));
    int tmpBrightness = atoi(tmpRoot.child_value("bright"));

    
    core::vector3df tmpDefaultPos = parent->getPosition();
    tmpDefaultPos.X += tmpOrbitRadius;
    
    //core::vector3df(tmpOrbitRadius,0.0f,0.0f);

    Body* rootBody = new Body(this->smgr,this->driver,tmpDefaultPos,tmpRadius,tmpName,tmpDesc,tmpType,tmpOrbitRadius,tmpOrbitSpeed,parent,tmpTexture,tmpBrightness);
    tmpNode = tmpRoot.child("children").first_child();
    bool morePlanets = true;

    while(tmpNode && morePlanets){
        rootBody->addChild(processChild(tmpNode,rootBody));
        if(tmpNode.next_sibling()){
            tmpNode = tmpNode.next_sibling();
            continue;
        }
        else{
            morePlanets=false;
        }
    }

    return rootBody;
}
Ejemplo n.º 15
0
// Checks ship path to destination for obstacles.
// clear_angle is angle
// returns true if path is clear, false if there is an obstacle.
static bool CheckClearPath(Ship* ship, Frame* destination_frame, vector3d destination_pos, float clear_angle = 0.0f)
{
	Body* sbody = ship->GetFrame()->GetBody();
	if (sbody == nullptr) {
		return true;
	}
	if (sbody->IsType(Object::PLANET) 
		|| (sbody->IsType(Object::SPACESTATION) && ship->GetFrame() != destination_frame)) 
	{
		vector3d ship_pos = ship->GetPositionRelTo(destination_frame);
		vector3d body_pos = sbody->GetPositionRelTo(destination_frame);
		double radius = GetTransitRadius(sbody);
		if (sbody->IsType(Object::PLANET)) {
			radius += 5000.0;
		}
		double ship_to_body_distance;
		vector3d ship_to_body_dir = (body_pos - ship_pos).Normalized(ship_to_body_distance);
		double ship_to_destination_distance;
		vector3d ship_to_destination_dir = (destination_pos - ship_pos).Normalized(ship_to_destination_distance);
		double cos = ship_to_destination_dir.Dot(ship_to_body_dir);
		if (cos > clear_angle) { // Path might be unclear
			double ship_to_closest_distance = cos * ship_to_body_distance;
			vector3d closest_point = ship_pos + (ship_to_destination_dir * ship_to_closest_distance);
			double closest_distance = (closest_point - body_pos).Length();
			if (closest_distance < radius && ship_to_closest_distance < ship_to_destination_distance) {
				return false;
			} else {
				return true;
			}
		} else {
			return true;
		}
	} else {
		return true;
	}
}
void OpenHRPOnlineViewerItemImpl::updateLog
(BodyItemInfo* info, const LinkPositionSequence& links, int numLinks, double time)
{
    BodyMotionItem* motionItem = info->logItem.get();
    if(!motionItem){
        motionItem = info->bodyItem->findChildItem<BodyMotionItem>(info->logName);
        if(!motionItem){
            motionItem = new BodyMotionItem();
            motionItem->setTemporal();
            motionItem->setName(info->logName);
            info->bodyItem->addChildItem(motionItem);
        }
        resetLogItem(info, motionItem);
    }

    if(info->needToSelectLogItem){
        ItemTreeView::instance()->selectItem(motionItem, true);
        info->needToSelectLogItem = false;
    }

    MultiSE3Seq& seq = *motionItem->motion()->linkPosSeq();
    int frame = seq.frameOfTime(time);
    int lastFrame = std::max(0, std::min(frame, seq.numFrames()));
    seq.setNumFrames(frame + 1);

    Body* body = info->bodyItem->body();
    for(int i=lastFrame; i <= frame; ++i){
        MultiSE3Seq::Frame positions = seq.frame(i);
        for(int j=0; j < numLinks; ++j){
            SE3& se3 = positions[j];
            se3.translation() = Eigen::Map<Vector3>(const_cast<double*>(links[j].p));
            Matrix3 Rs = body->link(j)->Rs().transpose();
            se3.rotation() = Eigen::Map<Matrix3>(const_cast<double*>(links[j].R)).transpose() * Rs;
        }
    }
}
Ejemplo n.º 17
0
void action()
{
            string thataction;
            bool tester = false;
            cout << "What action is involved?" << endl;
            getline(cin,thataction);
            thataction = lowercase(thataction);

            if(thataction.empty()) //Checking to see if user entered anything
            {
                cout << "Your input was not recognized." << endl;
            }

            for(int x = 0; x < token.get_action_size(); x++)
            {
                string tokenjr = token.get_action(x); //Inserts line to token
                int y = tokenjr.find_first_of(" "); //Takes number spot of where space
                int z = thataction.find_first_of(" "); //Same as above
                string compare1 = thataction.substr(0,z); //Taking substring from beginning to space
                string compare2 = tokenjr.substr(0,y); //Same as above

                if(compare1 < compare2) //Checks if the users input is shorter for imperative checking
                {
                    int difference = (compare2.length() - compare1.length()); //takes the difference

                    if(compare1 == compare2.substr(0,(compare2.length()- difference))) //To then make a substring and see if the words are the same
                    {
                        compare2 = token.get_action(x); //Takes the full entry
                        compare1 = thataction.substr(z+1, thataction.length()); //gets the next difference to compare
                        difference = (compare2.length() - compare1.length());

                        if(thataction.substr(z+1, thataction.length()) == compare2.substr(y+1,(compare2.length()- difference))) //Doing the same as before but now with both words
                        {
                            cout << "The " << token.get_muscle(x) << " muscle is involved." << endl;
                            tester = true; //Tester for error message
                        }
                    }
                }

                if(compare1 == compare2) //comparing the words to see if they are equal to move onto the next step
                {
                        if(thataction == token.get_action(x) ) //Since the first words equal it checks the entire line
                        {
                            cout << "The " << token.get_muscle(x) << " muscle is involved." << endl;
                            tester = true; //Tester for error message
                        }
                }
            }

            if(tester == false) //Mentioned above
            {
                cout << "Sorry there is no match." << endl;
            }

     cout << "\n";
}
Ejemplo n.º 18
0
    inline void update(FT mFT) override
    {
        if(isInAir())
        {
            action = (body->getVelocity().y > 0) ? Action::Fall : Action::Jump;
        }
        else
        {
            action = crouching ? Action::Crouch : Action::Stand;
        }

        movStatus = (std::abs(body->getVelocity().x) < 100) ? MovStatus::Stop
                                                            : MovStatus::Move;

        if(atkDelay > 0.f)
        {
            atkStatus = AtkStatus::Attack;
            atkDelay -= mFT;
        }
        else
        {
            atkStatus = AtkStatus::Idle;
        }
    }
Ejemplo n.º 19
0
TEST(TestMeiDocument, DocumentPointers) {
    Mei *mei = new Mei();
    Music *mus = new Music();
    Body *body = new Body();
    Staff *staff = new Staff();

    // If an element is added as a child and neither element is attached to a document, nothing happens. 
    ASSERT_EQ(NULL, mei->getDocument());
    mei->addChild(mus);
    ASSERT_EQ(NULL, mus->getDocument());

    MeiDocument *doc = new MeiDocument();

    // add root to document, all elements should have their document pointer updated
    mus->addChild(body);
    doc->setRootElement(mei);
    ASSERT_EQ(doc, mei->getDocument());
    ASSERT_EQ(doc, mus->getDocument());
    ASSERT_EQ(doc, body->getDocument());

    // add another element as a child, child element should be linked to the same document
    body->addChild(staff);
    ASSERT_EQ(doc, staff->getDocument());
}
Ejemplo n.º 20
0
Game::Game(const SystemPath &path, const vector3d &pos) :
	m_time(0),
	m_state(STATE_NORMAL),
	m_wantHyperspace(false),
	m_timeAccel(TIMEACCEL_1X),
	m_requestedTimeAccel(TIMEACCEL_1X),
	m_forceTimeAccel(false)
{
	m_space.Reset(new Space(this, path));
	Body *b = m_space->FindBodyForPath(&path);
	assert(b);

	CreatePlayer();

	m_space->AddBody(m_player.Get());

	m_player->Enable();
	m_player->SetFrame(b->GetFrame());

	m_player->SetPosition(pos);
	m_player->SetVelocity(vector3d(0,0,0));

	CreateViews();
}
Ejemplo n.º 21
0
int run() {
	int page = 0, npage;
	char *input = (char*)malloc(sizeof(char));
	do {
		npage = drawSide(page);
		drawBoard(page);

		Body *line = newLine(35, 1, 60, 'v', '-');
		Stroke *lineStroke = newStroke(1, newBorder("|"));
		line->addStroke(line, lineStroke);
		stroke.setStrokeJoint(lineStroke, '#');
		registerBody("NULL", line);

		draw();
		gets(input);

		handleInput(&page, npage, input);
		
		clearAndRefresh();
		clearBodies();
	} while(!isKeyword(input, "exit"));

	return 0;
}
Ejemplo n.º 22
0
void diagnostic()
{
    string thatmuscle;
    bool test; //Created to see if input was equal to anything and if not to print error
    cout << "What muscle would you like to check?" << endl;
    getline(cin,thatmuscle);
    thatmuscle = lowercase(thatmuscle);

    for(int m = 0; m < token.get_muscle_size(); m++)
    {
         if(thatmuscle == token.get_muscle(m) )
         {
            test = 1; //Entire for loop is to check if anything is equal for the error print
         }
    }

    if(test == 0) //first checks if its an error and if not it proceeds to next for loop
    {
        cout << "Sorry your input was not recognized" << endl;
    }

    else
        for(int m = 0; m < token.get_muscle_size(); m++)
        {
            if(thatmuscle == token.get_muscle(m) )
            {
                if(token.get_deep(m) == "both") //simply being checked for grammatical purposes
                {
                    cout << "Possible pain for " << token.get_deep(m) << " " << token.get_location(m) << "s." << endl;
                }

                else
                cout << "Possible " << token.get_deep(m) << " " << token.get_location(m) << " pain." << endl; //Just for grammer
            }

        }

    cout << "\n" << endl;
}
	void updateCenterOfMass(Body body) {
		if (_mass == 0) {
			_mass = body.getMass();
			_centerOfMass = body.getPos();
		} else {
			double new_mass = _mass + body.getMass();
			double new_cen_x = ((_mass*_centerOfMass.getX()) + (body.getMass() * body.getXPos()))/new_mass;
			double new_cen_y = ((_mass*_centerOfMass.getY()) + (body.getMass() * body.getYPos()))/new_mass;
			_centerOfMass = Vec2D(new_cen_x, new_cen_y);
			_mass = new_mass;
		}
	}
Ejemplo n.º 24
0
    inline FGCFighter(Entity& mE, FGGame& mGame) : Component{mE}, game(mGame)
    {
        cPhys = &getEntity().getComponent<FGCPhys>();
        body = &cPhys->getBody();

        fc = getTestFC();
        hp = fc.hp;

        getEntity().addGroups(FGGroup::FGGSolid, FGGroup::FGGFighter);
        body->addGroups(FGGroup::FGGSolid, FGGroup::FGGFighter);
        body->addGroupsToCheck(FGGroup::FGGSolid, FGGroup::FGGFighter);
        body->setRestitutionX(0.3f);
        body->setRestitutionY(0.0f);
        body->setMass(1.f);
        body->setVelTransferMultX(0.6f);
        body->setWidth(toCr(fc.width));

        cPhys->getGroundSensor().getShape().setWidth(body->getWidth());
    }
Ejemplo n.º 25
0
void strength()
{
        string strengthen;
        cout << "Which muscle would you like to strengthen?" << endl;
        getline(cin,strengthen);
        strengthen = lowercase(strengthen);

        int space_begin; //To store the spot of first space
        space_begin = strengthen.find_first_of(" ");
        strengthen = strengthen.substr(space_begin+1, strengthen.length()); //takes substring from word after space to the end

        int thecounter = 0;
        string sentence;
        for(int place = 0; place < token.get_location_size(); place++)
        {
            if(strengthen == token.get_location(place))
            {                         //This for loop is created to get the second to last place
                thecounter = place;   //for grammer purposes in the next for loop
            }
        }

        if(thecounter == 0 || strengthen.empty()) //Checks here for errors instead of second
        {                                          //loop because it ran it the first time checking for matches
            cout << "Sorry your input was not recognized." <<endl;
            return;
        }

        for(int place = 0; place < token.get_location_size(); place++)
        {
            if(place == 0) //To start the sentence off
                {
                    sentence.append("Work on the following muscles: ");
                }
                    if(strengthen == token.get_location(place) )
                    {
                        if(thecounter == place) //thecounter was created to keep track of how many
                        {                       //matches there were so the program can add the "and " part for grammer
                            sentence.append("and ");
                        }

                        sentence.append(token.get_muscle(place));//These two are added to create sentence with proper structure
                        sentence.append(", ");

                    }
                    if(place == token.get_location_size()-1)
                    {
                        cout << sentence.substr(0, sentence.length()-2) << "." << endl; //Last two characters to be deleted because they are ", "
                    }
        }
        //cout << sentence.substr(0, sentence.length()-2) << "." << endl; //Last two characters to be deleted because they are ", "
    cout << "\n";
}
Ejemplo n.º 26
0
void
timer (int t)
{
  if (Rocket.altitude (Earth) > 0)
    Rocket.vel =
      Rocket.vel +
      (Rocket.pos.direction (Earth.pos) * Earth.gravity (Rocket));
  else
    {
      Rocket.vel = Vtx (0, 0, 0);
      Rocket.rvel = 0;
    }
  Rocket.pos = Rocket.pos + Rocket.vel / 24;
  Rocket.rot = Rocket.rot * Quat (Rocket.rvel, Rocket.axis);
  Earth.rot = Earth.rot * Quat (Earth.rvel, Earth.axis);
  Rocket.setThrust (throttle);
  glutPostRedisplay ();
  glutTimerFunc (t, timer, t);
}
Ejemplo n.º 27
0
void Game::Init()
{
	GameInstance::instance()->setGame(this);

	Body* b;

	for(int i=0; i<512; i++) {
		Mine* m = new Mine(vec2(rand()%W_WIDTH, rand()%W_HEIGHT));
	}

	for(int i=0; i<400; i++) {
		b = PhysicsManager::instance()->getFromPool();
		b->fromConvexSet(createConvexSet(4+rand()%2, 180+rand()%50, vec2(rand()%W_WIDTH, rand()%W_HEIGHT)));
		b->setCollisionCallback(&dcallback);
		b->getShape().setColor(0x74BBFB);
		float area = getSetArea(b->getShape().getVertices());
		if(area == area) {} else {
			PhysicsManager::instance()->releaseToPool(b);
			continue;
		}
		float mass = area/100000.f;
		if(mass < 1.f) mass = 1.f;
		if(mass > 3.f) mass = 3.f;
		b->setMass(mass);
		renderQueue.push_back(b);
	}

	ctime = 0;
	ltime = 0;
	desired_fps = 240.f;

	debug = new DebugConsole(this, 16, 10, 10, 400);
	status = new StatusConsole(this, 4, 500, 10, 260);
//	status->addMsg("StatusConsole v0.1");

	state_pg = new PreGameState();
	state_ig =new InGameState();
	state_go =new GameOverState();

	StateManager::instance()->registerState("pregame", state_pg);
	StateManager::instance()->registerState("ingame", state_ig);
	StateManager::instance()->registerState("gameover", state_go);

	shiftDown = false;

	ConstraintSolver::instance()->setIterations(6);

	Rasterizer::instance()->setScreen(m_Screen);
}
Ejemplo n.º 28
0
void 
tau::Robot
::solveInverseDynamics( int debugLevel )
{
    solveKinematics( debugLevel );
    
    for( int i = bodies.size() - 1; i > 0; --i )
    {
        // compute:
        // \tau_i = S_i^T f_i

        if( debugLevel > 0 ) errorLog() << "------\n-----InvDyn for Body " << i << " -------\n";
        Body* b = bodies[i];
        Joint* j = b->joint();
        MatrixNxN S_i = j->motionSubspace();

        if( debugLevel > 0 ) errorLog() << "\tmotion subspace: \n" << S_i << "\n";

        SFV f_i = b->spatialForce();

        if( debugLevel > 0 ) errorLog() << "\tbody's spatialForce: \n" << f_i << "\n";

        VectorN tau_i = S_i.transpose() * f_i.asVector6();  // vector size is number of DOFs

        if( debugLevel > 0 ) errorLog() << "\ttau_i (size should be # of dofs): \n" << tau_i << "\n";

        j->setComputedTorque( tau_i );

        if( ! b->parent()->isBase() )
        {
            // update the force on the parent
            //
            // f_{\lambda(i)} = f_{\lambda(i)} + {}^{\lambda(i)}X_i^* f_i
            //
            XForm body_from_parent = j->xform() * j->treeXForm();
            XForm parent_from_body = body_from_parent.inverse();
            SFV f_i_inParentFrame = parent_from_body.apply( f_i ); // could use invapply for eff.

//            SFV f_p = b->parent()->spatialForce();

            if( debugLevel > 0 ) errorLog() << "\tf_i_inParentFrame:\n" << f_i_inParentFrame << "\n";

//            SFV f_p_new = SFV( f_p.asVector6() + body_from_parent.invApply( f_i ).asVector6() );
            SFV f_p_new = b->parent()->spatialForce() + body_from_parent.invApply( f_i );

            b->parent()->setSpatialForce( f_p_new );
        }
    }
}
Ejemplo n.º 29
0
KeplerOrbit<Frame>::KeplerOrbit(
    MassiveBody const& primary,
    Body const& secondary,
    KeplerianElements<Frame> const& elements_at_epoch,
    Instant const& epoch)
    : gravitational_parameter_(
          primary.gravitational_parameter() +
          (secondary.is_massless()
               ? GravitationalParameter{}
               : dynamic_cast<MassiveBody const&>(secondary).
                     gravitational_parameter())),
      elements_at_epoch_(elements_at_epoch),
      epoch_(epoch) {
  CHECK(static_cast<bool>(elements_at_epoch_.semimajor_axis) ^
        static_cast<bool>(elements_at_epoch_.mean_motion));
  GravitationalParameter const μ = gravitational_parameter_;
  if (elements_at_epoch_.semimajor_axis) {
    Length const& a = *elements_at_epoch_.semimajor_axis;
    elements_at_epoch_.mean_motion = Sqrt(μ / Pow<3>(a)) * Radian;
  } else {
Ejemplo n.º 30
0
void
display (void)
{
  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glLoadIdentity ();
  Vtx r = Rocket.rot.axis ();
  Vtx e = Earth.rot.axis ();
  Vtx c = camera.rotate (Vtx (0, 0, -1)) * Rocket.radius * zoom;
  Vtx u = camera.rotate (Vtx (0, 1, 0));
  
  //draw 8-ball
  //TODO: expose an API, and leave this to the interface and extension code
  glPushMatrix ();
  glBindTexture (GL_TEXTURE_2D, ballTexture);
  glMaterialfv (GL_FRONT_AND_BACK, GL_DIFFUSE, ball_dif);
  glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT, ball_amb);
  glTranslatef (0, -.6, -.75);
  glRotatef (50, 1, 0, 0);
  glRotatef (-Rocket.rot.angle (), r.x, r.z, r.y);
  gluSphere (Rocket.quadric, .125, 36, 18);
  glPopMatrix ();

  //apply camera transformation
  gluLookAt (c.x, c.y, c.z,
	     0, 0, 0,
	     u.x, u.y, u.z);
  glLightfv (GL_LIGHT0, GL_POSITION, sun_pos);


  //draw earth
  glPushMatrix ();
  glTranslatef (-Rocket.pos.x, -Rocket.pos.y, -Rocket.pos.z);
  Earth.display ();
  glPopMatrix ();

  //draw rocket
  Rocket.display ();

  glutSwapBuffers ();
}