Vector2f operator-() const { return Vector2f(-x, -y); }
//InitMenuSettings bool Menu::InitMenuSettings () { Err fErr (m_Err, L"InitMenuSettings"); wstring sMenuSettings, sFullscreen, sVerticalSync, sFramelimit, sOk, sLanguage, sResolution, sColorDepth, sMouseSensitivity, sAntialiasing, sAccept, sHelp; bool bFullscreen, bVerticalSync, bHelp; int nFramelimit, nMouseSensitivity, nAntialiasing; if (!m_pLanguage->Get (L"SettingsTitle", &sMenuSettings) || !m_pLanguage->Get (L"SettingsResolution", &sResolution) || !m_pLanguage->Get (L"SettingsColorDepth", &sColorDepth) || !m_pLanguage->Get (L"SettingsFullscreen", &sFullscreen) || !m_pLanguage->Get (L"SettingsAntialiasing", &sAntialiasing) || !m_pLanguage->Get (L"SettingsVerticalSync", &sVerticalSync) || !m_pLanguage->Get (L"SettingsFrameLimit", &sFramelimit) || !m_pLanguage->Get (L"SettingsLanguage", &sLanguage) || !m_pLanguage->Get (L"SettingsHelp", &sHelp) || !m_pLanguage->Get (L"SettingsMouseSensitivity", &sMouseSensitivity) || !m_pLanguage->Get (L"SettingsOk", &sOk) || !m_pLanguage->Get (L"SettingsAccept", &sAccept) || !m_pConfig->GetBool (sCONF_FULLSCREEN, &bFullscreen) || !m_pConfig->GetBool (s_sVerticalSync, &bVerticalSync) || !m_pConfig->GetBool (sCONF_HELP, &bHelp) || !m_pConfig->GetNum (s_sFramelimit, &nFramelimit) || !m_pConfig->GetNum (s_sMouseSensitivity, &nMouseSensitivity) || !m_pConfig->GetNum (s_sAntialiasing, &nAntialiasing)) { return false; } std::vector<wstring> lsLanguages; if (!ListFiles (m_sLanguageDir, &lsLanguages)) { return fErr.Set (L"Could not list the language files"); } unsigned int nLanguageId = 0; for (; nLanguageId != lsLanguages.size (); nLanguageId++) { if (lsLanguages.at (nLanguageId) == m_pLanguage->GetFileName ()) { break; } } std::vector<wstring> lsResolutions, lsDepths; unsigned int nOldColorDepth = 0, nCurResId = 0, nCurDepthId = 0, nCurDepth = 0; bool bNextDepth = false; wstring sCurResolution; if (!m_pConfig->Get (s_sResolution, &sCurResolution) || !m_pConfig->GetNum (s_sColorDepth, &nCurDepth)) { return false; } for (unsigned int i = 0; i != sf::VideoMode::GetModesCount (); i++) { sf::VideoMode Mode = sf::VideoMode::GetMode (i); if (Mode.BitsPerPixel != nOldColorDepth) { if (nOldColorDepth != 0) { bNextDepth = true; } nOldColorDepth = Mode.BitsPerPixel; if (nCurDepth == nOldColorDepth) { nCurDepthId = lsDepths.size (); } lsDepths.push_back (NumToStr (nOldColorDepth)); } //Because all resolutions are mutliply saved for every color depth if (bNextDepth) { continue; } wstring sEntry (NumToStr (Mode.Width) + s_sResDelim + NumToStr (Mode.Height)); if (sEntry == sCurResolution) { nCurResId = lsResolutions.size (); } lsResolutions.push_back (sEntry); } if (!m_ScreenSettings.Init (&m_Err, m_pProfiles, m_pWindow, sMenuSettings) || !m_ScreenSettings.AddList (sResolution, Vector2f (50, 150), lsResolutions, nCurResId, eSettingsListResolution) || !m_ScreenSettings.AddList (sColorDepth, Vector2f (500, 150), lsDepths, nCurDepthId, eSettingsListColorDepth) || !m_ScreenSettings.AddCheckbox (sFullscreen, Vector2f (50, 250), eSettingsCheckFullscreen, bFullscreen) || !m_ScreenSettings.AddEditbox (sAntialiasing, Vector2f (500, 250), 50, eSettingsEditAntialiasing, NumToStr (nAntialiasing)) || !m_ScreenSettings.AddCheckbox (sVerticalSync, Vector2f (50, 350), eSettingsCheckVerticalSync, bVerticalSync) || !m_ScreenSettings.AddEditbox (sFramelimit, Vector2f (600, 350), 100, eSettingsEditFramelimit, NumToStr (nFramelimit)) || !m_ScreenSettings.AddList (sLanguage, Vector2f (50, 450), lsLanguages, nLanguageId, eSettingsListLanguage) || !m_ScreenSettings.AddCheckbox (sHelp, Vector2f (400, 450), eSettingsCheckHelp, bHelp) || !m_ScreenSettings.AddEditbox (sMouseSensitivity, Vector2f (50, 550), 150, eSettingsEditMouseSensitivity, NumToStr (nMouseSensitivity)) || !m_ScreenSettings.AddButton (sOk, Vector2f (300, 650), eSettingsButtonOk) || !m_ScreenSettings.AddButton (m_sAbort, Vector2f (525, 650), eSettingsButtonAbort) || !m_ScreenSettings.AddButton (sAccept, Vector2f (750, 650), eSettingsButtonAccept)) { return false; } return true; }//InitMenuSettings
void KrecikApp::createCar() { Vector2f ltPos(320.0f, B2toSF(l.getB2Vertexes()[3].y) - 250.0f); // pozycja left-top autka // koła float whRad = 10.0f; float whFr = cc.wheelFriction; b2CircleShape wh; wh.m_radius = SFtoB2(whRad); wh.m_p = SFtoB2(ltPos + Vector2f(20.0f, 60.0f)); Body* lwheel = this->addDynamicBody("left wheel", wh, &whTex); lwheel->b->GetFixtureList()->SetFriction(whFr); wh.m_p = SFtoB2(ltPos + Vector2f(90.0f, 60.0f)); Body* rwheel = this->addDynamicBody("right wheel", wh, &whTex); rwheel->b->GetFixtureList()->SetFriction(whFr); // karoseria b2PolygonShape sh1; // budka kierownicza b2PolygonShape sh2; // reszta autka const unsigned vxNum = 4; b2Vec2 vx[vxNum]; vx[0] = SFtoB2(ltPos + Vector2f(80.0f, 20.0f)); vx[1] = SFtoB2(ltPos + Vector2f(60.0f, 0.0f)); vx[2] = SFtoB2(ltPos + Vector2f(30.0f, 0.0f)); vx[3] = SFtoB2(ltPos + Vector2f(30.0f, 20.0f)); sh1.Set(vx, vxNum); vx[0] = SFtoB2(ltPos + Vector2f(0.0f, 20.0f)); vx[1] = SFtoB2(ltPos + Vector2f(0.0f, 40.0f)); vx[2] = SFtoB2(ltPos + Vector2f(100.0f, 40.0f)); vx[3] = SFtoB2(ltPos + Vector2f(100.0f, 20.0f)); sh2.Set(vx, vxNum); Body* car = this->addDynamicBody("car", sh1, &bodyTex, false); car->addFixture(sh2, 1.0f, &chassTex, Vector2f(50.0f, 30.0f)); // amortyzatory b2WheelJointDef spr; spr.collideConnected = false; spr.enableMotor = true; spr.motorSpeed = 0.0f; spr.dampingRatio = cc.springDamp; spr.frequencyHz = cc.springHz; spr.maxMotorTorque = 1000.0f; spr.Initialize(car->b, lwheel->b, SFtoB2(ltPos + Vector2f(20.0f, 60.0f)), b2Vec2(0.0f, 0.4f)); this->world.CreateJoint(&spr); spr.Initialize(car->b, rwheel->b, SFtoB2(ltPos + Vector2f(90.0f, 60.0f)), b2Vec2(0.0f, 0.4f)); this->world.CreateJoint(&spr); }
ParticleEmitterSnow::ParticleEmitterSnow() { m_mode= eParticleModeGravity; // Gravity Mode: gravity m_modeA.gravity = Vector2f(0,0); // Gravity Mode: speed of particles m_modeA.speed = 10; m_modeA.speedVar = 1; // Gravity Mode: radial m_modeA.radialAccel = 0; m_modeA.radialAccelVar = 1; // Gravity mode: tagential m_modeA.tangentialAccel = 0; m_modeA.tangentialAccelVar = 1; // emitter position //CCSize winSize = CCDirector::sharedDirector()->getWinSize(); //this->setPosition(ccp(winSize.width/2, winSize.height + 10)); //m_tPosVar = ccp( winSize.width/2, 0 ); // angle m_angle = 90; m_angleVar = 5; // life of particles m_life = 60; m_lifeVar = 10; m_startFrame = 0; m_endFrame = 50; m_sourcePos.x = 480; m_sourcePos.y = 320; m_sourcePosVar.x = 480; // size, in pixels m_startSize = 0.8f; m_startSizeVar = 0.2f; //m_fEndSize = kCCParticleStartSizeEqualToEndSize; // emits per second m_emissionRate = 30; // color of particles m_startColor.r = 1.0f; m_startColor.g = 1.0f; m_startColor.b = 1.0f; m_startColor.a = 1.0f; m_startColorVar.r = 0.0f; m_startColorVar.g = 0.0f; m_startColorVar.b = 0.0f; m_startColorVar.a = 0.0f; m_endColor.r = 0.5f; m_endColor.g = 0.5f; m_endColor.b = 0.5f; m_endColor.a = 1.0f; m_endColorVar.r = 0.0f; m_endColorVar.g = 0.0f; m_endColorVar.b = 0.0f; m_endColorVar.a = 0.0f; setTexture("X:\\particle\\snow.png"); }
//InitProfilesScreen bool Menu::InitProfilesScreen (Screen *pScreen) { Err fErr (m_Err, L"InitProfilesScreen"); if (pScreen == NULL) { return fErr.Set (sERR_ARGUMENTS); } wstring sMenuProfiles, sList, sEdit, sDelete, sCreate, sCreateName, sStandard; if (!m_pLanguage->Get (L"ProfilesTitle", &sMenuProfiles) || !m_pLanguage->Get (L"ProfilesList", &sList) || !m_pLanguage->Get (L"ProfilesEdit", &sEdit) || !m_pLanguage->Get (L"ProfilesDelete", &sDelete) || !m_pLanguage->Get (L"ProfilesCreate", &sCreate) || !m_pLanguage->Get (L"ProfilesCreateName", &sCreateName) || !m_pLanguage->Get (L"ProfileStandard", &sStandard)) { return false; } if (!pScreen->Init (&m_Err, m_pProfiles, m_pWindow, sMenuProfiles)) { return false; } std::vector<Profile> *plProfiles; if (!m_pProfiles->GetList (&plProfiles)) { return false; } if (plProfiles->size () == 0 && !AddProfile (sStandard)) { return false; } std::vector<wstring> lsProfileList; for (unsigned int i = 0; i != plProfiles->size (); i++) { wstring sName; if (!m_pProfiles->GetName (i, &sName)) { return false; } lsProfileList.push_back (sName); } if (!pScreen->AddButton (sEdit, Vector2f (100, 190), eProfilesButtonEdit) || !pScreen->AddList (sList, Vector2f (350, 220), lsProfileList, 0, eProfilesListChoice) || !pScreen->AddButton (sDelete, Vector2f (100, 250), eProfilesButtonDelete) || !pScreen->AddButton (sCreate, Vector2f (100, 400), eProfilesButtonCreate) || !pScreen->AddEditbox (sCreateName, Vector2f (350, 400), 300, eProfilesEditCreateName) || !pScreen->AddButton (m_sAbort, Vector2f (700, 600), eProfilesButtonAbort)) { return false; } return true; }//InitProfilesScreen
void Player::update(Uint32 ticks) { int rangeY =worldHeight-frameHeight; int rangeX =worldWidth-frameWidth; advanceFrame(ticks); ShootingSprite::update(ticks); if (!flagStop){ if (up && count>0) { velocityY(velocityY()-95); --count; physics = true; } if (physics) { float deltaT = 0.05; Vector2f accel = Vector2f(0,60); Vector2f vnew = getVelocity() + accel* deltaT; setPosition(getPosition() + vnew * deltaT); setVelocity(vnew); } if (forward) { X(X()+8.0); flag=true; } if (back) { X(X()-8.0); flag=false; } } else{ score = 0; } // Collision Check with edge if ( Y() < 0) { velocityY( 0); Y(0); } if ( Y() > rangeY) { velocityY(0); velocityX(0); Y(rangeY); count=2; //std::cout<<"hit the ground"<<std::endl; //std::cout<<velocityY()<<std::endl; physics = false; } //else std::cout << "height = " << Y() << std::endl; if ( X() < 0) { velocityX( 0 ); X(0); } if ( X() > rangeX) { velocityX( 0 ); X( rangeX); } forward = back = up = down = false; }
void Player::Update(float elapsed) { //Add friction into the acceleration. //If the player isn't accelerating, slow down his velocity completely. if (Acceleration.x == 0.0f && Acceleration.y == 0.0f) { if (Velocity.x != 0.0f || Velocity.y != 0.0f) { Acceleration = -Velocity * LevelConstants::Instance.PlayerFriction; } } else { //Split the acceleration and velocity into "forward" and "side" components. Vector2f forward = LookDir.XY().Normalized(), side = Vector2f(forward.y, forward.x), forwardA = forward * forward.Dot(Acceleration), forwardV = forward * forward.Dot(Velocity), sideA = side * side.Dot(Acceleration), sideV = side * side.Dot(Velocity); //Add friction to any velocity components that go against the acceleration. if (forwardA.Dot(forwardV) < 0.0f && (abs(forwardV.x) > 0.00001f || abs(forwardV.y) > 0.00001f)) { Acceleration -= forwardV.Normalized() * LevelConstants::Instance.PlayerFriction; } if (sideA.Dot(sideV) < 0.0f && (abs(sideV.x) > 0.00001f || abs(sideV.y) > 0.00001f)) { Acceleration -= sideV.Normalized() * LevelConstants::Instance.PlayerFriction; } } //Update velocity and acceleration. Velocity += Acceleration * elapsed; Acceleration = Vector2f(); //Constrain the velocity. float speedSqr = Velocity.LengthSquared(); if (speedSqr > LevelConstants::Instance.PlayerMaxSpeed * LevelConstants::Instance.PlayerMaxSpeed) { Velocity = (Velocity / sqrtf(speedSqr)) * LevelConstants::Instance.PlayerMaxSpeed; } //Update position. TryMove(elapsed); //Handle weapons. if (Fire) { if (!firedLastFrame) { firedLastFrame = true; GetCurrentWeapon()->StartFire(); } Fire = false; } else if (firedLastFrame) { GetCurrentWeapon()->StopFire(); firedLastFrame = false; } GetCurrentWeapon()->Update(elapsed); }
// Called on a decorator to generate any required per-element data for a newly decorated element. DecoratorDataHandle DecoratorTiledHorizontal::GenerateElementData(Element* element) { // Initialise the tiles for this element. for (int i = 0; i < 3; i++) tiles[i].CalculateDimensions(element, *(GetTexture(tiles[i].texture_index))); DecoratorTiledHorizontalData* data = new DecoratorTiledHorizontalData(element); Vector2f padded_size = element->GetBox().GetSize(Box::PADDING); Vector2f left_dimensions = tiles[LEFT].GetDimensions(element); Vector2f right_dimensions = tiles[RIGHT].GetDimensions(element); Vector2f centre_dimensions = tiles[CENTRE].GetDimensions(element); // Scale the tile sizes by the height scale. ScaleTileDimensions(left_dimensions, padded_size.y, 1); ScaleTileDimensions(right_dimensions, padded_size.y, 1); ScaleTileDimensions(centre_dimensions, padded_size.y, 1); // Shrink the x-sizes on the left and right tiles if necessary. if (padded_size.x < left_dimensions.x + right_dimensions.x) { float minimum_width = left_dimensions.x + right_dimensions.x; left_dimensions.x = padded_size.x * (left_dimensions.x / minimum_width); right_dimensions.x = padded_size.x * (right_dimensions.x / minimum_width); } int num_indices; // Generate the geometry for the left tile. num_indices = tiles[LEFT].GenerateGeometry(data->geometry[tiles[LEFT].texture_index]->GetVertices(), element, Vector2f(0, 0), left_dimensions, left_dimensions, color_multiplier); data->geometry[tiles[LEFT].texture_index]->IncreaseNumIndices(num_indices); // Generate the geometry for the centre tiles. num_indices = tiles[CENTRE].GenerateGeometry(data->geometry[tiles[CENTRE].texture_index]->GetVertices(), element, Vector2f(left_dimensions.x, 0), Vector2f(padded_size.x - (left_dimensions.x + right_dimensions.x), centre_dimensions.y), centre_dimensions, color_multiplier); data->geometry[tiles[CENTRE].texture_index]->IncreaseNumIndices(num_indices); // Generate the geometry for the right tile. num_indices = tiles[RIGHT].GenerateGeometry(data->geometry[tiles[RIGHT].texture_index]->GetVertices(), element, Vector2f(padded_size.x - right_dimensions.x, 0), right_dimensions, right_dimensions, color_multiplier); data->geometry[tiles[RIGHT].texture_index]->IncreaseNumIndices(num_indices); // Set the textures on the geometry. const Texture* texture = NULL; int texture_index = 0; while ((texture = GetTexture(texture_index)) != NULL) data->geometry[texture_index++]->SetTexture(texture); return reinterpret_cast<DecoratorDataHandle>(data); }
void Model::MakeRaft(GCodeState &state, float &z) { vector<InFillHit> HitsBuffer; uint LayerNr = 0; float size = settings.Raft.Size; Vector2f raftMin = Vector2f(Min.x - size + printOffset.x, Min.y - size + printOffset.y); Vector2f raftMax = Vector2f(Max.x + size + printOffset.x, Max.y + size + printOffset.y); Vector2f Center = (Vector2f(Max.x + size, Max.y + size)-Vector2f(Min.x + size, Min.y + size))/2+Vector2f(printOffset.x, printOffset.y); float Length = sqrtf(2)*( ((raftMax.x)>(raftMax.y)? (raftMax.x):(raftMax.y)) - ((raftMin.x)<(raftMin.y)? (raftMin.x):(raftMin.y)) )/2.0f; // bbox of object float E = 0.0f; float rot; while(LayerNr < settings.Raft.Phase[0].LayerCount + settings.Raft.Phase[1].LayerCount) { Settings::RaftSettings::PhasePropertiesType *props; props = LayerNr < settings.Raft.Phase[0].LayerCount ? &settings.Raft.Phase[0] : &settings.Raft.Phase[1]; rot = (props->Rotation+(float)LayerNr * props->RotationPrLayer)/180.0f*M_PI; Vector2f InfillDirX(cosf(rot), sinf(rot)); Vector2f InfillDirY(-InfillDirX.y, InfillDirX.x); Vector3f LastPosition; bool reverseLines = false; Vector2f P1, P2; for(float x = -Length ; x < Length ; x+=props->Distance) { P1 = (InfillDirX * Length)+(InfillDirY*x) + Center; P2 = (InfillDirX * -Length)+(InfillDirY*x) + Center; if(reverseLines) { Vector2f tmp = P1; P1 = P2; P2 = tmp; } // glBegin(GL_LINES); // glVertex2fv(&P1.x); // glVertex2fv(&P2.x); // Crop lines to bbox*size Vector3f point; InFillHit hit; HitsBuffer.clear(); Vector2f P3(raftMin.x, raftMin.y); Vector2f P4(raftMin.x, raftMax.y); // glVertex2fv(&P3.x); // glVertex2fv(&P4.x); if(IntersectXY(P1,P2,P3,P4,hit)) //Intersect edges of bbox HitsBuffer.push_back(hit); P3 = Vector2f(raftMax.x,raftMax.y); // glVertex2fv(&P3.x); // glVertex2fv(&P4.x); if(IntersectXY(P1,P2,P3,P4,hit)) HitsBuffer.push_back(hit); P4 = Vector2f(raftMax.x,raftMin.y); // glVertex2fv(&P3.x); // glVertex2fv(&P4.x); if(IntersectXY(P1,P2,P3,P4,hit)) HitsBuffer.push_back(hit); P3 = Vector2f(raftMin.x,raftMin.y); // glVertex2fv(&P3.x); // glVertex2fv(&P4.x); if(IntersectXY(P1,P2,P3,P4,hit)) HitsBuffer.push_back(hit); // glEnd(); if(HitsBuffer.size() == 0) // it can only be 2 or zero continue; if(HitsBuffer.size() != 2) continue; std::sort(HitsBuffer.begin(), HitsBuffer.end(), InFillHitCompareFunc); P1 = HitsBuffer[0].p; P2 = HitsBuffer[1].p; state.MakeAcceleratedGCodeLine (Vector3f(P1.x,P1.y,z), Vector3f(P2.x,P2.y,z), props->MaterialDistanceRatio, E, z, settings.Slicing, settings.Hardware); reverseLines = !reverseLines; } // Set startspeed for Z-move Command g; g.Code = SETSPEED; g.where = Vector3f(P2.x, P2.y, z); g.f=settings.Hardware.MinPrintSpeedZ; g.comment = "Move Z"; g.e = E; gcode.commands.push_back(g); z += props->Thickness * settings.Hardware.LayerThickness; // Move Z g.Code = ZMOVE; g.where = Vector3f(P2.x, P2.y, z); g.f = settings.Hardware.MinPrintSpeedZ; g.comment = "Move Z"; g.e = E; gcode.commands.push_back(g); LayerNr++; } // restore the E state Command gotoE; gotoE.Code = GOTO; gotoE.e = 0; gotoE.comment = _("Reset E for the remaining print"); gcode.commands.push_back(gotoE); }
Vector2f Vector2f::operator-(const Vector2f& other) const { return Vector2f(v[0] - other.v[0], v[1] - other.v[1]); }
Vector2f Vector2f::operator-() const { return Vector2f(-v[0], -v[1]); }
Vector2f Vector2f::operator/(float scale) const { if (scale < 0.001 && scale > -0.001) throw std::string("scale too small in /"); return Vector2f(v[0] / scale, v[1] / scale); }
Vector2f Vector2f::operator*(float scale) const { return Vector2f(v[0] * scale, v[1] * scale); }
Vector2f Transform::TransformPoint(float x, float y) const { return Vector2f(myMatrix[0] * x + myMatrix[4] * y + myMatrix[12], myMatrix[1] * x + myMatrix[5] * y + myMatrix[13]); }
/* return the distance in meters in North/East plane as a N/E vector from loc1 to loc2 */ Vector2f location_diff(const struct Location &loc1, const struct Location &loc2) { return Vector2f((loc2.lat - loc1.lat) * LOCATION_SCALING_FACTOR, (loc2.lng - loc1.lng) * LOCATION_SCALING_FACTOR * longitude_scale(loc1)); }
// update L1 control for waypoint navigation void AP_L1_Control::update_waypoint(const struct Location &prev_WP, const struct Location &next_WP, float dist_min) { struct Location _current_loc; float Nu; float xtrackVel; float ltrackVel; uint32_t now = AP_HAL::micros(); float dt = (now - _last_update_waypoint_us) * 1.0e-6f; if (dt > 0.1) { dt = 0.1; _L1_xtrack_i = 0.0f; } _last_update_waypoint_us = now; // Calculate L1 gain required for specified damping float K_L1 = 4.0f * _L1_damping * _L1_damping; // Get current position and velocity if (_ahrs.get_position(_current_loc) == false) { // if no GPS loc available, maintain last nav/target_bearing _data_is_stale = true; return; } Vector2f _groundspeed_vector = _ahrs.groundspeed_vector(); // update _target_bearing_cd _target_bearing_cd = get_bearing_cd(_current_loc, next_WP); //Calculate groundspeed float groundSpeed = _groundspeed_vector.length(); if (groundSpeed < 0.1f) { // use a small ground speed vector in the right direction, // allowing us to use the compass heading at zero GPS velocity groundSpeed = 0.1f; _groundspeed_vector = Vector2f(cosf(get_yaw()), sinf(get_yaw())) * groundSpeed; } // Calculate time varying control parameters // Calculate the L1 length required for specified period // 0.3183099 = 1/1/pipi _L1_dist = MAX(0.3183099f * _L1_damping * _L1_period * groundSpeed, dist_min); // Calculate the NE position of WP B relative to WP A Vector2f AB = location_diff(prev_WP, next_WP); float AB_length = AB.length(); // Check for AB zero length and track directly to the destination // if too small if (AB.length() < 1.0e-6f) { AB = location_diff(_current_loc, next_WP); if (AB.length() < 1.0e-6f) { AB = Vector2f(cosf(get_yaw()), sinf(get_yaw())); } } AB.normalize(); // Calculate the NE position of the aircraft relative to WP A Vector2f A_air = location_diff(prev_WP, _current_loc); // calculate distance to target track, for reporting _crosstrack_error = A_air % AB; //Determine if the aircraft is behind a +-135 degree degree arc centred on WP A //and further than L1 distance from WP A. Then use WP A as the L1 reference point //Otherwise do normal L1 guidance float WP_A_dist = A_air.length(); float alongTrackDist = A_air * AB; if (WP_A_dist > _L1_dist && alongTrackDist/MAX(WP_A_dist, 1.0f) < -0.7071f) { //Calc Nu to fly To WP A Vector2f A_air_unit = (A_air).normalized(); // Unit vector from WP A to aircraft xtrackVel = _groundspeed_vector % (-A_air_unit); // Velocity across line ltrackVel = _groundspeed_vector * (-A_air_unit); // Velocity along line Nu = atan2f(xtrackVel,ltrackVel); _nav_bearing = atan2f(-A_air_unit.y , -A_air_unit.x); // bearing (radians) from AC to L1 point } else if (alongTrackDist > AB_length + groundSpeed*3) { // we have passed point B by 3 seconds. Head towards B // Calc Nu to fly To WP B Vector2f B_air = location_diff(next_WP, _current_loc); Vector2f B_air_unit = (B_air).normalized(); // Unit vector from WP B to aircraft xtrackVel = _groundspeed_vector % (-B_air_unit); // Velocity across line ltrackVel = _groundspeed_vector * (-B_air_unit); // Velocity along line Nu = atan2f(xtrackVel,ltrackVel); _nav_bearing = atan2f(-B_air_unit.y , -B_air_unit.x); // bearing (radians) from AC to L1 point } else { //Calc Nu to fly along AB line //Calculate Nu2 angle (angle of velocity vector relative to line connecting waypoints) xtrackVel = _groundspeed_vector % AB; // Velocity cross track ltrackVel = _groundspeed_vector * AB; // Velocity along track float Nu2 = atan2f(xtrackVel,ltrackVel); //Calculate Nu1 angle (Angle to L1 reference point) float sine_Nu1 = _crosstrack_error/MAX(_L1_dist, 0.1f); //Limit sine of Nu1 to provide a controlled track capture angle of 45 deg sine_Nu1 = constrain_float(sine_Nu1, -0.7071f, 0.7071f); float Nu1 = asinf(sine_Nu1); // compute integral error component to converge to a crosstrack of zero when traveling // straight but reset it when disabled or if it changes. That allows for much easier // tuning by having it re-converge each time it changes. if (_L1_xtrack_i_gain <= 0 || !is_equal(_L1_xtrack_i_gain.get(), _L1_xtrack_i_gain_prev)) { _L1_xtrack_i = 0; _L1_xtrack_i_gain_prev = _L1_xtrack_i_gain; } else if (fabsf(Nu1) < radians(5)) { _L1_xtrack_i += Nu1 * _L1_xtrack_i_gain * dt; // an AHRS_TRIM_X=0.1 will drift to about 0.08 so 0.1 is a good worst-case to clip at _L1_xtrack_i = constrain_float(_L1_xtrack_i, -0.1f, 0.1f); } // to converge to zero we must push Nu1 harder Nu1 += _L1_xtrack_i; Nu = Nu1 + Nu2; _nav_bearing = atan2f(AB.y, AB.x) + Nu1; // bearing (radians) from AC to L1 point } _prevent_indecision(Nu); _last_Nu = Nu; //Limit Nu to +-(pi/2) Nu = constrain_float(Nu, -1.5708f, +1.5708f); _latAccDem = K_L1 * groundSpeed * groundSpeed / _L1_dist * sinf(Nu); // Waypoint capture status is always false during waypoint following _WPcircle = false; _bearing_error = Nu; // bearing error angle (radians), +ve to left of track _data_is_stale = false; // status are correctly updated with current waypoint data }
void RendererHUDClassic::Compute() { { FastVertex thrustBuffer[6 * 32]; memset( thrustBuffer, 0, sizeof( thrustBuffer ) ); for ( uint32_t i = 0; i < 32; i++ ) { float height = std::exp( i * 0.05f ); int ofsy = height * 10.0f; float x = 50 + i * ( 5 + 1 ); float y = 720 - 75 - ofsy; thrustBuffer[i*6 + 0].x = x; thrustBuffer[i*6 + 0].y = y; thrustBuffer[i*6 + 1].x = x+5; thrustBuffer[i*6 + 1].y = y+ofsy; thrustBuffer[i*6 + 2].x = x+5; thrustBuffer[i*6 + 2].y = y; thrustBuffer[i*6 + 3].x = x; thrustBuffer[i*6 + 3].y = y; thrustBuffer[i*6 + 4].x = x; thrustBuffer[i*6 + 4].y = y+ofsy; thrustBuffer[i*6 + 5].x = x+5; thrustBuffer[i*6 + 5].y = y+ofsy; for ( int j = 0; j < 6; j++ ) { Vector2f vec = VR_Distort( Vector2f( thrustBuffer[i*6 + j].x, thrustBuffer[i*6 + j].y ) ); thrustBuffer[i*6 + j].x = vec.x; thrustBuffer[i*6 + j].y = vec.y; } } glGenBuffers( 1, &mThrustVBO ); glBindBuffer( GL_ARRAY_BUFFER, mThrustVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(FastVertex) * 6 * 32, thrustBuffer, GL_STATIC_DRAW ); } { FastVertexColor linkBuffer[6 * 16]; memset( linkBuffer, 0, sizeof( linkBuffer ) ); for ( uint32_t i = 0; i < 16; i++ ) { float height = std::exp( i * 0.1f ); int ofsy = height * 12.0f; float x = 1280.0f * 0.03f + i * ( 13 + 1 ); float y = 145.0f; linkBuffer[i*6 + 0].x = x; linkBuffer[i*6 + 0].y = y-ofsy; linkBuffer[i*6 + 1].x = x+13; linkBuffer[i*6 + 1].y = y; linkBuffer[i*6 + 2].x = x+13; linkBuffer[i*6 + 2].y = y-ofsy; linkBuffer[i*6 + 3].x = x; linkBuffer[i*6 + 3].y = y-ofsy; linkBuffer[i*6 + 4].x = x; linkBuffer[i*6 + 4].y = y; linkBuffer[i*6 + 5].x = x+13; linkBuffer[i*6 + 5].y = y; Vector4f fcolor = Vector4f( 0.5f + 0.5f * 0.0625f * ( 15 - i ), 0.5f + 0.5f * 0.0625f * i, 0.5f, 1.0f ); uint32_t color = 0xFF7F0000 | ( (uint32_t)( fcolor.y * 255.0f ) << 8 ) | ( (uint32_t)( fcolor.x * 255.0f ) ); linkBuffer[i*6 + 0].color = linkBuffer[i*6 + 1].color = linkBuffer[i*6 + 2].color = linkBuffer[i*6 + 3].color = linkBuffer[i*6 + 4].color = linkBuffer[i*6 + 5].color = color; for ( int j = 0; j < 6; j++ ) { Vector2f vec = VR_Distort( Vector2f( linkBuffer[i*6 + j].x, linkBuffer[i*6 + j].y ) ); linkBuffer[i*6 + j].x = vec.x; linkBuffer[i*6 + j].y = vec.y; } } glGenBuffers( 1, &mLinkVBO ); glBindBuffer( GL_ARRAY_BUFFER, mLinkVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(FastVertexColor) * 6 * 16, linkBuffer, GL_STATIC_DRAW ); } { glGenBuffers( 1, &mBatteryVBO ); glBindBuffer( GL_ARRAY_BUFFER, mBatteryVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(FastVertex) * 6, nullptr, GL_DYNAMIC_DRAW ); } { glGenBuffers( 1, &mLineVBO ); glBindBuffer( GL_ARRAY_BUFFER, mLineVBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(FastVertexColor) * 2 * 128, nullptr, GL_DYNAMIC_DRAW ); } }
// update L1 control for loitering void AP_L1_Control::update_loiter(const struct Location ¢er_WP, float radius, int8_t loiter_direction) { struct Location _current_loc; // scale loiter radius with square of EAS2TAS to allow us to stay // stable at high altitude radius = loiter_radius(radius); // Calculate guidance gains used by PD loop (used during circle tracking) float omega = (6.2832f / _L1_period); float Kx = omega * omega; float Kv = 2.0f * _L1_damping * omega; // Calculate L1 gain required for specified damping (used during waypoint capture) float K_L1 = 4.0f * _L1_damping * _L1_damping; //Get current position and velocity if (_ahrs.get_position(_current_loc) == false) { // if no GPS loc available, maintain last nav/target_bearing _data_is_stale = true; return; } Vector2f _groundspeed_vector = _ahrs.groundspeed_vector(); //Calculate groundspeed float groundSpeed = MAX(_groundspeed_vector.length() , 1.0f); // update _target_bearing_cd _target_bearing_cd = get_bearing_cd(_current_loc, center_WP); // Calculate time varying control parameters // Calculate the L1 length required for specified period // 0.3183099 = 1/pi _L1_dist = 0.3183099f * _L1_damping * _L1_period * groundSpeed; //Calculate the NE position of the aircraft relative to WP A Vector2f A_air = location_diff(center_WP, _current_loc); // Calculate the unit vector from WP A to aircraft // protect against being on the waypoint and having zero velocity // if too close to the waypoint, use the velocity vector // if the velocity vector is too small, use the heading vector Vector2f A_air_unit; if (A_air.length() > 0.1f) { A_air_unit = A_air.normalized(); } else { if (_groundspeed_vector.length() < 0.1f) { A_air_unit = Vector2f(cosf(_ahrs.yaw), sinf(_ahrs.yaw)); } else { A_air_unit = _groundspeed_vector.normalized(); } } //Calculate Nu to capture center_WP float xtrackVelCap = A_air_unit % _groundspeed_vector; // Velocity across line - perpendicular to radial inbound to WP float ltrackVelCap = - (_groundspeed_vector * A_air_unit); // Velocity along line - radial inbound to WP float Nu = atan2f(xtrackVelCap,ltrackVelCap); _prevent_indecision(Nu); _last_Nu = Nu; Nu = constrain_float(Nu, -M_PI_2, M_PI_2); //Limit Nu to +- Pi/2 //Calculate lat accln demand to capture center_WP (use L1 guidance law) float latAccDemCap = K_L1 * groundSpeed * groundSpeed / _L1_dist * sinf(Nu); //Calculate radial position and velocity errors float xtrackVelCirc = -ltrackVelCap; // Radial outbound velocity - reuse previous radial inbound velocity float xtrackErrCirc = A_air.length() - radius; // Radial distance from the loiter circle // keep crosstrack error for reporting _crosstrack_error = xtrackErrCirc; //Calculate PD control correction to circle waypoint_ahrs.roll float latAccDemCircPD = (xtrackErrCirc * Kx + xtrackVelCirc * Kv); //Calculate tangential velocity float velTangent = xtrackVelCap * float(loiter_direction); //Prevent PD demand from turning the wrong way by limiting the command when flying the wrong way if (ltrackVelCap < 0.0f && velTangent < 0.0f) { latAccDemCircPD = MAX(latAccDemCircPD, 0.0f); } // Calculate centripetal acceleration demand float latAccDemCircCtr = velTangent * velTangent / MAX((0.5f * radius), (radius + xtrackErrCirc)); //Sum PD control and centripetal acceleration to calculate lateral manoeuvre demand float latAccDemCirc = loiter_direction * (latAccDemCircPD + latAccDemCircCtr); // Perform switchover between 'capture' and 'circle' modes at the // point where the commands cross over to achieve a seamless transfer // Only fly 'capture' mode if outside the circle if (xtrackErrCirc > 0.0f && loiter_direction * latAccDemCap < loiter_direction * latAccDemCirc) { _latAccDem = latAccDemCap; _WPcircle = false; _bearing_error = Nu; // angle between demanded and achieved velocity vector, +ve to left of track _nav_bearing = atan2f(-A_air_unit.y , -A_air_unit.x); // bearing (radians) from AC to L1 point } else { _latAccDem = latAccDemCirc; _WPcircle = true; _bearing_error = 0.0f; // bearing error (radians), +ve to left of track _nav_bearing = atan2f(-A_air_unit.y , -A_air_unit.x); // bearing (radians)from AC to L1 point } _data_is_stale = false; // status are correctly updated with current waypoint data }
void Ball::Start() { mTrail.clear(); mVelocity = Vector2f(0, (float)INITIAL_SPEED); }
// Generates a quad from a position, size and colour. void GeometryUtilities::GenerateQuad(Vertex* vertices, int* indices, const Vector2f& origin, const Vector2f& dimensions, const Colourb& colour, int index_offset) { GenerateQuad(vertices, indices, origin, dimensions, colour, Vector2f(0, 0), Vector2f(1, 1), index_offset); }
void ScanGridProvider::update(ScanGrid& scanGrid) { scanGrid.y.clear(); scanGrid.lines.clear(); if(!theCameraMatrix.isValid) return; // Cannot compute grid without camera matrix // Compute the furthest point away that could be part of the field given an unknown own position. Vector2f pointInImage; const float fieldDiagional = Vector2f(theFieldDimensions.boundary.x.getSize(), theFieldDimensions.boundary.y.getSize()).norm(); if(!Transformation::robotWithCameraRotationToImage(Vector2f(fieldDiagional, 0), theCameraMatrix, theCameraInfo, pointInImage)) return; // Cannot project furthest possible point to image -> no grid in image scanGrid.fieldLimit = std::max(static_cast<int>(pointInImage.y()), -1); if(scanGrid.fieldLimit >= theCameraInfo.height) return; // Image is above field limit -> no grid in image // Determine the maximum distance between scanlines at the bottom of the image not to miss the ball. Vector2f leftOnField; Vector2f rightOnField; if(!Transformation::imageToRobotWithCameraRotation(Vector2i(0, theCameraInfo.height - 1), theCameraMatrix, theCameraInfo, leftOnField) || !Transformation::imageToRobotWithCameraRotation(Vector2i(theCameraInfo.width, theCameraInfo.height - 1), theCameraMatrix, theCameraInfo, rightOnField)) return; // Cannot project lower image border to field -> no grid const int xStepUpperBound = theCameraInfo.width / minNumOfLowResScanlines; const int maxXStep = std::min(xStepUpperBound, static_cast<int>(theCameraInfo.width * theFieldDimensions.ballRadius * 2.f * ballWidthRatio / (leftOnField - rightOnField).norm())); Vector2f pointOnField = (leftOnField + rightOnField) / 2.f; // Determine vertical sampling points of the grid scanGrid.y.reserve(theCameraInfo.height); const float fieldStep = theFieldDimensions.fieldLinesWidth * lineWidthRatio; bool singleSteps = false; for(int y = theCameraInfo.height - 1; y > scanGrid.fieldLimit;) { scanGrid.y.emplace_back(y); // Calc next vertical position for all scanlines. if(singleSteps) --y; else { pointOnField.x() += fieldStep; if(!Transformation::robotWithCameraRotationToImage(pointOnField, theCameraMatrix, theCameraInfo, pointInImage)) break; const int y2 = y; y = std::min(y2 - 1, static_cast<int>(pointInImage.y() + 0.5)); singleSteps = y2 - 1 == y; } } // Determine the maximum distance between scanlines at the top of the image not to miss the ball. Do not go below minStepSize. int minXStep = minStepSize; if(Transformation::imageToRobotWithCameraRotation(Vector2i(0, 0), theCameraMatrix, theCameraInfo, leftOnField) && Transformation::imageToRobotWithCameraRotation(Vector2i(theCameraInfo.width, 0), theCameraMatrix, theCameraInfo, rightOnField)) minXStep = std::max(minXStep, static_cast<int>(theCameraInfo.width * theFieldDimensions.ballRadius * 2.f * ballWidthRatio / (leftOnField - rightOnField).norm())); minXStep = std::min(xStepUpperBound, minXStep); // Determine a max step size that fulfills maxXStep2 = minXStep * 2^n, maxXStep2 <= maxXStep. // Also compute lower y coordinates for the different lengths of scanlines. int maxXStep2 = minXStep; std::vector<int> yStarts; while(maxXStep2 * 2 <= maxXStep) { float distance = Geometry::getDistanceBySize(theCameraInfo, theFieldDimensions.ballRadius * ballWidthRatio, static_cast<float>(maxXStep2)); VERIFY(Transformation::robotWithCameraRotationToImage(Vector2f(distance, 0), theCameraMatrix, theCameraInfo, pointInImage)); yStarts.push_back(static_cast<int>(pointInImage.y() + 0.5f)); maxXStep2 *= 2; } yStarts.push_back(theCameraInfo.height); // Determine a pattern with the different lengths of scan lines, in which the longest appears once, // the second longest twice, etc. The pattern starts with the longest. std::vector<int> yStarts2(maxXStep2 / minXStep); for(size_t i = 0, step = 1; i < yStarts.size(); ++i, step *= 2) for(size_t j = 0; j < yStarts2.size(); j += step) yStarts2[j] = yStarts[i]; // Initialize the scan states and the regions. const int xStart = theCameraInfo.width % (theCameraInfo.width / minXStep - 1) / 2; scanGrid.lines.reserve((theCameraInfo.width - xStart) / minXStep); size_t i = yStarts2.size() / 2; // Start with the second longest scanline. for(int x = xStart; x < theCameraInfo.width; x += minXStep) { int yMax = std::min(yStarts2[i++], theCameraInfo.height); i %= yStarts2.size(); theBodyContour.clipBottom(x, yMax); const size_t yMaxIndex = std::upper_bound(scanGrid.y.begin(), scanGrid.y.end(), yMax + 1, std::greater<int>()) - scanGrid.y.begin(); scanGrid.lines.emplace_back(x, yMax, static_cast<unsigned>(yMaxIndex)); } // Set low resolution scanline info scanGrid.lowResStep = maxXStep2 / minXStep; scanGrid.lowResStart = scanGrid.lowResStep / 2; }
float Map_Manager::GetZ(Vector3f pos, bool ignoreFlat) { //FIXME: support for slopes return GetZ(Vector2f(pos.x,pos.y),ignoreFlat); }
std::shared_ptr<ILoadableObject> ObjLoader::load(AssetManager *assetMgr, AssetInfo &asset) { shared_ptr<Node> node(new Node()); std::string currentDir = std::string(asset.getFilePath()); std::string nodeFileName = currentDir.substr(currentDir.find_last_of("\\/")+1); nodeFileName = nodeFileName.substr(0, nodeFileName.find_first_of(".")); // trim extension node->setName(nodeFileName); std::string line; while (std::getline(*asset.getStream(), line)) { vector<string> tokens = split(line, ' '); tokens = removeEmptyStrings(tokens); if (tokens.size() == 0 || strcmp(tokens[0].c_str(), "#") == 0) { } else if (strcmp(tokens[0].c_str(), "v") == 0) { float x = parse<float>(tokens[1]); float y = parse<float>(tokens[2]); float z = parse<float>(tokens[3]); Vector3f vec(x, y, z); positions.push_back(vec); } else if (strcmp(tokens[0].c_str(), "vn") == 0) { float x = parse<float>(tokens[1]); float y = parse<float>(tokens[2]); float z = parse<float>(tokens[3]); Vector3f vec(x, y, z); normals.push_back(vec); } else if (strcmp(tokens[0].c_str(), "vt") == 0) { float x = parse<float>(tokens[1]); float y = parse<float>(tokens[2]); Vector2f vec(x, y); texCoords.push_back(vec); } else if (strcmp(tokens[0].c_str(), "f") == 0) { vector<ObjIndex> *c_idx = currentList(); for (int i = 0; i < tokens.size() - 3; i++) { c_idx->push_back(parseObjIndex(tokens[1])); c_idx->push_back(parseObjIndex(tokens[2 + i])); c_idx->push_back(parseObjIndex(tokens[3 + i])); } } else if (strcmp(tokens[0].c_str(), "mtllib") == 0) { string libLoc = tokens[1]; std::string currentDir = std::string(asset.getFilePath()); currentDir = currentDir.substr(0, currentDir.find_last_of("\\/")); if (!contains(currentDir, "/") && !contains(currentDir, "\\")) // the file path is just current file name, { // so just make the string empty currentDir = ""; } currentDir += "/" + libLoc; std::shared_ptr<MaterialList> mtlList = assetMgr->loadAs<MaterialList>(currentDir.c_str()); this->mtlList = *mtlList.get(); } else if (strcmp(tokens[0].c_str(), "usemtl") == 0) { string matname = tokens[1]; newMesh(matname); } } for (int i = 0; i < objIndices.size(); i++) { vector<ObjIndex> *c_idx = objIndices[i]; vector<Vertex> vertices; for (int j = 0; j < c_idx->size(); j++) { Vertex vert(positions[(*c_idx)[j].vertex_idx], (hasTexCoords ? texCoords[(*c_idx)[j].texcoord_idx] : Vector2f()), (hasNormals ? normals[(*c_idx)[j].normal_idx] : Vector3f())); vertices.push_back(vert); } shared_ptr<Mesh> mesh(new Mesh()); mesh->setVertices(vertices); if (hasNormals) mesh->getAttributes().setAttribute(VertexAttributes::NORMALS); if (hasTexCoords) mesh->getAttributes().setAttribute(VertexAttributes::TEXCOORDS0); shared_ptr<Geometry> geom(new Geometry()); geom->setName(names[i]); geom->setMesh(mesh); geom->setMaterial(materialWithName(namesMtl[i])); node->add(geom); delete c_idx; } return std::static_pointer_cast<ILoadableObject>(node); }
void CWireFrame::AddLine(float x0, float y0, float x1, float y1) { mVertices.push_back(Vector2f(x0, y0)); mVertices.push_back(Vector2f(x1, y1)); }
//RunEditProfile bool Menu::RunEditProfile (wstring sName, bool *pbModified) { Err fErr (m_Err, L"RunEditProfile"); if (sName.empty () || pbModified == NULL) { return fErr.Set (sERR_ARGUMENTS); } *pbModified = false; Config *pProfile; bool bCreated; if (!m_pProfiles->GetByName (sName, &pProfile, &bCreated)) { return false; } wstring sMenuEdit, sLeft, sRight, sSpecial, sSet, sOk, sUndefined; if (!m_pLanguage->Get (L"ProfileEditTitle", &sMenuEdit) || !m_pLanguage->Get (L"ProfileEditLeft", &sLeft) || !m_pLanguage->Get (L"ProfileEditRight", &sRight) || !m_pLanguage->Get (L"ProfileEditSpecial", &sSpecial) || !m_pLanguage->Get (L"ProfileEditSet", &sSet) || !m_pLanguage->Get (L"ProfileEditOk", &sOk) || !m_pLanguage->Get (L"ProfileEditUndefined", &sUndefined)) { return false; } sLeft += L": "; sRight += L": "; sSpecial += L": "; wstring sLeftVal, sRightVal, sSpecialVal; if (!pProfile->Get (sKEY_LEFT, &sLeftVal) || !pProfile->Get (sKEY_RIGHT, &sRightVal) || !pProfile->Get (sKEY_SPECIAL, &sSpecialVal)) { return false; } unsigned int nAction; do { if (sLeftVal.empty ()) { sLeftVal = sUndefined; } if (sRightVal.empty ()) { sRightVal = sUndefined; } if (sSpecialVal.empty ()) { sSpecialVal = sUndefined; } Screen EditScreen; if (!EditScreen.Init (&m_Err, m_pProfiles, m_pWindow, sMenuEdit + sName) || !EditScreen.AddLabel (sLeft + sLeftVal, Vector2f (300, 150)) || !EditScreen.AddButton (sSet, Vector2f (50, 140), eProfileEditButtonLeft) || !EditScreen.AddLabel (sRight + sRightVal, Vector2f (300, 250)) || !EditScreen.AddButton (sSet, Vector2f (50, 240), eProfileEditButtonRight) || !EditScreen.AddLabel (sSpecial + sSpecialVal, Vector2f (300, 350)) || !EditScreen.AddButton (sSet, Vector2f (50, 340), eProfileEditButtonSpecial) || !EditScreen.AddButton (m_sAbort, Vector2f (700, 540), eProfileEditButtonAbort) || !EditScreen.AddButton (sOk, Vector2f (700, 600), eProfileEditButtonOk)) { return false; } if (!EditScreen.Run ()) { return false; } if (EditScreen.IsQuit ()) { m_bClose = true; break; } if (!EditScreen.GetSelectId (&nAction)) { return false; } wstring *psCurKey = NULL; switch (nAction) { case (eProfileEditButtonLeft): psCurKey = &sLeftVal; break; case (eProfileEditButtonRight): psCurKey = &sRightVal; break; case (eProfileEditButtonSpecial): psCurKey = &sSpecialVal; break; case (eProfileEditButtonOk): pProfile->Set (sKEY_LEFT, sLeftVal); pProfile->Set (sKEY_RIGHT, sRightVal); pProfile->Set (sKEY_SPECIAL, sSpecialVal); if (!pProfile->Save ()) { return false; } *pbModified = true; nAction = eProfileEditButtonAbort; break; } if (psCurKey != NULL) { wstring sCode; if (!AwaitInput (&sCode)) { return false; } if (!sCode.empty ()) { *psCurKey = sCode; } } } while (!m_bClose && nAction != eProfileEditButtonAbort); return true; }//RunEditProfile
Vector2f IRenderer::map_2d(const int x, const int y) { float aspect = (float)viewport_width() / (float)viewport_height(); return Vector2f(((float)x / (float)viewport_width() * 2.0f - 1.0f) * aspect / aspect_modifier_2d(), -((float)y / (float)viewport_height() * 2.0f - 1.0f)); }
GuiMetaDataEd::GuiMetaDataEd(Window* window, MetaDataList* md, const std::vector<MetaDataDecl>& mdd, ScraperSearchParams scraperParams, const std::string& /*header*/, std::function<void()> saveCallback, std::function<void()> deleteFunc) : GuiComponent(window), mScraperParams(scraperParams), mBackground(window, ":/frame.png"), mGrid(window, Vector2i(1, 3)), mMetaDataDecl(mdd), mMetaData(md), mSavedCallback(saveCallback), mDeleteFunc(deleteFunc) { addChild(&mBackground); addChild(&mGrid); mHeaderGrid = std::make_shared<ComponentGrid>(mWindow, Vector2i(1, 5)); mTitle = std::make_shared<TextComponent>(mWindow, "EDIT METADATA", Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER); mSubtitle = std::make_shared<TextComponent>(mWindow, Utils::String::toUpper(Utils::FileSystem::getFileName(scraperParams.game->getPath())), Font::get(FONT_SIZE_SMALL), 0x777777FF, ALIGN_CENTER); mHeaderGrid->setEntry(mTitle, Vector2i(0, 1), false, true); mHeaderGrid->setEntry(mSubtitle, Vector2i(0, 3), false, true); mGrid.setEntry(mHeaderGrid, Vector2i(0, 0), false, true); mList = std::make_shared<ComponentList>(mWindow); mGrid.setEntry(mList, Vector2i(0, 1), true, true); // populate list for(auto iter = mdd.cbegin(); iter != mdd.cend(); iter++) { std::shared_ptr<GuiComponent> ed; // don't add statistics if(iter->isStatistic) continue; // create ed and add it (and any related components) to mMenu // ed's value will be set below ComponentListRow row; auto lbl = std::make_shared<TextComponent>(mWindow, Utils::String::toUpper(iter->displayName), Font::get(FONT_SIZE_SMALL), 0x777777FF); row.addElement(lbl, true); // label switch(iter->type) { case MD_BOOL: { ed = std::make_shared<SwitchComponent>(window); row.addElement(ed, false, true); break; } case MD_RATING: { ed = std::make_shared<RatingComponent>(window); const float height = lbl->getSize().y() * 0.71f; ed->setSize(0, height); row.addElement(ed, false, true); auto spacer = std::make_shared<GuiComponent>(mWindow); spacer->setSize(Renderer::getScreenWidth() * 0.0025f, 0); row.addElement(spacer, false); // pass input to the actual RatingComponent instead of the spacer row.input_handler = std::bind(&GuiComponent::input, ed.get(), std::placeholders::_1, std::placeholders::_2); break; } case MD_DATE: { ed = std::make_shared<DateTimeEditComponent>(window); row.addElement(ed, false); auto spacer = std::make_shared<GuiComponent>(mWindow); spacer->setSize(Renderer::getScreenWidth() * 0.0025f, 0); row.addElement(spacer, false); // pass input to the actual DateTimeEditComponent instead of the spacer row.input_handler = std::bind(&GuiComponent::input, ed.get(), std::placeholders::_1, std::placeholders::_2); break; } case MD_TIME: { ed = std::make_shared<DateTimeEditComponent>(window, DateTimeEditComponent::DISP_RELATIVE_TO_NOW); row.addElement(ed, false); break; } case MD_MULTILINE_STRING: default: { // MD_STRING ed = std::make_shared<TextComponent>(window, "", Font::get(FONT_SIZE_SMALL, FONT_PATH_LIGHT), 0x777777FF, ALIGN_RIGHT); row.addElement(ed, true); auto spacer = std::make_shared<GuiComponent>(mWindow); spacer->setSize(Renderer::getScreenWidth() * 0.005f, 0); row.addElement(spacer, false); auto bracket = std::make_shared<ImageComponent>(mWindow); bracket->setImage(":/arrow.svg"); bracket->setResize(Vector2f(0, lbl->getFont()->getLetterHeight())); row.addElement(bracket, false); bool multiLine = iter->type == MD_MULTILINE_STRING; const std::string title = iter->displayPrompt; auto updateVal = [ed](const std::string& newVal) { ed->setValue(newVal); }; // ok callback (apply new value to ed) row.makeAcceptInputHandler([this, title, ed, updateVal, multiLine] { mWindow->pushGui(new GuiTextEditPopup(mWindow, title, ed->getValue(), updateVal, multiLine)); }); break; } } assert(ed); mList->addRow(row); ed->setValue(mMetaData->get(iter->key)); mEditors.push_back(ed); } std::vector< std::shared_ptr<ButtonComponent> > buttons; if(!scraperParams.system->hasPlatformId(PlatformIds::PLATFORM_IGNORE)) buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "SCRAPE", "scrape", std::bind(&GuiMetaDataEd::fetch, this))); buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "SAVE", "save", [&] { save(); delete this; })); buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "CANCEL", "cancel", [&] { delete this; })); if(mDeleteFunc) { auto deleteFileAndSelf = [&] { mDeleteFunc(); delete this; }; auto deleteBtnFunc = [this, deleteFileAndSelf] { mWindow->pushGui(new GuiMsgBox(mWindow, "THIS WILL DELETE A FILE!\nARE YOU SURE?", "YES", deleteFileAndSelf, "NO", nullptr)); }; buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "DELETE", "delete", deleteBtnFunc)); } mButtons = makeButtonGrid(mWindow, buttons); mGrid.setEntry(mButtons, Vector2i(0, 2), true, false); // resize + center float width = (float)Math::min(Renderer::getScreenHeight(), (int)(Renderer::getScreenWidth() * 0.90f)); setSize(width, Renderer::getScreenHeight() * 0.82f); setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - mSize.y()) / 2); }
Vector2f Graphics2D::getScale() { return Vector2f(ScaleX,ScaleY); }
void OculusWorldDemoApp::RenderGrid(ovrEyeType eye) { Recti renderViewport = EyeTexture[eye].Header.RenderViewport; // Draw actual pixel grid on the RT. // 1:1 mapping to screen pixels, origin in top-left. Matrix4f ortho; ortho.SetIdentity(); ortho.M[0][0] = 2.0f / (renderViewport.w); // X scale ortho.M[0][3] = -1.0f; // X offset ortho.M[1][1] = -2.0f / (renderViewport.h); // Y scale (for Y=down) ortho.M[1][3] = 1.0f; // Y offset (Y=down) ortho.M[2][2] = 0; pRender->SetProjection(ortho); pRender->SetDepthMode(false, false); Color cNormal ( 255, 0, 0 ); Color cSpacer ( 255, 255, 0 ); Color cMid ( 0, 128, 255 ); int lineStep = 1; int midX = 0; int midY = 0; int limitX = 0; int limitY = 0; switch ( GridMode ) { case Grid_Rendertarget4: lineStep = 4; midX = renderViewport.w / 2; midY = renderViewport.h / 2; limitX = renderViewport.w / 2; limitY = renderViewport.h / 2; break; case Grid_Rendertarget16: lineStep = 16; midX = renderViewport.w / 2; midY = renderViewport.h / 2; limitX = renderViewport.w / 2; limitY = renderViewport.h / 2; break; case Grid_Lens: { lineStep = 48; Vector2f rendertargetNDC = FovPort(EyeRenderDesc[eye].Fov).TanAngleToRendertargetNDC(Vector2f(0.0f)); midX = (int)( ( rendertargetNDC.x * 0.5f + 0.5f ) * (float)renderViewport.w + 0.5f ); midY = (int)( ( rendertargetNDC.y * 0.5f + 0.5f ) * (float)renderViewport.h + 0.5f ); limitX = Alg::Max ( renderViewport.w - midX, midX ); limitY = Alg::Max ( renderViewport.h - midY, midY ); } break; default: OVR_ASSERT ( false ); break; } int spacerMask = (lineStep<<2)-1; for ( int xp = 0; xp < limitX; xp += lineStep ) { float x[4]; float y[4]; x[0] = (float)( midX + xp ); y[0] = (float)0; x[1] = (float)( midX + xp ); y[1] = (float)renderViewport.h; x[2] = (float)( midX - xp ); y[2] = (float)0; x[3] = (float)( midX - xp ); y[3] = (float)renderViewport.h; if ( xp == 0 ) { pRender->RenderLines ( 1, cMid, x, y ); } else if ( ( xp & spacerMask ) == 0 ) { pRender->RenderLines ( 2, cSpacer, x, y ); } else { pRender->RenderLines ( 2, cNormal, x, y ); } } for ( int yp = 0; yp < limitY; yp += lineStep ) { float x[4]; float y[4]; x[0] = (float)0; y[0] = (float)( midY + yp ); x[1] = (float)renderViewport.w; y[1] = (float)( midY + yp ); x[2] = (float)0; y[2] = (float)( midY - yp ); x[3] = (float)renderViewport.w; y[3] = (float)( midY - yp ); if ( yp == 0 ) { pRender->RenderLines ( 1, cMid, x, y ); } else if ( ( yp & spacerMask ) == 0 ) { pRender->RenderLines ( 2, cSpacer, x, y ); } else { pRender->RenderLines ( 2, cNormal, x, y ); } } }
Vector2f operator/(float s) const { return Vector2f(x / s, y / s); }