repo_id
stringclasses
5 values
file_path
stringlengths
30
72
content
stringlengths
408
657k
__index_level_0__
int64
0
0
endless-sky-master/endless-sky.6
.TH endless\-sky 6 "21 Oct 2023" "ver. 0.10.5-alpha" "Endless Sky" .SH NAME endless\-sky \- a space exploration and combat game. .SH SYNOPSIS \fBendless\-sky\fR [\-h] [\-\-help] [\-v] [\-\-version] [\-s] [\-\-ships] [\-w] [\-\-weapons] [\-t] [\-\-talk] [\-r] [\-\-resources] [\-c] [\-\-config] [\-p] [\-\-parse\-save] [\-\-test] .SH DESCRIPTION \fBEndless Sky\fR is a space exploration and combat game combining action and role playing elements. Explore other star systems. Earn money by trading, carrying passengers, or completing missions. Use your earnings to buy a better ship or to upgrade the weapons and engines on your current one. Blow up pirates. Take sides in a civil war. Or leave human space behind and hope to find some friendly aliens whose culture is more civilized than your own. For keyboard controls, click the "Preferences" button on the title screen. You can pause and return to the title screen at any point in the game by pressing <escape>. Most of the controls should be self\-explanatory. Your ship has no reverse thrusters, so as with a real spacecraft, the only way to slow down is to turn your ship around and accelerate in the opposite direction from your current heading. To assist with some tricky maneuvers, your ship has an autopilot which engages when you press 'L' to land or 'J' to enter hyperspace; the autopilot disengages if you press any of the movement keys. The autopilot will also automatically aim your ship if you are firing a weapon and have a target selected. For a manual and other information, visit https://endless\-sky.github.io When run from the command line, if a resource directory is not specified, the program will check to see if the current directory contains directories named "data" and "images" and files named "keys.txt" and "credits.txt"; if so it will read resources from the current directory. Otherwise it will use /usr/local/share/games/endless\-sky if it exists, or /usr/share/games/endless\-sky/ otherwise. .SH OPTIONS .IP \fB\-h,\ \-\-help prints a short help message. .IP \fB\-v,\ \-\-version prints the software version. .IP \fB\-t,\ \-\-talk reads a data file from STDIN and looks for a "conversation" node at the root level (i.e. not indentated). If it finds one, that conversation is displayed in a pop\-up dialog. This is for testing conversations in a new mission you are developing. .IP \fB\-r,\ \-\-resources\ <directory> sets the directory from which game resources (images, etc.) will be loaded. .IP \fB\-c,\ \-\-config\ <directory> sets the directory where preferences and saved games will be stored. .IP \fB\-p,\ \-\-parse\-save prints any content or whitespace\-formatting errors found while loading data files and the most recent saved game. This option prevents the game from launching. .IP \fB\-\-test\ <name> execute the test case with the given name. By default, the game will be muted while running tests. .IP \fB\-\-tests prints (to STDOUT) a list of available tests, usable for automatic test runs. This option prevents the game from launching. .IP \fB\-\-nomute prevents muting the game when running tests. .IP \fB\-s,\ \-\-ships prints (to STDOUT) a table of ship stats (just the base stats, not considering any stored outfits). This option prevents the game from launching. .RS .IP \fB\-\-sales prints (to STDOUT) a table of ships with every 'shipyard' each appears in. .IP \fB\-\-loaded prints (to STDOUT) a table of ship stats accounting for installed outfits. Does not include variants. .IP \fB\-\-list prints (to STDOUT) a list of all ship names. .IP \fB\-\-variants consider ship variants as well. .RE .IP \fB\-w,\ \-\-weapons prints (to STDOUT) a table of characteristics of all the available weapons. This option prevents the game from launching. .IP \fB\-e,\ \-\-engines prints (to STDOUT) a table of characteristics of all the available engines. This option prevents the game from launching. .IP \fB\-\-power prints (to STDOUT) a table of power outfit stats. .IP \fB\-o,\ \-\-outfits prints (to STDOUT) a table of characteristics of all the available outfits. This option prevents the game from launching. .RS .IP \fB\-\-sales prints (to STDOUT) a list of outfits and every 'outfitter' each appears in. .IP \fB\-a,\ \-\-all prints a table of outfits and all attributes used by any outfits present. .RE .IP \fB\-\-sales prints (to STDOUT) a list of all shipyards and outfitters and the ships and outfits they each contain. .RS .IP \fB\-s,\ \-\-ships prints a list of shipyards and the ships they each contain. .IP \fB\-o,\ \-\-outfits pritns a list of outfitters and the outfits they each contain. .RE .IP \fB\-\-planets prints (to STDOUT) a list of all planets. .RS .IP \fB\-\-descriptions prints (to STDOUT) a table of all planets and their descriptions. .IP \fB\-\-attributes prints (to STDOUT) a table of all planets and their attributes. .RS .IP \fB\-\-reverse prints (to STDOUT) a table of all planet attributes and which planets have them. .RE .RE .IP \fB\-\-systems prints (to STDOUT) a list of all systems. .RS .IP \fB\-\-attributes prints (to STDOUT) a list of all systems and their attributes. .RS .IP \fB\-\-reverse prints (to STDOUT) a list of all system attributes and which systems have them. .RE .RE .IP \fB\-\-matches reads a data file from STDIN and looks for a "location" node at the root level (i.e. not indentated). If it finds one, prints a list of all systems and planets which match the location filter in that node. .SH AUTHOR Michael Zahniser (mzahniser@gmail.com) This is free software; you can redistribute it and/or modify it under the terms of the GPL.
0
endless-sky-master
endless-sky-master/source/AI.cpp
/* AI.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "AI.h" #include "Audio.h" #include "Command.h" #include "DistanceMap.h" #include "Flotsam.h" #include "GameData.h" #include "Gamerules.h" #include "Government.h" #include "Hardpoint.h" #include "JumpTypes.h" #include "Mask.h" #include "Messages.h" #include "Minable.h" #include "pi.h" #include "Planet.h" #include "PlayerInfo.h" #include "Point.h" #include "Port.h" #include "Preferences.h" #include "Random.h" #include "Ship.h" #include "ship/ShipAICache.h" #include "ShipEvent.h" #include "ShipJumpNavigation.h" #include "StellarObject.h" #include "System.h" #include "Weapon.h" #include "Wormhole.h" #include <algorithm> #include <cmath> #include <limits> #include <set> using namespace std; namespace { // If the player issues any of those commands, then any autopilot actions for the player get cancelled. const Command &AutopilotCancelCommands() { static const Command cancelers(Command::LAND | Command::JUMP | Command::FLEET_JUMP | Command::BOARD | Command::AFTERBURNER | Command::BACK | Command::FORWARD | Command::LEFT | Command::RIGHT | Command::AUTOSTEER | Command::STOP); return cancelers; } bool IsStranded(const Ship &ship) { return ship.GetSystem() && !ship.IsEnteringHyperspace() && !ship.GetSystem()->HasFuelFor(ship) && ship.NeedsFuel(); } bool CanBoard(const Ship &ship, const Ship &target) { if(&ship == &target) return false; if(target.IsDestroyed() || !target.IsTargetable() || target.GetSystem() != ship.GetSystem()) return false; if(IsStranded(target) && !ship.GetGovernment()->IsEnemy(target.GetGovernment())) return true; return target.IsDisabled(); } // Check if the given ship can "swarm" the targeted ship, e.g. to provide anti-missile cover. bool CanSwarm(const Ship &ship, const Ship &target) { if(target.GetPersonality().IsSwarming() || target.IsHyperspacing()) return false; if(target.GetGovernment()->IsEnemy(ship.GetGovernment())) return false; if(target.GetSystem() != ship.GetSystem()) return false; return target.IsTargetable(); } double AngleDiff(double a, double b) { a = abs(a - b); return min(a, 360. - a); } // Determine if all able, non-carried escorts are ready to jump with this // ship. Carried escorts are waited for in AI::Step. bool EscortsReadyToJump(const Ship &ship) { bool shipIsYours = ship.IsYours(); const Government *gov = ship.GetGovernment(); for(const weak_ptr<Ship> &ptr : ship.GetEscorts()) { shared_ptr<const Ship> escort = ptr.lock(); // Skip escorts which are not player-owned and not escort mission NPCs. if(!escort || (shipIsYours && !escort->IsYours() && (!escort->GetPersonality().IsEscort() || gov->IsEnemy(escort->GetGovernment())))) continue; if(!escort->IsDisabled() && !escort->CanBeCarried() && escort->GetSystem() == ship.GetSystem() && escort->JumpNavigation().JumpFuel() && !escort->IsReadyToJump(true)) return false; } return true; } // Determine if the ship has any usable weapons. bool IsArmed(const Ship &ship) { for(const Hardpoint &hardpoint : ship.Weapons()) { const Weapon *weapon = hardpoint.GetOutfit(); if(weapon && !hardpoint.IsAntiMissile()) { if(weapon->Ammo() && !ship.OutfitCount(weapon->Ammo())) continue; return true; } } return false; } void Deploy(const Ship &ship, bool includingDamaged) { for(const Ship::Bay &bay : ship.Bays()) if(bay.ship && (includingDamaged || bay.ship->Health() > .75) && (!bay.ship->IsYours() || bay.ship->HasDeployOrder())) bay.ship->SetCommands(Command::DEPLOY); } // Issue deploy orders for the selected ships (or the full fleet if no ships are selected). void IssueDeploy(const PlayerInfo &player) { // Lay out the rules for what constitutes a deployable ship. (Since player ships are not // deleted from memory until the next landing, check both parked and destroyed states.) auto isCandidate = [](const shared_ptr<Ship> &ship) -> bool { return ship->CanBeCarried() && !ship->IsParked() && !ship->IsDestroyed(); }; auto toDeploy = vector<Ship *> {}; auto toRecall = vector<Ship *> {}; { auto maxCount = player.Ships().size() / 2; toDeploy.reserve(maxCount); toRecall.reserve(maxCount); } // First, check if the player selected any carried ships. for(const weak_ptr<Ship> &it : player.SelectedShips()) { shared_ptr<Ship> ship = it.lock(); if(ship && ship->IsYours() && isCandidate(ship)) (ship->HasDeployOrder() ? toRecall : toDeploy).emplace_back(ship.get()); } // If needed, check the player's fleet for deployable ships. if(toDeploy.empty() && toRecall.empty()) for(const shared_ptr<Ship> &ship : player.Ships()) if(isCandidate(ship) && ship.get() != player.Flagship()) (ship->HasDeployOrder() ? toRecall : toDeploy).emplace_back(ship.get()); // If any ships were not yet ordered to deploy, deploy them. if(!toDeploy.empty()) { for(Ship *ship : toDeploy) ship->SetDeployOrder(true); Messages::Add("Deployed " + to_string(toDeploy.size()) + " carried ships.", Messages::Importance::High); } // Otherwise, instruct the carried ships to return to their berth. else if(!toRecall.empty()) { for(Ship *ship : toRecall) ship->SetDeployOrder(false); Messages::Add("Recalled " + to_string(toRecall.size()) + " carried ships", Messages::Importance::High); } } // Check if the ship contains a carried ship that needs to launch. bool HasDeployments(const Ship &ship) { for(const Ship::Bay &bay : ship.Bays()) if(bay.ship && bay.ship->HasDeployOrder()) return true; return false; } // Determine if the ship with the given travel plan should refuel in // its current system, or if it should keep traveling. bool ShouldRefuel(const Ship &ship, const DistanceMap &route, double fuelCapacity = 0.) { if(!fuelCapacity) fuelCapacity = ship.Attributes().Get("fuel capacity"); const System *from = ship.GetSystem(); const bool systemHasFuel = from->HasFuelFor(ship) && fuelCapacity; // If there is no fuel capacity in this ship, no fuel in this // system, if it is fully fueled, or its drive doesn't require // fuel, then it should not refuel before traveling. if(!systemHasFuel || ship.Fuel() == 1. || !ship.JumpNavigation().JumpFuel()) return false; // Calculate the fuel needed to reach the next system with fuel. double fuel = fuelCapacity * ship.Fuel(); const System *to = route.Route(from); while(to && !to->HasFuelFor(ship)) to = route.Route(to); // The returned system from Route is nullptr when the route is // "complete." If 'to' is nullptr here, then there are no fuel // stops between the current system (which has fuel) and the // desired endpoint system - refuel only if needed. return fuel < route.RequiredFuel(from, (to ? to : route.End())); } // Set the ship's TargetStellar or TargetSystem in order to reach the // next desired system. Will target a landable planet to refuel. void SelectRoute(Ship &ship, const System *targetSystem) { const System *from = ship.GetSystem(); if(from == targetSystem || !targetSystem) return; const DistanceMap route(ship, targetSystem); const bool needsRefuel = ShouldRefuel(ship, route); const System *to = route.Route(from); // The destination may be accessible by both jump and wormhole. // Prefer wormhole travel in these cases, to conserve fuel. Must // check accessibility as DistanceMap may only see the jump path. if(to && !needsRefuel) for(const StellarObject &object : from->Objects()) { if(!object.HasSprite() || !object.HasValidPlanet()) continue; const Planet &planet = *object.GetPlanet(); if(planet.IsWormhole() && planet.IsAccessible(&ship) && &planet.GetWormhole()->WormholeDestination(*from) == to) { ship.SetTargetStellar(&object); ship.SetTargetSystem(nullptr); return; } } else if(needsRefuel) { // There is at least one planet that can refuel the ship. ship.SetTargetStellar(AI::FindLandingLocation(ship)); return; } // Either there is no viable wormhole route to this system, or // the target system cannot be reached. ship.SetTargetSystem(to); ship.SetTargetStellar(nullptr); } // The health remaining before becoming disabled, at which fighters and // other ships consider retreating from battle. const double RETREAT_HEALTH = .25; bool ShouldFlee(Ship &ship) { const Personality &personality = ship.GetPersonality(); if(personality.IsFleeing()) return true; if(personality.IsStaying()) return false; const bool lowHealth = ship.Health() < RETREAT_HEALTH + .25 * personality.IsCoward(); if(!personality.IsDaring() && lowHealth) return true; if(ship.GetAICache().NeedsAmmo()) return true; return false; } bool StayOrLinger(Ship &ship) { const Personality &personality = ship.GetPersonality(); if(personality.IsStaying()) return true; const Government *government = ship.GetGovernment(); shared_ptr<const Ship> parent = ship.GetParent(); if(parent && government && parent->GetGovernment()->IsEnemy(government)) return true; if(ship.IsFleeing()) return false; // Everything after here is the lingering logic. if(!personality.IsLingering()) return false; // NPCs that can follow the player do not linger. if(ship.IsSpecial() && !personality.IsUninterested()) return false; const System *system = ship.GetSystem(); const System *destination = ship.GetTargetSystem(); // Ships not yet at their destination must go there before they can linger. if(destination && destination != system) return false; // Ship cannot linger any longer in this system. if(!system || ship.GetLingerSteps() >= system->MinimumFleetPeriod() / 4) return false; ship.Linger(); return true; } // Constants for the invisible fence timer. const int FENCE_DECAY = 4; const int FENCE_MAX = 600; // An offset to prevent the ship from being not quite over the point to departure. const double SAFETY_OFFSET = 1.; // The minimum speed advantage a ship has to have to consider running away. const double SAFETY_MULTIPLIER = 1.1; } AI::AI(const List<Ship> &ships, const List<Minable> &minables, const List<Flotsam> &flotsam) : ships(ships), minables(minables), flotsam(flotsam) { // Allocate a starting amount of hardpoints for ships. firingCommands.SetHardpoints(12); } // Fleet commands from the player. void AI::IssueShipTarget(const PlayerInfo &player, const shared_ptr<Ship> &target) { Orders newOrders; bool isEnemy = target->GetGovernment()->IsEnemy(); newOrders.type = (!isEnemy ? Orders::KEEP_STATION : target->IsDisabled() ? Orders::FINISH_OFF : Orders::ATTACK); newOrders.target = target; string description = (isEnemy ? "focusing fire on" : "following") + (" \"" + target->Name() + "\"."); IssueOrders(player, newOrders, description); } void AI::IssueAsteroidTarget(const PlayerInfo &player, const shared_ptr<Minable> &targetAsteroid) { Orders newOrders; newOrders.type = Orders::MINE; newOrders.targetAsteroid = targetAsteroid; IssueOrders(player, newOrders, "focusing fire on " + targetAsteroid->DisplayName() + " " + targetAsteroid->Noun() + "."); } void AI::IssueMoveTarget(const PlayerInfo &player, const Point &target, const System *moveToSystem) { Orders newOrders; newOrders.type = Orders::MOVE_TO; newOrders.point = target; newOrders.targetSystem = moveToSystem; string description = "moving to the given location"; description += player.GetSystem() == moveToSystem ? "." : (" in the " + moveToSystem->Name() + " system."); IssueOrders(player, newOrders, description); } // Commands issued via the keyboard (mostly, to the flagship). void AI::UpdateKeys(PlayerInfo &player, Command &activeCommands) { escortsUseAmmo = Preferences::Has("Escorts expend ammo"); escortsAreFrugal = Preferences::Has("Escorts use ammo frugally"); autoPilot |= activeCommands; if(activeCommands.Has(AutopilotCancelCommands())) { bool canceled = (autoPilot.Has(Command::JUMP) && !activeCommands.Has(Command::JUMP)); canceled |= (autoPilot.Has(Command::STOP) && !activeCommands.Has(Command::STOP)); canceled |= (autoPilot.Has(Command::LAND) && !activeCommands.Has(Command::LAND)); canceled |= (autoPilot.Has(Command::BOARD) && !activeCommands.Has(Command::BOARD)); if(canceled) Messages::Add("Disengaging autopilot.", Messages::Importance::High); autoPilot.Clear(); } const Ship *flagship = player.Flagship(); if(!flagship || flagship->IsDestroyed()) return; if(activeCommands.Has(Command::STOP)) Messages::Add("Coming to a stop.", Messages::Importance::High); // Only toggle the "cloak" command if one of your ships has a cloaking device. if(activeCommands.Has(Command::CLOAK)) for(const auto &it : player.Ships()) if(!it->IsParked() && it->Attributes().Get("cloak")) { isCloaking = !isCloaking; Messages::Add(isCloaking ? "Engaging cloaking device." : "Disengaging cloaking device." , Messages::Importance::High); break; } // Toggle your secondary weapon. if(activeCommands.Has(Command::SELECT)) player.SelectNextSecondary(); // The commands below here only apply if you have escorts or fighters. if(player.Ships().size() < 2) return; // Toggle the "deploy" command for the fleet or selected ships. if(activeCommands.Has(Command::DEPLOY)) IssueDeploy(player); shared_ptr<Ship> target = flagship->GetTargetShip(); shared_ptr<Minable> targetAsteroid = flagship->GetTargetAsteroid(); Orders newOrders; if(activeCommands.Has(Command::FIGHT) && target && !target->IsYours()) { newOrders.type = target->IsDisabled() ? Orders::FINISH_OFF : Orders::ATTACK; newOrders.target = target; IssueOrders(player, newOrders, "focusing fire on \"" + target->Name() + "\"."); } else if(activeCommands.Has(Command::FIGHT) && targetAsteroid) IssueAsteroidTarget(player, targetAsteroid); if(activeCommands.Has(Command::HOLD)) { newOrders.type = Orders::HOLD_POSITION; IssueOrders(player, newOrders, "holding position."); } if(activeCommands.Has(Command::GATHER)) { newOrders.type = Orders::GATHER; newOrders.target = player.FlagshipPtr(); IssueOrders(player, newOrders, "gathering around your flagship."); } // Get rid of any invalid orders. Carried ships will retain orders in case they are deployed. for(auto it = orders.begin(); it != orders.end(); ) { if(it->second.type == Orders::MINE && it->first->Cargo().Free() && it->second.targetAsteroid.expired()) it->second.type = Orders::HARVEST; else if(it->second.type & Orders::REQUIRES_TARGET) { shared_ptr<Ship> ship = it->second.target.lock(); shared_ptr<Minable> asteroid = it->second.targetAsteroid.lock(); // Check if the target ship itself is targetable. bool invalidTarget = !ship || !ship->IsTargetable() || (ship->IsDisabled() && it->second.type == Orders::ATTACK); // Alternately, if an asteroid is targeted, then not an invalid target. invalidTarget &= !asteroid; // Check if the target ship is in a system where we can target. // This check only checks for undocked ships (that have a current system). bool targetOutOfReach = !ship || (it->first->GetSystem() && ship->GetSystem() != it->first->GetSystem() && ship->GetSystem() != flagship->GetSystem()); // Asteroids are never out of reach since they're in the same system as flagship. targetOutOfReach &= !asteroid; if(invalidTarget || targetOutOfReach) { it = orders.erase(it); continue; } } ++it; } } void AI::UpdateEvents(const list<ShipEvent> &events) { for(const ShipEvent &event : events) { const auto &target = event.Target(); if(!target) continue; if(event.Actor()) { actions[event.Actor()][target] |= event.Type(); if(event.TargetGovernment()) notoriety[event.Actor()][event.TargetGovernment()] |= event.Type(); } const auto &actorGovernment = event.ActorGovernment(); if(actorGovernment) { governmentActions[actorGovernment][target] |= event.Type(); if(actorGovernment->IsPlayer() && event.TargetGovernment()) { int &bitmap = playerActions[target]; int newActions = event.Type() - (event.Type() & bitmap); bitmap |= event.Type(); // If you provoke the same ship twice, it should have an effect both times. if(event.Type() & ShipEvent::PROVOKE) newActions |= ShipEvent::PROVOKE; event.TargetGovernment()->Offend(newActions, target->CrewValue()); } } } } // Remove records of what happened in the previous system, now that // the player has entered a new one. void AI::Clean() { actions.clear(); notoriety.clear(); governmentActions.clear(); scanPermissions.clear(); playerActions.clear(); swarmCount.clear(); fenceCount.clear(); miningAngle.clear(); miningRadius.clear(); miningTime.clear(); appeasementThreshold.clear(); shipStrength.clear(); enemyStrength.clear(); allyStrength.clear(); } // Clear ship orders and assistance requests. These should be done // when the player lands, but not when they change systems. void AI::ClearOrders() { helperList.clear(); orders.clear(); } void AI::Step(const PlayerInfo &player, Command &activeCommands) { // First, figure out the comparative strengths of the present governments. const System *playerSystem = player.GetSystem(); map<const Government *, int64_t> strength; UpdateStrengths(strength, playerSystem); CacheShipLists(); // Update the counts of how long ships have been outside the "invisible fence." // If a ship ceases to exist, this also ensures that it will be removed from // the fence count map after a few seconds. for(auto it = fenceCount.begin(); it != fenceCount.end(); ) { it->second -= FENCE_DECAY; if(it->second < 0) it = fenceCount.erase(it); else ++it; } for(const auto &it : ships) { const System *system = it->GetActualSystem(); if(system && it->Position().Length() >= system->InvisibleFenceRadius()) { int &value = fenceCount[&*it]; value = min(FENCE_MAX, value + FENCE_DECAY + 1); } } const Ship *flagship = player.Flagship(); step = (step + 1) & 31; int targetTurn = 0; int minerCount = 0; const int maxMinerCount = minables.empty() ? 0 : 9; bool opportunisticEscorts = !Preferences::Has("Turrets focus fire"); bool fightersRetreat = Preferences::Has("Damaged fighters retreat"); const int npcMaxMiningTime = GameData::GetGamerules().NPCMaxMiningTime(); for(const auto &it : ships) { // A destroyed ship can't do anything. if(it->IsDestroyed()) continue; // Skip any carried fighters or drones that are somehow in the list. if(!it->GetSystem()) continue; if(it.get() == flagship) { // Player cannot do anything if the flagship is landing. if(!flagship->IsLanding()) MovePlayer(*it, player, activeCommands); continue; } const Government *gov = it->GetGovernment(); const Personality &personality = it->GetPersonality(); double healthRemaining = it->Health(); bool isPresent = (it->GetSystem() == playerSystem); bool isStranded = IsStranded(*it); bool thisIsLaunching = (isPresent && HasDeployments(*it)); if(isStranded || it->IsDisabled()) { // Attempt to find a friendly ship to render assistance. if(!it->GetPersonality().IsDerelict()) AskForHelp(*it, isStranded, flagship); if(it->IsDisabled()) { // Ships other than escorts should deploy fighters if disabled. if(!it->IsYours() || thisIsLaunching) { it->SetCommands(Command::DEPLOY); Deploy(*it, !(it->IsYours() && fightersRetreat)); } // Avoid jettisoning cargo as soon as this ship is repaired. if(personality.IsAppeasing()) { double health = .5 * it->Shields() + it->Hull(); double &threshold = appeasementThreshold[it.get()]; threshold = max((1. - health) + .1, threshold); } continue; } } // Overheated ships are effectively disabled, and cannot fire, cloak, etc. if(it->IsOverheated()) continue; Command command; firingCommands.SetHardpoints(it->Weapons().size()); if(it->IsYours()) { if(it->HasBays() && thisIsLaunching) { // If this is a carrier, launch whichever of its fighters are at // good enough health to survive a fight. command |= Command::DEPLOY; Deploy(*it, !fightersRetreat); } if(isCloaking) command |= Command::CLOAK; } // Cloak if the AI considers it appropriate. if(!it->IsYours() || !isCloaking) if(DoCloak(*it, command)) { // The ship chose to retreat from its target, e.g. to repair. it->SetCommands(command); continue; } shared_ptr<Ship> parent = it->GetParent(); if(parent && parent->IsDestroyed()) { // An NPC that loses its fleet leader should attempt to // follow that leader's parent. For most mission NPCs, // this is the player. Any regular NPCs and mission NPCs // with "personality uninterested" become independent. parent = parent->GetParent(); it->SetParent(parent); } // Pick a target and automatically fire weapons. shared_ptr<Ship> target = it->GetTargetShip(); shared_ptr<Minable> targetAsteroid = it->GetTargetAsteroid(); shared_ptr<Flotsam> targetFlotsam = it->GetTargetFlotsam(); if(isPresent && it->IsYours() && targetFlotsam && FollowOrders(*it, command)) continue; if(isPresent && !personality.IsSwarming()) { // Each ship only switches targets twice a second, so that it can // focus on damaging one particular ship. targetTurn = (targetTurn + 1) & 31; if(targetTurn == step || !target || target->IsDestroyed() || (target->IsDisabled() && personality.Disables()) || (target->IsFleeing() && personality.IsMerciful()) || !target->IsTargetable()) { target = FindTarget(*it); it->SetTargetShip(target); } } if(isPresent) { AimTurrets(*it, firingCommands, it->IsYours() ? opportunisticEscorts : personality.IsOpportunistic()); if(targetAsteroid) AutoFire(*it, firingCommands, *targetAsteroid); else AutoFire(*it, firingCommands); } // If this ship is hyperspacing, or in the act of // launching or landing, it can't do anything else. if(it->IsHyperspacing() || it->Zoom() < 1.) { it->SetCommands(command); it->SetCommands(firingCommands); continue; } // Run away if your hostile target is not disabled // and you are either badly damaged or have run out of ammo. // Player ships never stop targeting hostiles, while hostile mission NPCs will // do so only if they are allowed to leave. const bool shouldFlee = ShouldFlee(*it); if(!it->IsYours() && shouldFlee && target && target->GetGovernment()->IsEnemy(gov) && !target->IsDisabled() && (!it->GetParent() || !it->GetParent()->GetGovernment()->IsEnemy(gov))) { // Make sure the ship has somewhere to flee to. const System *system = it->GetSystem(); if(it->JumpsRemaining() && (!system->Links().empty() || it->JumpNavigation().HasJumpDrive())) target.reset(); else for(const StellarObject &object : system->Objects()) if(object.HasSprite() && object.HasValidPlanet() && object.GetPlanet()->IsInhabited() && object.GetPlanet()->CanLand(*it)) { target.reset(); break; } if(target) // This ship has nowhere to flee to: Stop fleeing. it->SetFleeing(false); else { // This ship has somewhere to flee to: Remove target and mark this ship as fleeing. it->SetTargetShip(target); it->SetFleeing(); } } else if(it->IsFleeing()) it->SetFleeing(false); // Special actions when a ship is heavily damaged: if(healthRemaining < RETREAT_HEALTH + .25) { // Cowards abandon their fleets. if(parent && personality.IsCoward()) { parent.reset(); it->SetParent(parent); } // Appeasing ships jettison cargo to distract their pursuers. if(personality.IsAppeasing() && it->Cargo().Used()) DoAppeasing(it, &appeasementThreshold[it.get()]); } // If recruited to assist a ship, follow through on the commitment // instead of ignoring it due to other personality traits. shared_ptr<Ship> shipToAssist = it->GetShipToAssist(); if(shipToAssist) { if(shipToAssist->IsDestroyed() || shipToAssist->GetSystem() != it->GetSystem() || shipToAssist->IsLanding() || shipToAssist->IsHyperspacing() || shipToAssist->GetGovernment()->IsEnemy(gov) || (!shipToAssist->IsDisabled() && !shipToAssist->NeedsFuel())) { shipToAssist.reset(); it->SetShipToAssist(nullptr); } else if(!it->IsBoarding()) { MoveTo(*it, command, shipToAssist->Position(), shipToAssist->Velocity(), 40., .8); command |= Command::BOARD; } if(shipToAssist) { it->SetTargetShip(shipToAssist); it->SetCommands(command); it->SetCommands(firingCommands); continue; } } // This ship may have updated its target ship. double targetDistance = numeric_limits<double>::infinity(); target = it->GetTargetShip(); if(target) targetDistance = target->Position().Distance(it->Position()); // Special case: if the player's flagship tries to board a ship to // refuel it, that escort should hold position for boarding. isStranded |= (flagship && it == flagship->GetTargetShip() && CanBoard(*flagship, *it) && autoPilot.Has(Command::BOARD)); // Stranded ships that have a helper need to stop and be assisted. bool strandedWithHelper = isStranded && (HasHelper(*it, isStranded) || it->GetPersonality().IsDerelict() || it->IsYours()); // Behave in accordance with personality traits. if(isPresent && personality.IsSwarming() && !strandedWithHelper) { // Swarming ships should not wait for (or be waited for by) any ship. if(parent) { parent.reset(); it->SetParent(parent); } // Flock between allied, in-system ships. DoSwarming(*it, command, target); it->SetCommands(command); it->SetCommands(firingCommands); continue; } if(isPresent && personality.IsSecretive()) { if(DoSecretive(*it, command)) { it->SetCommands(command); continue; } } // Surveillance NPCs with enforcement authority (or those from // missions) should perform scans and surveys of the system. if(isPresent && personality.IsSurveillance() && !strandedWithHelper && (scanPermissions[gov] || it->IsSpecial())) { DoSurveillance(*it, command, target); it->SetCommands(command); it->SetCommands(firingCommands); continue; } // Ships that harvest flotsam prioritize it over stopping to be refueled. if(isPresent && personality.Harvests() && DoHarvesting(*it, command)) { it->SetCommands(command); it->SetCommands(firingCommands); continue; } // Attacking a hostile ship, fleeing and stopping to be refueled are more important than mining. if(isPresent && personality.IsMining() && !shouldFlee && !target && !strandedWithHelper && maxMinerCount) { // Miners with free cargo space and available mining time should mine. Mission NPCs // should mine even if there are other miners or they have been mining a while. if(it->Cargo().Free() >= 5 && IsArmed(*it) && (it->IsSpecial() || (++miningTime[&*it] < npcMaxMiningTime && ++minerCount < maxMinerCount))) { if(it->HasBays()) { command |= Command::DEPLOY; Deploy(*it, false); } DoMining(*it, command); it->SetCommands(command); it->SetCommands(firingCommands); continue; } // Fighters and drones should assist their parent's mining operation if they cannot // carry ore, and the asteroid is near enough that the parent can harvest the ore. if(it->CanBeCarried() && parent && miningTime[parent.get()] < 3601) { const shared_ptr<Minable> &minable = parent->GetTargetAsteroid(); if(minable && minable->Position().Distance(parent->Position()) < 600.) { it->SetTargetAsteroid(minable); MoveToAttack(*it, command, *minable); AutoFire(*it, firingCommands, *minable); it->SetCommands(command); it->SetCommands(firingCommands); continue; } } it->SetTargetAsteroid(nullptr); } // Handle carried ships: if(it->CanBeCarried()) { // A carried ship must belong to the same government as its parent to dock with it. bool hasParent = parent && !parent->IsDestroyed() && parent->GetGovernment() == gov; bool inParentSystem = hasParent && parent->GetSystem() == it->GetSystem(); // NPCs may take 30 seconds or longer to find a new parent. Player // owned fighter shouldn't take more than a few seconds. bool findNewParent = it->IsYours() ? !Random::Int(30) : !Random::Int(1800); bool parentHasSpace = inParentSystem && parent->BaysFree(it->Attributes().Category()); if(findNewParent && parentHasSpace && it->IsYours()) parentHasSpace = parent->CanCarry(*it); if(!hasParent || (!inParentSystem && !it->JumpNavigation().JumpFuel()) || (!parentHasSpace && findNewParent)) { // Find the possible parents for orphaned fighters and drones. auto parentChoices = vector<shared_ptr<Ship>>{}; parentChoices.reserve(ships.size() * .1); auto getParentFrom = [&it, &gov, &parentChoices](const list<shared_ptr<Ship>> &otherShips) -> shared_ptr<Ship> { for(const auto &other : otherShips) if(other->GetGovernment() == gov && other->GetSystem() == it->GetSystem() && !other->CanBeCarried()) { if(!other->IsDisabled() && other->CanCarry(*it)) return other; else parentChoices.emplace_back(other); } return shared_ptr<Ship>(); }; // Mission ships should only pick amongst ships from the same mission. auto missionIt = it->IsSpecial() && !it->IsYours() ? find_if(player.Missions().begin(), player.Missions().end(), [&it](const Mission &m) { return m.HasShip(it); }) : player.Missions().end(); shared_ptr<Ship> newParent; if(missionIt != player.Missions().end()) { auto &npcs = missionIt->NPCs(); for(const auto &npc : npcs) { // Don't reparent to NPC ships that have not been spawned. if(!npc.ShouldSpawn()) continue; newParent = getParentFrom(npc.Ships()); if(newParent) break; } } else newParent = getParentFrom(ships); // If a new parent was found, then this carried ship should always reparent // as a ship of its own government is in-system and has space to carry it. if(newParent) parent = newParent; // Otherwise, if one or more in-system ships of the same government were found, // this carried ship should flock with one of them, even if they can't carry it. else if(!parentChoices.empty()) parent = parentChoices[Random::Int(parentChoices.size())]; // Player-owned carriables that can't be carried and have no ships to flock with // should keep their current parent, or if it is destroyed, their parent's parent. else if(it->IsYours()) { if(parent && parent->IsDestroyed()) parent = parent->GetParent(); } // All remaining non-player ships should forget their previous parent entirely. else parent.reset(); // Player-owned carriables should defer to player carrier if // selected parent can't carry it. This is necessary to prevent // fighters from jumping around fleet when there's not enough // bays. if(it->IsYours() && parent && parent->GetParent() && !parent->CanCarry(*it)) parent = parent->GetParent(); if(it->GetParent() != parent) it->SetParent(parent); } // Otherwise, check if this ship wants to return to its parent (e.g. to repair). else if(parentHasSpace && ShouldDock(*it, *parent, playerSystem)) { it->SetTargetShip(parent); MoveTo(*it, command, parent->Position(), parent->Velocity(), 40., .8); command |= Command::BOARD; it->SetCommands(command); it->SetCommands(firingCommands); continue; } // If we get here, it means that the ship has not decided to return // to its mothership. So, it should continue to be deployed. command |= Command::DEPLOY; } // If this ship has decided to recall all of its fighters because combat has ceased, // it comes to a stop to facilitate their reboarding process. bool mustRecall = false; if(!target && it->HasBays() && !(it->IsYours() ? thisIsLaunching : it->Commands().Has(Command::DEPLOY))) for(const weak_ptr<Ship> &ptr : it->GetEscorts()) { shared_ptr<const Ship> escort = ptr.lock(); // Note: HasDeployOrder is always `false` for NPC ships, as it is solely used for player ships. if(escort && escort->CanBeCarried() && !escort->HasDeployOrder() && escort->GetSystem() == it->GetSystem() && !escort->IsDisabled() && it->BaysFree(escort->Attributes().Category())) { mustRecall = true; break; } } // Construct movement / navigation commands as appropriate for the ship. if(mustRecall || (strandedWithHelper && !it->GetPersonality().IsDerelict())) { // Stopping to let fighters board or to be refueled takes priority // even over following orders from the player. if(it->Velocity().Length() > .001 || !target) Stop(*it, command); else command.SetTurn(TurnToward(*it, TargetAim(*it))); } else if(FollowOrders(*it, command)) { // If this is an escort and it followed orders, its only final task // is to convert completed MOVE_TO orders into HOLD_POSITION orders. UpdateOrders(*it); } // Hostile "escorts" (i.e. NPCs that are trailing you) only revert to // escort behavior when in a different system from you. Otherwise, // the behavior depends on what the parent is doing, whether there // are hostile targets nearby, and whether the escort has any // immediate needs (like refueling). else if(!parent) MoveIndependent(*it, command); else if(parent->GetSystem() != it->GetSystem()) { if(personality.IsStaying() || !it->Attributes().Get("fuel capacity")) MoveIndependent(*it, command); else MoveEscort(*it, command); } // From here down, we're only dealing with ships that have a "parent" // which is in the same system as them. else if(parent->GetGovernment()->IsEnemy(gov)) { // Fight your target, if you have one. if(target) MoveIndependent(*it, command); // Otherwise try to find and fight your parent. If your parent // can't be both targeted and pursued, then don't follow them. else if(parent->IsTargetable() && CanPursue(*it, *parent)) MoveEscort(*it, command); else MoveIndependent(*it, command); } else if(parent->IsDisabled() && !it->CanBeCarried()) { // Your parent is disabled, and is in this system. If you have enemy // targets present, fight them. Otherwise, repair your parent. if(target) MoveIndependent(*it, command); else if(!parent->GetPersonality().IsDerelict()) it->SetShipToAssist(parent); else CircleAround(*it, command, *parent); } else if(personality.IsStaying()) MoveIndependent(*it, command); // This is a friendly escort. If the parent is getting ready to // jump, always follow. else if(parent->Commands().Has(Command::JUMP) && !strandedWithHelper) MoveEscort(*it, command); // Timid ships always stay near their parent. Injured player // escorts will stay nearby until they have repaired a bit. else if((personality.IsTimid() || (it->IsYours() && healthRemaining < RETREAT_HEALTH)) && parent->Position().Distance(it->Position()) > 500.) MoveEscort(*it, command); // Otherwise, attack targets depending on your hunting attribute. else if(target && (targetDistance < 2000. || personality.IsHunting())) MoveIndependent(*it, command); // This ship does not feel like fighting. else MoveEscort(*it, command); // Force ships that are overlapping each other to "scatter": DoScatter(*it, command); it->SetCommands(command); it->SetCommands(firingCommands); } } void AI::SetMousePosition(Point position) { mousePosition = position; } // Get the in-system strength of each government's allies and enemies. int64_t AI::AllyStrength(const Government *government) { auto it = allyStrength.find(government); return (it == allyStrength.end() ? 0 : it->second); } int64_t AI::EnemyStrength(const Government *government) { auto it = enemyStrength.find(government); return (it == enemyStrength.end() ? 0 : it->second); } // Find nearest landing location. const StellarObject *AI::FindLandingLocation(const Ship &ship, const bool refuel) { const StellarObject *target = nullptr; const System *system = ship.GetSystem(); if(system) { // Determine which, if any, planet with fuel or without fuel is closest. double closest = numeric_limits<double>::infinity(); const Point &p = ship.Position(); for(const StellarObject &object : system->Objects()) { const Planet *planet = object.GetPlanet(); if(object.HasSprite() && object.HasValidPlanet() && !planet->IsWormhole() && planet->CanLand(ship) && planet->HasFuelFor(ship) == refuel) { double distance = p.Distance(object.Position()); if(distance < closest) { target = &object; closest = distance; } } } } return target; } // Check if the given target can be pursued by this ship. bool AI::CanPursue(const Ship &ship, const Ship &target) const { // If this ship does not care about the "invisible fence", it can always pursue. if(ship.GetPersonality().IsUnconstrained()) return true; // Owned ships ignore fence. if(ship.IsYours()) return true; // Check if the target is beyond the "invisible fence" for this system. const auto fit = fenceCount.find(&target); if(fit == fenceCount.end()) return true; else return (fit->second != FENCE_MAX); } // Check if the ship is being helped, and if not, ask for help. void AI::AskForHelp(Ship &ship, bool &isStranded, const Ship *flagship) { if(HasHelper(ship, isStranded)) isStranded = true; else if(!Random::Int(30)) { const Government *gov = ship.GetGovernment(); bool hasEnemy = false; vector<Ship *> canHelp; canHelp.reserve(ships.size()); for(const auto &helper : ships) { // Never ask yourself for help. if(helper.get() == &ship) continue; // If any able enemies of this ship are in its system, it cannot call for help. const System *system = ship.GetSystem(); if(helper->GetGovernment()->IsEnemy(gov) && flagship && system == flagship->GetSystem()) { // Disabled, overheated, or otherwise untargetable ships pose no threat. bool harmless = helper->IsDisabled() || (helper->IsOverheated() && helper->Heat() >= 1.1) || !helper->IsTargetable(); hasEnemy |= (system == helper->GetSystem() && !harmless); if(hasEnemy) break; } // Check if this ship is logically able to help. // If the ship is already assisting someone else, it cannot help this ship. if(helper->GetShipToAssist() && helper->GetShipToAssist().get() != &ship) continue; // If the ship is mining or chasing flotsam, it cannot help this ship. if(helper->GetTargetAsteroid() || helper->GetTargetFlotsam()) continue; // Your escorts only help other escorts, and your flagship never helps. if((helper->IsYours() && !ship.IsYours()) || helper.get() == flagship) continue; // Your escorts should not help each other if already under orders. auto foundOrders = orders.find(helper.get()); if(foundOrders != orders.end()) { int helperOrders = foundOrders->second.type; // If your own escorts become disabled, then your mining fleet // should prioritize repairing escorts instead of mining or // harvesting flotsam. if(helper->IsYours() && ship.IsYours() && helperOrders != Orders::MINE && helperOrders != Orders::HARVEST) continue; } // Check if this ship is physically able to help. if(!CanHelp(ship, *helper, isStranded)) continue; // Prefer fast ships over slow ones. canHelp.insert(canHelp.end(), 1 + .3 * helper->MaxVelocity(), helper.get()); } if(!hasEnemy && !canHelp.empty()) { Ship *helper = canHelp[Random::Int(canHelp.size())]; helper->SetShipToAssist((&ship)->shared_from_this()); helperList[&ship] = helper->shared_from_this(); isStranded = true; } else isStranded = false; } else isStranded = false; } // Determine if the selected ship is physically able to render assistance. bool AI::CanHelp(const Ship &ship, const Ship &helper, const bool needsFuel) const { // A ship being assisted cannot assist. if(helperList.find(&helper) != helperList.end()) return false; // Fighters, drones, and disabled / absent ships can't offer assistance. if(helper.CanBeCarried() || helper.GetSystem() != ship.GetSystem() || (helper.Cloaking() == 1. && helper.GetGovernment() != ship.GetGovernment()) || helper.IsDisabled() || helper.IsOverheated() || helper.IsHyperspacing()) return false; // An enemy cannot provide assistance, and only ships of the same government will repair disabled ships. if(helper.GetGovernment()->IsEnemy(ship.GetGovernment()) || (ship.IsDisabled() && helper.GetGovernment() != ship.GetGovernment())) return false; // If the helper has insufficient fuel, it cannot help this ship unless this ship is also disabled. if(!ship.IsDisabled() && needsFuel && !helper.CanRefuel(ship)) return false; return true; } bool AI::HasHelper(const Ship &ship, const bool needsFuel) { // Do we have an existing ship that was asked to assist? if(helperList.find(&ship) != helperList.end()) { shared_ptr<Ship> helper = helperList[&ship].lock(); if(helper && helper->GetShipToAssist().get() == &ship && CanHelp(ship, *helper, needsFuel)) return true; else helperList.erase(&ship); } return false; } // Pick a new target for the given ship. shared_ptr<Ship> AI::FindTarget(const Ship &ship) const { // If this ship has no government, it has no enemies. shared_ptr<Ship> target; const Government *gov = ship.GetGovernment(); if(!gov || ship.GetPersonality().IsPacifist()) return FindNonHostileTarget(ship); bool isYours = ship.IsYours(); if(isYours) { auto it = orders.find(&ship); if(it != orders.end() && (it->second.type == Orders::ATTACK || it->second.type == Orders::FINISH_OFF)) return it->second.target.lock(); } // If this ship is not armed, do not make it fight. double minRange = numeric_limits<double>::infinity(); double maxRange = 0.; for(const Hardpoint &weapon : ship.Weapons()) if(weapon.GetOutfit() && !weapon.IsAntiMissile()) { minRange = min(minRange, weapon.GetOutfit()->Range()); maxRange = max(maxRange, weapon.GetOutfit()->Range()); } if(!maxRange) return FindNonHostileTarget(ship); const Personality &person = ship.GetPersonality(); shared_ptr<Ship> oldTarget = ship.GetTargetShip(); if(oldTarget && !oldTarget->IsTargetable()) oldTarget.reset(); if(oldTarget && person.IsTimid() && oldTarget->IsDisabled() && ship.Position().Distance(oldTarget->Position()) > 1000.) oldTarget.reset(); // Ships with 'plunders' personality always destroy the ships they have boarded // unless they also have either or both of the 'disables' or 'merciful' personalities. if(oldTarget && person.Plunders() && !person.Disables() && !person.IsMerciful() && oldTarget->IsDisabled() && Has(ship, oldTarget, ShipEvent::BOARD)) return oldTarget; shared_ptr<Ship> parentTarget; if(ship.GetParent() && !ship.GetParent()->GetGovernment()->IsEnemy(gov)) parentTarget = ship.GetParent()->GetTargetShip(); if(parentTarget && !parentTarget->IsTargetable()) parentTarget.reset(); // Find the closest enemy ship (if there is one). If this ship is "hunting," // it will attack any ship in system. Otherwise, if all its weapons have a // range higher than 2000, it will engage ships up to 50% beyond its range. // If a ship has short range weapons and is not hunting, it will engage any // ship that is within 3000 of it. double closest = person.IsHunting() ? numeric_limits<double>::infinity() : (minRange > 1000.) ? maxRange * 1.5 : 4000.; bool hasNemesis = false; bool canPlunder = person.Plunders() && ship.Cargo().Free() && !ship.CanBeCarried(); // Figure out how strong this ship is. int64_t maxStrength = 0; auto strengthIt = shipStrength.find(&ship); if(!person.IsDaring() && strengthIt != shipStrength.end()) maxStrength = 2 * strengthIt->second; // Get a list of all targetable, hostile ships in this system. const auto enemies = GetShipsList(ship, true); for(const auto &foe : enemies) { // If this is a "nemesis" ship and it has found one of the player's // ships to target, it will only consider the player's owned fleet, // or NPCs being escorted by the player. const bool isPotentialNemesis = person.IsNemesis() && (foe->IsYours() || foe->GetPersonality().IsEscort()); if(hasNemesis && !isPotentialNemesis) continue; if(!CanPursue(ship, *foe)) continue; // Estimate the range a second from now, so ships prefer foes they are approaching. double range = (foe->Position() + 60. * foe->Velocity()).Distance( ship.Position() + 60. * ship.Velocity()); // Prefer the previous target, or the parent's target, if they are nearby. if(foe == oldTarget.get() || foe == parentTarget.get()) range -= 500.; // Unless this ship is "daring", it should not chase much stronger ships. if(maxStrength && range > 1000. && !foe->IsDisabled()) { const auto otherStrengthIt = shipStrength.find(foe); if(otherStrengthIt != shipStrength.end() && otherStrengthIt->second > maxStrength) continue; } // Merciful ships do not attack any ships that are trying to escape. if(person.IsMerciful() && foe->IsFleeing()) continue; // Ships which only disable never target already-disabled ships. if((person.Disables() || (!person.IsNemesis() && foe != oldTarget.get())) && foe->IsDisabled() && (!canPlunder || Has(ship, foe->shared_from_this(), ShipEvent::BOARD))) continue; // Ships that don't (or can't) plunder strongly prefer active targets. if(!canPlunder) range += 5000. * foe->IsDisabled(); // While those that do, do so only if no "live" enemies are nearby. else range += 2000. * (2 * foe->IsDisabled() - !Has(ship, foe->shared_from_this(), ShipEvent::BOARD)); // Prefer to go after armed targets, especially if you're not a pirate. range += 1000. * (!IsArmed(*foe) * (1 + !person.Plunders())); // Targets which have plundered this ship's faction earn extra scorn. range -= 1000 * Has(*foe, gov, ShipEvent::BOARD); // Focus on nearly dead ships. range += 500. * (foe->Shields() + foe->Hull()); // If a target is extremely overheated, focus on ships that can attack back. if(foe->IsOverheated()) range += 3000. * (foe->Heat() - .9); if((isPotentialNemesis && !hasNemesis) || range < closest) { closest = range; target = foe->shared_from_this(); hasNemesis = isPotentialNemesis; } } // With no hostile targets, NPCs with enforcement authority (and any // mission NPCs) should consider friendly targets for surveillance. if(!isYours && !target && (ship.IsSpecial() || scanPermissions.at(gov))) target = FindNonHostileTarget(ship); // Vindictive personalities without in-range hostile targets keep firing at an old // target (instead of perhaps moving about and finding one that is still alive). if(!target && person.IsVindictive()) { target = ship.GetTargetShip(); if(target && (target->Cloaking() == 1. || target->GetSystem() != ship.GetSystem())) target.reset(); } return target; } shared_ptr<Ship> AI::FindNonHostileTarget(const Ship &ship) const { shared_ptr<Ship> target; bool cargoScan = ship.Attributes().Get("cargo scan power"); bool outfitScan = ship.Attributes().Get("outfit scan power"); if(cargoScan || outfitScan) { const auto allies = GetShipsList(ship, false); // If this ship already has a target, and is in the process of scanning it, prioritise that. shared_ptr<Ship> oldTarget = ship.GetTargetShip(); if(oldTarget && !oldTarget->IsTargetable()) oldTarget.reset(); if(oldTarget) { bool cargoScanInProgress = ship.CargoScanFraction() > 0. && ship.CargoScanFraction() < 1.; bool outfitScanInProgress = ship.OutfitScanFraction() > 0. && ship.OutfitScanFraction() < 1.; if(cargoScanInProgress || outfitScanInProgress) target = std::move(oldTarget); } else { double closest = numeric_limits<double>::infinity(); const Government *gov = ship.GetGovernment(); for(const auto &it : allies) if(it->GetGovernment() != gov) { auto ptr = it->shared_from_this(); // Scan friendly ships that are as-yet unscanned by this ship's government. if((!cargoScan || Has(gov, ptr, ShipEvent::SCAN_CARGO)) && (!outfitScan || Has(gov, ptr, ShipEvent::SCAN_OUTFITS))) continue; double range = it->Position().DistanceSquared(ship.Position()); if(range < closest) { closest = range; target = std::move(ptr); } } } } return target; } // Return a list of all targetable ships in the same system as the player that // match the desired hostility (i.e. enemy or non-enemy). Does not consider the // ship's current target, as its inclusion may or may not be desired. vector<Ship *> AI::GetShipsList(const Ship &ship, bool targetEnemies, double maxRange) const { if(maxRange < 0.) maxRange = numeric_limits<double>::infinity(); auto targets = vector<Ship *>(); // The cached lists are built each step based on the current ships in the player's system. const auto &rosters = targetEnemies ? enemyLists : allyLists; const auto it = rosters.find(ship.GetGovernment()); if(it != rosters.end() && !it->second.empty()) { targets.reserve(it->second.size()); const System *here = ship.GetSystem(); const Point &p = ship.Position(); for(const auto &target : it->second) if(target->IsTargetable() && target->GetSystem() == here && !(target->IsHyperspacing() && target->Velocity().Length() > 10.) && p.Distance(target->Position()) < maxRange && (ship.IsYours() || !target->GetPersonality().IsMarked()) && (target->IsYours() || !ship.GetPersonality().IsMarked())) targets.emplace_back(target); } return targets; } bool AI::FollowOrders(Ship &ship, Command &command) const { auto it = orders.find(&ship); if(it == orders.end()) return false; int type = it->second.type; // If your parent is jumping or absent, that overrides your orders unless // your orders are to hold position. shared_ptr<Ship> parent = ship.GetParent(); if(parent && type != Orders::HOLD_POSITION && type != Orders::HOLD_ACTIVE && type != Orders::MOVE_TO) { if(parent->GetSystem() != ship.GetSystem()) return false; if(parent->Commands().Has(Command::JUMP) && ship.JumpsRemaining()) return false; } // Do not keep chasing flotsam because another order was given. if(ship.GetTargetFlotsam() && (type != Orders::HARVEST || (ship.CanBeCarried() && !ship.HasDeployOrder()))) { ship.SetTargetFlotsam(nullptr); return false; } shared_ptr<Ship> target = it->second.target.lock(); shared_ptr<Minable> targetAsteroid = it->second.targetAsteroid.lock(); if(type == Orders::MOVE_TO && it->second.targetSystem && ship.GetSystem() != it->second.targetSystem) { // The desired position is in a different system. Find the best // way to reach that system (via wormhole or jumping). This may // result in the ship landing to refuel. SelectRoute(ship, it->second.targetSystem); // Travel there even if your parent is not planning to travel. if((ship.GetTargetSystem() && ship.JumpsRemaining()) || ship.GetTargetStellar()) MoveIndependent(ship, command); else return false; } else if((type == Orders::MOVE_TO || type == Orders::HOLD_ACTIVE) && ship.Position().Distance(it->second.point) > 20.) MoveTo(ship, command, it->second.point, Point(), 10., .1); else if(type == Orders::HOLD_POSITION || type == Orders::HOLD_ACTIVE || type == Orders::MOVE_TO) { if(ship.Velocity().Length() > .001 || !ship.GetTargetShip()) Stop(ship, command); else command.SetTurn(TurnToward(ship, TargetAim(ship))); } else if(type == Orders::MINE && targetAsteroid) { ship.SetTargetAsteroid(targetAsteroid); // Escorts should chase the player-targeted asteroid. MoveToAttack(ship, command, *targetAsteroid); } else if(type == Orders::HARVEST) { if(DoHarvesting(ship, command)) { ship.SetCommands(command); ship.SetCommands(firingCommands); } else return false; } else if(!target) { // Note: in AI::UpdateKeys() we already made sure that if a set of orders // has a target, the target is in-system and targetable. But, to be sure: return false; } else if(type == Orders::KEEP_STATION) KeepStation(ship, command, *target); else if(type == Orders::GATHER) CircleAround(ship, command, *target); else MoveIndependent(ship, command); return true; } void AI::MoveIndependent(Ship &ship, Command &command) const { double invisibleFenceRadius = ship.GetSystem()->InvisibleFenceRadius(); shared_ptr<const Ship> target = ship.GetTargetShip(); // NPCs should not be beyond the "fence" unless their target is // fairly close to it (or they are intended to be there). if(!ship.IsYours() && !ship.GetPersonality().IsUnconstrained()) { if(target) { Point extrapolated = target->Position() + 120. * (target->Velocity() - ship.Velocity()); if(extrapolated.Length() >= invisibleFenceRadius) { MoveTo(ship, command, Point(), Point(), 40., .8); if(ship.Velocity().Dot(ship.Position()) > 0.) command |= Command::FORWARD; return; } } else if(ship.Position().Length() >= invisibleFenceRadius) { // This ship should not be beyond the fence. MoveTo(ship, command, Point(), Point(), 40, .8); return; } } bool friendlyOverride = false; bool ignoreTargetShip = false; if(ship.IsYours()) { auto it = orders.find(&ship); if(it != orders.end()) { if(it->second.type == Orders::MOVE_TO) ignoreTargetShip = (ship.GetTargetSystem() && ship.JumpsRemaining()) || ship.GetTargetStellar(); else if(it->second.type == Orders::ATTACK || it->second.type == Orders::FINISH_OFF) friendlyOverride = it->second.target.lock() == target; } } const Government *gov = ship.GetGovernment(); if(ignoreTargetShip) { // Do not move to attack, scan, or assist the target ship. } else if(target && (gov->IsEnemy(target->GetGovernment()) || friendlyOverride)) { bool shouldBoard = ship.Cargo().Free() && ship.GetPersonality().Plunders(); bool hasBoarded = Has(ship, target, ShipEvent::BOARD); if(shouldBoard && target->IsDisabled() && !hasBoarded) { if(ship.IsBoarding()) return; MoveTo(ship, command, target->Position(), target->Velocity(), 40., .8); command |= Command::BOARD; } else Attack(ship, command, *target); return; } else if(target) { // An AI ship that is targeting a non-hostile ship should scan it, or move on. bool cargoScan = ship.Attributes().Get("cargo scan power"); bool outfitScan = ship.Attributes().Get("outfit scan power"); // De-target if the target left my system. if(ship.GetSystem() != target->GetSystem()) { target.reset(); ship.SetTargetShip(nullptr); } // Detarget if I cannot scan, or if I already scanned the ship. else if((!cargoScan || Has(gov, target, ShipEvent::SCAN_CARGO)) && (!outfitScan || Has(gov, target, ShipEvent::SCAN_OUTFITS))) { target.reset(); ship.SetTargetShip(nullptr); } // Move to (or near) the ship and scan it. else { if(target->Velocity().Length() > ship.MaxVelocity() * 0.9) CircleAround(ship, command, *target); else MoveTo(ship, command, target->Position(), target->Velocity(), 1., 1.); if(!ship.IsYours() && (ship.IsSpecial() || scanPermissions.at(gov))) command |= Command::SCAN; return; } } // A ship has restricted movement options if it is 'staying', 'lingering', or hostile to its parent. const bool shouldStay = StayOrLinger(ship); // Ships should choose a random system/planet for travel if they do not // already have a system/planet in mind, and are free to move about. const System *origin = ship.GetSystem(); if(!ship.GetTargetSystem() && !ship.GetTargetStellar() && !shouldStay) { // TODO: This should problably be changed, because JumpsRemaining // does not return an accurate number. int jumps = ship.JumpsRemaining(false); // Each destination system has an average priority of 10. // If you only have one jump left, landing should be high priority. int planetWeight = jumps ? (1 + 40 / jumps) : 1; vector<int> systemWeights; int totalWeight = 0; const set<const System *> &links = ship.JumpNavigation().HasJumpDrive() ? origin->JumpNeighbors(ship.JumpNavigation().JumpRange()) : origin->Links(); if(jumps) { bool unrestricted = ship.GetPersonality().IsUnrestricted(); for(const System *link : links) { if(!unrestricted && gov->IsRestrictedFrom(*link)) { systemWeights.push_back(0); continue; } // Prefer systems in the direction we're facing. Point direction = link->Position() - origin->Position(); int weight = static_cast<int>( 11. + 10. * ship.Facing().Unit().Dot(direction.Unit())); systemWeights.push_back(weight); totalWeight += weight; } } int systemTotalWeight = totalWeight; // Anywhere you can land that has a port has the same weight. Ships will // not land anywhere without a port. vector<const StellarObject *> planets; for(const StellarObject &object : origin->Objects()) if(object.HasSprite() && object.HasValidPlanet() && object.GetPlanet()->HasServices() && object.GetPlanet()->CanLand(ship)) { planets.push_back(&object); totalWeight += planetWeight; } // If there are no ports to land on and this ship cannot jump, consider // landing on uninhabited planets. if(!totalWeight) for(const StellarObject &object : origin->Objects()) if(object.HasSprite() && object.HasValidPlanet() && object.GetPlanet()->CanLand(ship)) { planets.push_back(&object); totalWeight += planetWeight; } if(!totalWeight) { // If there is nothing this ship can land on, have it just go to the // star and hover over it rather than drifting far away. if(origin->Objects().empty()) return; totalWeight = 1; planets.push_back(&origin->Objects().front()); } set<const System *>::const_iterator it = links.begin(); int choice = Random::Int(totalWeight); if(choice < systemTotalWeight) { for(unsigned i = 0; i < systemWeights.size(); ++i, ++it) { choice -= systemWeights[i]; if(choice < 0) { ship.SetTargetSystem(*it); break; } } } else { choice = (choice - systemTotalWeight) / planetWeight; ship.SetTargetStellar(planets[choice]); } } // Choose the best method of reaching the target system, which may mean // using a local wormhole rather than jumping. If this ship has chosen // to land, this decision will not be altered. SelectRoute(ship, ship.GetTargetSystem()); if(ship.GetTargetSystem()) { PrepareForHyperspace(ship, command); // Issuing the JUMP command prompts the escorts to get ready to jump. command |= Command::JUMP; // Issuing the WAIT command will prevent this parent from jumping. // When all its non-carried, in-system escorts that are not disabled and // have the ability to jump are ready, the WAIT command will be omitted. if(!EscortsReadyToJump(ship)) command |= Command::WAIT; } else if(ship.GetTargetStellar()) { MoveToPlanet(ship, command); if(!shouldStay && ship.Attributes().Get("fuel capacity") && ship.GetTargetStellar()->HasSprite() && ship.GetTargetStellar()->GetPlanet() && ship.GetTargetStellar()->GetPlanet()->CanLand(ship)) command |= Command::LAND; else if(ship.Position().Distance(ship.GetTargetStellar()->Position()) < 100.) ship.SetTargetStellar(nullptr); } else if(shouldStay && !ship.GetSystem()->Objects().empty()) { unsigned i = Random::Int(origin->Objects().size()); ship.SetTargetStellar(&origin->Objects()[i]); } // Nowhere to go, and nothing to do, so stay near the system center. else if(shouldStay) MoveTo(ship, command, Point(), Point(), 40, 0.8); } void AI::MoveEscort(Ship &ship, Command &command) const { const Ship &parent = *ship.GetParent(); const System *currentSystem = ship.GetSystem(); bool hasFuelCapacity = ship.Attributes().Get("fuel capacity"); bool needsFuel = ship.NeedsFuel(); bool isStaying = ship.GetPersonality().IsStaying() || !hasFuelCapacity; bool parentIsHere = (currentSystem == parent.GetSystem()); // Check if the parent has a target planet that is in the parent's system. const Planet *parentPlanet = (parent.GetTargetStellar() ? parent.GetTargetStellar()->GetPlanet() : nullptr); bool planetIsHere = (parentPlanet && parentPlanet->IsInSystem(parent.GetSystem())); bool systemHasFuel = hasFuelCapacity && currentSystem->HasFuelFor(ship); if(parent.Cloaking() == 1 && (ship.GetGovernment() != parent.GetGovernment())) { if(parent.GetGovernment() && parent.GetGovernment()->IsPlayer() && ship.GetPersonality().IsEscort() && !ship.GetPersonality().IsUninterested()) { // NPCs with the "escort" personality that are not uninterested // act as if they were escorts, following the cloaked flagship. } else { MoveIndependent(ship, command); return; } } // Non-staying escorts should route to their parent ship's system if not already in it. if(!parentIsHere && !isStaying) { if(ship.GetTargetStellar()) { // An escort with an out-of-system parent only lands to // refuel or use a wormhole to route toward the parent. const Planet *targetPlanet = ship.GetTargetStellar()->GetPlanet(); if(!targetPlanet || !targetPlanet->CanLand(ship) || !ship.GetTargetStellar()->HasSprite() || (!targetPlanet->IsWormhole() && ship.Fuel() == 1.)) ship.SetTargetStellar(nullptr); } // If the ship has no destination or the destination is unreachable, route to the parent's system. if(!ship.GetTargetStellar() && (!ship.GetTargetSystem() || !ship.JumpNavigation().JumpFuel(ship.GetTargetSystem()))) { // Route to the parent ship's system and check whether // the ship should land (refuel or wormhole) or jump. SelectRoute(ship, parent.GetSystem()); } // Perform the action that this ship previously decided on. if(ship.GetTargetStellar()) { MoveToPlanet(ship, command); command |= Command::LAND; } else if(ship.GetTargetSystem() && ship.JumpsRemaining()) { PrepareForHyperspace(ship, command); command |= Command::JUMP; // If this ship is a parent to members of its fleet, // it should wait for them before jumping. if(!EscortsReadyToJump(ship)) command |= Command::WAIT; } else if(systemHasFuel && ship.Fuel() < 1.) // Refuel so that when the parent returns, this ship is ready to rendezvous with it. Refuel(ship, command); else // This ship has no route to the parent's system, so park at the system's center. MoveTo(ship, command, Point(), Point(), 40., 0.1); } // If the parent is in-system and planning to jump, non-staying escorts should follow suit. else if(parent.Commands().Has(Command::JUMP) && parent.GetTargetSystem() && !isStaying) { SelectRoute(ship, parent.GetTargetSystem()); if(ship.GetTargetSystem()) { PrepareForHyperspace(ship, command); command |= Command::JUMP; if(!(parent.IsEnteringHyperspace() || parent.IsReadyToJump()) || !EscortsReadyToJump(ship)) command |= Command::WAIT; } else if(needsFuel && systemHasFuel) Refuel(ship, command); else if(ship.GetTargetStellar()) { MoveToPlanet(ship, command); if(parent.IsEnteringHyperspace()) command |= Command::LAND; } else if(needsFuel) // Return to the system center to maximize solar collection rate. MoveTo(ship, command, Point(), Point(), 40., 0.1); else // This ship has no route to the parent's destination system, so protect it until it jumps away. KeepStation(ship, command, parent); } // If an escort is out of fuel, they should refuel without waiting for the // "parent" to land (because the parent may not be planning on landing). else if(systemHasFuel && needsFuel) Refuel(ship, command); else if(parent.Commands().Has(Command::LAND) && parentIsHere && planetIsHere) { if(parentPlanet->CanLand(ship)) { ship.SetTargetSystem(nullptr); ship.SetTargetStellar(parent.GetTargetStellar()); MoveToPlanet(ship, command); if(parent.IsLanding()) command |= Command::LAND; } else if(parentPlanet->IsWormhole()) { const auto *wormhole = parentPlanet->GetWormhole(); SelectRoute(ship, &wormhole->WormholeDestination(*currentSystem)); if(ship.GetTargetSystem()) { PrepareForHyperspace(ship, command); if(parent.IsLanding()) command |= Command::JUMP; } else if(ship.GetTargetStellar()) { MoveToPlanet(ship, command); if(parent.IsLanding()) command |= Command::LAND; } else if(needsFuel) // Return to the system center to maximize solar collection rate. MoveTo(ship, command, Point(), Point(), 40., 0.1); else // This ship has no route to the parent's destination system, so protect it until it jumps away. KeepStation(ship, command, parent); } else KeepStation(ship, command, parent); } else if(parent.Commands().Has(Command::BOARD) && parent.GetTargetShip().get() == &ship) Stop(ship, command, .2); else KeepStation(ship, command, parent); } // Prefer your parent's target planet for refueling, but if it and your current // target planet can't fuel you, try to find one that can. void AI::Refuel(Ship &ship, Command &command) { const StellarObject *parentTarget = (ship.GetParent() ? ship.GetParent()->GetTargetStellar() : nullptr); if(CanRefuel(ship, parentTarget)) ship.SetTargetStellar(parentTarget); else if(!CanRefuel(ship, ship.GetTargetStellar())) ship.SetTargetStellar(FindLandingLocation(ship)); if(ship.GetTargetStellar()) { MoveToPlanet(ship, command); command |= Command::LAND; } } bool AI::CanRefuel(const Ship &ship, const StellarObject *target) { if(!target) return false; const Planet *planet = target->GetPlanet(); if(!planet) return false; if(!planet->IsInSystem(ship.GetSystem())) return false; if(!planet->HasFuelFor(ship)) return false; return true; } // Determine if a carried ship meets any of the criteria for returning to its parent. bool AI::ShouldDock(const Ship &ship, const Ship &parent, const System *playerSystem) const { // If your parent is disabled, you should not attempt to board it. // (Doing so during combat will likely lead to its destruction.) if(parent.IsDisabled()) return false; // A player-owned carried ship should return to its carrier when the player // has ordered it to "no longer deploy" or when it is not in the current system. // A non-player-owned carried ship should retreat if its parent is calling it back. if(ship.IsYours()) { if(!ship.HasDeployOrder() || ship.GetSystem() != playerSystem) return true; } else if(!parent.Commands().Has(Command::DEPLOY)) return true; // If a carried ship has repair abilities, avoid having it get stuck oscillating between // retreating and attacking when at exactly 50% health by adding hysteresis to the check. double minHealth = RETREAT_HEALTH + .25 + .25 * !ship.Commands().Has(Command::DEPLOY); if(ship.Health() < minHealth && (!ship.IsYours() || Preferences::Has("Damaged fighters retreat"))) return true; // If a fighter is armed with only ammo-using weapons, but no longer has the ammunition // needed to use them, it should dock if the parent can supply that ammo. auto requiredAmmo = set<const Outfit *>{}; for(const Hardpoint &hardpoint : ship.Weapons()) { const Weapon *weapon = hardpoint.GetOutfit(); if(weapon && !hardpoint.IsAntiMissile()) { const Outfit *ammo = weapon->Ammo(); if(!ammo || ship.OutfitCount(ammo)) { // This fighter has at least one usable weapon, and // thus does not need to dock to continue fighting. requiredAmmo.clear(); break; } else if(parent.OutfitCount(ammo)) requiredAmmo.insert(ammo); } } if(!requiredAmmo.empty()) return true; // If a carried ship has fuel capacity but is very low, it should return if // the parent can refuel it. double maxFuel = ship.Attributes().Get("fuel capacity"); if(maxFuel && ship.Fuel() < .005 && parent.JumpNavigation().JumpFuel() < parent.Fuel() * parent.Attributes().Get("fuel capacity") - maxFuel) return true; // NPC ships should always transfer cargo. Player ships should only // transfer cargo if the player has the AI preference set for it. if(!ship.IsYours() || Preferences::Has("Fighters transfer cargo")) { // If an out-of-combat carried ship is carrying a significant cargo // load and can transfer some of it to the parent, it should do so. bool hasEnemy = ship.GetTargetShip() && ship.GetTargetShip()->GetGovernment()->IsEnemy(ship.GetGovernment()); if(!hasEnemy && parent.Cargo().Free()) { const CargoHold &cargo = ship.Cargo(); // Mining ships only mine while they have 5 or more free space. While mining, carried ships // do not consider docking unless their parent is far from a targetable asteroid. if(!cargo.IsEmpty() && cargo.Size() && cargo.Free() < 5) return true; } } return false; } double AI::TurnBackward(const Ship &ship) { return TurnToward(ship, -ship.Velocity()); } // Determine the value to use in Command::SetTurn() to turn the ship towards the desired facing. // "precision" is an optional argument corresponding to a value of the dot product of the current and target facing // vectors above which no turning should be attempting, to reduce constant, minute corrections. double AI::TurnToward(const Ship &ship, const Point &vector, const double precision) { Point facing = ship.Facing().Unit(); double cross = vector.Cross(facing); double dot = vector.Dot(facing); if(dot > 0.) { // Is the facing direction aligned with the target direction with sufficient precision? // The maximum angle between the two directions is given by: arccos(sqrt(precision)). bool close = false; if(precision < 1. && precision > 0. && dot * dot >= precision * vector.LengthSquared()) close = true; double angle = asin(min(1., max(-1., cross / vector.Length()))) * TO_DEG; // Is the angle between the facing and target direction smaller than // the angle the ship can turn through in one step? if(fabs(angle) < ship.TurnRate()) { // If the ship is within one step of the target direction, // and the facing is already sufficiently aligned with the target direction, // don't turn any further. if(close) return 0.; return -angle / ship.TurnRate(); } } bool left = cross < 0.; return left - !left; } bool AI::MoveToPlanet(Ship &ship, Command &command) { if(!ship.GetTargetStellar()) return false; const Point &target = ship.GetTargetStellar()->Position(); return MoveTo(ship, command, target, Point(), ship.GetTargetStellar()->Radius(), 1.); } // Instead of moving to a point with a fixed location, move to a moving point (Ship = position + velocity) bool AI::MoveTo(Ship &ship, Command &command, const Point &targetPosition, const Point &targetVelocity, double radius, double slow) { const Point &position = ship.Position(); const Point &velocity = ship.Velocity(); const Angle &angle = ship.Facing(); Point dp = targetPosition - position; Point dv = targetVelocity - velocity; double speed = dv.Length(); bool isClose = (dp.Length() < radius); if(isClose && speed < slow) return true; bool shouldReverse = false; dp = targetPosition - StoppingPoint(ship, targetVelocity, shouldReverse); bool isFacing = (dp.Unit().Dot(angle.Unit()) > .95); if(!isClose || (!isFacing && !shouldReverse)) command.SetTurn(TurnToward(ship, dp)); if(isFacing) command |= Command::FORWARD; else if(shouldReverse) { command.SetTurn(TurnToward(ship, velocity)); command |= Command::BACK; } return false; } bool AI::Stop(Ship &ship, Command &command, double maxSpeed, const Point direction) { const Point &velocity = ship.Velocity(); const Angle &angle = ship.Facing(); double speed = velocity.Length(); // If asked for a complete stop, the ship needs to be going much slower. if(speed <= (maxSpeed ? maxSpeed : .001)) return true; if(!maxSpeed) command |= Command::STOP; // If you're moving slow enough that one frame of acceleration could bring // you to a stop, make sure you're pointed perfectly in the right direction. // This is a fudge factor for how straight you must be facing: it increases // from 0.8 when it will take many frames to stop, to nearly 1 when it will // take less than 1 frame to stop. double stopTime = speed / ship.Acceleration(); double limit = .8 + .2 / (1. + stopTime * stopTime * stopTime * .001); // If you have a reverse thruster, figure out whether using it is faster // than turning around and using your main thruster. if(ship.Attributes().Get("reverse thrust")) { // Figure out your stopping time using your main engine: double degreesToTurn = TO_DEG * acos(min(1., max(-1., -velocity.Unit().Dot(angle.Unit())))); double forwardTime = degreesToTurn / ship.TurnRate(); forwardTime += stopTime; // Figure out your reverse thruster stopping time: double reverseTime = (180. - degreesToTurn) / ship.TurnRate(); reverseTime += speed / ship.ReverseAcceleration(); // If you want to end up facing a specific direction, add the extra turning time. if(direction) { // Time to turn from facing backwards to target: double degreesFromBackwards = TO_DEG * acos(min(1., max(-1., direction.Unit().Dot(-velocity.Unit())))); double turnFromBackwardsTime = degreesFromBackwards / ship.TurnRate(); forwardTime += turnFromBackwardsTime; // Time to turn from facing forwards to target: double degreesFromForward = TO_DEG * acos(min(1., max(-1., direction.Unit().Dot(angle.Unit())))); double turnFromForwardTime = degreesFromForward / ship.TurnRate(); reverseTime += turnFromForwardTime; } if(reverseTime < forwardTime) { command.SetTurn(TurnToward(ship, velocity)); if(velocity.Unit().Dot(angle.Unit()) > limit) command |= Command::BACK; return false; } } command.SetTurn(TurnBackward(ship)); if(velocity.Unit().Dot(angle.Unit()) < -limit) command |= Command::FORWARD; return false; } void AI::PrepareForHyperspace(Ship &ship, Command &command) { bool hasHyperdrive = ship.JumpNavigation().HasHyperdrive(); double scramThreshold = ship.Attributes().Get("scram drive"); bool hasJumpDrive = ship.JumpNavigation().HasJumpDrive(); if(!hasHyperdrive && !hasJumpDrive) return; bool isJump = (ship.JumpNavigation().GetCheapestJumpType(ship.GetTargetSystem()).first == JumpType::JUMP_DRIVE); Point direction = ship.GetTargetSystem()->Position() - ship.GetSystem()->Position(); double departure = isJump ? ship.GetSystem()->JumpDepartureDistance() : ship.GetSystem()->HyperDepartureDistance(); double squaredDeparture = departure * departure + SAFETY_OFFSET; if(ship.Position().LengthSquared() < squaredDeparture) { Point closestDeparturePoint = ship.Position().Unit() * (departure + SAFETY_OFFSET); MoveTo(ship, command, closestDeparturePoint, Point(), 0., 0.); } else if(!isJump && scramThreshold) { direction = direction.Unit(); Point normal(-direction.Y(), direction.X()); double deviation = ship.Velocity().Dot(normal); if(fabs(deviation) > scramThreshold) { // Need to maneuver; not ready to jump if((ship.Facing().Unit().Dot(normal) < 0) == (deviation < 0)) // Thrusting from this angle is counterproductive direction = -deviation * normal; else { command |= Command::FORWARD; // How much correction will be applied to deviation by thrusting // as I turn back toward the jump direction. double turnRateRadians = ship.TurnRate() * TO_RAD; double cos = ship.Facing().Unit().Dot(direction); // integral(t*sin(r*x), angle/r, 0) = t/r * (1 - cos(angle)), so: double correctionWhileTurning = fabs(1 - cos) * ship.Acceleration() / turnRateRadians; // (Note that this will always underestimate because thrust happens before turn) if(fabs(deviation) - correctionWhileTurning > scramThreshold) // Want to thrust from an even sharper angle direction = -deviation * normal; } } command.SetTurn(TurnToward(ship, direction)); } // If we're a jump drive, just stop. else if(isJump) Stop(ship, command, ship.Attributes().Get("jump speed")); // Else stop in the fastest way to end facing in the right direction else if(Stop(ship, command, ship.Attributes().Get("jump speed"), direction)) command.SetTurn(TurnToward(ship, direction)); } void AI::CircleAround(Ship &ship, Command &command, const Body &target) { Point direction = target.Position() - ship.Position(); command.SetTurn(TurnToward(ship, direction)); double length = direction.Length(); if(length > 200. && ship.Facing().Unit().Dot(direction) >= 0.) { command |= Command::FORWARD; // If the ship is far away enough the ship should use the afterburner. if(length > 750. && ShouldUseAfterburner(ship)) command |= Command::AFTERBURNER; } } void AI::Swarm(Ship &ship, Command &command, const Body &target) { Point direction = target.Position() - ship.Position(); double maxSpeed = ship.MaxVelocity(); double rendezvousTime = RendezvousTime(direction, target.Velocity(), maxSpeed); if(std::isnan(rendezvousTime) || rendezvousTime > 600.) rendezvousTime = 600.; direction += rendezvousTime * target.Velocity(); MoveTo(ship, command, target.Position() + direction, .5 * maxSpeed * direction.Unit(), 50., 2.); } void AI::KeepStation(Ship &ship, Command &command, const Body &target) { // Constants: static const double MAX_TIME = 600.; static const double LEAD_TIME = 500.; static const double POSITION_DEADBAND = 200.; static const double VELOCITY_DEADBAND = 1.5; static const double TIME_DEADBAND = 120.; static const double THRUST_DEADBAND = .5; // Current properties of the two ships: double maxV = ship.MaxVelocity(); double accel = ship.Acceleration(); double turn = ship.TurnRate(); double mass = ship.InertialMass(); Point unit = ship.Facing().Unit(); double currentAngle = ship.Facing().Degrees(); // This is where we want to be relative to where we are now: Point velocityDelta = target.Velocity() - ship.Velocity(); Point positionDelta = target.Position() + LEAD_TIME * velocityDelta - ship.Position(); double positionSize = positionDelta.Length(); double positionWeight = positionSize / (positionSize + POSITION_DEADBAND); // This is how fast we want to be going relative to how fast we're going now: velocityDelta -= unit * VELOCITY_DEADBAND; double velocitySize = velocityDelta.Length(); double velocityWeight = velocitySize / (velocitySize + VELOCITY_DEADBAND); // Time it will take (roughly) to move to the target ship: double positionTime = RendezvousTime(positionDelta, target.Velocity(), maxV); if(std::isnan(positionTime) || positionTime > MAX_TIME) positionTime = MAX_TIME; Point rendezvous = positionDelta + target.Velocity() * positionTime; double positionAngle = Angle(rendezvous).Degrees(); positionTime += AngleDiff(currentAngle, positionAngle) / turn; positionTime += (rendezvous.Unit() * maxV - ship.Velocity()).Length() / accel; // If you are very close, stop trying to adjust: positionTime *= positionWeight * positionWeight; // Time it will take (roughly) to adjust your velocity to match the target: double velocityTime = velocityDelta.Length() / accel; double velocityAngle = Angle(velocityDelta).Degrees(); velocityTime += AngleDiff(currentAngle, velocityAngle) / turn; // If you are very close, stop trying to adjust: velocityTime *= velocityWeight * velocityWeight; // Focus on matching position or velocity depending on which will take longer. double totalTime = positionTime + velocityTime + TIME_DEADBAND; positionWeight = positionTime / totalTime; velocityWeight = velocityTime / totalTime; double facingWeight = TIME_DEADBAND / totalTime; // Determine the angle we want to face, interpolating smoothly between three options. Point facingGoal = rendezvous.Unit() * positionWeight + velocityDelta.Unit() * velocityWeight + target.Facing().Unit() * facingWeight; double targetAngle = Angle(facingGoal).Degrees() - currentAngle; if(abs(targetAngle) > 180.) targetAngle += (targetAngle < 0. ? 360. : -360.); // Avoid "turn jitter" when position & velocity are well-matched. bool changedDirection = (signbit(ship.Commands().Turn()) != signbit(targetAngle)); double targetTurn = abs(targetAngle / turn); double lastTurn = abs(ship.Commands().Turn()); if(lastTurn && (changedDirection || (lastTurn < 1. && targetTurn > lastTurn))) { // Keep the desired turn direction, but damp the per-frame turn rate increase. double dampedTurn = (changedDirection ? 0. : lastTurn) + min(.025, targetTurn); command.SetTurn(copysign(dampedTurn, targetAngle)); } else if(targetTurn < 1.) command.SetTurn(copysign(targetTurn, targetAngle)); else command.SetTurn(targetAngle); // Determine whether to apply thrust. Point drag = ship.Velocity() * ship.DragForce(); if(ship.Attributes().Get("reverse thrust")) { // Don't take drag into account when reverse thrusting, because this // estimate of how it will be applied can be quite inaccurate. Point a = (unit * (-ship.Attributes().Get("reverse thrust") / mass)).Unit(); double direction = positionWeight * positionDelta.Dot(a) / POSITION_DEADBAND + velocityWeight * velocityDelta.Dot(a) / VELOCITY_DEADBAND; if(direction > THRUST_DEADBAND) { command |= Command::BACK; return; } } Point a = (unit * accel - drag).Unit(); double direction = positionWeight * positionDelta.Dot(a) / POSITION_DEADBAND + velocityWeight * velocityDelta.Dot(a) / VELOCITY_DEADBAND; if(direction > THRUST_DEADBAND) command |= Command::FORWARD; } void AI::Attack(Ship &ship, Command &command, const Ship &target) { // Deploy any fighters you are carrying. if(!ship.IsYours() && ship.HasBays()) { command |= Command::DEPLOY; Deploy(ship, false); } // Ramming AI doesn't take weapon range or self-damage into account, instead opting to bum-rush the target. if(ship.GetPersonality().IsRamming()) { MoveToAttack(ship, command, target); return; } // Check if this ship is fast enough to keep distance from target. // Have a 10% minimum to avoid ships getting in a chase loop. const bool isAbleToRun = target.MaxVelocity() * SAFETY_MULTIPLIER < ship.MaxVelocity(); ShipAICache &shipAICache = ship.GetAICache(); const bool useArtilleryAI = shipAICache.IsArtilleryAI() && isAbleToRun; const double shortestRange = shipAICache.ShortestRange(); const double shortestArtillery = shipAICache.ShortestArtillery(); double minSafeDistance = isAbleToRun ? shipAICache.MinSafeDistance() : 0.; const double totalRadius = ship.Radius() + target.Radius(); const Point direction = target.Position() - ship.Position(); // Average distance from this ship's weapons to the enemy ship. const double weaponDistanceFromTarget = direction.Length() - totalRadius / 3.; // If this ship has mostly long-range weapons, or some weapons have a // blast radius, it should keep some distance instead of closing in. // If a weapon has blast radius, some leeway helps avoid getting hurt. if(minSafeDistance || (useArtilleryAI && shortestRange < weaponDistanceFromTarget)) { minSafeDistance = 1.25 * minSafeDistance + totalRadius; double approachSpeed = (ship.Velocity() - target.Velocity()).Dot(direction.Unit()); double slowdownDistance = 0.; // If this ship can use reverse thrusters, consider doing so. double reverseSpeed = ship.MaxReverseVelocity(); bool useReverse = reverseSpeed && (reverseSpeed >= min(target.MaxVelocity(), ship.MaxVelocity()) || target.Velocity().Dot(-direction.Unit()) <= reverseSpeed); slowdownDistance = approachSpeed * approachSpeed / (useReverse ? ship.ReverseAcceleration() : (ship.Acceleration() + 160. / ship.TurnRate())) / 2.; // If we're too close, run away. if(direction.Length() < max(minSafeDistance + max(slowdownDistance, 0.), useArtilleryAI * .75 * shortestArtillery)) { if(useReverse) { command.SetTurn(TurnToward(ship, direction)); if(ship.Facing().Unit().Dot(direction) >= 0.) command |= Command::BACK; } else { command.SetTurn(TurnToward(ship, -direction)); if(ship.Facing().Unit().Dot(direction) <= 0.) command |= Command::FORWARD; } } else { // This isn't perfect, but it works well enough. if((useArtilleryAI && (approachSpeed > 0. && weaponDistanceFromTarget < shortestArtillery * .9)) || weaponDistanceFromTarget < shortestRange * .75) AimToAttack(ship, command, target); else MoveToAttack(ship, command, target); } } // Fire if we can or move closer to use all weapons. else if(weaponDistanceFromTarget < shortestRange * .75) AimToAttack(ship, command, target); else MoveToAttack(ship, command, target); } void AI::AimToAttack(Ship &ship, Command &command, const Body &target) { command.SetTurn(TurnToward(ship, TargetAim(ship, target))); } void AI::MoveToAttack(Ship &ship, Command &command, const Body &target) { Point direction = target.Position() - ship.Position(); // First of all, aim in the direction that will hit this target. AimToAttack(ship, command, target); // Calculate this ship's "turning radius"; that is, the smallest circle it // can make while at its current speed. double stepsInFullTurn = 360. / ship.TurnRate(); double circumference = stepsInFullTurn * ship.Velocity().Length(); double diameter = max(200., circumference / PI); const auto facing = ship.Facing().Unit().Dot(direction.Unit()); // If the ship has reverse thrusters and the target is behind it, we can // use them to reach the target more quickly. if(facing < -.75 && ship.Attributes().Get("reverse thrust")) command |= Command::BACK; // This isn't perfect, but it works well enough. else if((facing >= 0. && direction.Length() > diameter) || (ship.Velocity().Dot(direction) < 0. && facing) >= .9) command |= Command::FORWARD; // Use an equipped afterburner if possible. if(command.Has(Command::FORWARD) && direction.Length() < 1000. && ShouldUseAfterburner(ship)) command |= Command::AFTERBURNER; } void AI::PickUp(Ship &ship, Command &command, const Body &target) { // Figure out the target's velocity relative to the ship. Point p = target.Position() - ship.Position(); Point v = target.Velocity() - ship.Velocity(); double vMax = ship.MaxVelocity(); // Estimate where the target will be by the time we reach it. double time = RendezvousTime(p, v, vMax); if(std::isnan(time)) time = p.Length() / vMax; double degreesToTurn = TO_DEG * acos(min(1., max(-1., p.Unit().Dot(ship.Facing().Unit())))); time += degreesToTurn / ship.TurnRate(); p += v * time; // Move toward the target. command.SetTurn(TurnToward(ship, p)); double dp = p.Unit().Dot(ship.Facing().Unit()); if(dp > .7) command |= Command::FORWARD; // Use the afterburner if it will not cause you to miss your target. double squareDistance = p.LengthSquared(); if(command.Has(Command::FORWARD) && ShouldUseAfterburner(ship)) if(dp > max(.9, min(.9999, 1. - squareDistance / 10000000.))) command |= Command::AFTERBURNER; } // Determine if using an afterburner does not use up reserve fuel, cause undue // energy strain, or undue thermal loads if almost overheated. bool AI::ShouldUseAfterburner(Ship &ship) { if(!ship.Attributes().Get("afterburner thrust")) return false; double fuel = ship.Fuel() * ship.Attributes().Get("fuel capacity"); double neededFuel = ship.Attributes().Get("afterburner fuel"); double energy = ship.Energy() * ship.Attributes().Get("energy capacity"); double neededEnergy = ship.Attributes().Get("afterburner energy"); if(energy == 0.) energy = ship.Attributes().Get("energy generation") + 0.2 * ship.Attributes().Get("solar collection") - ship.Attributes().Get("energy consumption"); double outputHeat = ship.Attributes().Get("afterburner heat") / (100 * ship.Mass()); if((!neededFuel || fuel - neededFuel > ship.JumpNavigation().JumpFuel()) && (!neededEnergy || neededEnergy / energy < 0.25) && (!outputHeat || ship.Heat() + outputHeat < .9)) return true; return false; } // "Appeasing" ships will dump cargo after being injured, if they are being targeted. void AI::DoAppeasing(const shared_ptr<Ship> &ship, double *threshold) const { double health = .5 * ship->Shields() + ship->Hull(); if(1. - health <= *threshold) return; const auto enemies = GetShipsList(*ship, true); if(none_of(enemies.begin(), enemies.end(), [&ship](const Ship *foe) noexcept -> bool { return !foe->IsDisabled() && foe->GetTargetShip() == ship; })) return; int toDump = 11 + (1. - health) * .5 * ship->Cargo().Size(); for(auto &&commodity : ship->Cargo().Commodities()) if(commodity.second && toDump > 0) { int dumped = min(commodity.second, toDump); ship->Jettison(commodity.first, dumped, true); toDump -= dumped; } Messages::Add(ship->GetGovernment()->GetName() + " " + ship->Noun() + " \"" + ship->Name() + "\": Please, just take my cargo and leave me alone.", Messages::Importance::Low); *threshold = (1. - health) + .1; } // Find a target ship to flock around at high speed. void AI::DoSwarming(Ship &ship, Command &command, shared_ptr<Ship> &target) { // Find a new ship to target on average every 10 seconds, or if the current target // is no longer eligible. If landing, release the old target so others can swarm it. if(ship.IsLanding() || !target || !CanSwarm(ship, *target) || !Random::Int(600)) { if(target) { // Allow another swarming ship to consider the target. auto sit = swarmCount.find(target.get()); if(sit != swarmCount.end() && sit->second > 0) --sit->second; // Release the current target. target.reset(); ship.SetTargetShip(target); } // If here just because we are about to land, do not seek a new target. if(ship.IsLanding()) return; int lowestCount = 7; // Consider swarming around non-hostile ships in the same system. const auto others = GetShipsList(ship, false); for(auto *other : others) if(!other->GetPersonality().IsSwarming()) { // Prefer to swarm ships that are not already being heavily swarmed. int count = swarmCount[other] + Random::Int(4); if(count < lowestCount) { target = other->shared_from_this(); lowestCount = count; } } ship.SetTargetShip(target); if(target) ++swarmCount[target.get()]; } // If a friendly ship to flock with was not found, return to an available planet. if(target) Swarm(ship, command, *target); else if(ship.Zoom() == 1.) Refuel(ship, command); } void AI::DoSurveillance(Ship &ship, Command &command, shared_ptr<Ship> &target) const { const bool isStaying = ship.GetPersonality().IsStaying(); // Since DoSurveillance is called after target-seeking and firing, if this // ship has a target, that target is guaranteed to be targetable. if(target && (target->GetSystem() != ship.GetSystem() || target->IsEnteringHyperspace())) { target.reset(); ship.SetTargetShip(target); } // If you have a hostile target, pursuing and destroying it has priority. if(target && ship.GetGovernment()->IsEnemy(target->GetGovernment())) { // Automatic aiming and firing already occurred. MoveIndependent(ship, command); return; } // Choose a surveillance behavior. if(ship.GetTargetSystem()) { // Unload surveillance drones in this system before leaving. if(!isStaying) { PrepareForHyperspace(ship, command); command |= Command::JUMP; } if(ship.HasBays()) { command |= Command::DEPLOY; Deploy(ship, false); } } else if(ship.GetTargetStellar()) { // Approach the planet and "land" on it (i.e. scan it). MoveToPlanet(ship, command); double atmosphereScan = ship.Attributes().Get("atmosphere scan"); double distance = ship.Position().Distance(ship.GetTargetStellar()->Position()); if(distance < atmosphereScan && !Random::Int(100)) ship.SetTargetStellar(nullptr); else if(!isStaying) command |= Command::LAND; } else if(target && target->IsTargetable()) { // Approach and scan the targeted, friendly ship's cargo or outfits. bool cargoScan = ship.Attributes().Get("cargo scan power"); bool outfitScan = ship.Attributes().Get("outfit scan power"); // If the pointer to the target ship exists, it is targetable and in-system. bool mustScanCargo = cargoScan && !Has(ship, target, ShipEvent::SCAN_CARGO); bool mustScanOutfits = outfitScan && !Has(ship, target, ShipEvent::SCAN_OUTFITS); if(!mustScanCargo && !mustScanOutfits) ship.SetTargetShip(shared_ptr<Ship>()); else { if(target->Velocity().Length() > ship.MaxVelocity() * 0.9) CircleAround(ship, command, *target); else MoveTo(ship, command, target->Position(), target->Velocity(), 1., 1.); command |= Command::SCAN; } } else { const System *system = ship.GetSystem(); const Government *gov = ship.GetGovernment(); // Consider scanning any non-hostile ship in this system that you haven't yet personally scanned. vector<Ship *> targetShips; bool cargoScan = ship.Attributes().Get("cargo scan power"); bool outfitScan = ship.Attributes().Get("outfit scan power"); if(cargoScan || outfitScan) for(const auto &grit : governmentRosters) { if(gov == grit.first || gov->IsEnemy(grit.first)) continue; for(const auto &it : grit.second) { auto ptr = it->shared_from_this(); if((!cargoScan || Has(ship, ptr, ShipEvent::SCAN_CARGO)) && (!outfitScan || Has(ship, ptr, ShipEvent::SCAN_OUTFITS))) continue; if(it->IsTargetable()) targetShips.emplace_back(it); } } // Consider scanning any planetary object in the system, if able. vector<const StellarObject *> targetPlanets; double atmosphereScan = ship.Attributes().Get("atmosphere scan"); if(atmosphereScan) for(const StellarObject &object : system->Objects()) if(object.HasSprite() && !object.IsStar() && !object.IsStation()) targetPlanets.push_back(&object); // If this ship can jump away, consider traveling to a nearby system. vector<const System *> targetSystems; // TODO: These ships cannot travel through wormholes? if(ship.JumpsRemaining(false)) { const auto &links = ship.JumpNavigation().HasJumpDrive() ? system->JumpNeighbors(ship.JumpNavigation().JumpRange()) : system->Links(); bool unrestricted = ship.GetPersonality().IsUnrestricted(); for(const System *link : links) if(unrestricted || !gov->IsRestrictedFrom(*link)) targetSystems.push_back(link); } unsigned total = targetShips.size() + targetPlanets.size() + targetSystems.size(); // If there is nothing for this ship to scan, have it patrol the entire system // instead of drifting or stopping. if(!total) { DoPatrol(ship, command); return; } unsigned index = Random::Int(total); if(index < targetShips.size()) ship.SetTargetShip(targetShips[index]->shared_from_this()); else { index -= targetShips.size(); if(index < targetPlanets.size()) ship.SetTargetStellar(targetPlanets[index]); else ship.SetTargetSystem(targetSystems[index - targetPlanets.size()]); } } } void AI::DoMining(Ship &ship, Command &command) { // This function is only called for ships that are in the player's system. // Update the radius that the ship is searching for asteroids at. bool isNew = !miningAngle.count(&ship); Angle &angle = miningAngle[&ship]; if(isNew) { angle = Angle::Random(); miningRadius[&ship] = ship.GetSystem()->AsteroidBeltRadius(); } angle += Angle::Random(1.) - Angle::Random(1.); double radius = miningRadius[&ship] * pow(2., angle.Unit().X()); shared_ptr<Minable> target = ship.GetTargetAsteroid(); if(!target || target->Velocity().Length() > ship.MaxVelocity()) { for(const shared_ptr<Minable> &minable : minables) { Point offset = minable->Position() - ship.Position(); // Target only nearby minables that are within 45deg of the current heading // and not moving faster than the ship can catch. if(offset.Length() < 800. && offset.Unit().Dot(ship.Facing().Unit()) > .7 && minable->Velocity().Dot(offset.Unit()) < ship.MaxVelocity()) { target = minable; ship.SetTargetAsteroid(target); break; } } } if(target) { // If the asteroid has moved well out of reach, stop tracking it. if(target->Position().Distance(ship.Position()) > 1600.) ship.SetTargetAsteroid(nullptr); else { MoveToAttack(ship, command, *target); AutoFire(ship, firingCommands, *target); return; } } Point heading = Angle(30.).Rotate(ship.Position().Unit() * radius) - ship.Position(); command.SetTurn(TurnToward(ship, heading)); if(ship.Velocity().Dot(heading.Unit()) < .7 * ship.MaxVelocity()) command |= Command::FORWARD; } bool AI::DoHarvesting(Ship &ship, Command &command) const { // If the ship has no target to pick up, do nothing. shared_ptr<Flotsam> target = ship.GetTargetFlotsam(); if(target && !ship.CanPickUp(*target)) { target.reset(); ship.SetTargetFlotsam(target); } if(!target) { // Only check for new targets every 10 frames, on average. if(Random::Int(10)) return false; // Don't chase anything that will take more than 10 seconds to reach. double bestTime = 600.; for(const shared_ptr<Flotsam> &it : flotsam) { if(!ship.CanPickUp(*it)) continue; // Only pick up flotsam that is nearby and that you are facing toward. Player escorts should // always attempt to pick up nearby flotsams when they are given a harvest order, and so ignore // the facing angle check. Point p = it->Position() - ship.Position(); double range = p.Length(); // Player ships do not have a restricted field of view so that they target flotsam behind them. if(range > 800. || (range > 100. && p.Unit().Dot(ship.Facing().Unit()) < .9 && !ship.IsYours())) continue; // Estimate how long it would take to intercept this flotsam. Point v = it->Velocity() - ship.Velocity(); double vMax = ship.MaxVelocity(); double time = RendezvousTime(p, v, vMax); if(std::isnan(time)) continue; double degreesToTurn = TO_DEG * acos(min(1., max(-1., p.Unit().Dot(ship.Facing().Unit())))); time += degreesToTurn / ship.TurnRate(); if(time < bestTime) { bestTime = time; target = it; } } if(!target) return false; ship.SetTargetFlotsam(target); } // Deploy any carried ships to improve maneuverability. if(ship.HasBays()) { command |= Command::DEPLOY; Deploy(ship, false); } PickUp(ship, command, *target); return true; } // Check if this ship should cloak. Returns true if this ship decided to run away while cloaking. bool AI::DoCloak(Ship &ship, Command &command) { if(ship.GetPersonality().IsDecloaked()) return false; const Outfit &attributes = ship.Attributes(); if(!attributes.Get("cloak")) return false; // Never cloak if it will cause you to be stranded. double fuelCost = attributes.Get("cloaking fuel") + attributes.Get("fuel consumption") - attributes.Get("fuel generation"); if(attributes.Get("cloaking fuel") && !attributes.Get("ramscoop")) { double fuel = ship.Fuel() * attributes.Get("fuel capacity"); int steps = ceil((1. - ship.Cloaking()) / attributes.Get("cloak")); // Only cloak if you will be able to fully cloak and also maintain it // for as long as it will take you to reach full cloak. fuel -= fuelCost * (1 + 2 * steps); if(fuel < ship.JumpNavigation().JumpFuel()) return false; } // If your parent has chosen to cloak, cloak and rendezvous with them. const shared_ptr<const Ship> &parent = ship.GetParent(); bool shouldCloakWithParent = false; if(parent && parent->GetGovernment() && parent->Commands().Has(Command::CLOAK) && parent->GetSystem() == ship.GetSystem()) { const Government *parentGovernment = parent->GetGovernment(); bool isPlayer = parentGovernment->IsPlayer(); if(isPlayer && ship.GetGovernment() == parentGovernment) shouldCloakWithParent = true; else if(isPlayer && ship.GetPersonality().IsEscort() && !ship.GetPersonality().IsUninterested()) shouldCloakWithParent = true; else if(!isPlayer && !parent->GetGovernment()->IsEnemy(ship.GetGovernment())) shouldCloakWithParent = true; } if(shouldCloakWithParent) { command |= Command::CLOAK; KeepStation(ship, command, *parent); return true; } // Otherwise, always cloak if you are in imminent danger. static const double MAX_RANGE = 10000.; double range = MAX_RANGE; const Ship *nearestEnemy = nullptr; // Find the nearest targetable, in-system enemy that could attack this ship. const auto enemies = GetShipsList(ship, true); for(const auto &foe : enemies) if(!foe->IsDisabled()) { double distance = ship.Position().Distance(foe->Position()); if(distance < range) { range = distance; nearestEnemy = foe; } } // If this ship has started cloaking, it must get at least 40% repaired // or 40% farther away before it begins decloaking again. double hysteresis = ship.Commands().Has(Command::CLOAK) ? .4 : 0.; // If cloaking costs nothing, and no one has asked you for help, cloak at will. // Player ships should never cloak automatically if they are not in danger. bool cloakFreely = (fuelCost <= 0.) && !ship.GetShipToAssist() && !ship.IsYours(); // If this ship is injured / repairing, it should cloak while under threat. bool cloakToRepair = (ship.Health() < RETREAT_HEALTH + hysteresis) && (attributes.Get("shield generation") || attributes.Get("hull repair rate")); if(cloakToRepair && (cloakFreely || range < 2000. * (1. + hysteresis))) { command |= Command::CLOAK; // Move away from the nearest enemy. if(nearestEnemy) { Point safety; // TODO: This could use an "Avoid" method, to account for other in-system hazards. // Simple approximation: move equally away from both the system center and the // nearest enemy, until the constrainment boundary is reached. if(ship.GetPersonality().IsUnconstrained() || !fenceCount.count(&ship)) safety = 2 * ship.Position().Unit() - nearestEnemy->Position().Unit(); else safety = -ship.Position().Unit(); safety *= ship.MaxVelocity(); MoveTo(ship, command, ship.Position() + safety, safety, 1., .8); return true; } } // Choose to cloak if there are no enemies nearby and cloaking is sensible. if(range == MAX_RANGE && cloakFreely && !ship.GetTargetShip()) command |= Command::CLOAK; return false; } void AI::DoPatrol(Ship &ship, Command &command) const { double radius = ship.GetSystem()->ExtraHyperArrivalDistance(); if(radius == 0.) radius = 500.; // The ship is outside of the effective range of the system, // so we turn it around. if(ship.Position().LengthSquared() > radius * radius) { // Allow ships to land after a while, otherwise they would continue to accumulate in the system. if(!ship.GetPersonality().IsStaying() && !Random::Int(10000)) { vector<const StellarObject *> landingTargets; for(const StellarObject &object : ship.GetSystem()->Objects()) if(object.HasSprite() && object.GetPlanet() && object.GetPlanet()->CanLand(ship)) landingTargets.push_back(&object); if(!landingTargets.empty()) { ship.SetTargetStellar(landingTargets[Random::Int(landingTargets.size())]); MoveToPlanet(ship, command); command |= Command::LAND; return; } } // Hacky way of differentiating ship behaviour without additional storage, // while keeping it consistent for each ship. TODO: change when Ship::SetTargetLocation exists. // This uses the pointer of the ship to choose a pseudo-random angle and instructs it to // patrol the system in a criss-crossing pattern, where each turn is this specific angle. intptr_t seed = reinterpret_cast<intptr_t>(&ship); int behaviour = abs(seed % 23); Angle delta = Angle(360. / (behaviour / 2. + 2.) * (behaviour % 2 ? -1. : 1.)); Angle target = Angle(ship.Position()) + delta; MoveTo(ship, command, target.Unit() * radius / 2, Point(), 10., 1.); } // Otherwise, keep going forward. else { const Point targetVelocity = ship.Facing().Unit() * (ship.MaxVelocity() + 1); const Point targetPosition = ship.Position() + targetVelocity; MoveTo(ship, command, targetPosition, targetVelocity, 10., 1.); } } void AI::DoScatter(Ship &ship, Command &command) { if(!command.Has(Command::FORWARD) && !command.Has(Command::BACK)) return; double flip = command.Has(Command::BACK) ? -1 : 1; double turnRate = ship.TurnRate(); double acceleration = ship.Acceleration(); // TODO: If there are many ships, use CollisionSet::Circle or another // suitable method to limit which ships are checked. for(const shared_ptr<Ship> &other : ships) { // Do not scatter away from yourself, or ships in other systems. if(other.get() == &ship || other->GetSystem() != ship.GetSystem()) continue; // Check for any ships that have nearly the same movement profile as // this ship and are in nearly the same location. Point offset = other->Position() - ship.Position(); if(offset.LengthSquared() > 400.) continue; if(fabs(other->TurnRate() / turnRate - 1.) > .05) continue; if(fabs(other->Acceleration() / acceleration - 1.) > .05) continue; // We are too close to this ship. Turn away from it if we aren't already facing away. if(fabs(other->Facing().Unit().Dot(ship.Facing().Unit())) > 0.99) // 0.99 => 8 degrees command.SetTurn(flip * offset.Cross(ship.Facing().Unit()) > 0. ? 1. : -1.); return; } } bool AI::DoSecretive(Ship &ship, Command &command) { shared_ptr<Ship> scanningShip; // Figure out if any ship is currently scanning us. If that is the case, move away from it. for(auto &otherShip : GetShipsList(ship, false)) if(!ship.GetGovernment()->Trusts(otherShip->GetGovernment()) && otherShip->Commands().Has(Command::SCAN) && otherShip->GetTargetShip() == ship.shared_from_this() && !otherShip->IsDisabled() && !otherShip->IsDestroyed()) scanningShip = make_shared<Ship>(*otherShip); if(scanningShip) { Point scanningPos = scanningShip->Position(); Point pos = ship.Position(); double cargoDistance = scanningShip->Attributes().Get("cargo scan power"); double outfitDistance = scanningShip->Attributes().Get("outfit scan power"); double maxScanRange = max(cargoDistance, outfitDistance); double distance = scanningPos.DistanceSquared(pos) * .0001; // If it can scan us we need to evade. if(distance < maxScanRange) { Point away; if(ship.GetPersonality().IsUnconstrained() || !fenceCount.count(&ship)) away = pos - scanningPos; else away = -pos; away *= ship.MaxVelocity(); MoveTo(ship, command, pos + away, away, 1., 1.); return true; } } return false; } // Instead of coming to a full stop, adjust to a target velocity vector Point AI::StoppingPoint(const Ship &ship, const Point &targetVelocity, bool &shouldReverse) { Point position = ship.Position(); Point velocity = ship.Velocity() - targetVelocity; Angle angle = ship.Facing(); double acceleration = ship.Acceleration(); double turnRate = ship.TurnRate(); shouldReverse = false; // If I were to turn around and stop now the relative movement, where would that put me? double v = velocity.Length(); if(!v) return position; // It makes no sense to calculate a stopping point for a ship entering hyperspace. if(ship.IsHyperspacing()) { if(ship.IsUsingJumpDrive() || ship.IsEnteringHyperspace()) return position; double maxVelocity = ship.MaxVelocity(); double jumpTime = (v - maxVelocity) / 2.; position += velocity.Unit() * (jumpTime * (v + maxVelocity) * .5); v = maxVelocity; } // This assumes you're facing exactly the wrong way. double degreesToTurn = TO_DEG * acos(min(1., max(-1., -velocity.Unit().Dot(angle.Unit())))); double stopDistance = v * (degreesToTurn / turnRate); // Sum of: v + (v - a) + (v - 2a) + ... + 0. // The number of terms will be v / a. // The average term's value will be v / 2. So: stopDistance += .5 * v * v / acceleration; if(ship.Attributes().Get("reverse thrust")) { // Figure out your reverse thruster stopping distance: double reverseAcceleration = ship.Attributes().Get("reverse thrust") / ship.InertialMass(); double reverseDistance = v * (180. - degreesToTurn) / turnRate; reverseDistance += .5 * v * v / reverseAcceleration; if(reverseDistance < stopDistance) { shouldReverse = true; stopDistance = reverseDistance; } } return position + stopDistance * velocity.Unit(); } // Get a vector giving the direction this ship should aim in in order to do // maximum damaged to a target at the given position with its non-turret, // non-homing weapons. If the ship has no non-homing weapons, this just // returns the direction to the target. Point AI::TargetAim(const Ship &ship) { shared_ptr<const Ship> target = ship.GetTargetShip(); if(target) return TargetAim(ship, *target); shared_ptr<const Minable> targetAsteroid = ship.GetTargetAsteroid(); if(targetAsteroid) return TargetAim(ship, *targetAsteroid); return Point(); } Point AI::TargetAim(const Ship &ship, const Body &target) { Point result; for(const Hardpoint &hardpoint : ship.Weapons()) { const Weapon *weapon = hardpoint.GetOutfit(); if(!weapon || hardpoint.IsHoming() || hardpoint.IsTurret()) continue; Point start = ship.Position() + ship.Facing().Rotate(hardpoint.GetPoint()); Point p = target.Position() - start + ship.GetPersonality().Confusion(); Point v = target.Velocity() - ship.Velocity(); double steps = RendezvousTime(p, v, weapon->WeightedVelocity() + .5 * weapon->RandomVelocity()); if(std::isnan(steps)) continue; steps = min(steps, weapon->TotalLifetime()); p += steps * v; double damage = weapon->ShieldDamage() + weapon->HullDamage(); result += p.Unit() * abs(damage); } return result ? result : target.Position() - ship.Position(); } // Aim the given ship's turrets. void AI::AimTurrets(const Ship &ship, FireCommand &command, bool opportunistic) const { // First, get the set of potential hostile ships. auto targets = vector<const Body *>(); const Ship *currentTarget = ship.GetTargetShip().get(); if(opportunistic || !currentTarget || !currentTarget->IsTargetable()) { // Find the maximum range of any of this ship's turrets. double maxRange = 0.; for(const Hardpoint &weapon : ship.Weapons()) if(weapon.CanAim()) maxRange = max(maxRange, weapon.GetOutfit()->Range()); // If this ship has no turrets, bail out. if(!maxRange) return; // Extend the weapon range slightly to account for velocity differences. maxRange *= 1.5; // Now, find all enemy ships within that radius. auto enemies = GetShipsList(ship, true, maxRange); // Convert the shared_ptr<Ship> into const Body *, to allow aiming turrets // at a targeted asteroid. Skip disabled ships, which pose no threat. for(auto &&foe : enemies) if(!foe->IsDisabled()) targets.emplace_back(foe); // Even if the ship's current target ship is beyond maxRange, // or is already disabled, consider aiming at it. if(currentTarget && currentTarget->IsTargetable() && find(targets.cbegin(), targets.cend(), currentTarget) == targets.cend()) targets.push_back(currentTarget); } else targets.push_back(currentTarget); // If this ship is mining, consider aiming at its target asteroid. if(ship.GetTargetAsteroid()) targets.push_back(ship.GetTargetAsteroid().get()); // If there are no targets to aim at, opportunistic turrets should sweep // back and forth at random, with the sweep centered on the "outward-facing" // angle. Focused turrets should just point forward. if(targets.empty() && !opportunistic) { for(const Hardpoint &hardpoint : ship.Weapons()) if(hardpoint.CanAim()) { // Get the index of this weapon. int index = &hardpoint - &ship.Weapons().front(); double offset = (hardpoint.HarmonizedAngle() - hardpoint.GetAngle()).Degrees(); command.SetAim(index, offset / hardpoint.GetOutfit()->TurretTurn()); } return; } if(targets.empty()) { for(const Hardpoint &hardpoint : ship.Weapons()) if(hardpoint.CanAim()) { // Get the index of this weapon. int index = &hardpoint - &ship.Weapons().front(); // First, check if this turret is currently in motion. If not, // it only has a small chance of beginning to move. double previous = ship.FiringCommands().Aim(index); if(!previous && (Random::Int(60))) continue; Angle centerAngle = Angle(hardpoint.GetPoint()); double bias = (centerAngle - hardpoint.GetAngle()).Degrees() / 180.; double acceleration = Random::Real() - Random::Real() + bias; command.SetAim(index, previous + .1 * acceleration); } return; } // Each hardpoint should aim at the target that it is "closest" to hitting. for(const Hardpoint &hardpoint : ship.Weapons()) if(hardpoint.CanAim()) { // This is where this projectile fires from. Add some randomness // based on how skilled the pilot is. Point start = ship.Position() + ship.Facing().Rotate(hardpoint.GetPoint()); start += ship.GetPersonality().Confusion(); // Get the turret's current facing, in absolute coordinates: Angle aim = ship.Facing() + hardpoint.GetAngle(); // Get this projectile's average velocity. const Weapon *weapon = hardpoint.GetOutfit(); double vp = weapon->WeightedVelocity() + .5 * weapon->RandomVelocity(); // Loop through each body this hardpoint could shoot at. Find the // one that is the "best" in terms of how many frames it will take // to aim at it and for a projectile to hit it. double bestScore = numeric_limits<double>::infinity(); double bestAngle = 0.; for(const Body *target : targets) { Point p = target->Position() - start; Point v = target->Velocity(); // Only take the ship's velocity into account if this weapon // does not have its own acceleration. if(!weapon->Acceleration()) v -= ship.Velocity(); // By the time this action is performed, the target will // have moved forward one time step. p += v; double rendezvousTime = numeric_limits<double>::quiet_NaN(); double distance = p.Length(); // Beam weapons hit instantaneously if they are in range. bool isInstantaneous = weapon->TotalLifetime() == 1.; if(isInstantaneous && distance < vp) rendezvousTime = 0.; else { // Find out how long it would take for this projectile to reach the target. if(!isInstantaneous) rendezvousTime = RendezvousTime(p, v, vp); // If there is no intersection (i.e. the turret is not facing the target), // consider this target "out-of-range" but still targetable. if(std::isnan(rendezvousTime)) rendezvousTime = max(distance / (vp ? vp : 1.), 2 * weapon->TotalLifetime()); // Determine where the target will be at that point. p += v * rendezvousTime; // All bodies within weapons range have the same basic // weight. Outside that range, give them lower priority. rendezvousTime = max(0., rendezvousTime - weapon->TotalLifetime()); } // Determine how much the turret must turn to face that vector. double degrees = (Angle(p) - aim).Degrees(); double turnTime = fabs(degrees) / weapon->TurretTurn(); // Always prefer targets that you are able to hit. double score = turnTime + (180. / weapon->TurretTurn()) * rendezvousTime; if(score < bestScore) { bestScore = score; bestAngle = degrees; } } if(bestAngle) { // Get the index of this weapon. int index = &hardpoint - &ship.Weapons().front(); command.SetAim(index, bestAngle / weapon->TurretTurn()); } } } // Fire whichever of the given ship's weapons can hit a hostile target. void AI::AutoFire(const Ship &ship, FireCommand &command, bool secondary, bool isFlagship) const { const Personality &person = ship.GetPersonality(); if(person.IsPacifist() || ship.CannotAct()) return; bool beFrugal = (ship.IsYours() && !escortsUseAmmo); if(person.IsFrugal() || (ship.IsYours() && escortsAreFrugal && escortsUseAmmo)) { // The frugal personality is only active when ships have more than a certain fraction of their total health, // and are not outgunned. The default threshold is 75%. beFrugal = (ship.Health() > GameData::GetGamerules().UniversalFrugalThreshold()); if(beFrugal) { auto ait = allyStrength.find(ship.GetGovernment()); auto eit = enemyStrength.find(ship.GetGovernment()); if(ait != allyStrength.end() && eit != enemyStrength.end() && ait->second < eit->second) beFrugal = false; } } // Special case: your target is not your enemy. Do not fire, because you do // not want to risk damaging that target. Ships will target friendly ships // while assisting and performing surveillance. shared_ptr<Ship> currentTarget = ship.GetTargetShip(); const Government *gov = ship.GetGovernment(); bool friendlyOverride = false; bool disabledOverride = false; if(ship.IsYours()) { auto it = orders.find(&ship); if(it != orders.end() && it->second.target.lock() == currentTarget) { disabledOverride = (it->second.type == Orders::FINISH_OFF); friendlyOverride = disabledOverride | (it->second.type == Orders::ATTACK); } } bool currentIsEnemy = currentTarget && currentTarget->GetGovernment()->IsEnemy(gov) && currentTarget->GetSystem() == ship.GetSystem(); if(currentTarget && !(currentIsEnemy || friendlyOverride)) currentTarget.reset(); // Only fire on disabled targets if you don't want to plunder them. bool plunders = (person.Plunders() && ship.Cargo().Free()); bool disables = person.Disables(); // Don't use weapons with firing force if you are preparing to jump. bool isWaitingToJump = ship.Commands().Has(Command::JUMP | Command::WAIT); // Find the longest range of any of your non-homing weapons. Homing weapons // that don't consume ammo may also fire in non-homing mode. double maxRange = 0.; for(const Hardpoint &weapon : ship.Weapons()) if(weapon.IsReady() && !(!currentTarget && weapon.IsHoming() && weapon.GetOutfit()->Ammo()) && !(!secondary && weapon.GetOutfit()->Icon()) && !(beFrugal && weapon.GetOutfit()->Ammo()) && !(isWaitingToJump && weapon.GetOutfit()->FiringForce())) maxRange = max(maxRange, weapon.GetOutfit()->Range()); // Extend the weapon range slightly to account for velocity differences. maxRange *= 1.5; // Find all enemy ships within range of at least one weapon. auto enemies = GetShipsList(ship, true, maxRange); // Consider the current target if it is not already considered (i.e. it // is a friendly ship and this is a player ship ordered to attack it). if(currentTarget && currentTarget->IsTargetable() && find(enemies.cbegin(), enemies.cend(), currentTarget.get()) == enemies.cend()) enemies.push_back(currentTarget.get()); int index = -1; for(const Hardpoint &hardpoint : ship.Weapons()) { ++index; // Skip weapons that are not ready to fire. if(!hardpoint.IsReady()) continue; // Skip weapons omitted by the "Automatic firing" preference. if(isFlagship) { const Preferences::AutoFire autoFireMode = Preferences::GetAutoFire(); if(autoFireMode == Preferences::AutoFire::GUNS_ONLY && hardpoint.IsTurret()) continue; if(autoFireMode == Preferences::AutoFire::TURRETS_ONLY && !hardpoint.IsTurret()) continue; } const Weapon *weapon = hardpoint.GetOutfit(); // Don't expend ammo for homing weapons that have no target selected. if(!currentTarget && weapon->Homing() && weapon->Ammo()) continue; // Don't fire secondary weapons if told not to. if(!secondary && weapon->Icon()) continue; // Don't expend ammo if trying to be frugal. if(beFrugal && weapon->Ammo()) continue; // Don't use weapons with firing force if you are preparing to jump. if(isWaitingToJump && weapon->FiringForce()) continue; // Special case: if the weapon uses fuel, be careful not to spend so much // fuel that you cannot leave the system if necessary. if(weapon->FiringFuel()) { double fuel = ship.Fuel() * ship.Attributes().Get("fuel capacity"); fuel -= weapon->FiringFuel(); // If the ship is not ever leaving this system, it does not need to // reserve any fuel. bool isStaying = person.IsStaying(); if(!secondary || fuel < (isStaying ? 0. : ship.JumpNavigation().JumpFuel())) continue; } // Figure out where this weapon will fire from, but add some randomness // depending on how accurate this ship's pilot is. Point start = ship.Position() + ship.Facing().Rotate(hardpoint.GetPoint()); start += person.Confusion(); double vp = weapon->WeightedVelocity() + .5 * weapon->RandomVelocity(); double lifetime = weapon->TotalLifetime(); // Homing weapons revert to "dumb firing" if they have no target. if(weapon->Homing() && currentTarget) { // NPCs shoot ships that they just plundered. bool hasBoarded = !ship.IsYours() && Has(ship, currentTarget, ShipEvent::BOARD); if(currentTarget->IsDisabled() && (disables || (plunders && !hasBoarded)) && !disabledOverride) continue; // Don't fire secondary weapons at targets that have started jumping. if(weapon->Icon() && currentTarget->IsEnteringHyperspace()) continue; // For homing weapons, don't take the velocity of the ship firing it // into account, because the projectile will settle into a velocity // that depends on its own acceleration and drag. Point p = currentTarget->Position() - start; Point v = currentTarget->Velocity(); // By the time this action is performed, the ships will have moved // forward one time step. p += v; // If this weapon has a blast radius, don't fire it if the target is // so close that you'll be hit by the blast. Weapons using proximity // triggers will explode sooner, so a larger separation is needed. if(!weapon->IsSafe() && p.Length() <= (weapon->BlastRadius() + weapon->TriggerRadius())) continue; // Calculate how long it will take the projectile to reach its target. double steps = RendezvousTime(p, v, vp); if(!std::isnan(steps) && steps <= lifetime) { command.SetFire(index); continue; } continue; } // For non-homing weapons: for(const auto &target : enemies) { // NPCs shoot ships that they just plundered. bool hasBoarded = !ship.IsYours() && Has(ship, target->shared_from_this(), ShipEvent::BOARD); if(target->IsDisabled() && (disables || (plunders && !hasBoarded)) && !disabledOverride) continue; // Merciful ships let fleeing ships go. if(target->IsFleeing() && person.IsMerciful()) continue; Point p = target->Position() - start; Point v = target->Velocity(); // Only take the ship's velocity into account if this weapon // does not have its own acceleration. if(!weapon->Acceleration()) v -= ship.Velocity(); // By the time this action is performed, the ships will have moved // forward one time step. p += v; // Non-homing weapons may have a blast radius or proximity trigger. // Do not fire this weapon if we will be caught in the blast. if(!weapon->IsSafe() && p.Length() <= (weapon->BlastRadius() + weapon->TriggerRadius())) continue; // Get the vector the weapon will travel along. v = (ship.Facing() + hardpoint.GetAngle()).Unit() * vp - v; // Extrapolate over the lifetime of the projectile. v *= lifetime; const Mask &mask = target->GetMask(step); if(mask.Collide(-p, v, target->Facing()) < 1.) { command.SetFire(index); break; } } } } void AI::AutoFire(const Ship &ship, FireCommand &command, const Body &target) const { int index = -1; for(const Hardpoint &hardpoint : ship.Weapons()) { ++index; // Only auto-fire primary weapons that take no ammunition. if(!hardpoint.IsReady() || hardpoint.GetOutfit()->Icon() || hardpoint.GetOutfit()->Ammo()) continue; // Figure out where this weapon will fire from, but add some randomness // depending on how accurate this ship's pilot is. Point start = ship.Position() + ship.Facing().Rotate(hardpoint.GetPoint()); start += ship.GetPersonality().Confusion(); const Weapon *weapon = hardpoint.GetOutfit(); double vp = weapon->WeightedVelocity() + .5 * weapon->RandomVelocity(); double lifetime = weapon->TotalLifetime(); Point p = target.Position() - start; Point v = target.Velocity(); // Only take the ship's velocity into account if this weapon // does not have its own acceleration. if(!weapon->Acceleration()) v -= ship.Velocity(); // By the time this action is performed, the ships will have moved // forward one time step. p += v; // Get the vector the weapon will travel along. v = (ship.Facing() + hardpoint.GetAngle()).Unit() * vp - v; // Extrapolate over the lifetime of the projectile. v *= lifetime; const Mask &mask = target.GetMask(step); if(mask.Collide(-p, v, target.Facing()) < 1.) command.SetFire(index); } } // Get the amount of time it would take the given weapon to reach the given // target, assuming it can be fired in any direction (i.e. turreted). For // non-turreted weapons this can be used to calculate the ideal direction to // point the ship in. double AI::RendezvousTime(const Point &p, const Point &v, double vp) { // How many steps will it take this projectile // to intersect the target? // (p.x + v.x*t)^2 + (p.y + v.y*t)^2 = vp^2*t^2 // p.x^2 + 2*p.x*v.x*t + v.x^2*t^2 // + p.y^2 + 2*p.y*v.y*t + v.y^2t^2 // - vp^2*t^2 = 0 // (v.x^2 + v.y^2 - vp^2) * t^2 // + (2 * (p.x * v.x + p.y * v.y)) * t // + (p.x^2 + p.y^2) = 0 double a = v.Dot(v) - vp * vp; double b = 2. * p.Dot(v); double c = p.Dot(p); double discriminant = b * b - 4 * a * c; if(discriminant < 0.) return numeric_limits<double>::quiet_NaN(); discriminant = sqrt(discriminant); // The solutions are b +- discriminant. // But it's not a solution if it's negative. double r1 = (-b + discriminant) / (2. * a); double r2 = (-b - discriminant) / (2. * a); if(r1 >= 0. && r2 >= 0.) return min(r1, r2); else if(r1 >= 0. || r2 >= 0.) return max(r1, r2); return numeric_limits<double>::quiet_NaN(); } // Searches every asteroid within the ship scan limit and returns either the // asteroid closest to the ship or the asteroid of highest value in range, depending // on the player's preferences. bool AI::TargetMinable(Ship &ship) const { double scanRangeMetric = 10000. * ship.Attributes().Get("asteroid scan power"); if(!scanRangeMetric) return false; const bool findClosest = Preferences::Has("Target asteroid based on"); auto bestMinable = ship.GetTargetAsteroid(); double bestScore = findClosest ? numeric_limits<double>::max() : 0.; auto GetDistanceMetric = [&ship](const Minable &minable) -> double { return ship.Position().DistanceSquared(minable.Position()); }; if(bestMinable) { if(findClosest) bestScore = GetDistanceMetric(*bestMinable); else bestScore = bestMinable->GetValue(); } auto MinableStrategy = [&findClosest, &bestMinable, &bestScore, &GetDistanceMetric]() -> function<void(const shared_ptr<Minable> &)> { if(findClosest) return [&bestMinable, &bestScore, &GetDistanceMetric] (const shared_ptr<Minable> &minable) -> void { double newScore = GetDistanceMetric(*minable); if(newScore < bestScore || (newScore == bestScore && minable->GetValue() > bestMinable->GetValue())) { bestScore = newScore; bestMinable = minable; } }; else return [&bestMinable, &bestScore, &GetDistanceMetric] (const shared_ptr<Minable> &minable) -> void { double newScore = minable->GetValue(); if(newScore > bestScore || (newScore == bestScore && GetDistanceMetric(*minable) < GetDistanceMetric(*bestMinable))) { bestScore = newScore; bestMinable = minable; } }; }; auto UpdateBestMinable = MinableStrategy(); for(auto &&minable : minables) { if(GetDistanceMetric(*minable) > scanRangeMetric) continue; if(bestMinable) UpdateBestMinable(minable); else bestMinable = minable; } if(bestMinable) ship.SetTargetAsteroid(bestMinable); return static_cast<bool>(ship.GetTargetAsteroid()); } void AI::MovePlayer(Ship &ship, const PlayerInfo &player, Command &activeCommands) { Command command; firingCommands.SetHardpoints(ship.Weapons().size()); bool shift = activeCommands.Has(Command::SHIFT); bool isWormhole = false; if(player.HasTravelPlan()) { // Determine if the player is jumping to their target system or landing on a wormhole. const System *system = player.TravelPlan().back(); for(const StellarObject &object : ship.GetSystem()->Objects()) if(object.HasSprite() && object.HasValidPlanet() && object.GetPlanet()->IsWormhole() && object.GetPlanet()->IsAccessible(&ship) && player.HasVisited(*object.GetPlanet()) && player.HasVisited(*system)) { const auto *wormhole = object.GetPlanet()->GetWormhole(); if(&wormhole->WormholeDestination(*ship.GetSystem()) != system) continue; isWormhole = true; if(!ship.GetTargetStellar() || autoPilot.Has(Command::JUMP)) ship.SetTargetStellar(&object); break; } if(!isWormhole) ship.SetTargetSystem(system); } if(ship.IsEnteringHyperspace() && !ship.IsHyperspacing()) { // Check if there's a particular planet there we want to visit. const System *system = ship.GetTargetSystem(); set<const Planet *> destinations; Date deadline; const Planet *bestDestination = nullptr; size_t missions = 0; for(const Mission &mission : player.Missions()) { // Don't include invisible missions in the check. if(!mission.IsVisible()) continue; // If the accessible destination of a mission is in this system, and you've been // to all waypoints and stopovers (i.e. could complete it), consider landing on it. if(mission.Stopovers().empty() && mission.Waypoints().empty() && mission.Destination()->IsInSystem(system) && mission.Destination()->IsAccessible(&ship)) { destinations.insert(mission.Destination()); ++missions; // If this mission has a deadline, check if it is the soonest // deadline. If so, this should be your ship's destination. if(!deadline || (mission.Deadline() && mission.Deadline() < deadline)) { deadline = mission.Deadline(); bestDestination = mission.Destination(); } } // Also check for stopovers in the destination system. for(const Planet *planet : mission.Stopovers()) if(planet->IsInSystem(system) && planet->IsAccessible(&ship)) { destinations.insert(planet); ++missions; if(!bestDestination) bestDestination = planet; } } // Inform the player of any destinations in the system they are jumping to. if(!destinations.empty()) { string message = "Note: you have "; message += (missions == 1 ? "a mission that requires" : "missions that require"); message += " landing on "; size_t count = destinations.size(); bool oxfordComma = (count > 2); for(const Planet *planet : destinations) { message += planet->Name(); --count; if(count > 1) message += ", "; else if(count == 1) message += (oxfordComma ? ", and " : " and "); } message += " in the system you are jumping to."; Messages::Add(message, Messages::Importance::Info); } // If any destination was found, find the corresponding stellar object // and set it as your ship's target planet. if(bestDestination) ship.SetTargetStellar(system->FindStellar(bestDestination)); } if(activeCommands.Has(Command::NEAREST)) { // Find the nearest enemy ship to the flagship. If `Shift` is held, consider friendly ships too. double closest = numeric_limits<double>::infinity(); bool foundActive = false; bool found = false; for(const shared_ptr<Ship> &other : ships) if(other.get() != &ship && other->IsTargetable()) { bool enemy = other->GetGovernment()->IsEnemy(ship.GetGovernment()); // Do not let "target nearest" select a friendly ship, so that // if the player is repeatedly targeting nearest to, say, target // a bunch of fighters, they won't start firing on friendly // ships as soon as the last one is gone. if((!enemy && !shift) || other->IsYours()) continue; // Sort ships by active or disabled: // Prefer targeting an active ship over a disabled one bool active = !other->IsDisabled(); double d = other->Position().Distance(ship.Position()); if((!foundActive && active) || (foundActive == active && d < closest)) { ship.SetTargetShip(other); closest = d; foundActive = active; found = true; } } // If no ship was found, look for nearby asteroids. if(!found) TargetMinable(ship); } else if(activeCommands.Has(Command::TARGET)) { // Find the "next" ship to target. Holding `Shift` will cycle through escorts. shared_ptr<const Ship> target = ship.GetTargetShip(); // Whether the next eligible ship should be targeted. bool selectNext = !target || !target->IsTargetable(); for(const shared_ptr<Ship> &other : ships) { // Do not target yourself. if(other.get() == &ship) continue; // The default behavior is to ignore your fleet and any friendly escorts. bool isPlayer = other->IsYours() || (other->GetPersonality().IsEscort() && !other->GetGovernment()->IsEnemy()); if(other == target) selectNext = true; else if(selectNext && isPlayer == shift && other->IsTargetable()) { ship.SetTargetShip(other); selectNext = false; break; } } if(selectNext) ship.SetTargetShip(shared_ptr<Ship>()); } else if(activeCommands.Has(Command::BOARD)) { // Determine the player's boarding target based on their current target and their boarding preference. They may // press BOARD repeatedly to cycle between ships, or use SHIFT to prioritize repairing their owned escorts. shared_ptr<Ship> target = ship.GetTargetShip(); if(target && !CanBoard(ship, *target)) target.reset(); if(!target || activeCommands.Has(Command::WAIT) || (shift && !target->IsYours())) { if(shift) ship.SetTargetShip(shared_ptr<Ship>()); const auto boardingPriority = Preferences::GetBoardingPriority(); auto strategy = [&]() noexcept -> function<double(const Ship &)> { Point current = ship.Position(); switch(boardingPriority) { case Preferences::BoardingPriority::VALUE: return [this, &ship](const Ship &other) noexcept -> double { // Use the exact cost if the ship was scanned, otherwise use an estimation. return this->Has(ship, other.shared_from_this(), ShipEvent::SCAN_OUTFITS) ? other.Cost() : (other.ChassisCost() * 2.); }; case Preferences::BoardingPriority::MIXED: return [this, &ship, current](const Ship &other) noexcept -> double { double cost = this->Has(ship, other.shared_from_this(), ShipEvent::SCAN_OUTFITS) ? other.Cost() : (other.ChassisCost() * 2.); // Even if we divide by 0, doubles can contain and handle infinity, // and we should definitely board that one then. return cost * cost / (current.DistanceSquared(other.Position()) + 0.1); }; case Preferences::BoardingPriority::PROXIMITY: default: return [current](const Ship &other) noexcept -> double { return current.DistanceSquared(other.Position()); }; } }(); using ShipValue = pair<Ship *, double>; auto options = vector<ShipValue>{}; if(shift) { const auto &owned = governmentRosters[ship.GetGovernment()]; options.reserve(owned.size()); for(auto &&escort : owned) if(CanBoard(ship, *escort)) options.emplace_back(escort, strategy(*escort)); } else { auto ships = GetShipsList(ship, true); options.reserve(ships.size()); // The current target is not considered by GetShipsList. if(target) options.emplace_back(target.get(), strategy(*target)); // First check if we can board enemy ships, then allies. for(auto &&enemy : ships) if(CanBoard(ship, *enemy)) options.emplace_back(enemy, strategy(*enemy)); if(options.empty()) { ships = GetShipsList(ship, false); options.reserve(ships.size()); for(auto &&ally : ships) if(CanBoard(ship, *ally)) options.emplace_back(ally, strategy(*ally)); } } if(options.empty()) activeCommands.Clear(Command::BOARD); else { // Sort the list of options in increasing order of desirability. sort(options.begin(), options.end(), [&ship, boardingPriority](const ShipValue &lhs, const ShipValue &rhs) { if(boardingPriority == Preferences::BoardingPriority::PROXIMITY) return lhs.second > rhs.second; // If their cost is the same, prefer the closest ship. return (boardingPriority == Preferences::BoardingPriority::VALUE && lhs.second == rhs.second) ? lhs.first->Position().DistanceSquared(ship.Position()) > rhs.first->Position().DistanceSquared(ship.Position()) : lhs.second < rhs.second; } ); // Pick the (next) most desirable option. auto it = !target ? options.end() : find_if(options.begin(), options.end(), [&target](const ShipValue &lhs) noexcept -> bool { return lhs.first == target.get(); }); if(it == options.begin()) it = options.end(); ship.SetTargetShip((--it)->first->shared_from_this()); } } } // Player cannot attempt to land while departing from a planet. else if(activeCommands.Has(Command::LAND) && !ship.IsEnteringHyperspace() && ship.Zoom() == 1.) { // Track all possible landable objects in the current system. auto landables = vector<const StellarObject *>{}; string message; const bool isMovingSlowly = (ship.Velocity().Length() < (MIN_LANDING_VELOCITY / 60.)); const StellarObject *potentialTarget = nullptr; for(const StellarObject &object : ship.GetSystem()->Objects()) { if(!object.HasSprite()) continue; // If the player is moving slowly over an object, then the player is considering landing there. // The target object might not be able to be landed on, for example an enemy planet or a star. const bool isTryingLanding = (ship.Position().Distance(object.Position()) < object.Radius() && isMovingSlowly); if(object.HasValidPlanet() && object.GetPlanet()->IsAccessible(&ship)) { landables.emplace_back(&object); if(isTryingLanding) potentialTarget = &object; } else if(isTryingLanding) message = object.LandingMessage(); } const StellarObject *target = ship.GetTargetStellar(); // Require that the player's planetary target is one of the current system's planets. auto landIt = find(landables.cbegin(), landables.cend(), target); if(landIt == landables.cend()) target = nullptr; // Consider the potential target as a landing target first. if(!target && potentialTarget) { target = potentialTarget; ship.SetTargetStellar(potentialTarget); } // If the player has a target in mind already, don't emit an error if the player // is hovering above a star or inaccessible planet. if(target) message.clear(); else if(!message.empty()) Audio::Play(Audio::Get("fail")); Messages::Importance messageImportance = Messages::Importance::High; if(target && (ship.Zoom() < 1. || ship.Position().Distance(target->Position()) < target->Radius())) { // Special case: if there are two planets in system and you have one // selected, then press "land" again, do not toggle to the other if // you are within landing range of the one you have selected. } else if(message.empty() && target && activeCommands.Has(Command::WAIT)) { // Select the next landable in the list after the currently selected object. if(++landIt == landables.cend()) landIt = landables.cbegin(); const StellarObject *next = *landIt; ship.SetTargetStellar(next); if(!next->GetPlanet()->CanLand()) { message = "The authorities on this " + next->GetPlanet()->Noun() + " refuse to clear you to land here."; messageImportance = Messages::Importance::Highest; Audio::Play(Audio::Get("fail")); } else if(next != target) message = "Switching landing targets. Now landing on " + next->Name() + "."; } else if(message.empty()) { // This is the first press, or it has been long enough since the last press, // so land on the nearest eligible planet. Prefer inhabited ones with fuel. set<string> types; if(!target && !landables.empty()) { if(landables.size() == 1) ship.SetTargetStellar(landables.front()); else { double closest = numeric_limits<double>::infinity(); for(const auto &object : landables) { double distance = ship.Position().Distance(object->Position()); const Planet *planet = object->GetPlanet(); types.insert(planet->Noun()); if((!planet->CanLand() || !planet->GetPort().CanRecharge(Port::RechargeType::Fuel)) && !planet->IsWormhole()) distance += 10000.; if(distance < closest) { ship.SetTargetStellar(object); closest = distance; } } } target = ship.GetTargetStellar(); } if(!target) { message = "There are no planets in this system that you can land on."; messageImportance = Messages::Importance::Highest; Audio::Play(Audio::Get("fail")); } else if(!target->GetPlanet()->CanLand()) { message = "The authorities on this " + target->GetPlanet()->Noun() + " refuse to clear you to land here."; messageImportance = Messages::Importance::Highest; Audio::Play(Audio::Get("fail")); } else if(!types.empty()) { message = "You can land on more than one "; set<string>::const_iterator it = types.begin(); message += *it++; if(it != types.end()) { set<string>::const_iterator last = --types.end(); if(it != last) message += ','; while(it != last) message += ' ' + *it++ + ','; message += " or " + *it; } message += " in this system. Landing on " + target->Name() + "."; } else message = "Landing on " + target->Name() + "."; } if(!message.empty()) Messages::Add(message, messageImportance); } else if(activeCommands.Has(Command::JUMP | Command::FLEET_JUMP)) { if(player.TravelPlan().empty() && !isWormhole) { double bestMatch = -2.; const auto &links = (ship.JumpNavigation().HasJumpDrive() ? ship.GetSystem()->JumpNeighbors(ship.JumpNavigation().JumpRange()) : ship.GetSystem()->Links()); for(const System *link : links) { // Not all systems in range are necessarily visible. Don't allow // jumping to systems which haven't been seen. if(!player.HasSeen(*link)) continue; Point direction = link->Position() - ship.GetSystem()->Position(); double match = ship.Facing().Unit().Dot(direction.Unit()); if(match > bestMatch) { bestMatch = match; ship.SetTargetSystem(link); } } } else if(isWormhole) { // The player is guaranteed to have a travel plan for isWormhole to be true. Messages::Add("Landing on a local wormhole to navigate to the " + player.TravelPlan().back()->Name() + " system.", Messages::Importance::High); } if(ship.GetTargetSystem() && !isWormhole) { string name = "selected star"; if(player.KnowsName(*ship.GetTargetSystem())) name = ship.GetTargetSystem()->Name(); if(activeCommands.Has(Command::FLEET_JUMP)) Messages::Add("Engaging fleet autopilot to jump to the " + name + " system." " Your fleet will jump when ready.", Messages::Importance::High); else Messages::Add("Engaging autopilot to jump to the " + name + " system.", Messages::Importance::High); } } else if(activeCommands.Has(Command::SCAN)) command |= Command::SCAN; else if(activeCommands.Has(Command::HARVEST)) { Orders newOrders; newOrders.type = Orders::HARVEST; IssueOrders(player, newOrders, "preparing to harvest."); } else if(activeCommands.Has(Command::NEAREST_ASTEROID)) { TargetMinable(ship); } const shared_ptr<const Ship> target = ship.GetTargetShip(); AimTurrets(ship, firingCommands, !Preferences::Has("Turrets focus fire")); if(Preferences::GetAutoFire() != Preferences::AutoFire::OFF && !ship.IsBoarding() && !(autoPilot | activeCommands).Has(Command::LAND | Command::JUMP | Command::FLEET_JUMP | Command::BOARD) && (!target || target->GetGovernment()->IsEnemy())) AutoFire(ship, firingCommands, false, true); const bool mouseTurning = activeCommands.Has(Command::MOUSE_TURNING_HOLD); if(mouseTurning && !ship.IsBoarding() && !ship.IsReversing()) command.SetTurn(TurnToward(ship, mousePosition)); if(activeCommands) { if(activeCommands.Has(Command::FORWARD)) command |= Command::FORWARD; if(activeCommands.Has(Command::RIGHT | Command::LEFT) && !mouseTurning) command.SetTurn(activeCommands.Has(Command::RIGHT) - activeCommands.Has(Command::LEFT)); if(activeCommands.Has(Command::BACK)) { if(!activeCommands.Has(Command::FORWARD) && ship.Attributes().Get("reverse thrust")) command |= Command::BACK; else if(!activeCommands.Has(Command::RIGHT | Command::LEFT | Command::AUTOSTEER)) command.SetTurn(TurnBackward(ship)); } if(activeCommands.Has(Command::PRIMARY)) { int index = 0; for(const Hardpoint &hardpoint : ship.Weapons()) { if(hardpoint.IsReady() && !hardpoint.GetOutfit()->Icon()) firingCommands.SetFire(index); ++index; } } if(activeCommands.Has(Command::SECONDARY)) { int index = 0; const auto &playerSelectedWeapons = player.SelectedSecondaryWeapons(); for(const Hardpoint &hardpoint : ship.Weapons()) { if(hardpoint.IsReady() && (playerSelectedWeapons.find(hardpoint.GetOutfit()) != playerSelectedWeapons.end())) firingCommands.SetFire(index); ++index; } } if(activeCommands.Has(Command::AFTERBURNER)) command |= Command::AFTERBURNER; if(activeCommands.Has(AutopilotCancelCommands())) autoPilot = activeCommands; } bool shouldAutoAim = false; bool isFiring = activeCommands.Has(Command::PRIMARY) || activeCommands.Has(Command::SECONDARY); if(activeCommands.Has(Command::AUTOSTEER) && !command.Turn() && !ship.IsBoarding() && !autoPilot.Has(Command::LAND | Command::JUMP | Command::FLEET_JUMP | Command::BOARD)) { if(target && target->GetSystem() == ship.GetSystem() && target->IsTargetable()) command.SetTurn(TurnToward(ship, TargetAim(ship))); else if(ship.GetTargetAsteroid()) command.SetTurn(TurnToward(ship, TargetAim(ship, *ship.GetTargetAsteroid()))); else if(ship.GetTargetStellar()) command.SetTurn(TurnToward(ship, ship.GetTargetStellar()->Position() - ship.Position())); } else if((Preferences::GetAutoAim() == Preferences::AutoAim::ALWAYS_ON || (Preferences::GetAutoAim() == Preferences::AutoAim::WHEN_FIRING && isFiring)) && !command.Turn() && !ship.IsBoarding() && ((target && target->GetSystem() == ship.GetSystem() && target->IsTargetable()) || ship.GetTargetAsteroid()) && !autoPilot.Has(Command::LAND | Command::JUMP | Command::FLEET_JUMP | Command::BOARD)) { // Check if this ship has any forward-facing weapons. for(const Hardpoint &weapon : ship.Weapons()) if(!weapon.CanAim() && !weapon.IsTurret() && weapon.GetOutfit()) { shouldAutoAim = true; break; } } if(shouldAutoAim) { Point pos = (target ? target->Position() : ship.GetTargetAsteroid()->Position()); if((pos - ship.Position()).Unit().Dot(ship.Facing().Unit()) >= .8) command.SetTurn(TurnToward(ship, TargetAim(ship))); } if(autoPilot.Has(Command::JUMP | Command::FLEET_JUMP) && !(player.HasTravelPlan() || ship.GetTargetSystem())) { // The player completed their travel plan, which may have indicated a destination within the final system. autoPilot.Clear(Command::JUMP | Command::FLEET_JUMP); const Planet *planet = player.TravelDestination(); if(planet && planet->IsInSystem(ship.GetSystem()) && planet->IsAccessible(&ship)) { Messages::Add("Autopilot: landing on " + planet->Name() + ".", Messages::Importance::High); autoPilot |= Command::LAND; ship.SetTargetStellar(ship.GetSystem()->FindStellar(planet)); } } // Clear autopilot actions if actions can't be performed. if(autoPilot.Has(Command::LAND) && !ship.GetTargetStellar()) autoPilot.Clear(Command::LAND); if(autoPilot.Has(Command::JUMP | Command::FLEET_JUMP) && !(ship.GetTargetSystem() || isWormhole)) autoPilot.Clear(Command::JUMP | Command::FLEET_JUMP); if(autoPilot.Has(Command::BOARD) && !(ship.GetTargetShip() && CanBoard(ship, *ship.GetTargetShip()))) autoPilot.Clear(Command::BOARD); if(autoPilot.Has(Command::LAND) || (autoPilot.Has(Command::JUMP | Command::FLEET_JUMP) && isWormhole)) { if(ship.GetPlanet()) autoPilot.Clear(Command::LAND | Command::JUMP | Command::FLEET_JUMP); else { MoveToPlanet(ship, command); command |= Command::LAND; } } else if(autoPilot.Has(Command::STOP)) { // STOP is automatically cleared once the ship has stopped. if(Stop(ship, command)) autoPilot.Clear(Command::STOP); } else if(autoPilot.Has(Command::JUMP | Command::FLEET_JUMP) && !ship.IsEnteringHyperspace()) { if(!ship.JumpNavigation().HasHyperdrive() && !ship.JumpNavigation().HasJumpDrive()) { Messages::Add("You do not have a hyperdrive installed.", Messages::Importance::Highest); autoPilot.Clear(); Audio::Play(Audio::Get("fail")); } else if(!ship.JumpNavigation().JumpFuel(ship.GetTargetSystem())) { Messages::Add("You cannot jump to the selected system.", Messages::Importance::Highest); autoPilot.Clear(); Audio::Play(Audio::Get("fail")); } else if(!ship.JumpsRemaining() && !ship.IsEnteringHyperspace()) { Messages::Add("You do not have enough fuel to make a hyperspace jump.", Messages::Importance::Highest); autoPilot.Clear(); Audio::Play(Audio::Get("fail")); } else if(ship.IsLanding()) { Messages::Add("You cannot jump while landing.", Messages::Importance::Highest); autoPilot.Clear(Command::JUMP); Audio::Play(Audio::Get("fail")); } else { PrepareForHyperspace(ship, command); command |= Command::JUMP; // Don't jump yet if the player is holding jump key or fleet jump is active and // escorts are not ready to jump yet. if(activeCommands.Has(Command::WAIT) || (autoPilot.Has(Command::FLEET_JUMP) && !EscortsReadyToJump(ship))) command |= Command::WAIT; } } else if(autoPilot.Has(Command::BOARD)) { if(!CanBoard(ship, *target)) autoPilot.Clear(Command::BOARD); else { MoveTo(ship, command, target->Position(), target->Velocity(), 40., .8); command |= Command::BOARD; } } if(ship.HasBays() && HasDeployments(ship)) { command |= Command::DEPLOY; Deploy(ship, !Preferences::Has("Damaged fighters retreat")); } if(isCloaking) command |= Command::CLOAK; ship.SetCommands(command); ship.SetCommands(firingCommands); } bool AI::Has(const Ship &ship, const weak_ptr<const Ship> &other, int type) const { auto sit = actions.find(ship.shared_from_this()); if(sit == actions.end()) return false; auto oit = sit->second.find(other); if(oit == sit->second.end()) return false; return (oit->second & type); } bool AI::Has(const Government *government, const weak_ptr<const Ship> &other, int type) const { auto git = governmentActions.find(government); if(git == governmentActions.end()) return false; auto oit = git->second.find(other); if(oit == git->second.end()) return false; return (oit->second & type); } // True if the ship has committed the action against that government. For // example, if the player boarded any ship belonging to that government. bool AI::Has(const Ship &ship, const Government *government, int type) const { auto sit = notoriety.find(ship.shared_from_this()); if(sit == notoriety.end()) return false; auto git = sit->second.find(government); if(git == sit->second.end()) return false; return (git->second & type); } void AI::UpdateStrengths(map<const Government *, int64_t> &strength, const System *playerSystem) { // Tally the strength of a government by the strength of its present and able ships. governmentRosters.clear(); for(const auto &it : ships) if(it->GetGovernment() && it->GetSystem() == playerSystem) { governmentRosters[it->GetGovernment()].emplace_back(it.get()); if(!it->IsDisabled()) strength[it->GetGovernment()] += it->Strength(); } // Strengths of enemies and allies are rebuilt every step. enemyStrength.clear(); allyStrength.clear(); for(const auto &gov : strength) { set<const Government *> allies; for(const auto &enemy : strength) if(enemy.first->IsEnemy(gov.first)) { // "Know your enemies." enemyStrength[gov.first] += enemy.second; for(const auto &ally : strength) if(ally.first->IsEnemy(enemy.first) && !allies.count(ally.first)) { // "The enemy of my enemy is my friend." allyStrength[gov.first] += ally.second; allies.insert(ally.first); } } } // Ships with nearby allies consider their allies' strength as well as their own. for(const auto &it : ships) { const Government *gov = it->GetGovernment(); // Check if this ship's government has the authority to enforce scans & fines in this system. if(!scanPermissions.count(gov)) scanPermissions.emplace(gov, gov && gov->CanEnforce(playerSystem)); // Only have ships update their strength estimate once per second on average. if(!gov || it->GetSystem() != playerSystem || it->IsDisabled() || Random::Int(60)) continue; int64_t &myStrength = shipStrength[it.get()]; for(const auto &allies : governmentRosters) { // If this is not an allied government, its ships will not assist this ship when attacked. if(allies.first->AttitudeToward(gov) <= 0.) continue; for(const auto &ally : allies.second) if(!ally->IsDisabled() && ally->Position().Distance(it->Position()) < 2000.) myStrength += ally->Strength(); } } } // Cache various lists of all targetable ships in the player's system for this Step. void AI::CacheShipLists() { allyLists.clear(); enemyLists.clear(); for(const auto &git : governmentRosters) { allyLists.emplace(git.first, vector<Ship *>()); allyLists.at(git.first).reserve(ships.size()); enemyLists.emplace(git.first, vector<Ship *>()); enemyLists.at(git.first).reserve(ships.size()); for(const auto &oit : governmentRosters) { auto &list = git.first->IsEnemy(oit.first) ? enemyLists[git.first] : allyLists[git.first]; list.insert(list.end(), oit.second.begin(), oit.second.end()); } } } void AI::IssueOrders(const PlayerInfo &player, const Orders &newOrders, const string &description) { string who; // Find out what the target of these orders is. const Ship *targetShip = newOrders.target.lock().get(); const Minable *targetAsteroid = newOrders.targetAsteroid.lock().get(); // Figure out what ships we are giving orders to. vector<const Ship *> ships; if(player.SelectedShips().empty()) { for(const shared_ptr<Ship> &it : player.Ships()) if(it.get() != player.Flagship() && !it->IsParked()) ships.push_back(it.get()); who = ships.size() > 1 ? "Your fleet is " : "Your escort is "; } else { for(const weak_ptr<Ship> &it : player.SelectedShips()) { shared_ptr<Ship> ship = it.lock(); if(ship) ships.push_back(ship.get()); } who = ships.size() > 1 ? "The selected escorts are " : "The selected escort is "; } // This should never happen, but just in case: if(ships.empty()) return; Point centerOfGravity; bool isMoveOrder = (newOrders.type == Orders::MOVE_TO); int squadCount = 0; if(isMoveOrder) { for(const Ship *ship : ships) if(ship->GetSystem() && !ship->IsDisabled()) { centerOfGravity += ship->Position(); ++squadCount; } if(squadCount > 1) centerOfGravity /= squadCount; } // If this is a move command, make sure the fleet is bunched together // enough that each ship takes up no more than about 30,000 square pixels. double maxSquadOffset = sqrt(10000. * squadCount); // A target is valid if we have no target, or when the target is in the // same system as the flagship. bool isValidTarget = !targetShip || targetAsteroid || (targetShip && player.Flagship() && targetShip->GetSystem() == player.Flagship()->GetSystem()); // Now, go through all the given ships and set their orders to the new // orders. But, if it turns out that they already had the given orders, // their orders will be cleared instead. The only command that does not // toggle is a move command; it always counts as a new command. bool hasMismatch = isMoveOrder; bool gaveOrder = false; bool alreadyHarvesting = false; if(isValidTarget) { for(const Ship *ship : ships) { // Never issue orders to a ship to target itself. if(ship == targetShip) continue; gaveOrder = true; hasMismatch |= !orders.count(ship); Orders &existing = orders[ship]; // HOLD_ACTIVE cannot be given as manual order, but we make sure here // that any HOLD_ACTIVE order also matches when an HOLD_POSITION // command is given. if(existing.type == Orders::HOLD_ACTIVE) existing.type = Orders::HOLD_POSITION; hasMismatch |= (existing.type != newOrders.type); hasMismatch |= (existing.target.lock().get() != targetShip); hasMismatch |= (existing.targetAsteroid.lock().get() != targetAsteroid); // Skip giving any new orders if the fleet is already in harvest mode and the player has selected a new // asteroid. if(hasMismatch && targetAsteroid) alreadyHarvesting = (existing.type == newOrders.type) && (newOrders.type == Orders::HARVEST); existing = newOrders; if(isMoveOrder) { // In a move order, rather than commanding every ship to move to the // same point, they move as a mass so their center of gravity is // that point but their relative positions are unchanged. Point offset = ship->Position() - centerOfGravity; if(offset.Length() > maxSquadOffset) offset = offset.Unit() * maxSquadOffset; existing.point += offset; } else if(existing.type == Orders::HOLD_POSITION) { bool shouldReverse = false; // Set the point this ship will "guard," so it can return // to it if knocked away by projectiles / explosions. existing.point = StoppingPoint(*ship, Point(), shouldReverse); } } if(!gaveOrder) return; } if(alreadyHarvesting) return; else if(hasMismatch) Messages::Add(who + description, Messages::Importance::High); else { // Clear all the orders for these ships. if(!isValidTarget) Messages::Add(who + "unable to and no longer " + description, Messages::Importance::High); else Messages::Add(who + "no longer " + description, Messages::Importance::High); for(const Ship *ship : ships) orders.erase(ship); } } // Change the ship's order based on its current fulfillment of the order. void AI::UpdateOrders(const Ship &ship) { // This should only be called for ships with orders that can be carried out. auto it = orders.find(&ship); if(it == orders.end()) return; Orders &order = it->second; if((order.type == Orders::MOVE_TO || order.type == Orders::HOLD_ACTIVE) && ship.GetSystem() == order.targetSystem) { // If nearly stopped on the desired point, switch to a HOLD_POSITION order. if(ship.Position().Distance(order.point) < 20. && ship.Velocity().Length() < .001) order.type = Orders::HOLD_POSITION; } else if(order.type == Orders::HOLD_POSITION && ship.Position().Distance(order.point) > 20.) { // If far from the defined target point, return via a HOLD_ACTIVE order. order.type = Orders::HOLD_ACTIVE; // Ensure the system reference is maintained. order.targetSystem = ship.GetSystem(); } }
0
endless-sky-master
endless-sky-master/source/FillShader.h
/* FillShader.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef FILL_SHADER_H_ #define FILL_SHADER_H_ class Point; class Color; // Class holding a function to fill a rectangular region of the screen with a // given color. This can be used with translucent colors to darken or lighten a // part of the screen, or with additive colors (alpha = 0) as well. class FillShader { public: static void Init(); static void Fill(const Point &center, const Point &size, const Color &color); }; #endif
0
endless-sky-master
endless-sky-master/source/ShopPanel.cpp
/* ShopPanel.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ShopPanel.h" #include "text/alignment.hpp" #include "CategoryTypes.h" #include "Color.h" #include "Dialog.h" #include "text/DisplayText.h" #include "FillShader.h" #include "text/Font.h" #include "text/FontSet.h" #include "text/Format.h" #include "GameData.h" #include "Government.h" #include "MapOutfitterPanel.h" #include "MapShipyardPanel.h" #include "Mission.h" #include "OutlineShader.h" #include "Planet.h" #include "PlayerInfo.h" #include "PointerShader.h" #include "Preferences.h" #include "Sale.h" #include "Screen.h" #include "Ship.h" #include "Sprite.h" #include "SpriteSet.h" #include "SpriteShader.h" #include "text/truncate.hpp" #include "UI.h" #include "text/WrappedText.h" #include "opengl.h" #include <SDL2/SDL.h> #include <algorithm> using namespace std; namespace { const string SHIP_OUTLINES = "Ship outlines in shops"; constexpr int ICON_TILE = 62; constexpr int ICON_COLS = 4; constexpr float ICON_SIZE = ICON_TILE - 8; bool CanShowInSidebar(const Ship &ship, const Planet *here) { return ship.GetPlanet() == here; } // Update smooth scroll towards scroll. void UpdateSmoothScroll(const double scroll, double &smoothScroll) { const double dy = scroll - smoothScroll; if(dy) { // Handle small increments. if(fabs(dy) < 6 && fabs(dy) > 1) smoothScroll += copysign(1., dy); // Keep scroll value an integer to prevent odd text artifacts. else smoothScroll = round(smoothScroll + dy * 0.2); } } } ShopPanel::ShopPanel(PlayerInfo &player, bool isOutfitter) : player(player), day(player.GetDate().DaysSinceEpoch()), planet(player.GetPlanet()), isOutfitter(isOutfitter), playerShip(player.Flagship()), categories(GameData::GetCategory(isOutfitter ? CategoryType::OUTFIT : CategoryType::SHIP)), collapsed(player.Collapsed(isOutfitter ? "outfitter" : "shipyard")) { if(playerShip) playerShips.insert(playerShip); SetIsFullScreen(true); SetInterruptible(false); } void ShopPanel::Step() { // If the player has acquired a second ship for the first time, explain to // them how to reorder the ships in their fleet. if(player.Ships().size() > 1) DoHelp("multiple ships"); } void ShopPanel::Draw() { glClear(GL_COLOR_BUFFER_BIT); // These get added by both DrawMain and DrawDetailsSidebar, so clear them here. categoryZones.clear(); DrawMain(); DrawShipsSidebar(); DrawDetailsSidebar(); DrawButtons(); DrawKey(); shipInfo.DrawTooltips(); outfitInfo.DrawTooltips(); if(!warningType.empty()) { constexpr int WIDTH = 250; constexpr int PAD = 10; const string &text = GameData::Tooltip(warningType); WrappedText wrap(FontSet::Get(14)); wrap.SetWrapWidth(WIDTH - 2 * PAD); wrap.Wrap(text); bool isError = (warningType.back() == '!'); const Color &textColor = *GameData::Colors().Get("medium"); const Color &backColor = *GameData::Colors().Get(isError ? "error back" : "warning back"); Point size(WIDTH, wrap.Height() + 2 * PAD); Point anchor = Point(warningPoint.X(), min<double>(warningPoint.Y() + size.Y(), Screen::Bottom())); FillShader::Fill(anchor - .5 * size, size, backColor); wrap.Draw(anchor - size + Point(PAD, PAD), textColor); } if(dragShip && isDraggingShip && dragShip->GetSprite()) { const Sprite *sprite = dragShip->GetSprite(); float scale = ICON_SIZE / max(sprite->Width(), sprite->Height()); if(Preferences::Has(SHIP_OUTLINES)) { static const Color selected(.8f, 1.f); Point size(sprite->Width() * scale, sprite->Height() * scale); OutlineShader::Draw(sprite, dragPoint, size, selected); } else { int swizzle = dragShip->CustomSwizzle() >= 0 ? dragShip->CustomSwizzle() : GameData::PlayerGovernment()->GetSwizzle(); SpriteShader::Draw(sprite, dragPoint, scale, swizzle); } } // Check to see if we need to scroll things onto the screen. if(delayedAutoScroll) { delayedAutoScroll = false; const auto selected = Selected(); if(selected != zones.end()) MainAutoScroll(selected); } if(mainScroll > maxMainScroll) mainScroll = maxMainScroll; if(infobarScroll > maxInfobarScroll) infobarScroll = maxInfobarScroll; if(sidebarScroll > maxSidebarScroll) sidebarScroll = maxSidebarScroll; } void ShopPanel::DrawShip(const Ship &ship, const Point &center, bool isSelected) { const Sprite *back = SpriteSet::Get( isSelected ? "ui/shipyard selected" : "ui/shipyard unselected"); SpriteShader::Draw(back, center); const Sprite *thumbnail = ship.Thumbnail(); const Sprite *sprite = ship.GetSprite(); int swizzle = ship.CustomSwizzle() >= 0 ? ship.CustomSwizzle() : GameData::PlayerGovernment()->GetSwizzle(); if(thumbnail) SpriteShader::Draw(thumbnail, center + Point(0., 10.), 1., swizzle); else if(sprite) { // Make sure the ship sprite leaves 10 pixels padding all around. const float zoomSize = SHIP_SIZE - 60.f; float zoom = min(1.f, zoomSize / max(sprite->Width(), sprite->Height())); SpriteShader::Draw(sprite, center, zoom, swizzle); } // Draw the ship name. const Font &font = FontSet::Get(14); const string &name = ship.Name().empty() ? ship.DisplayModelName() : ship.Name(); Point offset(-SIDEBAR_WIDTH / 2, -.5f * SHIP_SIZE + 10.f); font.Draw({name, {SIDEBAR_WIDTH, Alignment::CENTER, Truncate::MIDDLE}}, center + offset, *GameData::Colors().Get("bright")); } void ShopPanel::CheckForMissions(Mission::Location location) { if(!GetUI()->IsTop(this)) return; Mission *mission = player.MissionToOffer(location); if(mission) mission->Do(Mission::OFFER, player, GetUI()); else player.HandleBlockedMissions(location, GetUI()); } void ShopPanel::FailSell(bool toStorage) const { } bool ShopPanel::CanSellMultiple() const { return true; } // Helper function for UI buttons to determine if the selected item is // already owned. Affects if "Install" is shown for already owned items // or if "Buy" is shown for items not yet owned. // // If we are buying into cargo, then items in cargo don't count as already // owned, but they count as "already installed" in cargo. bool ShopPanel::IsAlreadyOwned() const { return (playerShip && selectedOutfit && player.Cargo().Get(selectedOutfit)) || player.Storage().Get(selectedOutfit); } bool ShopPanel::ShouldHighlight(const Ship *ship) { return (hoverButton == 's'); } void ShopPanel::DrawKey() { } int ShopPanel::VisibilityCheckboxesSize() const { return 0; } void ShopPanel::ToggleForSale() { CheckSelection(); delayedAutoScroll = true; } void ShopPanel::ToggleStorage() { CheckSelection(); delayedAutoScroll = true; } void ShopPanel::ToggleCargo() { CheckSelection(); delayedAutoScroll = true; } // Only override the ones you need; the default action is to return false. bool ShopPanel::KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) { bool toStorage = planet && planet->HasOutfitter() && (key == 'r' || key == 'u'); if(key == 'l' || key == 'd' || key == SDLK_ESCAPE || (key == 'w' && (mod & (KMOD_CTRL | KMOD_GUI)))) { if(!isOutfitter) player.UpdateCargoCapacities(); GetUI()->Pop(this); } else if(command.Has(Command::HELP)) { if(player.Ships().size() > 1) DoHelp("multiple ships", true); if(isOutfitter) { DoHelp("uninstalling and storage", true); DoHelp("cargo management", true); DoHelp("outfitter", true); } } else if(command.Has(Command::MAP)) { if(isOutfitter) GetUI()->Push(new MapOutfitterPanel(player)); else GetUI()->Push(new MapShipyardPanel(player)); } else if(key == 'b' || key == 'i' || key == 'c') { const auto result = CanBuy(key == 'i' || key == 'c'); if(result) { Buy(key == 'i' || key == 'c'); // Ship-based updates to cargo are handled when leaving. // Ship-based selection changes are asynchronous, and handled by ShipyardPanel. if(isOutfitter) { player.UpdateCargoCapacities(); CheckSelection(); } } else if(result.HasMessage()) GetUI()->Push(new Dialog(result.Message())); } else if(key == 's' || toStorage) { if(!CanSell(toStorage)) FailSell(toStorage); else { int modifier = CanSellMultiple() ? Modifier() : 1; for(int i = 0; i < modifier && CanSell(toStorage); ++i) Sell(toStorage); if(isOutfitter) { player.UpdateCargoCapacities(); CheckSelection(); } } } else if(key == SDLK_LEFT) { if(activePane != ShopPane::Sidebar) MainLeft(); else SideSelect(-1); return true; } else if(key == SDLK_RIGHT) { if(activePane != ShopPane::Sidebar) MainRight(); else SideSelect(1); return true; } else if(key == SDLK_UP) { if(activePane != ShopPane::Sidebar) MainUp(); else SideSelect(-4); return true; } else if(key == SDLK_DOWN) { if(activePane != ShopPane::Sidebar) MainDown(); else SideSelect(4); return true; } else if(key == SDLK_PAGEUP) return DoScroll(Screen::Bottom()); else if(key == SDLK_PAGEDOWN) return DoScroll(Screen::Top()); else if(key == SDLK_HOME) return SetScrollToTop(); else if(key == SDLK_END) return SetScrollToBottom(); else if(key >= '0' && key <= '9') { int group = key - '0'; if(mod & (KMOD_CTRL | KMOD_GUI)) player.SetGroup(group, &playerShips); else if(mod & KMOD_SHIFT) { // If every single ship in this group is already selected, shift // plus the group number means to deselect all those ships. set<Ship *> added = player.GetGroup(group); bool allWereSelected = true; for(Ship *ship : added) allWereSelected &= playerShips.erase(ship); if(allWereSelected) added.clear(); const Planet *here = player.GetPlanet(); for(Ship *ship : added) if(CanShowInSidebar(*ship, here)) playerShips.insert(ship); if(!playerShips.count(playerShip)) playerShip = playerShips.empty() ? nullptr : *playerShips.begin(); } else { // Change the selection to the desired ships, if they are landed here. playerShips.clear(); set<Ship *> wanted = player.GetGroup(group); const Planet *here = player.GetPlanet(); for(Ship *ship : wanted) if(CanShowInSidebar(*ship, here)) playerShips.insert(ship); if(!playerShips.count(playerShip)) playerShip = playerShips.empty() ? nullptr : *playerShips.begin(); } } else if(key == SDLK_TAB) activePane = (activePane == ShopPane::Main ? ShopPane::Sidebar : ShopPane::Main); else if(key == 'f') GetUI()->Push(new Dialog(this, &ShopPanel::DoFind, "Search for:")); else return false; return true; } bool ShopPanel::Click(int x, int y, int /* clicks */) { dragShip = nullptr; // Handle clicks on the buttons. char button = CheckButton(x, y); if(button) return DoKey(button); // Check for clicks on the ShipsSidebar pane arrows. if(x >= Screen::Right() - 20) { if(y < Screen::Top() + 20) return Scroll(0, 4); if(y < Screen::Bottom() - BUTTON_HEIGHT && y >= Screen::Bottom() - BUTTON_HEIGHT - 20) return Scroll(0, -4); } // Check for clicks on the DetailsSidebar pane arrows. else if(x >= Screen::Right() - SIDEBAR_WIDTH - 20 && x < Screen::Right() - SIDEBAR_WIDTH) { if(y < Screen::Top() + 20) return Scroll(0, 4); if(y >= Screen::Bottom() - 20) return Scroll(0, -4); } // Check for clicks on the Main pane arrows. else if(x >= Screen::Right() - SIDE_WIDTH - 20 && x < Screen::Right() - SIDE_WIDTH) { if(y < Screen::Top() + 20) return Scroll(0, 4); if(y >= Screen::Bottom() - 20) return Scroll(0, -4); } const Point clickPoint(x, y); // Check for clicks in the category labels. for(const ClickZone<string> &zone : categoryZones) if(zone.Contains(clickPoint)) { bool toggleAll = (SDL_GetModState() & KMOD_SHIFT); auto it = collapsed.find(zone.Value()); if(it == collapsed.end()) { if(toggleAll) { selectedShip = nullptr; selectedOutfit = nullptr; for(const auto &category : categories) collapsed.insert(category.Name()); } else { collapsed.insert(zone.Value()); CategoryAdvance(zone.Value()); } } else { if(toggleAll) collapsed.clear(); else collapsed.erase(it); } return true; } // Check for clicks in the main zones. for(const Zone &zone : zones) if(zone.Contains(clickPoint)) { if(zone.GetShip()) selectedShip = zone.GetShip(); else selectedOutfit = zone.GetOutfit(); return true; } // Check for clicks in the sidebar zones. for(const ClickZone<const Ship *> &zone : shipZones) if(zone.Contains(clickPoint)) { const Ship *clickedShip = zone.Value(); for(const shared_ptr<Ship> &ship : player.Ships()) if(ship.get() == clickedShip) { dragShip = ship.get(); dragPoint.Set(x, y); SideSelect(dragShip); break; } return true; } return true; } bool ShopPanel::Hover(int x, int y) { Point point(x, y); // Check that the point is not in the button area. hoverButton = CheckButton(x, y); if(hoverButton) { shipInfo.ClearHover(); outfitInfo.ClearHover(); } else { shipInfo.Hover(point); outfitInfo.Hover(point); } activePane = ShopPane::Main; if(x > Screen::Right() - SIDEBAR_WIDTH) activePane = ShopPane::Sidebar; else if(x > Screen::Right() - SIDE_WIDTH) activePane = ShopPane::Info; return true; } bool ShopPanel::Drag(double dx, double dy) { if(dragShip) { isDraggingShip = true; dragPoint += Point(dx, dy); for(const ClickZone<const Ship *> &zone : shipZones) if(zone.Contains(dragPoint)) if(zone.Value() != dragShip) { int dragIndex = -1; int dropIndex = -1; for(unsigned i = 0; i < player.Ships().size(); ++i) { const Ship *ship = &*player.Ships()[i]; if(ship == dragShip) dragIndex = i; if(ship == zone.Value()) dropIndex = i; } if(dragIndex >= 0 && dropIndex >= 0) player.ReorderShip(dragIndex, dropIndex); } } else DoScroll(dy); return true; } bool ShopPanel::Release(int x, int y) { dragShip = nullptr; isDraggingShip = false; return true; } bool ShopPanel::Scroll(double dx, double dy) { return DoScroll(dy * 2.5 * Preferences::ScrollSpeed()); } void ShopPanel::DoFind(const string &text) { int index = FindItem(text); if(index >= 0 && index < static_cast<int>(zones.size())) { auto best = std::next(zones.begin(), index); if(best->GetShip()) selectedShip = best->GetShip(); else selectedOutfit = best->GetOutfit(); MainAutoScroll(best); } } int64_t ShopPanel::LicenseCost(const Outfit *outfit, bool onlyOwned) const { // If the player is attempting to install an outfit from cargo, storage, or that they just // sold to the shop, then ignore its license requirement, if any. (Otherwise there // would be no way to use or transfer license-restricted outfits between ships.) bool owned = (player.Cargo().Get(outfit) && playerShip) || player.Storage().Get(outfit); if((owned && onlyOwned) || player.Stock(outfit) > 0) return 0; const Sale<Outfit> &available = player.GetPlanet()->Outfitter(); int64_t cost = 0; for(const string &name : outfit->Licenses()) if(!player.HasLicense(name)) { const Outfit *license = GameData::Outfits().Find(name + " License"); if(!license || !license->Cost() || !available.Has(license)) return -1; cost += license->Cost(); } return cost; } ShopPanel::Zone::Zone(Point center, Point size, const Ship *ship) : ClickZone(center, size, ship) { } ShopPanel::Zone::Zone(Point center, Point size, const Outfit *outfit) : ClickZone(center, size, nullptr), outfit(outfit) { } const Ship *ShopPanel::Zone::GetShip() const { return Value(); } const Outfit *ShopPanel::Zone::GetOutfit() const { return outfit; } void ShopPanel::DrawShipsSidebar() { const Font &font = FontSet::Get(14); const Color &medium = *GameData::Colors().Get("medium"); const Color &bright = *GameData::Colors().Get("bright"); UpdateSmoothScroll(sidebarScroll, sidebarSmoothScroll); // Fill in the background. FillShader::Fill( Point(Screen::Right() - SIDEBAR_WIDTH / 2, 0.), Point(SIDEBAR_WIDTH, Screen::Height()), *GameData::Colors().Get("panel background")); FillShader::Fill( Point(Screen::Right() - SIDEBAR_WIDTH, 0.), Point(1, Screen::Height()), *GameData::Colors().Get("shop side panel background")); // Draw this string, centered in the side panel: static const string YOURS = "Your Ships:"; Point yoursPoint(Screen::Right() - SIDEBAR_WIDTH, Screen::Top() + 10 - sidebarSmoothScroll); font.Draw({YOURS, {SIDEBAR_WIDTH, Alignment::CENTER}}, yoursPoint, bright); // Start below the "Your Ships" label, and draw them. Point point( Screen::Right() - SIDEBAR_WIDTH / 2 - 93, Screen::Top() + SIDEBAR_WIDTH / 2 - sidebarSmoothScroll + 40 - 93); const Planet *here = player.GetPlanet(); int shipsHere = 0; for(const shared_ptr<Ship> &ship : player.Ships()) shipsHere += CanShowInSidebar(*ship, here); if(shipsHere < 4) point.X() += .5 * ICON_TILE * (4 - shipsHere); // Check whether flight check tooltips should be shown. const auto flightChecks = player.FlightCheck(); Point mouse = UI::GetMouse(); warningType.clear(); shipZones.clear(); static const Color selected(.8f, 1.f); static const Color unselected(.4f, 1.f); for(const shared_ptr<Ship> &ship : player.Ships()) { // Skip any ships that are "absent" for whatever reason. if(!CanShowInSidebar(*ship, here)) continue; if(point.X() > Screen::Right()) { point.X() -= ICON_TILE * ICON_COLS; point.Y() += ICON_TILE; } bool isSelected = playerShips.count(ship.get()); const Sprite *background = SpriteSet::Get(isSelected ? "ui/icon selected" : "ui/icon unselected"); SpriteShader::Draw(background, point); // If this is one of the selected ships, check if the currently hovered // button (if any) applies to it. If so, brighten the background. if(isSelected && ShouldHighlight(ship.get())) SpriteShader::Draw(background, point); const Sprite *sprite = ship->GetSprite(); if(sprite) { float scale = ICON_SIZE / max(sprite->Width(), sprite->Height()); if(Preferences::Has(SHIP_OUTLINES)) { Point size(sprite->Width() * scale, sprite->Height() * scale); OutlineShader::Draw(sprite, point, size, isSelected ? selected : unselected); } else { int swizzle = ship->CustomSwizzle() >= 0 ? ship->CustomSwizzle() : GameData::PlayerGovernment()->GetSwizzle(); SpriteShader::Draw(sprite, point, scale, swizzle); } } shipZones.emplace_back(point, Point(ICON_TILE, ICON_TILE), ship.get()); const auto checkIt = flightChecks.find(ship); if(checkIt != flightChecks.end()) { const string &check = (*checkIt).second.front(); const Sprite *icon = SpriteSet::Get(check.back() == '!' ? "ui/error" : "ui/warning"); SpriteShader::Draw(icon, point + .5 * Point(ICON_TILE - icon->Width(), ICON_TILE - icon->Height())); if(shipZones.back().Contains(mouse)) { warningType = check; warningPoint = shipZones.back().TopLeft(); } } if(isSelected && playerShips.size() > 1 && ship->OutfitCount(selectedOutfit)) PointerShader::Draw(Point(point.X() - static_cast<int>(ICON_TILE / 3), point.Y()), Point(1., 0.), 14.f, 12.f, 0., Color(.9f, .9f, .9f, .2f)); point.X() += ICON_TILE; } point.Y() += ICON_TILE; if(playerShip) { point.Y() += SHIP_SIZE / 2; point.X() = Screen::Right() - SIDEBAR_WIDTH / 2; DrawShip(*playerShip, point, true); Point offset(SIDEBAR_WIDTH / -2, SHIP_SIZE / 2); const int detailHeight = DrawPlayerShipInfo(point + offset); point.Y() += detailHeight + SHIP_SIZE / 2; } else if(player.Cargo().Size()) { point.X() = Screen::Right() - SIDEBAR_WIDTH + 10; font.Draw("cargo space:", point, medium); string space = Format::Number(player.Cargo().Free()) + " / " + Format::Number(player.Cargo().Size()); font.Draw({space, {SIDEBAR_WIDTH - 20, Alignment::RIGHT}}, point, bright); point.Y() += 20.; } maxSidebarScroll = max(0., point.Y() + sidebarSmoothScroll - Screen::Bottom() + BUTTON_HEIGHT); PointerShader::Draw(Point(Screen::Right() - 10, Screen::Top() + 10), Point(0., -1.), 10.f, 10.f, 5.f, Color(sidebarScroll > 0 ? .8f : .2f, 0.f)); PointerShader::Draw(Point(Screen::Right() - 10, Screen::Bottom() - 80), Point(0., 1.), 10.f, 10.f, 5.f, Color(sidebarScroll < maxSidebarScroll ? .8f : .2f, 0.f)); } void ShopPanel::DrawDetailsSidebar() { // Fill in the background. const Color &line = *GameData::Colors().Get("dim"); const Color &back = *GameData::Colors().Get("shop info panel background"); UpdateSmoothScroll(infobarScroll, infobarSmoothScroll); FillShader::Fill( Point(Screen::Right() - SIDEBAR_WIDTH - INFOBAR_WIDTH, 0.), Point(1., Screen::Height()), line); FillShader::Fill( Point(Screen::Right() - SIDEBAR_WIDTH - INFOBAR_WIDTH / 2, 0.), Point(INFOBAR_WIDTH - 1., Screen::Height()), back); Point point( Screen::Right() - SIDE_WIDTH + INFOBAR_WIDTH / 2, Screen::Top() + 10 - infobarSmoothScroll); int heightOffset = DrawDetails(point); maxInfobarScroll = max(0., heightOffset + infobarSmoothScroll - Screen::Bottom()); PointerShader::Draw(Point(Screen::Right() - SIDEBAR_WIDTH - 10, Screen::Top() + 10), Point(0., -1.), 10.f, 10.f, 5.f, Color(infobarScroll > 0 ? .8f : .2f, 0.f)); PointerShader::Draw(Point(Screen::Right() - SIDEBAR_WIDTH - 10, Screen::Bottom() - 10), Point(0., 1.), 10.f, 10.f, 5.f, Color(infobarScroll < maxInfobarScroll ? .8f : .2f, 0.f)); } void ShopPanel::DrawButtons() { // The last 70 pixels on the end of the side panel are for the buttons: Point buttonSize(SIDEBAR_WIDTH, BUTTON_HEIGHT); FillShader::Fill(Screen::BottomRight() - .5 * buttonSize, buttonSize, *GameData::Colors().Get("shop side panel background")); FillShader::Fill( Point(Screen::Right() - SIDEBAR_WIDTH / 2, Screen::Bottom() - BUTTON_HEIGHT), Point(SIDEBAR_WIDTH, 1), *GameData::Colors().Get("shop side panel footer")); const Font &font = FontSet::Get(14); const Color &bright = *GameData::Colors().Get("bright"); const Color &dim = *GameData::Colors().Get("medium"); const Color &back = *GameData::Colors().Get("panel background"); const Point creditsPoint( Screen::Right() - SIDEBAR_WIDTH + 10, Screen::Bottom() - 65); font.Draw("You have:", creditsPoint, dim); const auto credits = Format::CreditString(player.Accounts().Credits()); font.Draw({credits, {SIDEBAR_WIDTH - 20, Alignment::RIGHT}}, creditsPoint, bright); const Font &bigFont = FontSet::Get(18); const Color &hover = *GameData::Colors().Get("hover"); const Color &active = *GameData::Colors().Get("active"); const Color &inactive = *GameData::Colors().Get("inactive"); const Point buyCenter = Screen::BottomRight() - Point(210, 25); FillShader::Fill(buyCenter, Point(60, 30), back); bool isOwned = IsAlreadyOwned(); const Color *buyTextColor; if(!CanBuy(isOwned)) buyTextColor = &inactive; else if(hoverButton == (isOwned ? 'i' : 'b')) buyTextColor = &hover; else buyTextColor = &active; string BUY = isOwned ? (playerShip ? "_Install" : "_Cargo") : "_Buy"; bigFont.Draw(BUY, buyCenter - .5 * Point(bigFont.Width(BUY), bigFont.Height()), *buyTextColor); const Point sellCenter = Screen::BottomRight() - Point(130, 25); FillShader::Fill(sellCenter, Point(60, 30), back); static const string SELL = "_Sell"; bigFont.Draw(SELL, sellCenter - .5 * Point(bigFont.Width(SELL), bigFont.Height()), CanSell() ? hoverButton == 's' ? hover : active : inactive); const Point leaveCenter = Screen::BottomRight() - Point(45, 25); FillShader::Fill(leaveCenter, Point(70, 30), back); static const string LEAVE = "_Leave"; bigFont.Draw(LEAVE, leaveCenter - .5 * Point(bigFont.Width(LEAVE), bigFont.Height()), hoverButton == 'l' ? hover : active); const Point findCenter = Screen::BottomRight() - Point(580, 20); const Sprite *findIcon = hoverButton == 'f' ? SpriteSet::Get("ui/find selected") : SpriteSet::Get("ui/find unselected"); SpriteShader::Draw(findIcon, findCenter); static const string FIND = "_Find"; int modifier = Modifier(); if(modifier > 1) { string mod = "x " + to_string(modifier); int modWidth = font.Width(mod); font.Draw(mod, buyCenter + Point(-.5 * modWidth, 10.), dim); if(CanSellMultiple()) font.Draw(mod, sellCenter + Point(-.5 * modWidth, 10.), dim); } } void ShopPanel::DrawMain() { const Font &bigFont = FontSet::Get(18); const Color &dim = *GameData::Colors().Get("medium"); const Color &bright = *GameData::Colors().Get("bright"); const Sprite *collapsedArrow = SpriteSet::Get("ui/collapsed"); const Sprite *expandedArrow = SpriteSet::Get("ui/expanded"); UpdateSmoothScroll(mainScroll, mainSmoothScroll); // Draw all the available items. // First, figure out how many columns we can draw. const int TILE_SIZE = TileSize(); const int mainWidth = (Screen::Width() - SIDE_WIDTH - 1); // If the user horizontally compresses the window too far, draw nothing. if(mainWidth < TILE_SIZE) return; const int columns = mainWidth / TILE_SIZE; const int columnWidth = mainWidth / columns; const Point begin( (Screen::Width() - columnWidth) / -2, (Screen::Height() - TILE_SIZE) / -2 - mainSmoothScroll); Point point = begin; const float endX = Screen::Right() - (SIDE_WIDTH + 1); double nextY = begin.Y() + TILE_SIZE; zones.clear(); for(const auto &cat : categories) { const string &category = cat.Name(); map<string, vector<string>>::const_iterator it = catalog.find(category); if(it == catalog.end()) continue; // This should never happen, but bail out if we don't know what planet // we are on (meaning there's no way to know what items are for sale). if(!planet) break; Point side(Screen::Left() + 5., point.Y() - TILE_SIZE / 2 + 10); point.Y() += bigFont.Height() + 20; nextY += bigFont.Height() + 20; bool isCollapsed = collapsed.count(category); bool isEmpty = true; for(const string &name : it->second) { if(!HasItem(name)) continue; isEmpty = false; if(isCollapsed) break; DrawItem(name, point); point.X() += columnWidth; if(point.X() >= endX) { point.X() = begin.X(); point.Y() = nextY; nextY += TILE_SIZE; } } if(!isEmpty) { Point size(bigFont.Width(category) + 25., bigFont.Height()); categoryZones.emplace_back(Point(Screen::Left(), side.Y()) + .5 * size, size, category); SpriteShader::Draw(isCollapsed ? collapsedArrow : expandedArrow, side + Point(10., 10.)); bigFont.Draw(category, side + Point(25., 0.), isCollapsed ? dim : bright); if(point.X() != begin.X()) { point.X() = begin.X(); point.Y() = nextY; nextY += TILE_SIZE; } point.Y() += 40; nextY += 40; } else { point.Y() -= bigFont.Height() + 20; nextY -= bigFont.Height() + 20; } } // This is how much Y space was actually used. nextY -= 40 + TILE_SIZE; // What amount would mainScroll have to equal to make nextY equal the // bottom of the screen? (Also leave space for the "key" at the bottom.) maxMainScroll = max(0., nextY + mainSmoothScroll - Screen::Height() / 2 - TILE_SIZE / 2 + VisibilityCheckboxesSize() + 40.); PointerShader::Draw(Point(Screen::Right() - 10 - SIDE_WIDTH, Screen::Top() + 10), Point(0., -1.), 10.f, 10.f, 5.f, Color(mainScroll > 0 ? .8f : .2f, 0.f)); PointerShader::Draw(Point(Screen::Right() - 10 - SIDE_WIDTH, Screen::Bottom() - 10), Point(0., 1.), 10.f, 10.f, 5.f, Color(mainScroll < maxMainScroll ? .8f : .2f, 0.f)); } int ShopPanel::DrawPlayerShipInfo(const Point &point) { shipInfo.Update(*playerShip, player, collapsed.count("description"), true); shipInfo.DrawAttributes(point, !isOutfitter); const int attributesHeight = shipInfo.GetAttributesHeight(!isOutfitter); shipInfo.DrawOutfits(Point(point.X(), point.Y() + attributesHeight)); return attributesHeight + shipInfo.OutfitsHeight(); } bool ShopPanel::DoScroll(double dy) { if(activePane == ShopPane::Info) infobarScroll = max(0., min(maxInfobarScroll, infobarScroll - dy)); else if(activePane == ShopPane::Sidebar) sidebarScroll = max(0., min(maxSidebarScroll, sidebarScroll - dy)); else mainScroll = max(0., min(maxMainScroll, mainScroll - dy)); return true; } bool ShopPanel::SetScrollToTop() { if(activePane == ShopPane::Info) infobarScroll = 0.; else if(activePane == ShopPane::Sidebar) sidebarScroll = 0.; else mainScroll = 0.; return true; } bool ShopPanel::SetScrollToBottom() { if(activePane == ShopPane::Info) infobarScroll = maxInfobarScroll; else if(activePane == ShopPane::Sidebar) sidebarScroll = maxSidebarScroll; else mainScroll = maxMainScroll; return true; } void ShopPanel::SideSelect(int count) { // Find the currently selected ship in the list. vector<shared_ptr<Ship>>::const_iterator it = player.Ships().begin(); for( ; it != player.Ships().end(); ++it) if((*it).get() == playerShip) break; // Bail out if there are no ships to choose from. if(it == player.Ships().end()) { playerShips.clear(); playerShip = player.Flagship(); if(playerShip) playerShips.insert(playerShip); CheckSelection(); return; } const Planet *here = player.GetPlanet(); if(count < 0) { while(count) { if(it == player.Ships().begin()) it = player.Ships().end(); --it; if(CanShowInSidebar(**it, here)) ++count; } } else { while(count) { ++it; if(it == player.Ships().end()) it = player.Ships().begin(); if(CanShowInSidebar(**it, here)) --count; } } SideSelect(&**it); } void ShopPanel::SideSelect(Ship *ship) { bool shift = (SDL_GetModState() & KMOD_SHIFT); bool control = (SDL_GetModState() & (KMOD_CTRL | KMOD_GUI)); if(shift) { bool on = false; const Planet *here = player.GetPlanet(); for(const shared_ptr<Ship> &other : player.Ships()) { // Skip any ships that are "absent" for whatever reason. if(!CanShowInSidebar(*other, here)) continue; if(other.get() == ship || other.get() == playerShip) on = !on; else if(on) playerShips.insert(other.get()); } } else if(!control) playerShips.clear(); else if(playerShips.count(ship)) { playerShips.erase(ship); if(playerShip == ship) playerShip = playerShips.empty() ? nullptr : *playerShips.begin(); CheckSelection(); return; } playerShip = ship; playerShips.insert(playerShip); CheckSelection(); } // If selected item is offscreen, scroll just enough to put it on. void ShopPanel::MainAutoScroll(const vector<Zone>::const_iterator &selected) { const int TILE_SIZE = TileSize(); const int topY = selected->Center().Y() - TILE_SIZE / 2; const int offTop = topY + Screen::Bottom(); if(offTop < 0) mainScroll += offTop; else { const int offBottom = topY + TILE_SIZE - Screen::Bottom(); if(offBottom > 0) mainScroll += offBottom; } } void ShopPanel::MainLeft() { if(zones.empty()) return; vector<Zone>::const_iterator it = Selected(); if(it == zones.end() || it == zones.begin()) { it = zones.end(); --it; mainScroll = maxMainScroll; mainSmoothScroll = maxMainScroll; } else { --it; MainAutoScroll(it); } selectedShip = it->GetShip(); selectedOutfit = it->GetOutfit(); } void ShopPanel::MainRight() { if(zones.empty()) return; vector<Zone>::const_iterator it = Selected(); if(it == zones.end() || ++it == zones.end()) { it = zones.begin(); mainScroll = 0; mainSmoothScroll = 0; } else MainAutoScroll(it); selectedShip = it->GetShip(); selectedOutfit = it->GetOutfit(); } void ShopPanel::MainUp() { if(zones.empty()) return; vector<Zone>::const_iterator it = Selected(); // Special case: nothing is selected. Start from the first item. if(it == zones.end()) it = zones.begin(); const double previousX = it->Center().X(); const double previousY = it->Center().Y(); while(it != zones.begin() && it->Center().Y() == previousY) --it; if(it == zones.begin() && it->Center().Y() == previousY) { it = zones.end(); --it; mainScroll = maxMainScroll; mainSmoothScroll = maxMainScroll; } else MainAutoScroll(it); while(it->Center().X() > previousX) --it; selectedShip = it->GetShip(); selectedOutfit = it->GetOutfit(); } void ShopPanel::MainDown() { if(zones.empty()) return; vector<Zone>::const_iterator it = Selected(); // Special case: nothing is selected. Select the first item. if(it == zones.end()) { mainScroll = 0; mainSmoothScroll = 0; selectedShip = zones.begin()->GetShip(); selectedOutfit = zones.begin()->GetOutfit(); return; } const double previousX = it->Center().X(); const double previousY = it->Center().Y(); ++it; while(it != zones.end() && it->Center().Y() == previousY) ++it; if(it == zones.end()) { it = zones.begin(); mainScroll = 0; mainSmoothScroll = 0; } else MainAutoScroll(it); // Overshoot by one in case this line is shorter than the previous one. const double newY = it->Center().Y(); ++it; while(it != zones.end() && it->Center().X() <= previousX && it->Center().Y() == newY) ++it; --it; selectedShip = it->GetShip(); selectedOutfit = it->GetOutfit(); } // If the selected item is no longer displayed, advance selection until we find something that is. void ShopPanel::CheckSelection() { if((!selectedOutfit && !selectedShip) || (selectedShip && HasItem(selectedShip->VariantName())) || (selectedOutfit && HasItem(selectedOutfit->TrueName()))) return; vector<Zone>::const_iterator it = Selected(); if(it == zones.end()) return; const vector<Zone>::const_iterator oldIt = it; // Advance to find next valid selection. for( ; it != zones.end(); ++it) { const Ship *ship = it->GetShip(); const Outfit *outfit = it->GetOutfit(); if((ship && HasItem(ship->VariantName())) || (outfit && HasItem(outfit->TrueName()))) break; } // If that didn't work, try the other direction. if(it == zones.end()) { it = oldIt; while(it != zones.begin()) { --it; const Ship *ship = it->GetShip(); const Outfit *outfit = it->GetOutfit(); if((ship && HasItem(ship->VariantName())) || (outfit && HasItem(outfit->TrueName()))) { ++it; break; } } if(it == zones.begin()) { // No displayed objects, apparently. selectedShip = nullptr; selectedOutfit = nullptr; return; } --it; } selectedShip = it->GetShip(); selectedOutfit = it->GetOutfit(); MainAutoScroll(it); } // The selected item's category has collapsed, to advance to next displayed item. void ShopPanel::CategoryAdvance(const string &category) { vector<Zone>::const_iterator it = Selected(); if(it == zones.end()) return; const vector<Zone>::const_iterator oldIt = it; // Advance to find next valid selection. for( ; it != zones.end(); ++it) { const Ship *ship = it->GetShip(); const Outfit *outfit = it->GetOutfit(); if((ship && ship->Attributes().Category() != category) || (outfit && outfit->Category() != category)) break; } // If that didn't work, try the other direction. if(it == zones.end()) { it = oldIt; while(it != zones.begin()) { --it; const Ship *ship = it->GetShip(); const Outfit *outfit = it->GetOutfit(); if((ship && ship->Attributes().Category() != category) || (outfit && outfit->Category() != category)) { ++it; break; } } if(it == zones.begin()) { // No displayed objects, apparently. selectedShip = nullptr; selectedOutfit = nullptr; return; } --it; } selectedShip = it->GetShip(); selectedOutfit = it->GetOutfit(); } // Find the currently selected item. vector<ShopPanel::Zone>::const_iterator ShopPanel::Selected() const { vector<Zone>::const_iterator it = zones.begin(); for( ; it != zones.end(); ++it) if(it->GetShip() == selectedShip && it->GetOutfit() == selectedOutfit) break; return it; } // Check if the given point is within the button zone, and if so return the // letter of the button (or ' ' if it's not on a button). char ShopPanel::CheckButton(int x, int y) { if(x > Screen::Right() - SIDEBAR_WIDTH - 342 && x < Screen::Right() - SIDEBAR_WIDTH - 316 && y > Screen::Bottom() - 31 && y < Screen::Bottom() - 4) return 'f'; if(x < Screen::Right() - SIDEBAR_WIDTH || y < Screen::Bottom() - BUTTON_HEIGHT) return '\0'; if(y < Screen::Bottom() - 40 || y >= Screen::Bottom() - 10) return ' '; x -= Screen::Right() - SIDEBAR_WIDTH; if(x > 9 && x < 70) { if(!IsAlreadyOwned()) return 'b'; else return 'i'; } else if(x > 89 && x < 150) return 's'; else if(x > 169 && x < 240) return 'l'; return ' '; }
0
endless-sky-master
endless-sky-master/source/Plugins.h
/* Plugins.h Copyright (c) 2022 by Sam Gleske (samrocketman on GitHub) Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef PLUGINS_H_ #define PLUGINS_H_ #include "Set.h" #include <string> // Represents information about a single plugin. struct Plugin { // Checks whether this plugin is valid, i.e. whether it exists. bool IsValid() const; // The name that identifies this plugin. std::string name; // The path to the plugin's folder. std::string path; // The about text, if any, of this plugin. std::string aboutText; // Whether this plugin was enabled, i.e. if it was loaded by the game. bool enabled = true; // The current state of the plugin. bool currentState = true; }; // Tracks enabled and disabled plugins for loading plugin data or skipping it. // This object is updated by toggling plugins in the Preferences UI. class Plugins { public: // Attempt to load a plugin at the given path. static const Plugin *Load(const std::string &path); static void LoadSettings(); static void Save(); // Whether the path points to a valid plugin. static bool IsPlugin(const std::string &path); // Returns true if any plugin enabled or disabled setting has changed since // launched via user preferences. static bool HasChanged(); // Returns the list of plugins that have been identified by the game. static const Set<Plugin> &Get(); // Toggles enabling or disabling a plugin for the next game restart. static void TogglePlugin(const std::string &name); }; #endif
0
endless-sky-master
endless-sky-master/source/News.cpp
/* News.cpp Copyright (c) 2017 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "News.h" #include "DataNode.h" #include "Random.h" #include "SpriteSet.h" #include <algorithm> using namespace std; void News::Load(const DataNode &node) { for(const DataNode &child : node) { const bool add = (child.Token(0) == "add"); const bool remove = (child.Token(0) == "remove"); if((add || remove) && child.Size() < 2) { child.PrintTrace("Skipping " + child.Token(0) + " with no key given:"); continue; } // Get the key and value (if any). const string &tag = child.Token((add || remove) ? 1 : 0); const int valueIndex = (add || remove) ? 2 : 1; const bool hasValue = child.Size() > valueIndex; if(tag == "location") { if(remove) location = LocationFilter{}; else location.Load(child); } else if(tag == "name") { if(remove) names = Phrase{}; else names.Load(child); } else if(tag == "portrait") { if(remove && !hasValue) portraits.clear(); else if(remove) { // Collect all values to be removed. auto toRemove = set<const Sprite *>{}; for(int i = valueIndex; i < child.Size(); ++i) toRemove.emplace(SpriteSet::Get(child.Token(i))); // Erase them in unison. portraits.erase(remove_if(portraits.begin(), portraits.end(), [&toRemove](const Sprite *sprite) { return toRemove.find(sprite) != toRemove.end(); }), portraits.end()); } else { for(int i = valueIndex; i < child.Size(); ++i) portraits.push_back(SpriteSet::Get(child.Token(i))); for(const DataNode &grand : child) portraits.push_back(SpriteSet::Get(grand.Token(0))); } } else if(tag == "message") { if(remove) messages = Phrase{}; else messages.Load(child); } else if(tag == "to" && hasValue && child.Token(valueIndex) == "show") { if(remove) toShow = ConditionSet{}; else toShow.Load(child); } else child.PrintTrace("Skipping unrecognized attribute:"); } } bool News::IsEmpty() const { return messages.IsEmpty() || names.IsEmpty(); } // Check if this news item is available given the player's planet and conditions. bool News::Matches(const Planet *planet, const ConditionsStore &conditions) const { // If no location filter is specified, it should never match. This can be // used to create news items that are never shown until an event "activates" // them by specifying their location. // Similarly, by updating a news item with "remove location", it can be deactivated. return location.IsEmpty() ? false : (location.Matches(planet) && toShow.Test(conditions)); } // Get the speaker's name. string News::Name() const { return names.Get(); } // Pick a portrait at random out of the possible options. const Sprite *News::Portrait() const { return portraits.empty() ? nullptr : portraits[Random::Int(portraits.size())]; } // Get the speaker's message, chosen randomly. string News::Message() const { return messages.Get(); }
0
endless-sky-master
endless-sky-master/source/Set.h
/* Set.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef SET_H_ #define SET_H_ #include <map> #include <string> // Template representing a set of named objects of a given type, where you can // query it for a pointer to any object and it will return one, whether or not that // object has been loaded yet. (This allows cyclic pointers.) template<class Type> class Set { public: // Allow non-const access to the owner of this set; it can hand off only // const references to avoid anyone else modifying the objects. Type *Get(const std::string &name) { return &data[name]; } const Type *Get(const std::string &name) const { return &data[name]; } // If an item already exists in this set, get it. Otherwise, return a null // pointer rather than creating the item. const Type *Find(const std::string &name) const; bool Has(const std::string &name) const { return data.count(name); } typename std::map<std::string, Type>::iterator begin() { return data.begin(); } typename std::map<std::string, Type>::const_iterator begin() const { return data.begin(); } typename std::map<std::string, Type>::const_iterator find(const std::string &key) const { return data.find(key); } typename std::map<std::string, Type>::iterator end() { return data.end(); } typename std::map<std::string, Type>::const_iterator end() const { return data.end(); } int size() const { return data.size(); } bool empty() const { return data.empty(); } // Remove any objects in this set that are not in the given set, and for // those that are in the given set, revert to their contents. void Revert(const Set<Type> &other); private: mutable std::map<std::string, Type> data; }; template <class Type> const Type *Set<Type>::Find(const std::string &name) const { auto it = data.find(name); return (it == data.end() ? nullptr : &it->second); } template <class Type> void Set<Type>::Revert(const Set<Type> &other) { auto it = data.begin(); auto oit = other.data.begin(); while(it != data.end()) { if(oit == other.data.end() || it->first < oit->first) it = data.erase(it); else if(it->first == oit->first) { // If this is an entry that is in the set we are reverting to, copy // the state we are reverting to. it->second = oit->second; ++it; ++oit; } // There should never be a case when an entry in the set we are // reverting to has a name that is not also in this set. } } #endif
0
endless-sky-master
endless-sky-master/source/OutfitterPanel.h
/* OutfitterPanel.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef OUTFITTER_PANEL_H_ #define OUTFITTER_PANEL_H_ #include "ShopPanel.h" #include "Sale.h" #include <map> #include <set> #include <string> #include <vector> class Outfit; class PlayerInfo; class Point; class Ship; // Class representing the Outfitter UI panel, which allows you to buy new // outfits to install in your ship or to sell the ones you own. Any outfit you // sell is available to be bought again until you close this panel, even if it // is not normally sold here. You can also directly install any outfit that you // have plundered from another ship and are storing in your cargo bay. This // panel makes an attempt to ensure that you do not leave with a ship that is // configured in such a way that it cannot fly (e.g. no engines or steering). class OutfitterPanel : public ShopPanel { public: explicit OutfitterPanel(PlayerInfo &player); virtual void Step() override; protected: virtual int TileSize() const override; virtual int VisibilityCheckboxesSize() const override; virtual bool HasItem(const std::string &name) const override; virtual void DrawItem(const std::string &name, const Point &point) override; virtual int DividerOffset() const override; virtual int DetailWidth() const override; virtual int DrawDetails(const Point &center) override; virtual BuyResult CanBuy(bool onlyOwned = false) const override; virtual void Buy(bool onlyOwned = false) override; virtual bool CanSell(bool toStorage = false) const override; virtual void Sell(bool toStorage = false) override; virtual void FailSell(bool toStorage = false) const override; virtual bool ShouldHighlight(const Ship *ship) override; virtual void DrawKey() override; virtual void ToggleForSale() override; virtual void ToggleStorage() override; virtual void ToggleCargo() override; virtual int FindItem(const std::string &text) const override; private: static bool ShipCanBuy(const Ship *ship, const Outfit *outfit); static bool ShipCanSell(const Ship *ship, const Outfit *outfit); static void DrawOutfit(const Outfit &outfit, const Point &center, bool isSelected, bool isOwned); bool IsLicense(const std::string &name) const; bool HasLicense(const std::string &name) const; std::string LicenseRoot(const std::string &name) const; void CheckRefill(); void Refill(); // Shared code for reducing the selected ships to those that have the // same quantity of the selected outfit. const std::vector<Ship *> GetShipsToOutfit(bool isBuy = false) const; private: // Record whether we've checked if the player needs ammo refilled. bool checkedRefill = false; // Allow toggling whether outfits that are for sale are shown. bool showForSale = true; // Allow toggling whether stored outfits are shown. bool showStorage = true; // Allow toggling whether outfits in cargo are shown. bool showCargo = true; Sale<Outfit> outfitter; // Keep track of how many of the outfitter help screens have been shown bool checkedHelp = false; }; #endif
0
endless-sky-master
endless-sky-master/source/PointerShader.cpp
/* PointerShader.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "PointerShader.h" #include "Color.h" #include "Point.h" #include "Screen.h" #include "Shader.h" #include <stdexcept> using namespace std; namespace { Shader shader; GLint scaleI; GLint centerI; GLint angleI; GLint sizeI; GLint offsetI; GLint colorI; GLuint vao; GLuint vbo; } void PointerShader::Init() { static const char *vertexCode = "// vertex pointer shader\n" "precision mediump float;\n" "uniform vec2 scale;\n" "uniform vec2 center;\n" "uniform vec2 angle;\n" "uniform vec2 size;\n" "uniform float offset;\n" "in vec2 vert;\n" "out vec2 coord;\n" "void main() {\n" " coord = vert * size.x;\n" " vec2 base = center + angle * (offset - size.y * (vert.x + vert.y));\n" " vec2 wing = vec2(angle.y, -angle.x) * (size.x * .5 * (vert.x - vert.y));\n" " gl_Position = vec4((base + wing) * scale, 0, 1);\n" "}\n"; static const char *fragmentCode = "// fragment pointer shader\n" "precision mediump float;\n" "uniform vec4 color;\n" "uniform vec2 size;\n" "in vec2 coord;\n" "out vec4 finalColor;\n" "void main() {\n" " float height = (coord.x + coord.y) / size.x;\n" " float taper = height * height * height;\n" " taper *= taper * .5 * size.x;\n" " float alpha = clamp(.8 * min(coord.x, coord.y) - taper, 0.f, 1.f);\n" " alpha *= clamp(1.8 * (1. - height), 0.f, 1.f);\n" " finalColor = color * alpha;\n" "}\n"; shader = Shader(vertexCode, fragmentCode); scaleI = shader.Uniform("scale"); centerI = shader.Uniform("center"); angleI = shader.Uniform("angle"); sizeI = shader.Uniform("size"); offsetI = shader.Uniform("offset"); colorI = shader.Uniform("color"); // Generate the vertex data for drawing sprites. glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); GLfloat vertexData[] = { 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, }; glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glEnableVertexAttribArray(shader.Attrib("vert")); glVertexAttribPointer(shader.Attrib("vert"), 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); // unbind the VBO and VAO glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void PointerShader::Draw(const Point &center, const Point &angle, float width, float height, float offset, const Color &color) { Bind(); Add(center, angle, width, height, offset, color); Unbind(); } void PointerShader::Bind() { if(!shader.Object()) throw runtime_error("PointerShader: Bind() called before Init()."); glUseProgram(shader.Object()); glBindVertexArray(vao); GLfloat scale[2] = {2.f / Screen::Width(), -2.f / Screen::Height()}; glUniform2fv(scaleI, 1, scale); } void PointerShader::Add(const Point &center, const Point &angle, float width, float height, float offset, const Color &color) { GLfloat c[2] = {static_cast<float>(center.X()), static_cast<float>(center.Y())}; glUniform2fv(centerI, 1, c); GLfloat a[2] = {static_cast<float>(angle.X()), static_cast<float>(angle.Y())}; glUniform2fv(angleI, 1, a); GLfloat size[2] = {width, height}; glUniform2fv(sizeI, 1, size); glUniform1f(offsetI, offset); glUniform4fv(colorI, 1, color.Get()); glDrawArrays(GL_TRIANGLES, 0, 3); } void PointerShader::Unbind() { glBindVertexArray(0); glUseProgram(0); }
0
endless-sky-master
endless-sky-master/source/LogbookPanel.h
/* LogbookPanel.h Copyright (c) 2017 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef LOGBOOK_PANEL_H_ #define LOGBOOK_PANEL_H_ #include "Panel.h" #include "Date.h" #include <map> #include <string> #include <vector> class PlayerInfo; // User interface panel that displays a conversation, allowing you to make // choices. If a callback function is given, that function will be called when // the panel closes, to report the outcome of the conversation. class LogbookPanel : public Panel { public: LogbookPanel(PlayerInfo &player); // Draw this panel. virtual void Draw() override; protected: // Event handlers. virtual bool KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) override; virtual bool Click(int x, int y, int clicks) override; virtual bool Drag(double dx, double dy) override; virtual bool Scroll(double dx, double dy) override; virtual bool Hover(int x, int y) override; private: void Update(bool selectLast = true); private: // Reference to the player, to apply any changes to them. PlayerInfo &player; // Current month being displayed: Date selectedDate; std::string selectedName; std::multimap<Date, std::string>::const_iterator begin; std::multimap<Date, std::string>::const_iterator end; // Other months available for display: std::vector<std::string> contents; std::vector<Date> dates; Point hoverPoint; // Current scroll: double categoryScroll = 0.; double scroll = 0.; mutable double maxCategoryScroll = 0.; mutable double maxScroll = 0.; }; #endif
0
endless-sky-master
endless-sky-master/source/SpriteQueue.h
/* SpriteQueue.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef SPRITE_QUEUE_H_ #define SPRITE_QUEUE_H_ #include <condition_variable> #include <map> #include <memory> #include <mutex> #include <queue> #include <string> #include <thread> #include <vector> class ImageBuffer; class ImageSet; class Mask; class Sprite; // Class for queuing up a list of sprites to be loaded from the disk, with a set of // worker threads that begins loading them as soon as they are added. class SpriteQueue { public: SpriteQueue(); ~SpriteQueue(); // No moving or copying this class. SpriteQueue(const SpriteQueue &other) = delete; SpriteQueue(SpriteQueue &&other) = delete; SpriteQueue &operator=(const SpriteQueue &other) = delete; SpriteQueue &operator=(SpriteQueue &&other) = delete; // Add a sprite to load. void Add(const std::shared_ptr<ImageSet> &images); // Unload the texture for the given sprite (to free up memory). void Unload(const std::string &name); // Determine the fraction of sprites uploaded to the GPU. double GetProgress() const; // Uploads any available sprites to the GPU. void UploadSprites(); // Finish loading. void Finish(); // Thread entry point. void operator()(); private: void DoLoad(std::unique_lock<std::mutex> &lock); private: // These are the image sets that need to be loaded from disk. std::queue<std::shared_ptr<ImageSet>> toRead; mutable std::mutex readMutex; std::condition_variable readCondition; int added = 0; // These image sets have been loaded from disk but have not been uploaded. std::queue<std::shared_ptr<ImageSet>> toLoad; std::mutex loadMutex; std::condition_variable loadCondition; int completed = 0; // These sprites must be unloaded to reclaim GPU memory. std::queue<std::string> toUnload; // Worker threads for loading sprites from disk. std::vector<std::thread> threads; }; #endif
0
endless-sky-master
endless-sky-master/source/Outfit.h
/* Outfit.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef OUTFIT_H_ #define OUTFIT_H_ #include "Weapon.h" #include "Dictionary.h" #include <map> #include <string> #include <utility> #include <vector> class Body; class DataNode; class Effect; class Sound; class Sprite; // Class representing an outfit that can be installed in a ship. A ship's // "attributes" are simply stored as a series of key-value pairs, and an outfit // can add to or subtract from any of those values. Weapons also have another // set of attributes unique to them, and outfits can also specify additional // information like the sprite to use in the outfitter panel for selling them, // or the sprite or sound to be used for an engine flare. class Outfit : public Weapon { public: // These are all the possible category strings for outfits. static const std::vector<std::string> CATEGORIES; public: // An "outfit" can be loaded from an "outfit" node or from a ship's // "attributes" node. void Load(const DataNode &node); bool IsDefined() const; const std::string &TrueName() const; const std::string &DisplayName() const; void SetName(const std::string &name); const std::string &PluralName() const; const std::string &Category() const; const std::string &Series() const; const int Index() const; const std::string &Description() const; int64_t Cost() const; double Mass() const; // Get the licenses needed to buy or operate this ship. const std::vector<std::string> &Licenses() const; // Get the image to display in the outfitter when buying this item. const Sprite *Thumbnail() const; double Get(const char *attribute) const; double Get(const std::string &attribute) const; const Dictionary &Attributes() const; // Determine whether the given number of instances of the given outfit can // be added to a ship with the attributes represented by this instance. If // not, return the maximum number that can be added. int CanAdd(const Outfit &other, int count = 1) const; // For tracking a combination of outfits in a ship: add the given number of // instances of the given outfit to this outfit. void Add(const Outfit &other, int count = 1); // Modify this outfit's attributes. Note that this cannot be used to change // special attributes, like cost and mass. void Set(const char *attribute, double value); // Get this outfit's engine flare sprites, if any. const std::vector<std::pair<Body, int>> &FlareSprites() const; const std::vector<std::pair<Body, int>> &ReverseFlareSprites() const; const std::vector<std::pair<Body, int>> &SteeringFlareSprites() const; const std::map<const Sound *, int> &FlareSounds() const; const std::map<const Sound *, int> &ReverseFlareSounds() const; const std::map<const Sound *, int> &SteeringFlareSounds() const; // Get the afterburner effect, if any. const std::map<const Effect *, int> &AfterburnerEffects() const; // Get this outfit's jump effects and sounds, if any. const std::map<const Effect *, int> &JumpEffects() const; const std::map<const Sound *, int> &HyperSounds() const; const std::map<const Sound *, int> &HyperInSounds() const; const std::map<const Sound *, int> &HyperOutSounds() const; const std::map<const Sound *, int> &JumpSounds() const; const std::map<const Sound *, int> &JumpInSounds() const; const std::map<const Sound *, int> &JumpOutSounds() const; // Get the sprite this outfit uses when dumped into space. const Sprite *FlotsamSprite() const; private: bool isDefined = false; std::string trueName; std::string displayName; std::string pluralName; std::string category; // The series that this outfit is a part of and its index within that series. // Used for sorting within shops. std::string series; int index; std::string description; const Sprite *thumbnail = nullptr; int64_t cost = 0; double mass = 0.; // Licenses needed to purchase this item. std::vector<std::string> licenses; Dictionary attributes; // The integers in these pairs/maps indicate the number of // sprites/effects/sounds to be placed/played. std::vector<std::pair<Body, int>> flareSprites; std::vector<std::pair<Body, int>> reverseFlareSprites; std::vector<std::pair<Body, int>> steeringFlareSprites; std::map<const Sound *, int> flareSounds; std::map<const Sound *, int> reverseFlareSounds; std::map<const Sound *, int> steeringFlareSounds; std::map<const Effect *, int> afterburnerEffects; std::map<const Effect *, int> jumpEffects; std::map<const Sound *, int> hyperSounds; std::map<const Sound *, int> hyperInSounds; std::map<const Sound *, int> hyperOutSounds; std::map<const Sound *, int> jumpSounds; std::map<const Sound *, int> jumpInSounds; std::map<const Sound *, int> jumpOutSounds; const Sprite *flotsamSprite = nullptr; }; // These get called a lot, so inline them for speed. inline int64_t Outfit::Cost() const { return cost; } inline double Outfit::Mass() const { return mass; } #endif
0
endless-sky-master
endless-sky-master/source/CaptureOdds.h
/* CaptureOdds.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef CAPTURE_ODDS_H_ #define CAPTURE_ODDS_H_ #include <vector> class Ship; // This class stores the odds that one ship will be able to capture another, and // can report the odds for any number of crew up to what each ship starts out // with (because the odds change each time a crew member is lost). If either // ship has hand-to-hand weapons available, the crew members will make use of // them starting with whatever weapon is most useful to them. In each round of // combat, one ship will lose one crew member. Which ship loses depends on the // ratio of the strengths of the two crews (plus weapons), and whether each crew // is attacking or defending; defending crew get a +1 power bonus. class CaptureOdds { public: // Calculate odds that the first given ship can capture the second, assuming // the first ship always attacks and the second one always defends. CaptureOdds(const Ship &attacker, const Ship &defender); // Get the odds of the attacker winning if the two ships have the given // number of crew members remaining. double Odds(int attackingCrew, int defendingCrew) const; // Get the expected number of casualties in the remainder of the battle if // the two ships have the given number of crew remaining. double AttackerCasualties(int attackingCrew, int defendingCrew) const; double DefenderCasualties(int attackingCrew, int defendingCrew) const; // Get the total power (inherent crew power plus bonuses from hand to hand // weapons) for each ship when they have the given number of crew remaining. double AttackerPower(int attackingCrew) const; double DefenderPower(int defendingCrew) const; private: // Generate the lookup table. void Calculate(); // Map crew numbers into an index in the lookup table. int Index(int attackingCrew, int defendingCrew) const; // Calculate attack or defense power for each number of crew members up to // the given ship's full complement. static std::vector<double> Power(const Ship &ship, bool isDefender); private: // Attacker and defender power lookup tables. std::vector<double> powerA; std::vector<double> powerD; // Capture odds lookup table. std::vector<double> capture; // Expected casualties lookup table. std::vector<double> casualtiesA; std::vector<double> casualtiesD; }; #endif
0
endless-sky-master
endless-sky-master/source/Logger.h
/* Logger.h Copyright (c) 2022 by Peter van der Meer Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef ES_LOGGER_H_ #define ES_LOGGER_H_ #include <functional> #include <string> // Default static logging facility, different programs might have different // conventions and requirements on how they handle logging, so the running // program should register its preferred logging facility when starting up. class Logger { public: static void SetLogErrorCallback(std::function<void(const std::string &message)> callback); static void LogError(const std::string &message); }; #endif
0
endless-sky-master
endless-sky-master/source/Sprite.h
/* Sprite.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef SPRITE_H_ #define SPRITE_H_ #include "Point.h" #include <cstdint> #include <string> class ImageBuffer; // Class representing a drawable sprite. A sprite can have multiple frames, for // animation. Each frame is stored in a separate OpenGL texture object. This may // not be as efficient as sprite sheets, but with modern graphics cards it will // not matter much and it makes working with the graphics a lot simpler. class Sprite { public: explicit Sprite(const std::string &name = ""); const std::string &Name() const; // Upload the given frames. The given buffer will be cleared afterwards. void AddFrames(ImageBuffer &buffer, bool is2x); void AddSwizzleMaskFrames(ImageBuffer &buffer, bool is2x); // Free up all textures loaded for this sprite. void Unload(); // Image dimensions, in pixels. float Width() const; float Height() const; // Number of frames in the animation. If high DPI frames exist, the code has // ensured that they have the same number of frames. int Frames() const; // Get the offset of the center from the top left corner; this is for easy // shifting of corner to center coordinates. Point Center() const; // Get the texture index, either looking it up based on the Screen's HighDPI // setting or specifying it manually. uint32_t Texture() const; uint32_t Texture(bool isHighDPI) const; uint32_t SwizzleMask() const; uint32_t SwizzleMask(bool isHighDPI) const; private: std::string name; uint32_t texture[2] = {0, 0}; uint32_t swizzleMask[2] = {0, 0}; float width = 0.f; float height = 0.f; int frames = 0; }; #endif
0
endless-sky-master
endless-sky-master/source/BoardingPanel.h
/* BoardingPanel.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef BOARDING_PANEL_H_ #define BOARDING_PANEL_H_ #include "Panel.h" #include "CaptureOdds.h" #include <memory> #include <string> #include <vector> class Outfit; class PlayerInfo; class Ship; // This panel is displayed whenever your flagship boards another ship, to give // you a choice of what to plunder or whether to attempt to capture it. The // items you can plunder are shown in a list sorted by value per ton. Ship // capture is "turn-based" combat where each "turn" one or both ships lose crew. class BoardingPanel : public Panel { public: BoardingPanel(PlayerInfo &player, const std::shared_ptr<Ship> &victim); virtual void Draw() override; protected: // Overrides from Panel. virtual bool KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) override; virtual bool Click(int x, int y, int clicks) override; virtual bool Drag(double dx, double dy) override; virtual bool Scroll(double dx, double dy) override; private: // You can't exit this dialog if you are in the middle of combat. bool CanExit() const; // Check if you can take the outfit at the given position in the list. bool CanTake() const; // Check if you can initiate hand to hand combat. bool CanCapture() const; // Check if you are in the midst of hand to hand combat. bool CanAttack() const; // Handle the keyboard scrolling and selection in the panel list. void DoKeyboardNavigation(const SDL_Keycode key); private: // This class represents one item in the list of outfits you can plunder. class Plunder { public: // Plunder can be either outfits or commodities. Plunder(const std::string &commodity, int count, int unitValue); Plunder(const Outfit *outfit, int count); // Sort by value per ton of mass. bool operator<(const Plunder &other) const; // Check how many of this item are left un-plundered. Once this is zero, // the item can be removed from the list. int Count() const; // Get the value of each unit of this plunder item. int64_t UnitValue() const; // Get the name of this item. If it is a commodity, this is its name. const std::string &Name() const; // Get the mass, in the format "<count> x <unit mass>". If this is a // commodity, no unit mass is given (because it is 1). If the count is // 1, only the unit mass is reported. const std::string &Size() const; // Get the total value (unit value times count) as a string. const std::string &Value() const; // If this is an outfit, get the outfit. Otherwise, this returns null. const Outfit *GetOutfit() const; // Find out how many of these I can take if I have this amount of cargo // space free. bool CanTake(const Ship &ship) const; // Take some or all of this plunder item. void Take(int count); private: void UpdateStrings(); double UnitMass() const; private: std::string name; const Outfit *outfit; int count; int64_t unitValue; std::string size; std::string value; }; private: PlayerInfo &player; std::shared_ptr<Ship> you; std::shared_ptr<Ship> victim; // List of items you can plunder. std::vector<Plunder> plunder; int selected = 0; double scroll = 0.; bool playerDied = false; bool isCapturing = false; bool isFirstCaptureAction = true; // Calculating the odds of combat success, and the expected casualties, is // non-trivial. So, cache the results for all crew amounts up to full. CaptureOdds attackOdds; CaptureOdds defenseOdds; // These messages are shown to report the results of hand to hand combat. std::vector<std::string> messages; // Whether or not the ship can be captured. bool canCapture = false; }; #endif
0
endless-sky-master
endless-sky-master/source/DistanceCalculationSettings.cpp
/* DistanceCalculationSettings.cpp Copyright (c) 2023 by warp-core Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "DistanceCalculationSettings.h" #include "DataNode.h" using namespace std; DistanceCalculationSettings::DistanceCalculationSettings(const DataNode &node) { Load(node); } bool DistanceCalculationSettings::operator!=(const DistanceCalculationSettings &other) const { if(wormholeStrategy != other.wormholeStrategy) return true; return assumesJumpDrive != other.assumesJumpDrive; } void DistanceCalculationSettings::Load(const DataNode &node) { for(const auto &child : node) { const string &key = child.Token(0); if(key == "no wormholes") wormholeStrategy = WormholeStrategy::NONE; else if(key == "only unrestricted wormholes") wormholeStrategy = WormholeStrategy::ONLY_UNRESTRICTED; else if(key == "all wormholes") wormholeStrategy = WormholeStrategy::ALL; else if(key == "assumes jump drive") assumesJumpDrive = true; else child.PrintTrace("Invalid distance calculation setting:"); } } WormholeStrategy DistanceCalculationSettings::WormholeStrat() const { return wormholeStrategy; } bool DistanceCalculationSettings::AssumesJumpDrive() const { return assumesJumpDrive; }
0
endless-sky-master
endless-sky-master/source/DistanceMap.h
/* DistanceMap.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef DISTANCE_MAP_H_ #define DISTANCE_MAP_H_ #include "WormholeStrategy.h" #include <map> #include <queue> #include <set> #include <utility> class PlayerInfo; class Ship; class System; // This is a map of how many hyperspace jumps it takes to get to other systems // from the given "center" system. Ships with a hyperdrive travel using the // "links" between systems. Ships with jump drives can make use of those links, // but can also travel to any of a system's "neighbors." A distance map can also // be used to calculate the shortest route between two systems. class DistanceMap { public: // Find paths to the given system. The optional arguments put a limit on how // many systems will be returned and how far away they are allowed to be. explicit DistanceMap(const System *center, int maxCount = -1, int maxDistance = -1); // Find paths to the given system, potentially using wormholes, a jump drive, or both. // Optional arguments are as above. explicit DistanceMap(const System *center, WormholeStrategy wormholeStrategy, bool useJumpDrive, int maxCount = -1, int maxDistance = -1); // If a player is given, the map will only use hyperspace paths known to the // player; that is, one end of the path has been visited. Also, if the // player's flagship has a jump drive, the jumps will be make use of it. explicit DistanceMap(const PlayerInfo &player, const System *center = nullptr); // Calculate the path for the given ship to get to the given system. The // ship will use a jump drive or hyperdrive depending on what it has. The // pathfinding will stop once a path to the destination is found. DistanceMap(const Ship &ship, const System *destination); // Find out if the given system is reachable. bool HasRoute(const System *system) const; // Find out how many days away the given system is. int Days(const System *system) const; // Starting in the given system, what is the next system along the route? const System *Route(const System *system) const; // Get a set containing all the systems. std::set<const System *> Systems() const; // Get the end of the route. const System *End() const; // How much fuel is needed to travel between two systems. int RequiredFuel(const System *system1, const System *system2) const; private: // For each system, track how much fuel it will take to get there, how many // days, how much danger you will pass through, and where you will go next. class Edge { public: explicit Edge(const System *system = nullptr); // Sorting operator to prioritize the "best" edges. The priority queue // returns the "largest" item, so this should return true if this item // is lower priority than the given item. bool operator<(const Edge &other) const; const System *next = nullptr; int fuel = 0; int days = 0; double danger = 0.; }; private: // Depending on the capabilities of the given ship, use hyperspace paths, // jump drive paths, or both to find the shortest route. Bail out if the // source system or the maximum count is reached. void Init(const Ship *ship = nullptr); // Add the given links to the map. Return false if an end condition is hit. bool Propagate(Edge edge, bool useJump); // Check if we already have a better path to the given system. bool HasBetter(const System &to, const Edge &edge); // Add the given path to the record. void Add(const System &to, Edge edge); // Check whether the given link is travelable. If no player was given in the // constructor then this is always true; otherwise, the player must know // that the given link exists. bool CheckLink(const System &from, const System &to, bool useJump) const; private: std::map<const System *, Edge> route; // Variables only used during construction: std::priority_queue<Edge> edges; const PlayerInfo *player = nullptr; const System *source = nullptr; const System *center = nullptr; WormholeStrategy wormholeStrategy = WormholeStrategy::ALL; int maxCount = -1; int maxDistance = -1; // How much fuel is used for travel. If either value is zero, it means that // the ship does not have that type of drive. int hyperspaceFuel = 100; int jumpFuel = 0; double jumpRange = 0.; }; #endif
0
endless-sky-master
endless-sky-master/source/RaidFleet.cpp
/* RaidFleet.cpp Copyright (c) 2023 by Hurleveur Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "RaidFleet.h" #include "DataNode.h" #include "Fleet.h" #include "GameData.h" #include <algorithm> using namespace std; RaidFleet::RaidFleet(const Fleet *fleet, double minAttraction, double maxAttraction) : fleet(fleet), minAttraction(minAttraction), maxAttraction(maxAttraction) { } void RaidFleet::Load(vector<RaidFleet> &raidFleets, const DataNode &node, bool remove, int valueIndex) { const Fleet *fleet = GameData::Fleets().Get(node.Token(valueIndex)); if(remove) { auto fleetMatcher = [fleet](const RaidFleet &raidFleet) noexcept -> bool { return raidFleet.GetFleet() == fleet; }; raidFleets.erase(remove_if(raidFleets.begin(), raidFleets.end(), fleetMatcher), raidFleets.end()); } else raidFleets.emplace_back(fleet, node.Size() > (valueIndex + 1) ? node.Value(valueIndex + 1) : 2., node.Size() > (valueIndex + 2) ? node.Value(valueIndex + 2) : 0.); } const Fleet *RaidFleet::GetFleet() const { return fleet; } double RaidFleet::MinAttraction() const { return minAttraction; } double RaidFleet::MaxAttraction() const { return maxAttraction; }
0
endless-sky-master
endless-sky-master/source/Panel.cpp
/* Panel.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Panel.h" #include "Color.h" #include "Command.h" #include "Dialog.h" #include "FillShader.h" #include "text/Format.h" #include "GameData.h" #include "Point.h" #include "Preferences.h" #include "Screen.h" #include "UI.h" using namespace std; // Move the state of this panel forward one game step. void Panel::Step() { // It is ok for panels to be stateless. } // Return true if this is a full-screen panel, so there is no point in // drawing any of the panels under it. bool Panel::IsFullScreen() const noexcept { return isFullScreen; } // Return true if, when this panel is on the stack, no events should be // passed to any panel under it. By default, all panels do this. bool Panel::TrapAllEvents() const noexcept { return trapAllEvents; } // Check if this panel can be "interrupted" to return to the main menu. bool Panel::IsInterruptible() const noexcept { return isInterruptible; } // Clear the list of clickable zones. void Panel::ClearZones() { zones.clear(); } // Add a clickable zone to the panel. void Panel::AddZone(const Rectangle &rect, const function<void()> &fun) { // The most recently added zone will typically correspond to what was drawn // most recently, so it should be on top. zones.emplace_front(rect, fun); } void Panel::AddZone(const Rectangle &rect, SDL_Keycode key) { AddZone(rect, [this, key](){ this->KeyDown(key, 0, Command(), true); }); } // Check if a click at the given coordinates triggers a clickable zone. If // so, apply that zone's action and return true. bool Panel::ZoneClick(const Point &point) { for(const Zone &zone : zones) if(zone.Contains(point)) { // If the panel is in editing mode, make sure it knows that a mouse // click has broken it out of that mode, so it doesn't interpret a // button press and a text character entered. EndEditing(); zone.Click(); return true; } return false; } // Forward the given TestContext to the Engine under MainPanel. void Panel::SetTestContext(TestContext &testContext) { } // Panels will by default not allow fast-forward. The ones that do allow // it will override this (virtual) function and return true. bool Panel::AllowsFastForward() const noexcept { return false; } // Only override the ones you need; the default action is to return false. bool Panel::KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) { return false; } bool Panel::Click(int x, int y, int clicks) { return false; } bool Panel::RClick(int x, int y) { return false; } bool Panel::Hover(int x, int y) { return false; } bool Panel::Drag(double dx, double dy) { return false; } bool Panel::Scroll(double dx, double dy) { return false; } bool Panel::Release(int x, int y) { return false; } void Panel::SetIsFullScreen(bool set) { isFullScreen = set; } void Panel::SetTrapAllEvents(bool set) { trapAllEvents = set; } void Panel::SetInterruptible(bool set) { isInterruptible = set; } // Dim the background of this panel. void Panel::DrawBackdrop() const { if(!GetUI()->IsTop(this)) return; // Darken everything but the dialog. const Color &back = *GameData::Colors().Get("dialog backdrop"); FillShader::Fill(Point(), Point(Screen::Width(), Screen::Height()), back); } UI *Panel::GetUI() const noexcept { return ui; } // This is not for overriding, but for calling KeyDown with only one or two // arguments. In this form, the command is never set, so you can call this // with a key representing a known keyboard shortcut without worrying that a // user-defined command key will override it. bool Panel::DoKey(SDL_Keycode key, Uint16 mod) { return KeyDown(key, mod, Command(), true); } // A lot of different UI elements allow a modifier to change the number of // something you are buying, so the shared function is defined here: int Panel::Modifier() { SDL_Keymod mod = SDL_GetModState(); int modifier = 1; if(mod & KMOD_ALT) modifier *= 500; if(mod & (KMOD_CTRL | KMOD_GUI)) modifier *= 20; if(mod & KMOD_SHIFT) modifier *= 5; return modifier; } // Display the given help message if it has not yet been shown // (or if force is set to true). Return true if the message was displayed. bool Panel::DoHelp(const string &name, bool force) const { string preference = "help: " + name; if(!force && Preferences::Has(preference)) return false; const string &message = GameData::HelpMessage(name); if(message.empty()) return false; Preferences::Set(preference); ui->Push(new Dialog(Format::Capitalize(name) + ":\n\n" + message)); return true; } void Panel::SetUI(UI *ui) { this->ui = ui; }
0
endless-sky-master
endless-sky-master/source/PlayerInfoPanel.h
/* PlayerInfoPanel.h Copyright (c) 2017 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef PLAYER_INFO_PANEL_H_ #define PLAYER_INFO_PANEL_H_ #include "Panel.h" #include "ClickZone.h" #include "InfoPanelState.h" #include "text/layout.hpp" #include "Point.h" #include <set> #include <vector> class PlayerInfo; class Rectangle; // This panel displays detailed information about the player and their fleet. If // the player is landed on a planet, it also allows them to reorder the ships in // their fleet (including changing which one is the flagship). class PlayerInfoPanel : public Panel { public: explicit PlayerInfoPanel(PlayerInfo &player); explicit PlayerInfoPanel(PlayerInfo &player, InfoPanelState panelState); virtual void Step() override; virtual void Draw() override; // The player info panel allow fast-forward to stay active. bool AllowsFastForward() const noexcept final; protected: // Only override the ones you need; the default action is to return false. virtual bool KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) override; virtual bool Click(int x, int y, int clicks) override; virtual bool Hover(int x, int y) override; virtual bool Drag(double dx, double dy) override; virtual bool Release(int x, int y) override; virtual bool Scroll(double dx, double dy) override; private: // Draw the two subsections of this panel. void DrawPlayer(const Rectangle &bounds); void DrawFleet(const Rectangle &bounds); // Handle mouse hover (also including hover during drag actions): bool Hover(const Point &point); // Adjust the scroll by the given amount. Return true if it changed. bool Scroll(int distance); // Try to scroll to the given position. Return true if position changed. bool ScrollAbsolute(int scroll); void SortShips(InfoPanelState::ShipComparator *shipComparator); class SortableColumn { public: SortableColumn(std::string name, double offset, double endX, Layout layout, InfoPanelState::ShipComparator *shipSort); std::string name; double offset = 0.; double endX = 0.; Layout layout; InfoPanelState::ShipComparator *shipSort = nullptr; }; private: PlayerInfo &player; static const SortableColumn columns[]; InfoPanelState panelState; // Column headers that sort ships when clicked. std::vector<ClickZone<InfoPanelState::ShipComparator *>> menuZones; // Keep track of which ship the mouse is hovering over. int hoverIndex = -1; // Initialize mouse point to something off-screen to not // make the game think the player is hovering on something. Point hoverPoint = Point(-10000, -10000); // When reordering ships, the names of ships being moved are displayed alongside the cursor. bool isDragging = false; }; #endif
0
endless-sky-master
endless-sky-master/source/Test.cpp
/* Test.cpp Copyright (c) 2019-2020 by Peter van der Meer Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Test.h" #include "DataNode.h" #include "text/Format.h" #include "GameData.h" #include "Logger.h" #include "Planet.h" #include "PlayerInfo.h" #include "Ship.h" #include "System.h" #include "TestContext.h" #include "TestData.h" #include <SDL2/SDL.h> #include <algorithm> #include <map> #include <numeric> #include <set> #include <stdexcept> using namespace std; namespace { const auto STATUS_TO_TEXT = map<Test::Status, const string> { {Test::Status::ACTIVE, "active"}, {Test::Status::BROKEN, "broken"}, {Test::Status::KNOWN_FAILURE, "known failure"}, {Test::Status::MISSING_FEATURE, "missing feature"}, {Test::Status::PARTIAL, "partial"}, }; const auto STEPTYPE_TO_TEXT = map<Test::TestStep::Type, const string> { {Test::TestStep::Type::APPLY, "apply"}, {Test::TestStep::Type::ASSERT, "assert"}, {Test::TestStep::Type::BRANCH, "branch"}, {Test::TestStep::Type::CALL, "call"}, {Test::TestStep::Type::INJECT, "inject"}, {Test::TestStep::Type::INPUT, "input"}, {Test::TestStep::Type::LABEL, "label"}, {Test::TestStep::Type::NAVIGATE, "navigate"}, {Test::TestStep::Type::WATCHDOG, "watchdog"}, }; template<class K, class... Args> string ExpectedOptions(const map<K, const string, Args...> &m) { if(m.empty()) return "no options supported"; string beginning = "expected \"" + m.begin()->second; auto lastValidIt = prev(m.end()); // Handle maps with just 1 element. if(lastValidIt == m.begin()) return beginning + "\""; return accumulate(next(m.begin()), lastValidIt, beginning, [](string a, const pair<K, const string> &b) -> string { return std::move(a) + "\", \"" + b.second; }) + "\", or \"" + lastValidIt->second + '"'; } // Prepare a keyboard input to one of the UIs. bool KeyInputToEvent(const char *keyName, Uint16 modKeys) { // Construct the event to send (from keyboard code and modifiers) SDL_Event event; event.type = SDL_KEYDOWN; event.key.state = SDL_PRESSED; event.key.repeat = 0; event.key.keysym.sym = SDL_GetKeyFromName(keyName); if(event.key.keysym.sym == SDLK_UNKNOWN) return false; event.key.keysym.mod = modKeys; return SDL_PushEvent(&event); } bool SendQuitEvent() { SDL_Event event; event.type = SDL_QUIT; return SDL_PushEvent(&event); } string ShipToString(const Ship &ship) { string description = "name: " + ship.Name(); const System *system = ship.GetSystem(); const Planet *planet = ship.GetPlanet(); description += ", system: " + (system ? system->Name() : "<not set>"); description += ", planet: " + (planet ? planet->TrueName() : "<not set>"); description += ", hull: " + Format::Number(ship.Hull()); description += ", shields: " + Format::Number(ship.Shields()); description += ", energy: " + Format::Number(ship.Energy()); description += ", fuel: " + Format::Number(ship.Fuel()); description += ", heat: " + Format::Number(ship.Heat()); return description; } } Test::TestStep::TestStep(Type stepType) : stepType(stepType) { } void Test::TestStep::LoadInput(const DataNode &node) { for(const DataNode &child : node) { if(child.Token(0) == "key") { for(int i = 1; i < child.Size(); ++i) inputKeys.insert(child.Token(i)); for(const DataNode &grand : child) { if(grand.Token(0) == "shift") modKeys |= KMOD_SHIFT; else if(grand.Token(0) == "alt") modKeys |= KMOD_ALT; else if(grand.Token(0) == "control") modKeys |= KMOD_CTRL; else grand.PrintTrace("Skipping unrecognized attribute:"); } } else if(child.Token(0) == "pointer") { for(const DataNode &grand : child) { static const string BAD_AXIS_INPUT = "Error: Pointer axis input without coordinate:"; if(grand.Token(0) == "X") { if(grand.Size() < 2) grand.PrintTrace(BAD_AXIS_INPUT); else XValue = grand.Value(1); } else if(grand.Token(0) == "Y") { if(grand.Size() < 2) grand.PrintTrace(BAD_AXIS_INPUT); else YValue = grand.Value(1); } else if(grand.Token(0) == "click") for(int i = 1; i < grand.Size(); ++i) { if(grand.Token(i) == "left") clickLeft = true; else if(grand.Token(i) == "right") clickRight = true; else if(grand.Token(i) == "middle") clickMiddle = true; else grand.PrintTrace("Warning: Unknown click/button \"" + grand.Token(i) + "\":"); } else grand.PrintTrace("Skipping unrecognized attribute:"); } } else if(child.Token(0) == "command") command.Load(child); else child.PrintTrace("Skipping unrecognized attribute:"); } } void Test::LoadSequence(const DataNode &node) { if(!steps.empty()) { status = Status::BROKEN; node.PrintTrace("Error: duplicate sequence keyword"); return; } for(const DataNode &child : node) { const string &typeName = child.Token(0); auto it = find_if(STEPTYPE_TO_TEXT.begin(), STEPTYPE_TO_TEXT.end(), [&typeName](const std::pair<TestStep::Type, const string> &e) { return e.second == typeName; }); if(it == STEPTYPE_TO_TEXT.end()) { status = Status::BROKEN; child.PrintTrace("Error: Unsupported step type (" + ExpectedOptions(STEPTYPE_TO_TEXT) + "):"); // Don't bother loading more steps once broken. return; } steps.emplace_back(it->first); TestStep &step = steps.back(); switch(step.stepType) { case TestStep::Type::APPLY: case TestStep::Type::ASSERT: step.conditions.Load(child); break; case TestStep::Type::BRANCH: if(child.Size() < 2) { status = Status::BROKEN; child.PrintTrace("Error: Invalid use of \"branch\" without target label:"); return; } step.jumpOnTrueTarget = child.Token(1); if(child.Size() > 2) step.jumpOnFalseTarget = child.Token(2); step.conditions.Load(child); break; case TestStep::Type::CALL: if(child.Size() < 2) { status = Status::BROKEN; child.PrintTrace("Error: Invalid use of \"call\" without name of called (sub)test:"); return; } else step.nameOrLabel = child.Token(1); break; case TestStep::Type::INJECT: if(child.Size() < 2) { status = Status::BROKEN; child.PrintTrace("Error: Invalid use of \"inject\" without data identifier:"); return; } else step.nameOrLabel = child.Token(1); break; case TestStep::Type::INPUT: step.LoadInput(child); break; case TestStep::Type::LABEL: if(child.Size() < 2) child.PrintTrace("Ignoring empty label"); else { step.nameOrLabel = child.Token(1); if(jumpTable.find(step.nameOrLabel) != jumpTable.end()) { child.PrintTrace("Error: duplicate label"); status = Status::BROKEN; return; } else jumpTable[step.nameOrLabel] = steps.size() - 1; } break; case TestStep::Type::NAVIGATE: for(const DataNode &grand : child) { if(grand.Token(0) == "travel" && grand.Size() >= 2) step.travelPlan.push_back(GameData::Systems().Get(grand.Token(1))); else if(grand.Token(0) == "travel destination" && grand.Size() >= 2) step.travelDestination = GameData::Planets().Get(grand.Token(1)); else { grand.PrintTrace("Error: Invalid or incomplete keywords for navigation"); status = Status::BROKEN; } } break; case TestStep::Type::WATCHDOG: step.watchdog = child.Size() >= 2 ? child.Value(1) : 0; break; default: child.PrintTrace("Error: unknown step type in test"); status = Status::BROKEN; return; } } // Check if all jump-labels are present after loading the sequence. for(const TestStep &step : steps) { if(!step.jumpOnTrueTarget.empty() && jumpTable.find(step.jumpOnTrueTarget) == jumpTable.end()) { node.PrintTrace("Error: missing label " + step.jumpOnTrueTarget); status = Status::BROKEN; return; } if(!step.jumpOnFalseTarget.empty() && jumpTable.find(step.jumpOnFalseTarget) == jumpTable.end()) { node.PrintTrace("Error: missing label " + step.jumpOnFalseTarget); status = Status::BROKEN; return; } } } void Test::Load(const DataNode &node) { if(node.Size() < 2) { node.PrintTrace("Error: Unnamed test:"); return; } // If a test object is "loaded" twice, that is most likely an error (e.g. // due to a plugin containing a test with the same name as the base game // or another plugin). Tests should be globally unique. if(!name.empty()) { node.PrintTrace("Error: Duplicate test definition:"); return; } // Validate if the testname contains valid characters. if(node.Token(1).find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _-") != std::string::npos) { node.PrintTrace("Error: Unsupported character(s) in test name:"); return; } name = node.Token(1); for(const DataNode &child : node) { if(child.Token(0) == "status" && child.Size() >= 2) { const string &statusText = child.Token(1); auto it = find_if(STATUS_TO_TEXT.begin(), STATUS_TO_TEXT.end(), [&statusText](const std::pair<Status, const string> &e) { return e.second == statusText; }); if(it != STATUS_TO_TEXT.end()) { // If the test already has a broken status (due to anything // else in loading having failed badly), then don't update // the status from broken. if(status != Status::BROKEN) status = it->first; } else { status = Status::BROKEN; child.PrintTrace("Error: Unsupported status (" + ExpectedOptions(STATUS_TO_TEXT) + "):"); } } else if(child.Token(0) == "sequence") LoadSequence(child); else if(child.Token(0) == "description") { // Provides a human friendly description of the test, but it is not used internally. } else child.PrintTrace("Error: Skipping unrecognized attribute:"); } } const string &Test::Name() const { return name; } Test::Status Test::GetStatus() const { return status; } // Check the game status and perform the next test action. void Test::Step(TestContext &context, PlayerInfo &player, Command &commandToGive) const { // Only run tests once all data has been loaded. if(!GameData::IsLoaded()) return; if(status == Status::BROKEN) Fail(context, player, "Test has a broken status."); // Track if we need to return to the main gameloop. bool continueGameLoop = false; // If the step to run is beyond the end of the steps, then we finished // the current test (and step to the step higher in the stack or we are // done testing if we are at toplevel). if(context.callstack.back().step >= steps.size()) { context.callstack.pop_back(); if(context.callstack.empty()) { // If this test was supposed to fail diagnose this here. if(status >= Status::KNOWN_FAILURE) UnexpectedSuccessResult(); // Done, no failures, exit the game. SendQuitEvent(); return; } else // Step beyond the call statement we just finished. ++(context.callstack.back().step); // We changed the active test or are quitting, so don't run the current one. continueGameLoop = true; } // All processing was done just before this step started. context.branchesSinceGameStep.clear(); while(context.callstack.back().step < steps.size() && !continueGameLoop) { // Fail if we encounter a watchdog timeout if(context.watchdog == 1) Fail(context, player, "watchdog timeout"); else if(context.watchdog > 1) --(context.watchdog); const TestStep &stepToRun = steps[context.callstack.back().step]; switch(stepToRun.stepType) { case TestStep::Type::APPLY: stepToRun.conditions.Apply(player.Conditions()); ++(context.callstack.back().step); break; case TestStep::Type::ASSERT: if(!stepToRun.conditions.Test(player.Conditions())) Fail(context, player, "asserted false"); ++(context.callstack.back().step); break; case TestStep::Type::BRANCH: // If we encounter a branch entry twice, then resume the gameloop before the second encounter. // Encountering branch entries twice typically only happen in "wait loops" and we should give // the game cycles to proceed if we are in a wait loop for something that happens over time. if(context.branchesSinceGameStep.count(context.callstack.back())) { continueGameLoop = true; break; } context.branchesSinceGameStep.emplace(context.callstack.back()); if(stepToRun.conditions.Test(player.Conditions())) context.callstack.back().step = jumpTable.find(stepToRun.jumpOnTrueTarget)->second; else if(!stepToRun.jumpOnFalseTarget.empty()) context.callstack.back().step = jumpTable.find(stepToRun.jumpOnFalseTarget)->second; else ++(context.callstack.back().step); break; case TestStep::Type::CALL: { auto calledTest = GameData::Tests().Find(stepToRun.nameOrLabel); if(nullptr == calledTest) Fail(context, player, "Calling non-existing test \"" + stepToRun.nameOrLabel + "\""); // Put the called test on the stack and start it from 0. context.callstack.push_back({calledTest, 0}); // Break the loop to switch to the test just pushed. } continueGameLoop = true; break; case TestStep::Type::INJECT: { // Lookup the data and inject it in the game or into the environment. const TestData *testData = GameData::TestDataSets().Get(stepToRun.nameOrLabel); if(!testData->Inject()) Fail(context, player, "injecting data failed"); } ++(context.callstack.back().step); break; case TestStep::Type::INPUT: if(stepToRun.command) commandToGive |= stepToRun.command; if(!stepToRun.inputKeys.empty()) { // TODO: handle keys also in-flight (as single inputset) // TODO: combine keys with mouse-inputs for(const string &key : stepToRun.inputKeys) if(!KeyInputToEvent(key.c_str(), stepToRun.modKeys)) Fail(context, player, "key \"" + key + + "\" input towards SDL eventqueue failed"); } // TODO: handle mouse inputs // Make sure that we run a gameloop to process the input. continueGameLoop = true; ++(context.callstack.back().step); break; case TestStep::Type::LABEL: ++(context.callstack.back().step); break; case TestStep::Type::NAVIGATE: player.TravelPlan().clear(); player.TravelPlan() = stepToRun.travelPlan; player.SetTravelDestination(stepToRun.travelDestination); ++(context.callstack.back().step); break; case TestStep::Type::WATCHDOG: context.watchdog = stepToRun.watchdog; ++(context.callstack.back().step); break; default: Fail(context, player, "Unknown step type"); break; } } } const string &Test::StatusText() const { return STATUS_TO_TEXT.at(status); } // Get the names of the conditions relevant for this test. std::set<std::string> Test::RelevantConditions() const { set<string> conditionNames; for(const auto &step : steps) { switch(step.stepType) { case TestStep::Type::APPLY: case TestStep::Type::ASSERT: case TestStep::Type::BRANCH: { for(const auto &name : step.conditions.RelevantConditions()) conditionNames.emplace(name); } break; case TestStep::Type::CALL: { auto calledTest = GameData::Tests().Find(step.nameOrLabel); if(!calledTest) continue; for(const auto &name : calledTest->RelevantConditions()) conditionNames.emplace(name); } break; default: continue; } } return conditionNames; } // Fail the test using the given message as reason. void Test::Fail(const TestContext &context, const PlayerInfo &player, const string &testFailReason) const { string message = "Test failed"; if(!testFailReason.empty()) message += ": " + testFailReason; message += "\n"; Logger::LogError(message); // Print the callstack if we have any. string stackMessage = "Call-stack:\n"; if(context.callstack.empty()) stackMessage += " No callstack info at moment of failure."; for(auto i = context.callstack.rbegin(); i != context.callstack.rend(); ++i) { stackMessage += "- \"" + i->test->Name() + "\", step: " + to_string(1 + i->step); if(i->step < i->test->steps.size()) stackMessage += " (" + STEPTYPE_TO_TEXT.at(((i->test->steps)[i->step]).stepType) + ")"; stackMessage += "\n"; } Logger::LogError(stackMessage); // Print some debug information about the flagship and the first 5 escorts. const Ship *flagship = player.Flagship(); if(!flagship) Logger::LogError("No flagship at the moment of failure."); else { string shipsOverview = "flagship " + ShipToString(*flagship) + "\n"; int escorts = 0; int escortsNotPrinted = 0; for(auto &&ptr : flagship->GetEscorts()) { auto escort = ptr.lock(); if(!escort) continue; if(++escorts <= 5) shipsOverview += "escort " + ShipToString(*escort) + "\n"; else ++escortsNotPrinted; } if(escortsNotPrinted > 0) shipsOverview += "(plus " + to_string(escortsNotPrinted) + " additional escorts)\n"; Logger::LogError(shipsOverview); } // Print all conditions that are used in the test. string conditions; for(const auto &it : RelevantConditions()) { const auto &val = player.Conditions().HasGet(it); conditions += "Condition: \"" + it + "\" = " + (val.first ? to_string(val.second) : "(not set)") + "\n"; } if(!conditions.empty()) Logger::LogError(conditions); else Logger::LogError("No conditions to display at the moment of failure."); // If this test was expected to fail, then return a success exitcode from the program // because the test did what it was expected to do. if(status >= Status::KNOWN_FAILURE) throw known_failure_tag{}; // Throwing a runtime_error is kinda rude, but works for this version of // the tester. Might want to add a menuPanels.QuitError() function in // a later version (which can set a non-zero exitcode and exit properly). throw runtime_error(message); } void Test::UnexpectedSuccessResult() const { throw runtime_error("Unexpected test result: Test marked with status '" + StatusText() + "' was not expected to finish successfully.\n"); }
0
endless-sky-master
endless-sky-master/source/Plugins.cpp
/* Plugins.cpp Copyright (c) 2022 by Sam Gleske (samrocketman on GitHub) Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Plugins.h" #include "DataFile.h" #include "DataNode.h" #include "DataWriter.h" #include "Files.h" #include "Logger.h" #include <algorithm> #include <map> using namespace std; namespace { Set<Plugin> plugins; void LoadSettingsFromFile(const string &path) { DataFile prefs(path); for(const DataNode &node : prefs) { if(node.Token(0) != "state") continue; for(const DataNode &child : node) if(child.Size() == 2) { auto *plugin = plugins.Get(child.Token(0)); plugin->enabled = child.Value(1); plugin->currentState = child.Value(1); } } } } // Checks whether this plugin is valid, i.e. whether it exists. bool Plugin::IsValid() const { return !name.empty(); } // Attempt to load a plugin at the given path. const Plugin *Plugins::Load(const string &path) { // Get the name of the folder containing the plugin. size_t pos = path.rfind('/', path.length() - 2) + 1; string name = path.substr(pos, path.length() - 1 - pos); string pluginFile = path + "plugin.txt"; string aboutText; // Load plugin metadata from plugin.txt. bool hasName = false; for(const DataNode &child : DataFile(pluginFile)) { if(child.Token(0) == "name" && child.Size() >= 2) { name = child.Token(1); hasName = true; } else if(child.Token(0) == "about" && child.Size() >= 2) aboutText = child.Token(1); else child.PrintTrace("Skipping unrecognized attribute:"); } // 'name' is a required field for plugins with a plugin description file. if(Files::Exists(pluginFile) && !hasName) Logger::LogError("Warning: Missing required \"name\" field inside plugin.txt"); // Plugin names should be unique. auto *plugin = plugins.Get(name); if(plugin && plugin->IsValid()) { Logger::LogError("Warning: Skipping plugin located at \"" + path + "\" because another plugin with the same name has already been loaded from: \"" + plugin->path + "\"."); return nullptr; } plugin->name = std::move(name); plugin->path = path; // Read the deprecated about.txt content if no about text was specified. plugin->aboutText = aboutText.empty() ? Files::Read(path + "about.txt") : std::move(aboutText); return plugin; } void Plugins::LoadSettings() { // Global plugin settings LoadSettingsFromFile(Files::Resources() + "plugins.txt"); // Local plugin settings LoadSettingsFromFile(Files::Config() + "plugins.txt"); } void Plugins::Save() { if(plugins.empty()) return; DataWriter out(Files::Config() + "plugins.txt"); out.Write("state"); out.BeginChild(); { for(const auto &it : plugins) if(it.second.IsValid()) out.Write(it.first, it.second.currentState); } out.EndChild(); } // Whether the path points to a valid plugin. bool Plugins::IsPlugin(const string &path) { // A folder is a valid plugin if it contains one (or more) of the assets folders. // (They can be empty too). return Files::Exists(path + "data") || Files::Exists(path + "images") || Files::Exists(path + "sounds"); } // Returns true if any plugin enabled or disabled setting has changed since // launched via user preferences. bool Plugins::HasChanged() { for(const auto &it : plugins) if(it.second.enabled != it.second.currentState) return true; return false; } // Returns the list of plugins that have been identified by the game. const Set<Plugin> &Plugins::Get() { return plugins; } // Toggles enabling or disabling a plugin for the next game restart. void Plugins::TogglePlugin(const string &name) { auto *plugin = plugins.Get(name); plugin->currentState = !plugin->currentState; }
0
endless-sky-master
endless-sky-master/source/RaidFleet.h
/* RaidFleet.h Copyright (c) 2023 by Hurleveur Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef RAID_FLEET_H_ #define RAID_FLEET_H_ #include <vector> class Fleet; class DataNode; // Information about how a fleet intended for raiding behaves. class RaidFleet { public: RaidFleet(const Fleet *fleet, double minAttraction, double maxAttraction); // Handles the addition and removal of raid fleets from the given vector. static void Load(std::vector<RaidFleet> &raidFleets, const DataNode &node, bool remove, int valueIndex); const Fleet *GetFleet() const; double MinAttraction() const; double MaxAttraction() const; private: const Fleet *fleet = nullptr; double minAttraction; double maxAttraction; }; #endif
0
endless-sky-master
endless-sky-master/source/Projectile.cpp
/* Projectile.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Projectile.h" #include "Effect.h" #include "pi.h" #include "Random.h" #include "Ship.h" #include "Visual.h" #include "Weapon.h" #include <algorithm> #include <cmath> using namespace std; namespace { // Given the probability of losing a lock in five tries, check randomly // whether it should be lost on this try. inline bool Check(double probability, double base) { return (Random::Real() < base * pow(probability, .2)); } // Returns if the missile is confused or not. bool ConfusedTracking(double tracking, double weaponRange, double jamming, double distance) { if(!jamming) return Random::Real() > tracking; else return Random::Real() > (tracking * distance) / (sqrt(jamming) * weaponRange); } } Projectile::Projectile(const Ship &parent, Point position, Angle angle, const Weapon *weapon) : Body(weapon->WeaponSprite(), position, parent.Velocity(), angle), weapon(weapon), targetShip(parent.GetTargetShip()), lifetime(weapon->Lifetime()) { government = parent.GetGovernment(); // If you are boarding your target, do not fire on it. if(parent.IsBoarding() || parent.Commands().Has(Command::BOARD)) targetShip.reset(); cachedTarget = TargetPtr().get(); if(cachedTarget) targetGovernment = cachedTarget->GetGovernment(); dV = this->angle.Unit() * (weapon->Velocity() + Random::Real() * weapon->RandomVelocity()); velocity += dV; // If a random lifetime is specified, add a random amount up to that amount. if(weapon->RandomLifetime()) lifetime += Random::Int(weapon->RandomLifetime() + 1); } Projectile::Projectile(const Projectile &parent, const Point &offset, const Angle &angle, const Weapon *weapon) : Body(weapon->WeaponSprite(), parent.position + parent.velocity + parent.angle.Rotate(offset), parent.velocity, parent.angle + angle), weapon(weapon), targetShip(parent.targetShip), lifetime(weapon->Lifetime()) { government = parent.government; targetGovernment = parent.targetGovernment; cachedTarget = TargetPtr().get(); // Given that submunitions inherit the velocity of the parent projectile, // it is often the case that submunitions don't add any additional velocity. // But we still want inaccuracy to have an effect on submunitions. Because of // this, we tilt the velocity of submunitions in the direction of the inaccuracy. dV = this->angle.Unit() * (parent.dV.Length() + weapon->Velocity() + Random::Real() * weapon->RandomVelocity()); velocity += dV - parent.dV; // If a random lifetime is specified, add a random amount up to that amount. if(weapon->RandomLifetime()) lifetime += Random::Int(weapon->RandomLifetime() + 1); } // Ship explosion. Projectile::Projectile(Point position, const Weapon *weapon) : weapon(weapon) { this->position = std::move(position); } // This returns false if it is time to delete this projectile. void Projectile::Move(vector<Visual> &visuals, vector<Projectile> &projectiles) { if(--lifetime <= 0) { if(lifetime > -100) { // This projectile died a "natural" death. Create any death effects // and submunitions. for(const auto &it : weapon->DieEffects()) for(int i = 0; i < it.second; ++i) visuals.emplace_back(*it.first, position, velocity, angle); for(const auto &it : weapon->Submunitions()) for(size_t i = 0; i < it.count; ++i) { const Weapon *const subWeapon = it.weapon; Angle inaccuracy = Distribution::GenerateInaccuracy(subWeapon->Inaccuracy(), subWeapon->InaccuracyDistribution()); projectiles.emplace_back(*this, it.offset, it.facing + inaccuracy, subWeapon); } } MarkForRemoval(); return; } for(const auto &it : weapon->LiveEffects()) if(!Random::Int(it.second)) visuals.emplace_back(*it.first, position, velocity, angle); // If the target has left the system, stop following it. Also stop if the // target has been captured by a different government. const Ship *target = cachedTarget; if(target) { target = TargetPtr().get(); if(!target || !target->IsTargetable() || target->GetGovernment() != targetGovernment) { targetShip.reset(); cachedTarget = nullptr; target = nullptr; } } double turn = weapon->Turn(); double accel = weapon->Acceleration(); int homing = weapon->Homing(); if(target && homing && !Random::Int(30)) CheckLock(*target); if(target && homing && hasLock) { // Vector d is the direction we want to turn towards. Point d = target->Position() - position; Point unit = d.Unit(); double drag = weapon->Drag(); double trueVelocity = drag ? accel / drag : velocity.Length(); double stepsToReach = d.Length() / trueVelocity; bool isFacingAway = d.Dot(angle.Unit()) < 0.; // At the highest homing level, compensate for target motion. if(homing >= 4) { if(unit.Dot(target->Velocity()) < 0.) { // If the target is moving toward this projectile, the intercept // course is where the target and the projectile have the same // velocity normal to the distance between them. Point normal(unit.Y(), -unit.X()); double vN = normal.Dot(target->Velocity()); double vT = sqrt(max(0., trueVelocity * trueVelocity - vN * vN)); d = vT * unit + vN * normal; } else { // Adjust the target's position based on where it will be when we // reach it (assuming we're pointed right towards it). d += stepsToReach * target->Velocity(); stepsToReach = d.Length() / trueVelocity; } unit = d.Unit(); } double cross = angle.Unit().Cross(unit); // The very dumbest of homing missiles lose their target if pointed // away from it. if(isFacingAway && homing == 1) targetShip.reset(); else { double desiredTurn = TO_DEG * asin(cross); if(fabs(desiredTurn) > turn) turn = copysign(turn, desiredTurn); else turn = desiredTurn; // Levels 3 and 4 stop accelerating when facing away. if(homing >= 3) { double stepsToFace = desiredTurn / turn; // If you are facing away from the target, stop accelerating. if(stepsToFace * 1.5 > stepsToReach) accel = 0.; } } } // Homing weapons that have lost their lock have a chance to get confused // and turn in a random direction ("go haywire"). Each tracking method has // a different haywire condition. Weapons with multiple tracking methods // only go haywire if all of the tracking methods have gotten confused. else if(target && homing) { bool infraredConfused = true; bool opticalConfused = true; bool radarConfused = true; // Infrared: proportional to tracking quality. if(weapon->InfraredTracking()) infraredConfused = Random::Real() > weapon->InfraredTracking(); // Optical and Radar: If the target has no jamming, then proportional to tracking // quality. If the target does have jamming, then it's proportional to // tracking quality, the strength of target's jamming, and the distance // to the target (jamming power attenuates with distance). double distance = position.Distance(target->Position()); if(weapon->OpticalTracking()) { double opticalTracking = weapon->OpticalTracking(); double opticalJamming = target->Attributes().Get("optical jamming"); opticalConfused = ConfusedTracking(opticalTracking, weapon->Range(), opticalJamming, distance); } if(weapon->RadarTracking()) { double radarTracking = weapon->RadarTracking(); double radarJamming = target->Attributes().Get("radar jamming"); radarConfused = ConfusedTracking(radarTracking, weapon->Range(), radarJamming, distance); } if(infraredConfused && opticalConfused && radarConfused) turn = Random::Real() - min(.5, turn); } // If a weapon is homing but has no target, do not turn it. else if(homing) turn = 0.; if(turn) angle += Angle(turn); if(accel) { double d = 1. - weapon->Drag(); Point a = accel * angle.Unit(); velocity *= d; velocity += a; dV *= d; dV += a; } position += velocity; // Only measure the distance that this projectile traveled under its own // power, as opposed to including any velocity that came from the firing // ship. distanceTraveled += dV.Length(); // If this projectile is now within its "split range," it should split into // sub-munitions next turn. if(target && (position - target->Position()).Length() < weapon->SplitRange()) lifetime = 0; // A projectile will begin to fade out when the remaining lifetime is smaller // than the specified "fade out" time. if(lifetime < weapon->FadeOut()) alpha = static_cast<double>(lifetime) / weapon->FadeOut(); } // This projectile hit something. Create the explosion, if any. This also // marks the projectile as needing deletion. void Projectile::Explode(vector<Visual> &visuals, double intersection, Point hitVelocity) { clip = intersection; distanceTraveled += dV.Length() * intersection; for(const auto &it : weapon->HitEffects()) for(int i = 0; i < it.second; ++i) { visuals.emplace_back(*it.first, position + velocity * intersection, velocity, angle, hitVelocity); } lifetime = -100; } // Get the amount of clipping that should be applied when drawing this projectile. double Projectile::Clip() const { return clip; } // This projectile was killed, e.g. by an anti-missile system. void Projectile::Kill() { lifetime = 0; } // Find out if this is a missile, and if so, how strong it is (i.e. what // chance an anti-missile shot has of destroying it). int Projectile::MissileStrength() const { return weapon->MissileStrength(); } // Get information on the weapon that fired this projectile. const Weapon &Projectile::GetWeapon() const { return *weapon; } // Get information on how this projectile impacted a ship. Projectile::ImpactInfo Projectile::GetInfo() const { return ImpactInfo(*weapon, position, distanceTraveled); } // Find out which ship this projectile is targeting. const Ship *Projectile::Target() const { return cachedTarget; } const Government *Projectile::TargetGovernment() const { return targetGovernment; } shared_ptr<Ship> Projectile::TargetPtr() const { return targetShip.lock(); } // Clear the targeting information on this projectile. void Projectile::BreakTarget() { targetShip.reset(); cachedTarget = nullptr; targetGovernment = nullptr; } // TODO: add more conditions in the future. For example maybe proximity to stars // and their brightness could could cause IR missiles to lose their locks more // often, and dense asteroid fields could do the same for radar and optically // guided missiles. void Projectile::CheckLock(const Ship &target) { double base = hasLock ? 1. : .15; hasLock = false; // For each tracking type, calculate the probability twice every second that a // lock will be lost. if(weapon->Tracking()) hasLock |= Check(weapon->Tracking(), base); // Optical tracking is about 15% for interceptors and 75% for medium warships, // but can be affected by jamming. if(weapon->OpticalTracking()) { double opticalJamming = target.IsDisabled() ? 0. : target.Attributes().Get("optical jamming"); if(opticalJamming) { double distance = position.Distance(target.Position()); double jammingRange = 500. + sqrt(opticalJamming) * 500.; double rangeFraction = min(1., distance / jammingRange); opticalJamming = (1. - rangeFraction) * opticalJamming; } double weight = target.Mass() * target.Mass(); double probability = weapon->OpticalTracking() * weight / (150000. + weight) / (1. + opticalJamming); hasLock |= Check(probability, base); } // Infrared tracking is 5% when heat is zero and 100% when heat is full. // When the missile is at under 1/3 of its maximum range, tracking is // linearly increased by up to a factor of 3, representing the fact that the // wavelengths of IR radiation are easier to distinguish at closer distances. if(weapon->InfraredTracking()) { double distance = position.Distance(target.Position()); double shortRange = weapon->Range() * 0.33; double multiplier = 1.; if(distance <= shortRange) multiplier = 2. - distance / shortRange; double probability = weapon->InfraredTracking() * min(1., target.Heat() * multiplier + .05); hasLock |= Check(probability, base); } // Radar tracking depends on whether the target ship has jamming capabilities. // The jamming effect attenuates with range, and that range is affected by // the power of the jamming. Jamming of 2 will cause a sidewinder fired at // least 1200 units away from a maneuvering target to miss about 25% of the // time. Jamming of 10 will increase that to about 60%. if(weapon->RadarTracking()) { double radarJamming = target.IsDisabled() ? 0. : target.Attributes().Get("radar jamming"); if(radarJamming) { double distance = position.Distance(target.Position()); double jammingRange = 500. + sqrt(radarJamming) * 500.; double rangeFraction = min(1., distance / jammingRange); radarJamming = (1. - rangeFraction) * radarJamming; } double probability = weapon->RadarTracking() / (1. + radarJamming); hasLock |= Check(probability, base); } } double Projectile::DistanceTraveled() const { return distanceTraveled; }
0
endless-sky-master
endless-sky-master/source/EscortDisplay.h
/* EscortDisplay.h Copyright (c) 2015 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef ESCORT_DISPLAY_H_ #define ESCORT_DISPLAY_H_ #include "Rectangle.h" #include <cstdint> #include <list> #include <string> #include <vector> class Interface; class Ship; class Sprite; // This class stores a list of escorts, sorted according to their value and // stacked if necessary to get them to all fit on screen. class EscortDisplay { public: void Clear(); void Add(const Ship &ship, bool isHere, bool fleetIsJumping, bool isSelected); // Draw as many escort icons as will fit in the given bounding box. void Draw(const Rectangle &bounds) const; // Check if the given point is a click on an escort icon. If so, return the // stack of ships represented by the icon. Otherwise, return an empty stack. const std::vector<const Ship *> &Click(const Point &point) const; private: class Icon { public: Icon(const Ship &ship, bool isHere, bool fleetIsJumping, bool isSelected, int basicHeight, int systemLabelHeight); // Sorting operator. bool operator<(const Icon &other) const; int Height() const; void Merge(const Icon &other); const Sprite *sprite; bool isDisabled; bool isHere; bool isHostile; bool notReadyToJump; bool cannotJump; bool isSelected; int64_t cost; std::string system; std::vector<double> low; std::vector<double> high; std::vector<const Ship *> ships; int height = 0; }; private: void MergeStacks(int maxHeight) const; private: mutable std::list<Icon> icons; mutable std::vector<std::vector<const Ship *>> stacks; mutable std::vector<Rectangle> zones; const Interface *element = nullptr; int basicHeight = 0; int systemLabelHeight = 0; }; #endif
0
endless-sky-master
endless-sky-master/source/ImageSet.h
/* ImageSet.h Copyright (c) 2017 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef IMAGE_SET_H_ #define IMAGE_SET_H_ #include "ImageBuffer.h" #include <cstddef> #include <map> #include <string> #include <vector> class Mask; class Sprite; // An ImageSet is a collection of file paths for all the images that must be // loaded for a given sprite, including 1x and 2x resolution variants. It also // stores masks for any sprite for which they should be calculated. class ImageSet { public: // Check if the given path is to an image of a valid file type. static bool IsImage(const std::string &path); // Get the base name for the given path. The path should be relative to one // of the source image directories, not a full filesystem path. static std::string Name(const std::string &path); // Determine whether the given path or name is for a sprite whose loading // should be deferred until needed. static bool IsDeferred(const std::string &path); public: // ImageSets should be created with a name, as some image paths (e.g. plugin icons) // do not contain the associated image name. explicit ImageSet(std::string name); // Get the name of the sprite for this image set. const std::string &Name() const; // Whether this image set is empty, i.e. has no images. bool IsEmpty() const; // Add a single image to this set. Assume the name of the image has already // been checked to make sure it belongs in this set. void Add(std::string path); // Reduce all given paths to frame images into a sequence of consecutive frames. void ValidateFrames() noexcept(false); // Load all the frames. This should be called in one of the image-loading // worker threads. This also generates collision masks if needed. void Load() noexcept(false); // Create the sprite and upload the image data to the GPU. After this is // called, the internal image buffers and mask vector will be cleared, but // the paths are saved in case the sprite needs to be loaded again. void Upload(Sprite *sprite); private: // Name of the sprite that will be initialized with these images. std::string name; // Paths to all the images that were discovered during loading. std::map<std::size_t, std::string> framePaths[4]; // Paths that comprise a valid animation sequence of 1 or more frames. std::vector<std::string> paths[4]; // Data loaded from the images: ImageBuffer buffer[4]; std::vector<Mask> masks; }; #endif
0
endless-sky-master
endless-sky-master/source/Sound.h
/* Sound.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef SOUND_H_ #define SOUND_H_ #include <string> // This is a sound that can be played. The sound's file name will determine // whether it is looping (ends in '~') or not. class Sound { public: bool Load(const std::string &path, const std::string &name); const std::string &Name() const; unsigned Buffer() const; bool IsLooping() const; private: std::string name; unsigned buffer = 0; bool isLooped = false; }; #endif
0
endless-sky-master
endless-sky-master/source/SpriteQueue.cpp
/* SpriteQueue.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "SpriteQueue.h" #include "ImageSet.h" #include "Sprite.h" #include "SpriteSet.h" #include <algorithm> #include <functional> using namespace std; namespace { // The maximum number of loaded images in the queue that are // waiting to be uploaded to the GPU. constexpr int MAX_QUEUE = 100; } // Constructor, which allocates worker threads. SpriteQueue::SpriteQueue() { threads.resize(max(4u, thread::hardware_concurrency())); for(thread &t : threads) t = thread(ref(*this)); } // Destructor, which waits for all worker threads to wrap up. SpriteQueue::~SpriteQueue() { { lock_guard<mutex> lock(readMutex); added = -1; } readCondition.notify_all(); for(thread &t : threads) t.join(); } // Add a sprite to load. void SpriteQueue::Add(const shared_ptr<ImageSet> &images) { { lock_guard<mutex> lock(readMutex); // Do nothing if we are destroying the queue already. if(added < 0) return; toRead.push(images); ++added; } readCondition.notify_one(); } // Unload the texture for the given sprite (to free up memory). void SpriteQueue::Unload(const string &name) { unique_lock<mutex> lock(loadMutex); toUnload.push(name); } // Determine the fraction of sprites uploaded to the GPU. double SpriteQueue::GetProgress() const { // Wait until we have completed loading of as many sprites as we have added. // The value of "added" is protected by readMutex. unique_lock<mutex> readLock(readMutex); // Special cases: we're bailing out, or we are done. if(added <= 0 || added == completed) return 1.; return static_cast<double>(completed) / static_cast<double>(added); } void SpriteQueue::UploadSprites() { unique_lock<mutex> lock(loadMutex); DoLoad(lock); } // Finish loading. void SpriteQueue::Finish() { // Loop until done loading. while(true) { unique_lock<mutex> lock(loadMutex); // Load whatever is already queued up for loading. DoLoad(lock); lock.unlock(); if(GetProgress() == 1.) break; lock.lock(); // We still have sprites to upload, but none of them have been read from // disk yet. Wait until one arrives. loadCondition.wait(lock, [this] { return !toLoad.empty(); }); } } // Thread entry point. void SpriteQueue::operator()() { while(true) { unique_lock<mutex> lock(readMutex); while(true) { // To signal this thread that it is time for it to quit, we set // "added" to -1. if(added < 0) return; if(toRead.empty()) break; { // Stop loading images so that the main thread can keep up. unique_lock<mutex> lock(loadMutex); if(toLoad.size() > MAX_QUEUE) break; } // Extract the one item we should work on reading right now. shared_ptr<ImageSet> imageSet = toRead.front(); toRead.pop(); // It's now safe to add to the lists. lock.unlock(); // Load the sprite. // TODO: investigate catching exceptions from Load() (e.g. bad_alloc), to enable // the UI thread to display a message prior to terminating the process. imageSet->Load(); { // The texture must be uploaded to OpenGL in the main thread. unique_lock<mutex> lock(loadMutex); toLoad.push(imageSet); } loadCondition.notify_one(); lock.lock(); } readCondition.wait(lock, [this] { return added < 0 || !toRead.empty(); }); } } void SpriteQueue::DoLoad(unique_lock<mutex> &lock) { while(!toUnload.empty()) { Sprite *sprite = SpriteSet::Modify(toUnload.front()); toUnload.pop(); lock.unlock(); sprite->Unload(); lock.lock(); } for(int i = 0; !toLoad.empty() && i < MAX_QUEUE; ++i) { // Extract the one item we should work on uploading right now. shared_ptr<ImageSet> imageSet = toLoad.front(); toLoad.pop(); // It's now safe to modify the lists. lock.unlock(); readCondition.notify_one(); imageSet->Upload(SpriteSet::Modify(imageSet->Name())); lock.lock(); ++completed; } }
0
endless-sky-master
endless-sky-master/source/Minable.cpp
/* Minable.cpp Copyright (c) 2016 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Minable.h" #include "DataNode.h" #include "Effect.h" #include "Flotsam.h" #include "text/Format.h" #include "GameData.h" #include "Outfit.h" #include "pi.h" #include "Projectile.h" #include "Random.h" #include "SpriteSet.h" #include "Visual.h" #include <algorithm> #include <cmath> using namespace std; // Load a definition of a minable object. void Minable::Load(const DataNode &node) { // Set the name of this minable, so we know it has been loaded. if(node.Size() >= 2) name = node.Token(1); for(const DataNode &child : node) { if(child.Token(0) == "display name" && child.Size() >= 2) displayName = child.Token(1); else if(child.Token(0) == "noun" && child.Size() >= 2) noun = child.Token(1); // A full sprite definition (frame rate, etc.) is not needed, because // the frame rate will be set randomly and it will always be looping. else if(child.Token(0) == "sprite" && child.Size() >= 2) SetSprite(SpriteSet::Get(child.Token(1))); else if(child.Token(0) == "hull" && child.Size() >= 2) hull = child.Value(1); else if(child.Token(0) == "random hull" && child.Size() >= 2) randomHull = max(0., child.Value(1)); else if((child.Token(0) == "payload" || child.Token(0) == "explode") && child.Size() >= 2) { int count = (child.Size() == 2 ? 1 : child.Value(2)); if(child.Token(0) == "payload") payload[GameData::Outfits().Get(child.Token(1))] += count; else explosions[GameData::Effects().Get(child.Token(1))] += count; } else child.PrintTrace("Skipping unrecognized attribute:"); } if(displayName.empty()) displayName = Format::Capitalize(name); if(noun.empty()) noun = "Asteroid"; } // Calculate the expected payload value of this Minable after all outfits have been fully loaded. void Minable::FinishLoading() { for(const auto &it : payload) value += it.first->Cost() * it.second * 0.25; } const string &Minable::TrueName() const { return name; } const string &Minable::DisplayName() const { return displayName; } const string &Minable::Noun() const { return noun; } // Place a minable object with up to the given energy level, on a random // orbit and a random position along that orbit. void Minable::Place(double energy, double beltRadius) { // Note: there's no closed-form equation for orbital position as a function // of time, so either I need to use Newton's method to get high precision // (which, for a game would be overkill) or something will drift over time. // If that drift caused the orbit to decay, that would be a problem, which // rules out just applying gravity as a force from the system center. // Instead, each orbit is defined by an ellipse equation: // 1 / radius = constant * (1 + eccentricity * cos(theta)). // The only thing that will change over time is theta, the "true anomaly." // That way, the orbital period will only be approximate (which does not // really matter) but the orbit itself will never decay. // Generate random orbital parameters. Limit eccentricity so that the // objects do not spend too much time far away and moving slowly. eccentricity = Random::Real() * .6; // Since an object is moving slower at apoapsis than at periapsis, it is // more likely to start out there. So, rather than a uniform distribution of // angles, favor ones near 180 degrees. (Note: this is not the "correct" // equation; it is just a reasonable approximation.) theta = Random::Real(); double curved = (pow(asin(theta * 2. - 1.) / (.5 * PI), 3.) + 1.) * .5; theta = (eccentricity * curved + (1. - eccentricity) * theta) * 2. * PI; // Now, pick the orbital "scale" such that, relative to the "belt radius": // periapsis distance (scale / (1 + e)) is no closer than .4: scale >= .4 * (1 + e) // apoapsis distance (scale / (1 - e)) is no farther than 4.: scale <= 4. * (1 - e) // periapsis distance is no farther than 1.3: scale <= 1.3 * (1 + e) // apoapsis distance is no closer than .8: scale >= .8 * (1 - e) double sMin = max(.4 * (1. + eccentricity), .8 * (1. - eccentricity)); double sMax = min(4. * (1. - eccentricity), 1.3 * (1. + eccentricity)); orbitScale = (sMin + Random::Real() * (sMax - sMin)) * beltRadius; // At periapsis, the object should have this velocity: double maximumVelocity = (Random::Real() + 2. * eccentricity) * .5 * energy; // That means that its angular momentum is equal to: angularMomentum = (maximumVelocity * orbitScale) / (1. + eccentricity); // Start the object off with a random facing angle and spin rate. angle = Angle::Random(); spin = Angle::Random(energy) - Angle::Random(energy); SetFrameRate(Random::Real() * 4. * energy + 5.); // Choose a random direction for the angle of periapsis. rotation = Random::Real() * 2. * PI; // Calculate the object's initial position. radius = orbitScale / (1. + eccentricity * cos(theta)); position = radius * Point(cos(theta + rotation), sin(theta + rotation)); // Add a random amount of hull value to the object. hull += Random::Real() * randomHull; maxHull = hull; } // Move the object forward one step. If it has been reduced to zero hull, it // will "explode" instead of moving, creating flotsam and explosion effects. // In that case it will return false, meaning it should be deleted. bool Minable::Move(vector<Visual> &visuals, list<shared_ptr<Flotsam>> &flotsam) { if(hull < 0) { // This object has been destroyed. Create explosions and flotsam. double scale = .1 * Radius(); for(const auto &it : explosions) { for(int i = 0; i < it.second; ++i) { // Add a random velocity. Point dp = (Random::Real() * scale) * Angle::Random().Unit(); visuals.emplace_back(*it.first, position + 2. * dp, velocity + dp, angle); } } for(const auto &it : payload) { if(it.second < 1) continue; // Each payload object has a 25% chance of surviving. This creates // a distribution with occasional very good payoffs. for(int amount = Random::Binomial(it.second, .25); amount > 0; amount -= Flotsam::TONS_PER_BOX) { flotsam.emplace_back(new Flotsam(it.first, min(amount, Flotsam::TONS_PER_BOX))); flotsam.back()->Place(*this); } } return false; } // Spin the object. angle += spin; // Advance the object forward one step. theta += angularMomentum / (radius * radius); radius = orbitScale / (1. + eccentricity * cos(theta)); // Calculate the new position. Point newPosition(radius * cos(theta + rotation), radius * sin(theta + rotation)); // Calculate the velocity this object is moving at, so that its motion blur // will be rendered correctly. velocity = newPosition - position; position = newPosition; return true; } // Damage this object (because a projectile collided with it). void Minable::TakeDamage(const Projectile &projectile) { hull -= projectile.GetWeapon().MinableDamage() + projectile.GetWeapon().RelativeMinableDamage() * maxHull; } double Minable::Hull() const { return min(1., hull / maxHull); } // Determine what flotsam this asteroid will create. const map<const Outfit *, int> &Minable::Payload() const { return payload; } // Get the expected value of the flotsams this minable will create when destroyed. const int64_t &Minable::GetValue() const { return value; }
0
endless-sky-master
endless-sky-master/source/PrintData.h
/* PrintData.h Copyright (c) 2022 by warp-core Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef PRINT_DATA_H_ #define PRINT_DATA_H_ // A class containing methods used to print ship and outfit stats to the console. class PrintData { public: static bool IsPrintDataArgument(const char *const *argv); static void Print(const char *const *argv); static void Help(); }; #endif
0
endless-sky-master
endless-sky-master/source/Dictionary.cpp
/* Dictionary.cpp Copyright (c) 2017 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Dictionary.h" #include <cstring> #include <mutex> #include <set> #include <string> using namespace std; namespace { // Perform a binary search on a sorted vector. Return the key's location (or // proper insertion spot) in the first element of the pair, and "true" in // the second element if the key is already in the vector. pair<size_t, bool> Search(const char *key, const vector<pair<const char *, double>> &v) { // At each step of the search, we know the key is in [low, high). size_t low = 0; size_t high = v.size(); while(low != high) { size_t mid = (low + high) / 2; int cmp = strcmp(key, v[mid].first); if(!cmp) return make_pair(mid, true); if(cmp < 0) high = mid; else low = mid + 1; } return make_pair(low, false); } // String interning: return a pointer to a character string that matches the // given string but has static storage duration. const char *Intern(const char *key) { static set<string> interned; static mutex m; // Just in case this function is accessed from multiple threads: lock_guard<mutex> lock(m); return interned.insert(key).first->c_str(); } } double &Dictionary::operator[](const char *key) { pair<size_t, bool> pos = Search(key, *this); if(pos.second) return data()[pos.first].second; return insert(begin() + pos.first, make_pair(Intern(key), 0.))->second; } double &Dictionary::operator[](const string &key) { return (*this)[key.c_str()]; } double Dictionary::Get(const char *key) const { pair<size_t, bool> pos = Search(key, *this); return (pos.second ? data()[pos.first].second : 0.); } double Dictionary::Get(const string &key) const { return Get(key.c_str()); }
0
endless-sky-master
endless-sky-master/source/FleetCargo.h
/* FleetCargo.h Copyright (c) 2022 by warp-core Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef FLEET_CARGO_H_ #define FLEET_CARGO_H_ #include "Sale.h" class DataNode; class Outfit; class Ship; // A collection of cargo settings to be applied to ships from a Fleet or NPC. class FleetCargo { public: void Load(const DataNode &node); void LoadSingle(const DataNode &node); void SetCargo(Ship *ship) const; private: // The number of different items this object can assign to ships. int cargo = 3; std::vector<std::string> commodities; std::set<const Sale<Outfit> *> outfitters; }; #endif
0
endless-sky-master
endless-sky-master/source/DataWriter.cpp
/* DataWriter.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "DataWriter.h" #include "DataNode.h" #include "Files.h" using namespace std; // This string constant is just used for remembering what string needs to be // written before the next token - either the full indentation or this, a space: const string DataWriter::space = " "; // Constructor, specifying the file to save. DataWriter::DataWriter(const string &path) : DataWriter() { this->path = path; } // Constructor for a DataWriter that will not save its contents automatically DataWriter::DataWriter() : before(&indent) { out.precision(8); } // Destructor, which saves the file all in one block. DataWriter::~DataWriter() { if(!path.empty()) SaveToPath(path); } // Save the contents to a file. void DataWriter::SaveToPath(const std::string &filepath) { Files::Write(filepath, out.str()); } // Write a DataNode with all its children. void DataWriter::Write(const DataNode &node) { // Write all this node's tokens. for(int i = 0; i < node.Size(); ++i) WriteToken(node.Token(i).c_str()); Write(); // If this node has any children, call this function recursively on them. if(node.HasChildren()) { BeginChild(); { for(const DataNode &child : node) Write(child); } EndChild(); } } // Begin a new line of the file. void DataWriter::Write() { out << '\n'; before = &indent; } // Increase the indentation level. void DataWriter::BeginChild() { indent += '\t'; } // Decrease the indentation level. void DataWriter::EndChild() { indent.erase(indent.length() - 1); } // Write a comment line, at the current indentation level. void DataWriter::WriteComment(const string &str) { out << indent << "# " << str << '\n'; } // Write a token, given as a character string. void DataWriter::WriteToken(const char *a) { WriteToken(string(a)); } // Write a token, given as a string object. void DataWriter::WriteToken(const string &a) { // Figure out what kind of quotation marks need to be used for this string. bool hasSpace = any_of(a.begin(), a.end(), [](char c) { return isspace(c); }); bool hasQuote = any_of(a.begin(), a.end(), [](char c) { return (c == '"'); }); // If the token is an empty string, it needs to be wrapped in quotes as if it had a space. hasSpace |= a.empty(); // Write the token, enclosed in quotes if necessary. out << *before; if(hasQuote) out << '`' << a << '`'; else if(hasSpace) out << '"' << a << '"'; else out << a; // The next token written will not be the first one on this line, so it only // needs to have a single space before it. before = &space; }
0
endless-sky-master
endless-sky-master/source/TestData.h
/* TestData.h Copyright (c) 2019-2020 by Peter van der Meer Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef ENDLESS_SKY_AC_TESTDATA_H_ #define ENDLESS_SKY_AC_TESTDATA_H_ #include <string> class DataFile; class DataNode; // Class representing a dataset for automated testing class TestData { public: const std::string &Name() const; void Load(const DataNode &node, const std::string &sourceDataFilePath); // Function to inject the test-data into the game or into the games // environment. bool Inject() const; // Types of datafiles that can be stored. enum class Type {UNSPECIFIED, SAVEGAME, MISSION}; private: const DataNode *GetContentsNode(const DataFile &sourceData) const; // Writes out testdata as savegame file. bool InjectSavegame() const; // Loads a mission stored in testdata into a Mission through GameData. bool InjectMission() const; private: // Name of the dataset std::string dataSetName; // Type of the dataset Type dataSetType = Type::UNSPECIFIED; // File containing the test-data std::string sourceDataFile; }; #endif
0
endless-sky-master
endless-sky-master/source/DamageDealt.h
/* DamageDealt.h Copyright (c) 2022 by Amazinite Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef DAMAGE_DEALT_H_ #define DAMAGE_DEALT_H_ #include "Point.h" class Weapon; // A class representing the exact damage dealt to a ship for all // damage types, passed to Ship so that it can be applied. Includes // the weapon used, damage scale, and whether the damage was from a // blast for Ship::TakeDamage to access. class DamageDealt { public: DamageDealt(const Weapon &weapon, double scaling) : weapon(weapon), scaling(scaling) {} // The weapon that dealt damage. const Weapon &GetWeapon() const; // The damage scaling that was used for this damage. double Scaling() const; // Instantaneous damage types. double Shield() const noexcept; double Hull() const noexcept; double Energy() const noexcept; double Heat() const noexcept; double Fuel() const noexcept; // DoT damage types with an instantaneous analog. double Discharge() const noexcept; double Corrosion() const noexcept; double Ion() const noexcept; double Scrambling() const noexcept; double Burn() const noexcept; double Leak() const noexcept; // Unique special damage types. double Disruption() const noexcept; double Slowing() const noexcept; // Hit force applied as a point vector. const Point &HitForce() const noexcept; private: // Friend of DamageProfile so that it can easily set all the damage // values. friend class DamageProfile; const Weapon &weapon; double scaling; double hullDamage = 0.; double shieldDamage = 0.; double energyDamage = 0.; double heatDamage = 0.; double fuelDamage = 0.; double corrosionDamage = 0.; double dischargeDamage = 0.; double ionDamage = 0.; double scramblingDamage = 0.; double burnDamage = 0.; double leakDamage = 0.; double disruptionDamage = 0.; double slowingDamage = 0.; Point forcePoint; }; inline const Weapon &DamageDealt::GetWeapon() const { return weapon; } inline double DamageDealt::Scaling() const { return scaling; } inline double DamageDealt::Shield() const noexcept { return shieldDamage; } inline double DamageDealt::Hull() const noexcept { return hullDamage; } inline double DamageDealt::Energy() const noexcept { return energyDamage; } inline double DamageDealt::Heat() const noexcept { return heatDamage; } inline double DamageDealt::Fuel() const noexcept { return fuelDamage; } inline double DamageDealt::Discharge() const noexcept { return dischargeDamage; } inline double DamageDealt::Corrosion() const noexcept { return corrosionDamage; } inline double DamageDealt::Ion() const noexcept { return ionDamage; } inline double DamageDealt::Scrambling() const noexcept { return scramblingDamage; } inline double DamageDealt::Burn() const noexcept { return burnDamage; } inline double DamageDealt::Leak() const noexcept { return leakDamage; } inline double DamageDealt::Disruption() const noexcept { return disruptionDamage; } inline double DamageDealt::Slowing() const noexcept { return slowingDamage; } inline const Point &DamageDealt::HitForce() const noexcept { return forcePoint; } #endif
0
endless-sky-master
endless-sky-master/source/Command.cpp
/* Command.cpp Copyright (c) 2015 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Command.h" #include "DataFile.h" #include "DataNode.h" #include "DataWriter.h" #include "text/Format.h" #include <SDL2/SDL.h> #include <algorithm> #include <cmath> #include <map> using namespace std; namespace { // These lookup tables make it possible to map a command to its description, // the name of the key it is mapped to, or the SDL keycode it is mapped to. map<Command, string> description; map<Command, string> keyName; map<int, Command> commandForKeycode; map<Command, int> keycodeForCommand; // Keep track of any keycodes that are mapped to multiple commands, in order // to display a warning to the player. map<int, int> keycodeCount; // Need a uint64_t 1 to generate Commands. const uint64_t ONE = 1; } // Command enumeration, including the descriptive strings that are used for the // commands both in the preferences panel and in the saved key settings. const Command Command::NONE(0, ""); const Command Command::MENU(ONE << 0, "Show main menu"); const Command Command::FORWARD(ONE << 1, "Forward thrust"); const Command Command::LEFT(ONE << 2, "Turn left"); const Command Command::RIGHT(ONE << 3, "Turn right"); const Command Command::BACK(ONE << 4, "Reverse"); const Command Command::MOUSE_TURNING_HOLD(ONE << 5, "Mouse turning (hold)"); const Command Command::PRIMARY(ONE << 6, "Fire primary weapon"); const Command Command::SECONDARY(ONE << 7, "Fire secondary weapon"); const Command Command::SELECT(ONE << 8, "Select secondary weapon"); const Command Command::LAND(ONE << 9, "Land on planet / station"); const Command Command::BOARD(ONE << 10, "Board selected ship"); const Command Command::HAIL(ONE << 11, "Talk to selected ship"); const Command Command::SCAN(ONE << 12, "Scan selected ship"); const Command Command::JUMP(ONE << 13, "Initiate hyperspace jump"); const Command Command::FLEET_JUMP(ONE << 14, ""); const Command Command::TARGET(ONE << 15, "Select next ship"); const Command Command::NEAREST(ONE << 16, "Select nearest hostile ship"); const Command Command::NEAREST_ASTEROID(ONE << 17, "Select nearest asteroid"); const Command Command::DEPLOY(ONE << 18, "Deploy / recall fighters"); const Command Command::AFTERBURNER(ONE << 19, "Fire afterburner"); const Command Command::CLOAK(ONE << 20, "Toggle cloaking device"); const Command Command::MAP(ONE << 21, "View star map"); const Command Command::INFO(ONE << 22, "View player info"); const Command Command::FULLSCREEN(ONE << 23, "Toggle fullscreen"); const Command Command::FASTFORWARD(ONE << 24, "Toggle fast-forward"); const Command Command::HELP(ONE << 25, "Show help"); const Command Command::FIGHT(ONE << 26, "Fleet: Fight my target"); const Command Command::GATHER(ONE << 27, "Fleet: Gather around me"); const Command Command::HOLD(ONE << 28, "Fleet: Hold position"); const Command Command::HARVEST(ONE << 29, "Fleet: Harvest flotsam"); const Command Command::AMMO(ONE << 30, "Fleet: Toggle ammo usage"); const Command Command::AUTOSTEER(ONE << 31, "Auto steer"); const Command Command::WAIT(ONE << 32, ""); const Command Command::STOP(ONE << 33, ""); const Command Command::SHIFT(ONE << 34, ""); // In the given text, replace any instances of command names (in angle brackets) // with key names (in quotes). string Command::ReplaceNamesWithKeys(const string &text) { map<string, string> subs; for(const auto &it : description) subs['<' + it.second + '>'] = '"' + keyName[it.first] + '"'; return Format::Replace(text, subs); } // Create a command representing whatever is mapped to the given key code. Command::Command(int keycode) { auto it = commandForKeycode.find(keycode); if(it != commandForKeycode.end()) *this = it->second; } // Read the current keyboard state. void Command::ReadKeyboard() { Clear(); const Uint8 *keyDown = SDL_GetKeyboardState(nullptr); // Each command can only have one keycode, but misconfigured settings can // temporarily cause one keycode to be used for two commands. Also, more // than one key can be held down at once. for(const auto &it : keycodeForCommand) if(keyDown[SDL_GetScancodeFromKey(it.second)]) *this |= it.first; // Check whether the `Shift` modifier key was pressed for this step. if(SDL_GetModState() & KMOD_SHIFT) *this |= SHIFT; } // Load the keyboard preferences. void Command::LoadSettings(const string &path) { DataFile file(path); // Create a map of command names to Command objects in the enumeration above. map<string, Command> commands; for(const auto &it : description) commands[it.second] = it.first; // Each command can only have one keycode, one keycode can be assigned // to multiple commands. for(const DataNode &node : file) { auto it = commands.find(node.Token(0)); if(it != commands.end() && node.Size() >= 2) { Command command = it->second; int keycode = node.Value(1); keycodeForCommand[command] = keycode; keyName[command] = SDL_GetKeyName(keycode); } } // Regenerate the lookup tables. commandForKeycode.clear(); keycodeCount.clear(); for(const auto &it : keycodeForCommand) { commandForKeycode[it.second] = it.first; ++keycodeCount[it.second]; } } // Save the keyboard preferences. void Command::SaveSettings(const string &path) { DataWriter out(path); for(const auto &it : keycodeForCommand) { auto dit = description.find(it.first); if(dit != description.end()) out.Write(dit->second, it.second); } } // Set the key that is mapped to the given command. void Command::SetKey(Command command, int keycode) { // Always reset *all* the mappings when one is set. That way, if two commands // are mapped to the same key and you change one of them, the other stays mapped. keycodeForCommand[command] = keycode; keyName[command] = SDL_GetKeyName(keycode); commandForKeycode.clear(); keycodeCount.clear(); for(const auto &it : keycodeForCommand) { commandForKeycode[it.second] = it.first; ++keycodeCount[it.second]; } } // Get the description of this command. If this command is a combination of more // than one command, an empty string is returned. const string &Command::Description() const { static const string empty; auto it = description.find(*this); return (it == description.end() ? empty : it->second); } // Get the name of the key that is mapped to this command. If this command is // a combination of more than one command, an empty string is returned. const string &Command::KeyName() const { static const string empty = "(none)"; auto it = keyName.find(*this); return (!HasBinding() ? empty : it->second); } // Check if the key has no binding. bool Command::HasBinding() const { auto it = keyName.find(*this); if(it == keyName.end()) return false; if(it->second.empty()) return false; return true; } // Check whether this is the only command mapped to the key it is mapped to. bool Command::HasConflict() const { auto it = keycodeForCommand.find(*this); if(it == keycodeForCommand.end()) return false; auto cit = keycodeCount.find(it->second); return (cit != keycodeCount.end() && cit->second > 1); } // Load this command from an input file (for testing or scripted missions). void Command::Load(const DataNode &node) { for(int i = 1; i < node.Size(); ++i) { static const map<string, Command> lookup = { {"none", Command::NONE}, {"menu", Command::MENU}, {"forward", Command::FORWARD}, {"left", Command::LEFT}, {"right", Command::RIGHT}, {"back", Command::BACK}, {"primary", Command::PRIMARY}, {"secondary", Command::SECONDARY}, {"select", Command::SELECT}, {"land", Command::LAND}, {"board", Command::BOARD}, {"hail", Command::HAIL}, {"scan", Command::SCAN}, {"jump", Command::JUMP}, {"mouseturninghold", Command::MOUSE_TURNING_HOLD}, {"fleet jump", Command::FLEET_JUMP}, {"target", Command::TARGET}, {"nearest", Command::NEAREST}, {"deploy", Command::DEPLOY}, {"afterburner", Command::AFTERBURNER}, {"cloak", Command::CLOAK}, {"map", Command::MAP}, {"info", Command::INFO}, {"fullscreen", Command::FULLSCREEN}, {"fastforward", Command::FASTFORWARD}, {"fight", Command::FIGHT}, {"gather", Command::GATHER}, {"hold", Command::HOLD}, {"ammo", Command::AMMO}, {"nearest asteroid", Command::NEAREST_ASTEROID}, {"wait", Command::WAIT}, {"stop", Command::STOP}, {"shift", Command::SHIFT} }; auto it = lookup.find(node.Token(i)); if(it != lookup.end()) Set(it->second); else node.PrintTrace("Warning: Skipping unrecognized command \"" + node.Token(i) + "\":"); } } // Reset this to an empty command. void Command::Clear() { *this = Command(); } // Clear any commands that are set in the given command. void Command::Clear(Command command) { state &= ~command.state; } // Set any commands that are set in the given command. void Command::Set(Command command) { state |= command.state; } // Check if any of the given command's bits that are set, are also set here. bool Command::Has(Command command) const { return (state & command.state); } // Get the commands that are set in this and in the given command. Command Command::And(Command command) const { return Command(state & command.state); } // Get the commands that are set in this and not in the given command. Command Command::AndNot(Command command) const { return Command(state & ~command.state); } // Set the turn direction and amount to a value between -1 and 1. void Command::SetTurn(double amount) { turn = max(-1., min(1., amount)); } // Get the turn amount. double Command::Turn() const { return turn; } // Check if any bits are set in this command (including a nonzero turn). Command::operator bool() const { return !!*this; } // Check whether this command is entirely empty. bool Command::operator!() const { return !state && !turn; } // For sorting commands (e.g. so a command can be the key in a map): bool Command::operator<(const Command &command) const { return (state < command.state); } // Get the commands that are set in either of these commands. Command Command::operator|(const Command &command) const { Command result = *this; result |= command; return result; } // Combine everything in the given command with this command. If the given // command has a nonzero turn set, it overrides this command's turn value. Command &Command::operator|=(const Command &command) { state |= command.state; if(command.turn) turn = command.turn; return *this; } // Private constructor. Command::Command(uint64_t state) : state(state) { } // Private constructor that also stores the given description in the lookup // table. (This is used for the enumeration at the top of this file.) Command::Command(uint64_t state, const string &text) : state(state) { if(!text.empty()) description[*this] = text; }
0
endless-sky-master
endless-sky-master/source/Personality.cpp
/* Personality.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Personality.h" #include "Angle.h" #include "DataNode.h" #include "DataWriter.h" #include <map> #include <vector> using namespace std; namespace { // Make sure the length of PersonalityTrait matches PERSONALITY_COUNT // or the build will fail. enum PersonalityTrait { PACIFIST, FORBEARING, TIMID, DISABLES, PLUNDERS, HUNTING, STAYING, ENTERING, NEMESIS, SURVEILLANCE, UNINTERESTED, WAITING, DERELICT, FLEEING, ESCORT, FRUGAL, COWARD, VINDICTIVE, SWARMING, UNCONSTRAINED, MINING, HARVESTS, APPEASING, MUTE, OPPORTUNISTIC, MERCIFUL, TARGET, MARKED, LAUNCHING, LINGERING, DARING, SECRETIVE, RAMMING, UNRESTRICTED, DECLOAKED, // This must be last so it can be used for bounds checking. LAST_ITEM_IN_PERSONALITY_TRAIT_ENUM }; const map<string, PersonalityTrait> TOKEN = { {"pacifist", PACIFIST}, {"forbearing", FORBEARING}, {"timid", TIMID}, {"disables", DISABLES}, {"plunders", PLUNDERS}, {"hunting", HUNTING}, {"staying", STAYING}, {"entering", ENTERING}, {"nemesis", NEMESIS}, {"surveillance", SURVEILLANCE}, {"uninterested", UNINTERESTED}, {"waiting", WAITING}, {"derelict", DERELICT}, {"fleeing", FLEEING}, {"escort", ESCORT}, {"frugal", FRUGAL}, {"coward", COWARD}, {"vindictive", VINDICTIVE}, {"swarming", SWARMING}, {"unconstrained", UNCONSTRAINED}, {"mining", MINING}, {"harvests", HARVESTS}, {"appeasing", APPEASING}, {"mute", MUTE}, {"opportunistic", OPPORTUNISTIC}, {"merciful", MERCIFUL}, {"target", TARGET}, {"marked", MARKED}, {"launching", LAUNCHING}, {"lingering", LINGERING}, {"daring", DARING}, {"secretive", SECRETIVE}, {"ramming", RAMMING}, {"unrestricted", UNRESTRICTED}, {"decloaked", DECLOAKED} }; // Tokens that combine two or more flags. const map<string, vector<PersonalityTrait>> COMPOSITE_TOKEN = { {"heroic", {DARING, HUNTING}} }; const double DEFAULT_CONFUSION = 10.; } // Default settings for player's ships. Personality::Personality() noexcept : flags(1LL << DISABLES), confusionMultiplier(DEFAULT_CONFUSION), aimMultiplier(1.) { static_assert(LAST_ITEM_IN_PERSONALITY_TRAIT_ENUM == PERSONALITY_COUNT, "PERSONALITY_COUNT must match the length of PersonalityTraits"); } void Personality::Load(const DataNode &node) { bool add = (node.Token(0) == "add"); bool remove = (node.Token(0) == "remove"); if(!(add || remove)) flags.reset(); for(int i = 1 + (add || remove); i < node.Size(); ++i) Parse(node, i, remove); for(const DataNode &child : node) { if(child.Token(0) == "confusion") { if(add || remove) child.PrintTrace("Error: Cannot \"" + node.Token(0) + "\" a confusion value:"); else if(child.Size() < 2) child.PrintTrace("Skipping \"confusion\" tag with no value specified:"); else confusionMultiplier = child.Value(1); } else { for(int i = 0; i < child.Size(); ++i) Parse(child, i, remove); } } isDefined = true; } void Personality::Save(DataWriter &out) const { out.Write("personality"); out.BeginChild(); { out.Write("confusion", confusionMultiplier); for(const auto &it : TOKEN) if(flags.test(it.second)) out.Write(it.first); } out.EndChild(); } bool Personality::IsDefined() const { return isDefined; } bool Personality::IsPacifist() const { return flags.test(PACIFIST); } bool Personality::IsForbearing() const { return flags.test(FORBEARING); } bool Personality::IsTimid() const { return flags.test(TIMID); } bool Personality::IsHunting() const { return flags.test(HUNTING); } bool Personality::IsNemesis() const { return flags.test(NEMESIS); } bool Personality::IsDaring() const { return flags.test(DARING); } bool Personality::IsFrugal() const { return flags.test(FRUGAL); } bool Personality::Disables() const { return flags.test(DISABLES); } bool Personality::Plunders() const { return flags.test(PLUNDERS); } bool Personality::IsVindictive() const { return flags.test(VINDICTIVE); } bool Personality::IsUnconstrained() const { return flags.test(UNCONSTRAINED); } bool Personality::IsUnrestricted() const { return flags.test(UNRESTRICTED); } bool Personality::IsCoward() const { return flags.test(COWARD); } bool Personality::IsAppeasing() const { return flags.test(APPEASING); } bool Personality::IsOpportunistic() const { return flags.test(OPPORTUNISTIC); } bool Personality::IsMerciful() const { return flags.test(MERCIFUL); } bool Personality::IsRamming() const { return flags.test(RAMMING); } bool Personality::IsStaying() const { return flags.test(STAYING); } bool Personality::IsEntering() const { return flags.test(ENTERING); } bool Personality::IsWaiting() const { return flags.test(WAITING); } bool Personality::IsLaunching() const { return flags.test(LAUNCHING); } bool Personality::IsFleeing() const { return flags.test(FLEEING); } bool Personality::IsDerelict() const { return flags.test(DERELICT); } bool Personality::IsUninterested() const { return flags.test(UNINTERESTED); } bool Personality::IsSurveillance() const { return flags.test(SURVEILLANCE); } bool Personality::IsMining() const { return flags.test(MINING); } bool Personality::Harvests() const { return flags.test(HARVESTS); } bool Personality::IsSwarming() const { return flags.test(SWARMING); } bool Personality::IsLingering() const { return flags.test(LINGERING); } bool Personality::IsSecretive() const { return flags.test(SECRETIVE); } bool Personality::IsEscort() const { return flags.test(ESCORT); } bool Personality::IsTarget() const { return flags.test(TARGET); } bool Personality::IsMarked() const { return flags.test(MARKED); } bool Personality::IsMute() const { return flags.test(MUTE); } bool Personality::IsDecloaked() const { return flags.test(DECLOAKED); } const Point &Personality::Confusion() const { return confusion; } void Personality::UpdateConfusion(bool isFiring) { // If you're firing weapons, aiming accuracy should slowly improve until it // is 4 times more precise than it initially was. aimMultiplier = .99 * aimMultiplier + .01 * (isFiring ? .5 : 2.); // Try to correct for any error in the aim, but constantly introduce new // error and overcompensation so it oscillates around the origin. Apply // damping to the position and velocity to avoid extreme outliers, though. if(confusion.X() || confusion.Y()) confusionVelocity -= .001 * confusion.Unit(); confusionVelocity += .001 * Angle::Random().Unit(); confusionVelocity *= .999; confusion += confusionVelocity * (confusionMultiplier * aimMultiplier); confusion *= .9999; } Personality Personality::Defender() { Personality defender; defender.flags = bitset<PERSONALITY_COUNT>((1LL << STAYING) | (1LL << MARKED) | (1LL << HUNTING) | (1LL << DARING) | (1LL << UNCONSTRAINED) | (1LL << TARGET)); return defender; } // Remove target and marked since the defender defeat check doesn't actually care // about carried ships. Personality Personality::DefenderFighter() { Personality defender; defender.flags = bitset<PERSONALITY_COUNT>((1LL << STAYING) | (1LL << HUNTING) | (1LL << DARING) | (1LL << UNCONSTRAINED)); return defender; } void Personality::Parse(const DataNode &node, int index, bool remove) { const string &token = node.Token(index); auto it = TOKEN.find(token); if(it == TOKEN.end()) { auto cit = COMPOSITE_TOKEN.find(token); if(cit == COMPOSITE_TOKEN.end()) node.PrintTrace("Warning: Skipping unrecognized personality \"" + token + "\":"); else { if(remove) for(auto personality : cit->second) flags &= ~(1LL << personality); else for(auto personality : cit->second) flags |= 1LL << personality; } } else { if(remove) flags &= ~(1LL << it->second); else flags |= 1LL << it->second; } }
0
endless-sky-master
endless-sky-master/source/PlanetLabel.h
/* PlanetLabel.h Copyright (c) 2016 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef PLANET_LABEL_H_ #define PLANET_LABEL_H_ #include "Color.h" #include "Point.h" #include "Rectangle.h" #include <string> #include <vector> class StellarObject; class System; class PlanetLabel { public: PlanetLabel(const std::vector<PlanetLabel> &labels, const System &system, const StellarObject &object); void Update(const Point &center, double zoom); void Draw() const; private: // Overlap detection. void SetBoundingBox(const Point &labelDimensions, double angle); Rectangle GetBoundingBox(double zoom) const; bool HasOverlaps(const std::vector<PlanetLabel> &labels, const System &system, const StellarObject &object, double zoom) const; private: Point objectPosition; double objectRadius = 0.; // Used for overlap detection during label creation. Rectangle box; Point zoomOffset; // Position and radius for drawing label. Point position; double radius = 0.; std::string name; std::string government; Point nameOffset; Point governmentOffset; Color color; int hostility = 0; double innerAngle = -1.; }; #endif
0
endless-sky-master
endless-sky-master/source/Information.cpp
/* Information.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Information.h" #include "Sprite.h" using namespace std; void Information::SetRegion(const Rectangle &rect) { region = rect; hasCustomRegion = true; } const Rectangle &Information::GetCustomRegion() const { return region; } bool Information::HasCustomRegion() const { return hasCustomRegion; } void Information::SetSprite(const string &name, const Sprite *sprite, const Point &unit, float frame) { sprites[name] = sprite; spriteUnits[name] = unit; spriteFrames[name] = frame; } const Sprite *Information::GetSprite(const string &name) const { static const Sprite empty; auto it = sprites.find(name); return (it == sprites.end()) ? &empty : it->second; } const Point &Information::GetSpriteUnit(const string &name) const { static const Point up(0., -1.); auto it = spriteUnits.find(name); return (it == spriteUnits.end()) ? up : it->second; } float Information::GetSpriteFrame(const string &name) const { auto it = spriteFrames.find(name); return (it == spriteFrames.end()) ? 0.f : it->second; } void Information::SetString(const string &name, const string &value) { strings[name] = value; } const string &Information::GetString(const string &name) const { static const string empty; auto it = strings.find(name); return (it == strings.end()) ? empty : it->second; } void Information::SetBar(const string &name, double value, double segments) { bars[name] = value; barSegments[name] = segments; } double Information::BarValue(const string &name) const { auto it = bars.find(name); return (it == bars.end()) ? 0. : it->second; } double Information::BarSegments(const string &name) const { auto it = barSegments.find(name); return (it == barSegments.end()) ? 1. : it->second; } void Information::SetCondition(const string &condition) { conditions.insert(condition); } bool Information::HasCondition(const string &condition) const { if(condition.empty()) return true; if(condition.front() == '!') return !HasCondition(condition.substr(1)); return conditions.count(condition); } void Information::SetOutlineColor(const Color &color) { outlineColor = color; } const Color &Information::GetOutlineColor() const { return outlineColor; }
0
endless-sky-master
endless-sky-master/source/Account.cpp
/* Account.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Account.h" #include "DataNode.h" #include "DataWriter.h" #include "text/Format.h" #include <algorithm> #include <numeric> #include <sstream> using namespace std; namespace { // For tracking the player's average income, store daily net worth over this // number of days. const unsigned HISTORY = 100; } // Load account information from a data file (saved game or starting conditions). void Account::Load(const DataNode &node, bool clearFirst) { if(clearFirst) { credits = 0; crewSalariesOwed = 0; maintenanceDue = 0; creditScore = 400; mortgages.clear(); history.clear(); } for(const DataNode &child : node) { if(child.Token(0) == "credits" && child.Size() >= 2) credits = child.Value(1); else if(child.Token(0) == "salaries income") for(const DataNode &grand : child) { if(grand.Size() < 2) grand.PrintTrace("Skipping incomplete salary income:"); else salariesIncome[grand.Token(0)] = grand.Value(1); } else if(child.Token(0) == "salaries" && child.Size() >= 2) crewSalariesOwed = child.Value(1); else if(child.Token(0) == "maintenance" && child.Size() >= 2) maintenanceDue = child.Value(1); else if(child.Token(0) == "score" && child.Size() >= 2) creditScore = child.Value(1); else if(child.Token(0) == "mortgage") mortgages.emplace_back(child); else if(child.Token(0) == "history") for(const DataNode &grand : child) history.push_back(grand.Value(0)); else child.PrintTrace("Skipping unrecognized account item:"); } } // Write account information to a saved game file. void Account::Save(DataWriter &out) const { out.Write("account"); out.BeginChild(); { out.Write("credits", credits); if(!salariesIncome.empty()) { out.Write("salaries income"); out.BeginChild(); { for(const auto &income : salariesIncome) out.Write(income.first, income.second); } out.EndChild(); } if(crewSalariesOwed) out.Write("salaries", crewSalariesOwed); if(maintenanceDue) out.Write("maintenance", maintenanceDue); out.Write("score", creditScore); out.Write("history"); out.BeginChild(); { for(int64_t worth : history) out.Write(worth); } out.EndChild(); for(const Mortgage &mortgage : mortgages) mortgage.Save(out); } out.EndChild(); } // How much the player currently has in the bank. int64_t Account::Credits() const { return credits; } // Give the player credits (or pass negative number to subtract). If subtracting, // the calling function needs to check that this will not result in negative credits. void Account::AddCredits(int64_t value) { credits += value; } // Pay down extra principal on a mortgage. void Account::PayExtra(int mortgage, int64_t amount) { if(static_cast<unsigned>(mortgage) >= mortgages.size() || amount > credits || amount > mortgages[mortgage].Principal()) return; mortgages[mortgage].PayExtra(amount); credits -= amount; // If this payment was for the entire remaining amount in the mortgage, // remove it from the list. if(!mortgages[mortgage].Principal()) mortgages.erase(mortgages.begin() + mortgage); } // Step forward one day, and return a string summarizing payments made. string Account::Step(int64_t assets, int64_t salaries, int64_t maintenance) { ostringstream out; // Keep track of what payments were made and whether any could not be made. crewSalariesOwed += salaries; maintenanceDue += maintenance; bool missedPayment = false; // Crew salaries take highest priority. int64_t salariesPaid = crewSalariesOwed; if(crewSalariesOwed) { if(crewSalariesOwed > credits) { // If you can't pay the full salary amount, still pay some of it and // remember how much back wages you owe to your crew. salariesPaid = max<int64_t>(credits, 0); crewSalariesOwed -= salariesPaid; credits -= salariesPaid; missedPayment = true; out << "You could not pay all your crew salaries."; } else { credits -= crewSalariesOwed; crewSalariesOwed = 0; } } // Maintenance costs are dealt with after crew salaries given that they act similarly. int64_t maintenancePaid = maintenanceDue; if(maintenanceDue) { if(maintenanceDue > credits) { // Like with crew salaries, maintenance costs can be paid in part with // the unpaid costs being paid later. maintenancePaid = max<int64_t>(credits, 0); maintenanceDue -= maintenancePaid; credits -= maintenancePaid; if(!missedPayment) out << "You could not pay all your maintenance costs."; missedPayment = true; } else { credits -= maintenanceDue; maintenanceDue = 0; } } // Unlike salaries, each mortgage payment must either be made in its entirety, // or skipped completely (accruing interest and reducing your credit score). int64_t mortgagesPaid = 0; int64_t finesPaid = 0; for(Mortgage &mortgage : mortgages) { int64_t payment = mortgage.Payment(); if(payment > credits) { mortgage.MissPayment(); if(!missedPayment) out << "You missed a mortgage payment."; missedPayment = true; } else { payment = mortgage.MakePayment(); credits -= payment; // For the status text, keep track of whether this is a mortgage or a fine. if(mortgage.Type() == "Mortgage") mortgagesPaid += payment; else finesPaid += payment; } assets -= mortgage.Principal(); } // If any mortgage has been fully paid off, remove it from the list. for(auto it = mortgages.begin(); it != mortgages.end(); ) { if(!it->Principal()) it = mortgages.erase(it); else ++it; } // Keep track of your net worth over the last HISTORY days. if(history.size() > HISTORY) history.erase(history.begin()); history.push_back(credits + assets - crewSalariesOwed - maintenanceDue); // If you failed to pay any debt, your credit score drops. Otherwise, even // if you have no debts, it increases. (Because, having no debts at all // makes you at least as credit-worthy as someone who pays debts on time.) creditScore = max(200, min(800, creditScore + (missedPayment ? -5 : 1))); // If you didn't make any payments, no need to continue further. if(!(salariesPaid + maintenancePaid + mortgagesPaid + finesPaid)) return out.str(); else if(missedPayment) out << " "; out << "You paid "; map<string, int64_t> typesPaid; if(salariesPaid) typesPaid["crew salaries"] = salariesPaid; if(maintenancePaid) typesPaid["maintenance"] = maintenancePaid; if(mortgagesPaid) typesPaid["mortgages"] = mortgagesPaid; if(finesPaid) typesPaid["fines"] = finesPaid; // If you made payments of three or more types, the punctuation needs to // include commas, so just handle that separately here. if(typesPaid.size() >= 3) { auto it = typesPaid.begin(); for(unsigned int i = 0; i < typesPaid.size() - 1; ++i) { out << Format::CreditString(it->second) << " in " << it->first << ", "; ++it; } out << "and " << Format::CreditString(it->second) << " in " << it->first + "."; } else { if(salariesPaid) out << Format::CreditString(salariesPaid) << " in crew salaries" << ((mortgagesPaid || finesPaid || maintenancePaid) ? " and " : "."); if(maintenancePaid) out << Format::CreditString(maintenancePaid) << " in maintenance" << ((mortgagesPaid || finesPaid) ? " and " : "."); if(mortgagesPaid) out << Format::CreditString(mortgagesPaid) << " in mortgages" << (finesPaid ? " and " : "."); if(finesPaid) out << Format::CreditString(finesPaid) << " in fines."; } return out.str(); } const map<string, int64_t> &Account::SalariesIncome() const { return salariesIncome; } int64_t Account::SalariesIncomeTotal() const { return accumulate( salariesIncome.begin(), salariesIncome.end(), 0, [](int64_t value, const std::map<string, int64_t>::value_type &salary) { return value + salary.second; } ); } void Account::SetSalaryIncome(const string &name, int64_t amount) { if(amount == 0) salariesIncome.erase(name); else salariesIncome[name] = amount; } int64_t Account::CrewSalariesOwed() const { return crewSalariesOwed; } void Account::PaySalaries(int64_t amount) { amount = min(min(amount, crewSalariesOwed), credits); credits -= amount; crewSalariesOwed -= amount; } int64_t Account::MaintenanceDue() const { return maintenanceDue; } void Account::PayMaintenance(int64_t amount) { amount = min(min(amount, maintenanceDue), credits); credits -= amount; maintenanceDue -= amount; } // Access the list of mortgages. const vector<Mortgage> &Account::Mortgages() const { return mortgages; } // Add a new mortgage for the given amount, with an interest rate determined by // your credit score. void Account::AddMortgage(int64_t principal) { mortgages.emplace_back(principal, creditScore); credits += principal; } // Add a "fine" with a high, fixed interest rate and a short term. void Account::AddFine(int64_t amount) { mortgages.emplace_back(amount, 0, 60); } // Check how big a mortgage the player can afford to pay at their current income. int64_t Account::Prequalify() const { double payments = 0.; int64_t liabilities = 0; for(const Mortgage &mortgage : mortgages) { payments += mortgage.PrecisePayment(); liabilities += mortgage.Principal(); } // Put a limit on new debt that the player can take out, as a fraction of // their net worth, to avoid absurd mortgages being offered when the player // has just captured some very lucrative ships. return max<int64_t>(0, min( NetWorth() / 3 + 500000 - liabilities, Mortgage::Maximum(YearlyRevenue(), creditScore, payments))); } // Get the player's total net worth (counting all ships and all debts). int64_t Account::NetWorth() const { return history.empty() ? 0 : history.back(); } // Find out the player's credit rating. int Account::CreditScore() const { return creditScore; } // Get the total amount owed for "Mortgage", "Fine", or both. int64_t Account::TotalDebt(const string &type) const { int64_t total = 0; for(const Mortgage &mortgage : mortgages) if(type.empty() || mortgage.Type() == type) total += mortgage.Principal(); return total; } // Extrapolate from the player's current net worth history to determine how much // their net worth is expected to change over the course of the next year. int64_t Account::YearlyRevenue() const { if(history.empty() || history.back() <= history.front()) return 0; // Note that this intentionally under-estimates if the player has not yet // played for long enough to accumulate a full income history. return ((history.back() - history.front()) * 365) / HISTORY; }
0
endless-sky-master
endless-sky-master/source/ImageSet.cpp
/* ImageSet.cpp Copyright (c) 2017 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ImageSet.h" #include "GameData.h" #include "ImageBuffer.h" #include "Logger.h" #include "Mask.h" #include "MaskManager.h" #include "Sprite.h" #include <algorithm> #include <cassert> #include <iterator> using namespace std; namespace { // Determine whether the given path is to an @2x image. bool Is2x(const string &path) { if(path.length() < 7) return false; size_t pos = path.length() - 7; return (path[pos] == '@' && path[pos + 1] == '2' && path[pos + 2] == 'x'); } // Determine whether the given path is to a swizzle mask. bool IsSwizzleMask(const string &path, bool is2x) { if(path.length() < 7 || (is2x && path.length() < 10)) return false; size_t pos = path.length() - (is2x ? 10 : 7); return (path[pos] == '@' && path[pos + 1] == 's' && path[pos + 2] == 'w'); } // Check if the given character is a valid blending mode. bool IsBlend(char c) { return (c == '-' || c == '~' || c == '+' || c == '='); } // Determine whether the given path or name is to a sprite for which a // collision mask ought to be generated. bool IsMasked(const string &path) { if(path.length() >= 5 && path.compare(0, 5, "ship/") == 0) return true; if(path.length() >= 9 && path.compare(0, 9, "asteroid/") == 0) return true; return false; } // Get the character index where the sprite name in the given path ends. size_t NameEnd(const string &path) { // The path always ends in a three-letter extension, ".png" or ".jpg". // In addition, 3 more characters may be taken up by an @2x label or a mask label. bool is2x = Is2x(path); size_t end = path.length() - (is2x ? 7 : 4) - (IsSwizzleMask(path, is2x) ? 3 : 0); // This should never happen, but just in case: if(!end) return 0; // Skip any numbers at the end of the name. size_t pos = end; while(--pos) if(path[pos] < '0' || path[pos] > '9') break; // If there is not a blending mode specifier before the numbers, they // are part of the sprite name, not a frame index. return (IsBlend(path[pos]) ? pos : end); } // Get the frame index from the given path. size_t FrameIndex(const string &path) { // Get the character index where the "name" portion of the path ends. // A path's format is always: <name>(<blend><frame>)(@sw)(@2x).(png|jpg) size_t i = NameEnd(path); // If the name contains a frame index, it must be separated from the name // by a character indicating the additive blending mode. if(!IsBlend(path[i])) return 0; size_t frame = 0; // The path ends in an extension, so there's no need to check for going off // the end of the string in this loop; we're guaranteed to hit a non-digit. for(++i; path[i] >= '0' && path[i] <= '9'; ++i) frame = (frame * 10) + (path[i] - '0'); return frame; } // Add consecutive frames from the given map to the given vector. Issue warnings for missing or mislabeled frames. void AddValid(const map<size_t, string> &frameData, vector<string> &sequence, const string &prefix, bool is2x, bool isSwizzleMask) noexcept(false) { if(frameData.empty()) return; // Valid animations (or stills) begin with frame 0. if(frameData.begin()->first != 0) { Logger::LogError(prefix + "ignored " + (isSwizzleMask ? "mask " : "") + (is2x ? "@2x " : "") + "frame " + to_string(frameData.begin()->first) + " (" + to_string(frameData.size()) + " ignored in total). Animations must start at frame 0."); return; } // Find the first frame that is not a single increment over the previous frame. auto it = frameData.begin(); auto next = it; auto end = frameData.end(); while(++next != end && next->first == it->first + 1) it = next; // Copy the sorted, valid paths from the map to the frame sequence vector. size_t count = distance(frameData.begin(), next); sequence.resize(count); transform(frameData.begin(), next, sequence.begin(), [](const pair<size_t, string> &p) -> string { return p.second; }); // If `next` is not the end, then there was at least one discontinuous frame. if(next != frameData.end()) { size_t ignored = distance(next, frameData.end()); Logger::LogError(prefix + "missing " + (isSwizzleMask ? "mask " : "") + (is2x ? "@2x " : "") + "frame " + to_string(it->first + 1) + " (" + to_string(ignored) + (ignored > 1 ? " frames" : " frame") + " ignored in total)."); } } } // Check if the given path is to an image of a valid file type. bool ImageSet::IsImage(const string &path) { if(path.length() < 4) return false; string ext = path.substr(path.length() - 4); return (ext == ".png" || ext == ".jpg" || ext == ".PNG" || ext == ".JPG"); } // Get the base name for the given path. The path should be relative to one // of the source image directories, not a full filesystem path. string ImageSet::Name(const string &path) { return path.substr(0, NameEnd(path)); } // Determine whether the given path or name is for a sprite whose loading // should be deferred until needed. bool ImageSet::IsDeferred(const string &path) { if(path.length() >= 5 && !path.compare(0, 5, "land/")) return true; return false; } ImageSet::ImageSet(string name) : name(std::move(name)) { } // Get the name of the sprite for this image set. const string &ImageSet::Name() const { return name; } // Whether this image set is empty, i.e. has no images. bool ImageSet::IsEmpty() const { return framePaths[0].empty() && framePaths[1].empty(); } // Add a single image to this set. Assume the name of the image has already // been checked to make sure it belongs in this set. void ImageSet::Add(string path) { // Determine which frame of the sprite this image will be. bool is2x = Is2x(path); size_t frame = FrameIndex(path); // Store the requested path. framePaths[is2x + (2 * IsSwizzleMask(path, is2x))][frame].swap(path); } // Reduce all given paths to frame images into a sequence of consecutive frames. void ImageSet::ValidateFrames() noexcept(false) { string prefix = "Sprite \"" + name + "\": "; AddValid(framePaths[0], paths[0], prefix, false, false); AddValid(framePaths[1], paths[1], prefix, true, false); AddValid(framePaths[2], paths[2], prefix, false, true); AddValid(framePaths[3], paths[3], prefix, true, true); framePaths[0].clear(); framePaths[1].clear(); framePaths[2].clear(); framePaths[3].clear(); auto DropPaths = [&](vector<string> &toResize, const string &specifier) { if(toResize.size() > paths[0].size()) { Logger::LogError(prefix + to_string(toResize.size() - paths[0].size()) + " extra frames for the " + specifier + " sprite will be ignored."); toResize.resize(paths[0].size()); } }; // Drop any @2x and mask paths that will not be used. DropPaths(paths[1], "@2x"); DropPaths(paths[2], "mask"); DropPaths(paths[3], "@2x mask"); } // Load all the frames. This should be called in one of the image-loading // worker threads. This also generates collision masks if needed. void ImageSet::Load() noexcept(false) { assert(framePaths[0].empty() && "should call ValidateFrames before calling Load"); // Determine how many frames there will be, total. The image buffers will // not actually be allocated until the first image is loaded (at which point // the sprite's dimensions will be known). size_t frames = paths[0].size(); buffer[0].Clear(frames); buffer[1].Clear(frames); buffer[2].Clear(frames); buffer[3].Clear(frames); // Check whether we need to generate collision masks. bool makeMasks = IsMasked(name); if(makeMasks) masks.resize(frames); // Load the 1x sprites first, then the 2x sprites, because they are likely // to be in separate locations on the disk. Create masks if needed. for(size_t i = 0; i < frames; ++i) { if(!buffer[0].Read(paths[0][i], i)) Logger::LogError("Failed to read image data for \"" + name + "\" frame #" + to_string(i)); else if(makeMasks) { masks[i].Create(buffer[0], i); if(!masks[i].IsLoaded()) Logger::LogError("Failed to create collision mask for \"" + name + "\" frame #" + to_string(i)); } } auto FillSwizzleMasks = [&](vector<string> &toFill, unsigned int intendedSize) { if(toFill.size() == 1 && intendedSize > 1) for(unsigned int i = toFill.size(); i < intendedSize; i++) toFill.emplace_back(toFill.back()); }; // If there is only a swizzle-mask defined for the first frame fill up the swizzle-masks // with this mask. FillSwizzleMasks(paths[2], paths[0].size()); FillSwizzleMasks(paths[3], paths[0].size()); auto LoadSprites = [&](vector<string> &toLoad, ImageBuffer &buffer, const string &specifier) { for(size_t i = 0; i < frames && i < toLoad.size(); ++i) if(!buffer.Read(toLoad[i], i)) { Logger::LogError("Removing " + specifier + " frames for \"" + name + "\" due to read error"); buffer.Clear(); break; } }; // Now, load the mask and 2x sprites, if they exist. Because the number of 1x frames // is definitive, don't load any frames beyond the size of the 1x list. LoadSprites(paths[1], buffer[1], "@2x"); LoadSprites(paths[2], buffer[2], "mask"); LoadSprites(paths[3], buffer[3], "@2x mask"); // Warn about a "high-profile" image that will be blurry due to rendering at 50% scale. bool willBlur = (buffer[0].Width() & 1) || (buffer[0].Height() & 1); if(willBlur && ( (name.length() > 5 && !name.compare(0, 5, "ship/")) || (name.length() > 7 && !name.compare(0, 7, "outfit/")) || (name.length() > 10 && !name.compare(0, 10, "thumbnail/")) )) Logger::LogError("Warning: image \"" + name + "\" will be blurry since width and/or height are not even (" + to_string(buffer[0].Width()) + "x" + to_string(buffer[0].Height()) + ")."); } // Create the sprite and upload the image data to the GPU. After this is // called, the internal image buffers and mask vector will be cleared, but // the paths are saved in case the sprite needs to be loaded again. void ImageSet::Upload(Sprite *sprite) { // Load the frames (this will clear the buffers). sprite->AddFrames(buffer[0], false); sprite->AddFrames(buffer[1], true); sprite->AddSwizzleMaskFrames(buffer[2], false); sprite->AddSwizzleMaskFrames(buffer[3], true); GameData::GetMaskManager().SetMasks(sprite, std::move(masks)); masks.clear(); }
0
endless-sky-master
endless-sky-master/source/DataFile.h
/* DataFile.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef DATA_FILE_H_ #define DATA_FILE_H_ #include "DataNode.h" #include <istream> #include <list> #include <string> // A class which represents a hierarchical data file. Each line of the file that // is not empty or a comment is a "node," and the relationship between the nodes // is determined by indentation: if a node is more indented than the node before // it, it is a "child" of that node. Otherwise, it is a "sibling." Each node is // just a collection of one or more tokens that can be interpreted either as // strings or as floating point values; see DataNode for more information. class DataFile { public: // A DataFile can be loaded either from a file path or an istream. DataFile() = default; explicit DataFile(const std::string &path); explicit DataFile(std::istream &in); void Load(const std::string &path); void Load(std::istream &in); // Functions for iterating through all DataNodes in this file. std::list<DataNode>::const_iterator begin() const; std::list<DataNode>::const_iterator end() const; private: void LoadData(const std::string &data); private: // This is the container for all DataNodes in this file. DataNode root; }; #endif
0
endless-sky-master
endless-sky-master/source/BatchShader.h
/* BatchShader.h Copyright (c) 2017 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef BATCH_SHADER_H_ #define BATCH_SHADER_H_ class Sprite; #include <vector> // Class for drawing sprites in a batch. The input to each draw command is a // sprite, whether it should be drawn high DPI, and the vertex data. class BatchShader { public: // Initialize the shaders. static void Init(); static void Bind(); static void Add(const Sprite *sprite, bool isHighDPI, const std::vector<float> &data); static void Unbind(); }; #endif
0
endless-sky-master
endless-sky-master/source/NPCAction.cpp
/* NPCAction.cpp Copyright (c) 2023 by Amazinite Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "NPCAction.h" #include "DataNode.h" #include "DataWriter.h" #include "PlayerInfo.h" #include "System.h" #include "UI.h" using namespace std; // Construct and Load() at the same time. NPCAction::NPCAction(const DataNode &node) { Load(node); } void NPCAction::Load(const DataNode &node) { if(node.Size() >= 2) trigger = node.Token(1); for(const DataNode &child : node) { const string &key = child.Token(0); if(key == "triggered") triggered = true; else action.LoadSingle(child); } } // Note: the Save() function can assume this is an instantiated action, not // a template, so it only has to save a subset of the data. void NPCAction::Save(DataWriter &out) const { out.Write("on", trigger); out.BeginChild(); { if(triggered) out.Write("triggered"); action.SaveBody(out); } out.EndChild(); } // Check this template or instantiated NPCAction to see if any used content // is not fully defined (e.g. plugin removal, typos in names, etc.). string NPCAction::Validate() const { return action.Validate(); } void NPCAction::Do(PlayerInfo &player, UI *ui, const Mission *caller) { // All actions are currently one-time-use. Actions that are used // are marked as triggered, and cannot be used again. if(triggered) return; triggered = true; action.Do(player, ui, caller); } // Convert this validated template into a populated action. NPCAction NPCAction::Instantiate(map<string, string> &subs, const System *origin, int jumps, int64_t payload) const { NPCAction result; result.trigger = trigger; result.action = action.Instantiate(subs, origin, jumps, payload); return result; }
0
endless-sky-master
endless-sky-master/source/Personality.h
/* Personality.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef PERSONALITY_H_ #define PERSONALITY_H_ #include "Angle.h" #include "Point.h" #include <bitset> class DataNode; class DataWriter; // Class defining an AI "personality": what actions it takes, and how skilled // and aggressive it is in combat. This also includes some more specialized // behaviors, like plundering ships or launching surveillance drones, that are // used to make some fleets noticeably different from others. class Personality { public: Personality() noexcept; void Load(const DataNode &node); void Save(DataWriter &out) const; bool IsDefined() const; // Who a ship decides to attack: bool IsPacifist() const; bool IsForbearing() const; bool IsTimid() const; bool IsHunting() const; bool IsNemesis() const; bool IsDaring() const; // How they fight: bool IsFrugal() const; bool Disables() const; bool Plunders() const; bool IsVindictive() const; bool IsUnconstrained() const; bool IsUnrestricted() const; bool IsCoward() const; bool IsAppeasing() const; bool IsOpportunistic() const; bool IsMerciful() const; bool IsRamming() const; // Mission NPC states: bool IsStaying() const; bool IsEntering() const; bool IsWaiting() const; bool IsLaunching() const; bool IsFleeing() const; bool IsDerelict() const; bool IsUninterested() const; // Non-combat goals: bool IsSurveillance() const; bool IsMining() const; bool Harvests() const; bool IsSwarming() const; bool IsLingering() const; bool IsSecretive() const; // Special flags: bool IsEscort() const; bool IsTarget() const; bool IsMarked() const; bool IsMute() const; bool IsDecloaked() const; // Current inaccuracy in this ship's targeting: const Point &Confusion() const; void UpdateConfusion(bool isFiring); // Personality to use for ships defending a planet from domination: static Personality Defender(); static Personality DefenderFighter(); private: void Parse(const DataNode &node, int index, bool remove); private: // Make sure this matches the number of items in PersonalityTrait, // or the build will fail. static const int PERSONALITY_COUNT = 35; bool isDefined = false; std::bitset<PERSONALITY_COUNT> flags; double confusionMultiplier; double aimMultiplier; Point confusion; Point confusionVelocity; }; #endif
0
endless-sky-master
endless-sky-master/source/MapShipyardPanel.h
/* MapShipyardPanel.h Copyright (c) 2015 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef MAP_SHIPYARD_PANEL_H_ #define MAP_SHIPYARD_PANEL_H_ #include "MapSalesPanel.h" #include "ShipInfoDisplay.h" #include <vector> class PlayerInfo; class Ship; class Sprite; // A panel that displays the galaxy star map, along with a side panel showing // all ships that are for sale in known systems. You can click on one of them // to see which systems it is available in. class MapShipyardPanel : public MapSalesPanel { public: explicit MapShipyardPanel(PlayerInfo &player); explicit MapShipyardPanel(const MapPanel &panel, bool onlyHere = false); protected: virtual const Sprite *SelectedSprite() const override; virtual const Sprite *CompareSprite() const override; virtual int SelectedSpriteSwizzle() const override; virtual int CompareSpriteSwizzle() const override; virtual const ItemInfoDisplay &SelectedInfo() const override; virtual const ItemInfoDisplay &CompareInfo() const override; virtual const std::string &KeyLabel(int index) const override; virtual void Select(int index) override; virtual void Compare(int index) override; virtual double SystemValue(const System *system) const override; virtual int FindItem(const std::string &text) const override; virtual void DrawItems() override; private: void Init(); private: std::map<std::string, std::vector<const Ship *>> catalog; std::vector<const Ship *> list; std::map<const System *, std::map<const Ship *, int>> parkedShips; const Ship *selected = nullptr; const Ship *compare = nullptr; ShipInfoDisplay selectedInfo; ShipInfoDisplay compareInfo; }; #endif
0
endless-sky-master
endless-sky-master/source/Person.h
/* Person.h Copyright (c) 2015 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef PERSON_H_ #define PERSON_H_ #include "LocationFilter.h" #include "Personality.h" #include "Phrase.h" #include <list> #include <memory> class DataNode; class Government; class Ship; class System; // A unique individual who may appear at random times in the game. class Person { public: void Load(const DataNode &node); // Finish loading all the ships in this person specification. void FinishLoading(); // Prevent this person from being spawned in any system. void NeverSpawn(); // Find out how often this person should appear in the given system. If this // person is dead or already active, this will return zero. int Frequency(const System *system) const; // Get the person's characteristics. The ship object is persistent, i.e. it // will be recycled every time this person appears. const std::list<std::shared_ptr<Ship>> &Ships() const; const Government *GetGovernment() const; const Personality &GetPersonality() const; const Phrase &GetHail() const; // Check if a person has been destroyed or captured. bool IsDestroyed() const; // Mark this person as destroyed. void Destroy(); // Mark this person as no longer destroyed. void Restore(); // Check if a person is already placed somewhere. bool IsPlaced() const; // Mark this person as being no longer "placed" somewhere. void ClearPlacement(); private: LocationFilter location; int frequency = 100; std::list<std::shared_ptr<Ship>> ships; const Government *government = nullptr; Personality personality; Phrase hail; }; #endif
0
endless-sky-master
endless-sky-master/source/AlertLabel.cpp
/* AlertLabel.cpp Copyright (c) 2022 by Daniel Yoon Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "AlertLabel.h" #include "Angle.h" #include "GameData.h" #include "PointerShader.h" #include "Projectile.h" #include "RingShader.h" #include "Ship.h" #include <algorithm> using namespace std; namespace { const double DANGEROUS_ABOVE = .1; } AlertLabel::AlertLabel(const Point &position, const Projectile &projectile, const shared_ptr<Ship> &flagship, double zoom) : position(position), zoom(zoom) { bool isDangerous = false; isTargetingFlagship = false; if(flagship) { isTargetingFlagship = projectile.TargetPtr() == flagship; double maxHP = flagship->MaxHull() + flagship->MaxShields(); double missileDamage = projectile.GetWeapon().HullDamage() + projectile.GetWeapon().ShieldDamage(); isDangerous = (missileDamage / maxHP) > DANGEROUS_ABOVE; } if(isDangerous) color = GameData::Colors().Get("missile dangerous"); else if(isTargetingFlagship) color = GameData::Colors().Get("missile locked"); else color = GameData::Colors().Get("missile enemy"); radius = zoom * projectile.Radius() * 0.75; rotation = projectile.Facing().Degrees(); } void AlertLabel::Draw() const { const double angle[3] = {330., 210., 90.}; for(int i = 0; i < 3; i++) { RingShader::Draw(position * zoom, radius, 1.2f, .16f, *color, 0.f, angle[i] + rotation); if(isTargetingFlagship) PointerShader::Draw(position * zoom, Angle(angle[i] + 30. + rotation).Unit(), 7.5f, (i ? 10.f : 22.f) * zoom, radius + (i ? 10.f : 20.f) * zoom, *color); } }
0
endless-sky-master
endless-sky-master/source/HiringPanel.h
/* HiringPanel.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef HIRING_PANEL_H_ #define HIRING_PANEL_H_ #include "Panel.h" class PlayerInfo; // This panel is drawn as an overlay on top of the PlanetPanel. It shows your // current crew and passengers and allows you to hire extra crew if you are // hunting other ships to capture. class HiringPanel : public Panel { public: explicit HiringPanel(PlayerInfo &player); virtual void Step() override; virtual void Draw() override; protected: // Only override the ones you need; the default action is to return false. virtual bool KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) override; private: PlayerInfo &player; int maxHire; int maxFire; }; #endif
0
endless-sky-master
endless-sky-master/source/SavedGame.cpp
/* SavedGame.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "SavedGame.h" #include "DataFile.h" #include "DataNode.h" #include "Date.h" #include "text/Format.h" #include "SpriteSet.h" using namespace std; SavedGame::SavedGame(const string &path) { Load(path); } void SavedGame::Load(const string &path) { Clear(); DataFile file(path); if(file.begin() != file.end()) this->path = path; int flagshipIterator = -1; int flagshipTarget = 0; for(const DataNode &node : file) { if(node.Token(0) == "pilot" && node.Size() >= 3) name = node.Token(1) + " " + node.Token(2); else if(node.Token(0) == "date" && node.Size() >= 4) date = Date(node.Value(1), node.Value(2), node.Value(3)).ToString(); else if(node.Token(0) == "system" && node.Size() >= 2) system = node.Token(1); else if(node.Token(0) == "planet" && node.Size() >= 2) planet = node.Token(1); else if(node.Token(0) == "playtime" && node.Size() >= 2) playTime = Format::PlayTime(node.Value(1)); else if(node.Token(0) == "flagship index" && node.Size() >= 2) flagshipTarget = node.Value(1); else if(node.Token(0) == "account") { for(const DataNode &child : node) if(child.Token(0) == "credits" && child.Size() >= 2) { credits = Format::Credits(child.Value(1)); break; } } else if(node.Token(0) == "ship" && ++flagshipIterator == flagshipTarget) { for(const DataNode &child : node) { if(child.Token(0) == "name" && child.Size() >= 2) shipName = child.Token(1); else if(child.Token(0) == "sprite" && child.Size() >= 2) shipSprite = SpriteSet::Get(child.Token(1)); } } } } const string &SavedGame::Path() const { return path; } bool SavedGame::IsLoaded() const { return !path.empty(); } void SavedGame::Clear() { path.clear(); name.clear(); credits.clear(); date.clear(); system.clear(); planet.clear(); playTime = "0s"; shipSprite = nullptr; shipName.clear(); } const string &SavedGame::Name() const { return name; } const string &SavedGame::Credits() const { return credits; } const string &SavedGame::GetDate() const { return date; } const string &SavedGame::GetSystem() const { return system; } const string &SavedGame::GetPlanet() const { return planet; } const string &SavedGame::GetPlayTime() const { return playTime; } const Sprite *SavedGame::ShipSprite() const { return shipSprite; } const string &SavedGame::ShipName() const { return shipName; }
0
endless-sky-master
endless-sky-master/source/Hardpoint.cpp
/* Hardpoint.cpp Copyright (c) 2016 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Hardpoint.h" #include "Audio.h" #include "Effect.h" #include "Outfit.h" #include "pi.h" #include "Projectile.h" #include "Random.h" #include "Ship.h" #include "Visual.h" #include <cmath> #include <map> using namespace std; namespace { // Create all the effects in the given list, at the given location, velocity, and angle. void CreateEffects(const map<const Effect *, int> &m, Point pos, Point vel, Angle angle, vector<Visual> &visuals) { for(const auto &it : m) for(int i = 0; i < it.second; ++i) visuals.emplace_back(*it.first, pos, vel, angle); } } // Constructor. Hardpoint::Hardpoint(const Point &point, const Angle &baseAngle, bool isTurret, bool isParallel, bool isUnder, const Outfit *outfit) : outfit(outfit), point(point * .5), baseAngle(baseAngle), isTurret(isTurret), isParallel(isParallel), isUnder(isUnder) { } // Get the weapon in this hardpoint. This returns null if there is none. const Outfit *Hardpoint::GetOutfit() const { return outfit; } // Get the location, relative to the center of the ship, from which // projectiles of this weapon should originate. const Point &Hardpoint::GetPoint() const { return point; } // Get the convergence angle adjustment of this weapon (guns only, not turrets). const Angle &Hardpoint::GetAngle() const { return angle; } // Get the default facing direction for a gun const Angle &Hardpoint::GetBaseAngle() const { return baseAngle; } // Get the angle this weapon ought to point at for ideal gun harmonization. Angle Hardpoint::HarmonizedAngle() const { if(!outfit) return Angle(); // Calculate reference point for non-forward facing guns. Angle rotateAngle = Angle() - baseAngle; Point refPoint = rotateAngle.Rotate(point); // Find the point of convergence of shots fired from this gun. That is, // find the angle where the projectile's X offset will be zero when it // reaches the very end of its range. double d = outfit->Range(); // Projectiles with a range of zero should fire straight forward. A // special check is needed to avoid divide by zero errors. return Angle(d <= 0. ? 0. : -asin(refPoint.X() / d) * TO_DEG); } // Find out if this is a turret hardpoint (whether or not it has a turret installed). bool Hardpoint::IsTurret() const { return isTurret; } bool Hardpoint::IsParallel() const { return isParallel; } bool Hardpoint::IsUnder() const { return isUnder; } // Find out if this hardpoint has a homing weapon installed. bool Hardpoint::IsHoming() const { return outfit && outfit->Homing(); } // Find out if this hardpoint has an anti-missile installed. bool Hardpoint::IsAntiMissile() const { return outfit && outfit->AntiMissile() > 0; } bool Hardpoint::CanAim() const { return outfit && outfit->TurretTurn(); } // Check if this weapon is ready to fire. bool Hardpoint::IsReady() const { return outfit && burstReload <= 0. && burstCount; } // Check if this weapon fired the last time it was able to fire. This is to // figure out if the stream spacing timer should be applied or not. bool Hardpoint::WasFiring() const { return wasFiring; } // Get the number of remaining burst shots before a full reload is required. int Hardpoint::BurstRemaining() const { return burstCount; } // Perform one step (i.e. decrement the reload count). void Hardpoint::Step() { if(!outfit) return; wasFiring = isFiring; if(reload > 0.) --reload; // If the full reload time is elapsed, reset the burst counter. if(reload <= 0.) burstCount = outfit->BurstCount(); if(burstReload > 0.) --burstReload; // If the burst reload time has elapsed, this weapon will not count as firing // continuously if it is not fired this frame. if(burstReload <= 0.) isFiring = false; } // Adjust this weapon's aim by the given amount, relative to its maximum // "turret turn" rate. void Hardpoint::Aim(double amount) { if(!outfit) return; angle += outfit->TurretTurn() * amount; } // Fire this weapon. If it is a turret, it automatically points toward // the given ship's target. If the weapon requires ammunition, it will // be subtracted from the given ship. void Hardpoint::Fire(Ship &ship, vector<Projectile> &projectiles, vector<Visual> &visuals) { // Since this is only called internally by Armament (no one else has non- // const access), assume Armament checked that this is a valid call. Angle aim = ship.Facing(); Point start = ship.Position() + aim.Rotate(point); // Apply the aim and hardpoint offset. aim += angle; start += aim.Rotate(outfit->HardpointOffset()); // Apply the weapon's inaccuracy to the aim. This allows firing effects // to share the same inaccuracy as the projectile. aim += Distribution::GenerateInaccuracy(outfit->Inaccuracy(), outfit->InaccuracyDistribution()); // Create a new projectile, originating from this hardpoint. // In order to get projectiles to start at the right position they are drawn // at an offset of (.5 * velocity). See BatchDrawList.cpp for more details. projectiles.emplace_back(ship, start - .5 * ship.Velocity(), aim, outfit); // Create any effects this weapon creates when it is fired. CreateEffects(outfit->FireEffects(), start, ship.Velocity(), aim, visuals); // Update the reload and burst counters, and expend ammunition if applicable. Fire(ship, start, aim); } // Fire an anti-missile. Returns true if the missile should be killed. bool Hardpoint::FireAntiMissile(Ship &ship, const Projectile &projectile, vector<Visual> &visuals) { // Make sure this hardpoint really is an anti-missile. int strength = outfit->AntiMissile(); if(!strength) return false; // Get the anti-missile range. Anti-missile shots always last a single frame, // so their range is equal to their velocity. double range = outfit->Velocity(); // Check if the missile is within range of this hardpoint. Point start = ship.Position() + ship.Facing().Rotate(point); Point offset = projectile.Position() - start; if(offset.Length() > range) return false; // Precompute the number of visuals that will be added. visuals.reserve(visuals.size() + outfit->FireEffects().size() + outfit->HitEffects().size() + outfit->DieEffects().size()); // Firing effects are displayed at the anti-missile hardpoint that just fired. Angle aim(offset); angle = aim - ship.Facing(); start += aim.Rotate(outfit->HardpointOffset()); CreateEffects(outfit->FireEffects(), start, ship.Velocity(), aim, visuals); // Figure out where the effect should be placed. Anti-missiles do not create // projectiles; they just create a blast animation. CreateEffects(outfit->HitEffects(), start + (.5 * range) * aim.Unit(), ship.Velocity(), aim, visuals); // Die effects are displayed at the projectile, whether or not it actually "dies." CreateEffects(outfit->DieEffects(), projectile.Position(), projectile.Velocity(), aim, visuals); // Update the reload and burst counters, and expend ammunition if applicable. Fire(ship, start, aim); // Check whether the missile was destroyed. return (Random::Int(strength) > Random::Int(projectile.MissileStrength())); } // This weapon jammed. Increase its reload counters, but don't fire. void Hardpoint::Jam() { // Since this is only called internally by Armament (no one else has non- // const access), assume Armament checked that this is a valid call. // Reset the reload count. reload += outfit->Reload(); burstReload += outfit->BurstReload(); } // Install a weapon here (assuming it is empty). This is only for // Armament to call internally. void Hardpoint::Install(const Outfit *outfit) { // If the given outfit is not a valid weapon, this hardpoint becomes empty. // Also check that the type of the weapon (gun or turret) is right. if(!outfit || !outfit->IsWeapon() || (isTurret == !outfit->Get("turret mounts"))) Uninstall(); else { // Reset all the reload counters. this->outfit = outfit; Reload(); // For fixed weapons, apply "gun harmonization," pointing them slightly // inward so the projectiles will converge. For turrets, start them out // pointing outward from the center of the ship. if(!isTurret) { angle = baseAngle; // Weapons that fire in parallel beams don't get a harmonized angle. // And some hardpoints/gunslots are configured not to get harmonized. // So only harmonize when both the port and the outfit supports it. if(!isParallel && !outfit->IsParallel()) angle += HarmonizedAngle(); } else angle = Angle(point); } } // Reload this weapon. void Hardpoint::Reload() { reload = 0.; burstReload = 0.; burstCount = outfit ? outfit->BurstCount() : 0; } // Uninstall the outfit from this port (if it has one). void Hardpoint::Uninstall() { outfit = nullptr; } // Update any counters that change when this projectile fires. void Hardpoint::Fire(Ship &ship, const Point &start, const Angle &aim) { // Since this is only called internally, it is safe to assume that the // outfit pointer is not null. // Reset the reload count. reload += outfit->Reload(); burstReload += outfit->BurstReload(); --burstCount; isFiring = true; // Anti-missile sounds can be specified either in the outfit itself or in // the effect they create. if(outfit->WeaponSound()) Audio::Play(outfit->WeaponSound(), start); // Apply any "kick" from firing this weapon. double force = outfit->FiringForce(); if(force) ship.ApplyForce(aim.Unit() * -force); // Expend any ammo that this weapon uses. Do this as the very last thing, in // case the outfit is its own ammunition. ship.ExpendAmmo(*outfit); }
0
endless-sky-master
endless-sky-master/source/opengl.cpp
/* opengl.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "opengl.h" #if !defined(__APPLE__) && !defined(ES_GLES) #ifdef _WIN32 #include <GL/wglew.h> #else #include <GL/glxew.h> #endif #endif #include <cstring> #if defined(ES_GLES) || defined(_WIN32) namespace { bool HasOpenGLExtension(const char *name) { #ifndef __APPLE__ auto extensions = reinterpret_cast<const char *>(glGetString(GL_EXTENSIONS)); return strstr(extensions, name); #else bool value = false; GLint extensionCount = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &extensionCount); for(GLint i = 0; i < extensionCount && !value; ++i) { auto extension = reinterpret_cast<const char *>(glGetStringi(GL_EXTENSIONS, i)); value = (extension && strstr(extension, name)); } return value; #endif } } #endif bool OpenGL::HasAdaptiveVSyncSupport() { #ifdef __APPLE__ // macOS doesn't support Adaptive VSync for OpenGL. return false; #elif defined(ES_GLES) return HasOpenGLExtension("_swap_control_tear"); #elif defined(_WIN32) return WGL_EXT_swap_control_tear || HasOpenGLExtension("_swap_control_tear"); #else return GLX_EXT_swap_control_tear; #endif }
0
endless-sky-master
endless-sky-master/source/Screen.h
/* Screen.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef SCREEN_H_ #define SCREEN_H_ #include "Point.h" // Class that simply holds the screen dimensions. This is really just a wrapper // around some global variables, which means that no one but the drawing thread // is allowed to use it. class Screen { public: static void SetRaw(int width, int height); // Zoom level as specified by the user. static int UserZoom(); // Effective zoom level, as restricted by the current resolution / window size. static int Zoom(); static void SetZoom(int percent); // Specify that this is a high-DPI window. static void SetHighDPI(bool isHighDPI = true); // This is true if the screen is high DPI, or if the zoom is above 100%. static bool IsHighResolution(); static Point Dimensions(); static int Width(); static int Height(); static int RawWidth(); static int RawHeight(); // Get the positions of the edges and corners of the viewport. static int Left(); static int Top(); static int Right(); static int Bottom(); static Point TopLeft(); static Point TopRight(); static Point BottomLeft(); static Point BottomRight(); }; #endif
0
endless-sky-master
endless-sky-master/source/ShipInfoPanel.cpp
/* ShipInfoPanel.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ShipInfoPanel.h" #include "text/alignment.hpp" #include "CategoryList.h" #include "CategoryTypes.h" #include "Command.h" #include "Dialog.h" #include "text/DisplayText.h" #include "text/Font.h" #include "text/FontSet.h" #include "text/Format.h" #include "GameData.h" #include "Information.h" #include "Interface.h" #include "LineShader.h" #include "LogbookPanel.h" #include "Messages.h" #include "MissionPanel.h" #include "OutlineShader.h" #include "PlayerInfo.h" #include "PlayerInfoPanel.h" #include "Rectangle.h" #include "Ship.h" #include "Sprite.h" #include "SpriteShader.h" #include "text/Table.h" #include "text/truncate.hpp" #include "UI.h" #include <algorithm> using namespace std; namespace { constexpr double WIDTH = 250.; constexpr int COLUMN_WIDTH = static_cast<int>(WIDTH) - 20; } ShipInfoPanel::ShipInfoPanel(PlayerInfo &player) : ShipInfoPanel(player, InfoPanelState(player)) { } ShipInfoPanel::ShipInfoPanel(PlayerInfo &player, InfoPanelState state) : player(player), panelState(std::move(state)) { shipIt = this->panelState.Ships().begin(); SetInterruptible(false); // If a valid ship index was given, show that ship. if(static_cast<unsigned>(panelState.SelectedIndex()) < player.Ships().size()) shipIt += panelState.SelectedIndex(); else if(player.Flagship()) { // Find the player's flagship. It may not be first in the list, if the // first item in the list cannot be a flagship. while(shipIt != this->panelState.Ships().end() && shipIt->get() != player.Flagship()) ++shipIt; } UpdateInfo(); } void ShipInfoPanel::Step() { DoHelp("ship info"); } void ShipInfoPanel::Draw() { // Dim everything behind this panel. DrawBackdrop(); // Fill in the information for how this interface should be drawn. Information interfaceInfo; interfaceInfo.SetCondition("ship tab"); if(panelState.CanEdit() && shipIt != panelState.Ships().end() && (shipIt->get() != player.Flagship() || (*shipIt)->IsParked())) { if(!(*shipIt)->IsDisabled()) interfaceInfo.SetCondition("can park"); interfaceInfo.SetCondition((*shipIt)->IsParked() ? "show unpark" : "show park"); interfaceInfo.SetCondition("show disown"); } else if(!panelState.CanEdit()) { interfaceInfo.SetCondition("show dump"); if(CanDump()) interfaceInfo.SetCondition("enable dump"); } if(player.Ships().size() > 1) interfaceInfo.SetCondition("five buttons"); else interfaceInfo.SetCondition("three buttons"); if(player.HasLogs()) interfaceInfo.SetCondition("enable logbook"); // Draw the interface. const Interface *infoPanelUi = GameData::Interfaces().Get("info panel"); infoPanelUi->Draw(interfaceInfo, this); // Draw all the different information sections. ClearZones(); if(shipIt == panelState.Ships().end()) return; Rectangle cargoBounds = infoPanelUi->GetBox("cargo"); DrawShipStats(infoPanelUi->GetBox("stats")); DrawOutfits(infoPanelUi->GetBox("outfits"), cargoBounds); DrawWeapons(infoPanelUi->GetBox("weapons")); DrawCargo(cargoBounds); // If the player hovers their mouse over a ship attribute, show its tooltip. info.DrawTooltips(); } bool ShipInfoPanel::KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool /* isNewPress */) { bool control = (mod & (KMOD_CTRL | KMOD_GUI)); bool shift = (mod & KMOD_SHIFT); if(key == 'd' || key == SDLK_ESCAPE || (key == 'w' && control)) GetUI()->Pop(this); else if(command.Has(Command::HELP)) DoHelp("ship info", true); else if(!player.Ships().empty() && ((key == 'p' && !shift) || key == SDLK_LEFT || key == SDLK_UP)) { if(shipIt == panelState.Ships().begin()) shipIt = panelState.Ships().end(); --shipIt; UpdateInfo(); } else if(!panelState.Ships().empty() && (key == 'n' || key == SDLK_RIGHT || key == SDLK_DOWN)) { ++shipIt; if(shipIt == panelState.Ships().end()) shipIt = panelState.Ships().begin(); UpdateInfo(); } else if(key == 'i' || command.Has(Command::INFO) || (control && key == SDLK_TAB)) { GetUI()->Pop(this); GetUI()->Push(new PlayerInfoPanel(player, std::move(panelState))); } else if(key == 'R' || (key == 'r' && shift)) GetUI()->Push(new Dialog(this, &ShipInfoPanel::Rename, "Change this ship's name?", (*shipIt)->Name())); else if(panelState.CanEdit() && (key == 'P' || (key == 'p' && shift) || key == 'k')) { if(shipIt->get() != player.Flagship() || (*shipIt)->IsParked()) player.ParkShip(shipIt->get(), !(*shipIt)->IsParked()); } else if(panelState.CanEdit() && key == 'D') { if(shipIt->get() != player.Flagship()) { map<const Outfit*, int> uniqueOutfits; auto AddToUniques = [&uniqueOutfits] (const std::map<const Outfit *, int> &outfits) { for(const auto &it : outfits) if(it.first->Attributes().Get("unique")) uniqueOutfits[it.first] += it.second; }; AddToUniques(shipIt->get()->Outfits()); AddToUniques(shipIt->get()->Cargo().Outfits()); string message = "Are you sure you want to disown \"" + shipIt->get()->Name() + "\"? Disowning a ship rather than selling it means you will not get any money for it."; if(!uniqueOutfits.empty()) { const int uniquesSize = uniqueOutfits.size(); const int detailedOutfitSize = (uniquesSize > 20 ? 19 : uniquesSize); message += "\nThe following unique items carried by the ship will be lost:"; auto it = uniqueOutfits.begin(); for(int i = 0; i < detailedOutfitSize; ++i) { message += "\n" + to_string(it->second) + " " + (it->second == 1 ? it->first->DisplayName() : it->first->PluralName()); ++it; } if(it != uniqueOutfits.end()) { int otherUniquesCount = 0; for( ; it != uniqueOutfits.end(); ++it) otherUniquesCount += it->second; message += "\nand " + to_string(otherUniquesCount) + " other unique outfits"; } } GetUI()->Push(new Dialog(this, &ShipInfoPanel::Disown, message)); } } else if(key == 'c' && CanDump()) { int commodities = (*shipIt)->Cargo().CommoditiesSize(); int amount = (*shipIt)->Cargo().Get(selectedCommodity); int plunderAmount = (*shipIt)->Cargo().Get(selectedPlunder); if(amount) { GetUI()->Push(new Dialog(this, &ShipInfoPanel::DumpCommodities, "How many tons of " + Format::LowerCase(selectedCommodity) + " do you want to jettison?", amount)); } else if(plunderAmount > 0 && selectedPlunder->Get("installable") < 0.) { GetUI()->Push(new Dialog(this, &ShipInfoPanel::DumpPlunder, "How many tons of " + Format::LowerCase(selectedPlunder->DisplayName()) + " do you want to jettison?", plunderAmount)); } else if(plunderAmount == 1) { GetUI()->Push(new Dialog(this, &ShipInfoPanel::Dump, "Are you sure you want to jettison a " + selectedPlunder->DisplayName() + "?")); } else if(plunderAmount > 1) { GetUI()->Push(new Dialog(this, &ShipInfoPanel::DumpPlunder, "How many " + selectedPlunder->PluralName() + " do you want to jettison?", plunderAmount)); } else if(commodities) { GetUI()->Push(new Dialog(this, &ShipInfoPanel::Dump, "Are you sure you want to jettison all of this ship's regular cargo?")); } else { GetUI()->Push(new Dialog(this, &ShipInfoPanel::Dump, "Are you sure you want to jettison all of this ship's cargo?")); } } else if(command.Has(Command::MAP) || key == 'm') GetUI()->Push(new MissionPanel(player)); else if(key == 'l' && player.HasLogs()) GetUI()->Push(new LogbookPanel(player)); else return false; return true; } bool ShipInfoPanel::Click(int x, int y, int /* clicks */) { if(shipIt == panelState.Ships().end()) return true; draggingIndex = -1; if(panelState.CanEdit() && hoverIndex >= 0 && (**shipIt).GetSystem() == player.GetSystem() && !(**shipIt).IsDisabled()) draggingIndex = hoverIndex; selectedCommodity.clear(); selectedPlunder = nullptr; Point point(x, y); for(const auto &zone : commodityZones) if(zone.Contains(point)) selectedCommodity = zone.Value(); for(const auto &zone : plunderZones) if(zone.Contains(point)) selectedPlunder = zone.Value(); return true; } bool ShipInfoPanel::Hover(int x, int y) { Point point(x, y); info.Hover(point); return Hover(point); } bool ShipInfoPanel::Drag(double dx, double dy) { return Hover(hoverPoint + Point(dx, dy)); } bool ShipInfoPanel::Release(int /* x */, int /* y */) { if(draggingIndex >= 0 && hoverIndex >= 0 && hoverIndex != draggingIndex) (**shipIt).GetArmament().Swap(hoverIndex, draggingIndex); draggingIndex = -1; return true; } void ShipInfoPanel::UpdateInfo() { draggingIndex = -1; hoverIndex = -1; ClearZones(); if(shipIt == panelState.Ships().end()) return; const Ship &ship = **shipIt; info.Update(ship, player); if(player.Flagship() && ship.GetSystem() == player.GetSystem() && &ship != player.Flagship()) player.Flagship()->SetTargetShip(*shipIt); outfits.clear(); for(const auto &it : ship.Outfits()) outfits[it.first->Category()].push_back(it.first); panelState.SelectOnly(shipIt - panelState.Ships().begin()); } void ShipInfoPanel::ClearZones() { zones.clear(); commodityZones.clear(); plunderZones.clear(); } void ShipInfoPanel::DrawShipStats(const Rectangle &bounds) { // Check that the specified area is big enough. if(bounds.Width() < WIDTH) return; // Colors to draw with. Color dim = *GameData::Colors().Get("medium"); Color bright = *GameData::Colors().Get("bright"); const Ship &ship = **shipIt; // Two columns of opposite alignment are used to simulate a single visual column. Table table; table.AddColumn(0, {COLUMN_WIDTH, Alignment::LEFT}); table.AddColumn(COLUMN_WIDTH, {COLUMN_WIDTH, Alignment::RIGHT, Truncate::MIDDLE}); table.SetUnderline(0, COLUMN_WIDTH); table.DrawAt(bounds.TopLeft() + Point(10., 8.)); table.DrawTruncatedPair("ship:", dim, ship.Name(), bright, Truncate::MIDDLE, true); info.DrawAttributes(table.GetRowBounds().TopLeft() - Point(10., 10.)); } void ShipInfoPanel::DrawOutfits(const Rectangle &bounds, Rectangle &cargoBounds) { // Check that the specified area is big enough. if(bounds.Width() < WIDTH) return; // Colors to draw with. Color dim = *GameData::Colors().Get("medium"); Color bright = *GameData::Colors().Get("bright"); const Ship &ship = **shipIt; // Two columns of opposite alignment are used to simulate a single visual column. Table table; table.AddColumn(0, {COLUMN_WIDTH, Alignment::LEFT}); table.AddColumn(COLUMN_WIDTH, {COLUMN_WIDTH, Alignment::RIGHT}); table.SetUnderline(0, COLUMN_WIDTH); Point start = bounds.TopLeft() + Point(10., 8.); table.DrawAt(start); // Draw the outfits in the same order used in the outfitter. for(const auto &cat : GameData::GetCategory(CategoryType::OUTFIT)) { const string &category = cat.Name(); auto it = outfits.find(category); if(it == outfits.end()) continue; // Skip to the next column if there is not space for this category label // plus at least one outfit. if(table.GetRowBounds().Bottom() + 40. > bounds.Bottom()) { start += Point(WIDTH, 0.); if(start.X() + COLUMN_WIDTH > bounds.Right()) break; table.DrawAt(start); } // Draw the category label. table.Draw(category, bright); table.Advance(); for(const Outfit *outfit : it->second) { // Check if we've gone below the bottom of the bounds. if(table.GetRowBounds().Bottom() > bounds.Bottom()) { start += Point(WIDTH, 0.); if(start.X() + COLUMN_WIDTH > bounds.Right()) break; table.DrawAt(start); table.Draw(category, bright); table.Advance(); } // Draw the outfit name and count. table.DrawTruncatedPair(outfit->DisplayName(), dim, to_string(ship.OutfitCount(outfit)), bright, Truncate::BACK, false); } // Add an extra gap in between categories. table.DrawGap(10.); } // Check if this information spilled over into the cargo column. if(table.GetPoint().X() >= cargoBounds.Left()) { double startY = table.GetRowBounds().Top() - 8.; cargoBounds = Rectangle::WithCorners( Point(cargoBounds.Left(), startY), Point(cargoBounds.Right(), max(startY, cargoBounds.Bottom()))); } } void ShipInfoPanel::DrawWeapons(const Rectangle &bounds) { // Colors to draw with. Color dim = *GameData::Colors().Get("medium"); Color bright = *GameData::Colors().Get("bright"); const Font &font = FontSet::Get(14); const Ship &ship = **shipIt; // Figure out how much to scale the sprite by. const Sprite *sprite = ship.GetSprite(); double scale = 0.; if(sprite) scale = min(1., min((WIDTH - 10) / sprite->Width(), (WIDTH - 10) / sprite->Height())); // Figure out the left- and right-most hardpoints on the ship. If they are // too far apart, the scale may need to be reduced. // Also figure out how many weapons of each type are on each side. double maxX = 0.; int count[2][2] = {{0, 0}, {0, 0}}; for(const Hardpoint &hardpoint : ship.Weapons()) { // Multiply hardpoint X by 2 to convert to sprite pixels. maxX = max(maxX, fabs(2. * hardpoint.GetPoint().X())); ++count[hardpoint.GetPoint().X() >= 0.][hardpoint.IsTurret()]; } // If necessary, shrink the sprite to keep the hardpoints inside the labels. // The width of this UI block will be 2 * (LABEL_WIDTH + HARDPOINT_DX). static const double LABEL_WIDTH = 150.; static const double LABEL_DX = 95.; static const double LABEL_PAD = 5.; if(maxX > (LABEL_DX - LABEL_PAD)) scale = min(scale, (LABEL_DX - LABEL_PAD) / (2. * maxX)); // Draw the ship, using the black silhouette swizzle. if(sprite) { SpriteShader::Draw(sprite, bounds.Center(), scale, 28); OutlineShader::Draw(sprite, bounds.Center(), scale * Point(sprite->Width(), sprite->Height()), Color(.5f)); } // Figure out how tall each part of the weapon listing will be. int gunRows = max(count[0][0], count[1][0]); int turretRows = max(count[0][1], count[1][1]); // If there are both guns and turrets, add a gap of ten pixels. double height = 20. * (gunRows + turretRows) + 10. * (gunRows && turretRows); double gunY = bounds.Top() + .5 * (bounds.Height() - height); double turretY = gunY + 20. * gunRows + 10. * (gunRows != 0); double nextY[2][2] = { {gunY + 20. * (gunRows - count[0][0]), turretY + 20. * (turretRows - count[0][1])}, {gunY + 20. * (gunRows - count[1][0]), turretY + 20. * (turretRows - count[1][1])}}; int index = 0; const double centerX = bounds.Center().X(); const double labelCenter[2] = {-.5 * LABEL_WIDTH - LABEL_DX, LABEL_DX + .5 * LABEL_WIDTH}; const double fromX[2] = {-LABEL_DX + LABEL_PAD, LABEL_DX - LABEL_PAD}; static const double LINE_HEIGHT = 20.; static const double TEXT_OFF = .5 * (LINE_HEIGHT - font.Height()); static const Point LINE_SIZE(LABEL_WIDTH, LINE_HEIGHT); Point topFrom; Point topTo; Color topColor; bool hasTop = false; auto layout = Layout(static_cast<int>(LABEL_WIDTH), Truncate::BACK); for(const Hardpoint &hardpoint : ship.Weapons()) { string name = "[empty]"; if(hardpoint.GetOutfit()) name = hardpoint.GetOutfit()->DisplayName(); bool isRight = (hardpoint.GetPoint().X() >= 0.); bool isTurret = hardpoint.IsTurret(); double &y = nextY[isRight][isTurret]; double x = centerX + (isRight ? LABEL_DX : -LABEL_DX - LABEL_WIDTH); bool isHover = (index == hoverIndex); layout.align = isRight ? Alignment::LEFT : Alignment::RIGHT; font.Draw({name, layout}, Point(x, y + TEXT_OFF), isHover ? bright : dim); Point zoneCenter(labelCenter[isRight], y + .5 * LINE_HEIGHT); zones.emplace_back(zoneCenter, LINE_SIZE, index); // Determine what color to use for the line. Color color; if(isTurret) color = *GameData::Colors().Get(isHover ? "player info hardpoint turret hover" : "player info hardpoint turret"); else color = *GameData::Colors().Get(isHover ? "player info hardpoint gun hover" : "player info hardpoint gun"); // Draw the line. Point from(fromX[isRight], zoneCenter.Y()); Point to = bounds.Center() + (2. * scale) * hardpoint.GetPoint(); DrawLine(from, to, color); if(isHover) { topFrom = from; topTo = to; topColor = color; hasTop = true; } y += LINE_HEIGHT; ++index; } // Make sure the line for whatever hardpoint we're hovering is always on top. if(hasTop) DrawLine(topFrom, topTo, topColor); // Re-positioning weapons. if(draggingIndex >= 0) { const Outfit *outfit = ship.Weapons()[draggingIndex].GetOutfit(); string name = outfit ? outfit->DisplayName() : "[empty]"; Point pos(hoverPoint.X() - .5 * font.Width(name), hoverPoint.Y()); font.Draw(name, pos + Point(1., 1.), Color(0., 1.)); font.Draw(name, pos, bright); } } void ShipInfoPanel::DrawCargo(const Rectangle &bounds) { Color dim = *GameData::Colors().Get("medium"); Color bright = *GameData::Colors().Get("bright"); Color backColor = *GameData::Colors().Get("faint"); const Ship &ship = **shipIt; // Cargo list. const CargoHold &cargo = (player.Cargo().Used() ? player.Cargo() : ship.Cargo()); Table table; table.AddColumn(0, {COLUMN_WIDTH, Alignment::LEFT}); table.AddColumn(COLUMN_WIDTH, {COLUMN_WIDTH, Alignment::RIGHT}); table.SetUnderline(-5, COLUMN_WIDTH + 5); table.DrawAt(bounds.TopLeft() + Point(10., 8.)); double endY = bounds.Bottom() - 30. * (cargo.Passengers() != 0); bool hasSpace = (table.GetRowBounds().Bottom() < endY); if((cargo.CommoditiesSize() || cargo.HasOutfits() || cargo.MissionCargoSize()) && hasSpace) { table.Draw("Cargo", bright); table.Advance(); hasSpace = (table.GetRowBounds().Bottom() < endY); } if(cargo.CommoditiesSize() && hasSpace) { for(const auto &it : cargo.Commodities()) { if(!it.second) continue; commodityZones.emplace_back(table.GetCenterPoint(), table.GetRowSize(), it.first); if(it.first == selectedCommodity) table.DrawHighlight(backColor); table.Draw(it.first, dim); table.Draw(to_string(it.second), bright); // Truncate the list if there is not enough space. if(table.GetRowBounds().Bottom() >= endY) { hasSpace = false; break; } } table.DrawGap(10.); } if(cargo.HasOutfits() && hasSpace) { for(const auto &it : cargo.Outfits()) { if(!it.second) continue; plunderZones.emplace_back(table.GetCenterPoint(), table.GetRowSize(), it.first); if(it.first == selectedPlunder) table.DrawHighlight(backColor); // For outfits, show how many of them you have and their total mass. bool isSingular = (it.second == 1 || it.first->Get("installable") < 0.); string name = (isSingular ? it.first->DisplayName() : it.first->PluralName()); if(!isSingular) name += " (" + to_string(it.second) + "x)"; table.Draw(name, dim); double mass = it.first->Mass() * it.second; table.Draw(Format::Number(mass), bright); // Truncate the list if there is not enough space. if(table.GetRowBounds().Bottom() >= endY) { hasSpace = false; break; } } table.DrawGap(10.); } if(cargo.HasMissionCargo() && hasSpace) { for(const auto &it : cargo.MissionCargo()) { // Capitalize the name of the cargo. table.Draw(Format::Capitalize(it.first->Cargo()), dim); table.Draw(to_string(it.second), bright); // Truncate the list if there is not enough space. if(table.GetRowBounds().Bottom() >= endY) break; } table.DrawGap(10.); } if(cargo.Passengers() && endY >= bounds.Top()) { table.DrawAt(Point(bounds.Left(), endY) + Point(10., 8.)); table.Draw("passengers:", dim); table.Draw(to_string(cargo.Passengers()), bright); } } void ShipInfoPanel::DrawLine(const Point &from, const Point &to, const Color &color) const { Color black(0.f, 1.f); Point mid(to.X(), from.Y()); LineShader::Draw(from, mid, 3.5f, black); LineShader::Draw(mid, to, 3.5f, black); LineShader::Draw(from, mid, 1.5f, color); LineShader::Draw(mid, to, 1.5f, color); } bool ShipInfoPanel::Hover(const Point &point) { if(shipIt == panelState.Ships().end()) return true; hoverPoint = point; hoverIndex = -1; const vector<Hardpoint> &weapons = (**shipIt).Weapons(); bool dragIsTurret = (draggingIndex >= 0 && weapons[draggingIndex].IsTurret()); for(const auto &zone : zones) { bool isTurret = weapons[zone.Value()].IsTurret(); if(zone.Contains(hoverPoint) && (draggingIndex == -1 || isTurret == dragIsTurret)) hoverIndex = zone.Value(); } return true; } void ShipInfoPanel::Rename(const string &name) { if(shipIt != panelState.Ships().end() && !name.empty()) { player.RenameShip(shipIt->get(), name); UpdateInfo(); } } bool ShipInfoPanel::CanDump() const { if(panelState.CanEdit() || shipIt == panelState.Ships().end()) return false; CargoHold &cargo = (*shipIt)->Cargo(); return (selectedPlunder && cargo.Get(selectedPlunder) > 0) || cargo.CommoditiesSize() || cargo.OutfitsSize(); } void ShipInfoPanel::Dump() { if(!CanDump()) return; CargoHold &cargo = (*shipIt)->Cargo(); int commodities = (*shipIt)->Cargo().CommoditiesSize(); int amount = cargo.Get(selectedCommodity); int plunderAmount = cargo.Get(selectedPlunder); int64_t loss = 0; if(amount) { int64_t basis = player.GetBasis(selectedCommodity, amount); loss += basis; player.AdjustBasis(selectedCommodity, -basis); (*shipIt)->Jettison(selectedCommodity, amount); } else if(plunderAmount > 0) { loss += plunderAmount * selectedPlunder->Cost(); (*shipIt)->Jettison(selectedPlunder, plunderAmount); } else if(commodities) { for(const auto &it : cargo.Commodities()) { int64_t basis = player.GetBasis(it.first, it.second); loss += basis; player.AdjustBasis(it.first, -basis); (*shipIt)->Jettison(it.first, it.second); } } else { for(const auto &it : cargo.Outfits()) { loss += it.first->Cost() * max(0, it.second); (*shipIt)->Jettison(it.first, it.second); } } selectedCommodity.clear(); selectedPlunder = nullptr; info.Update(**shipIt, player); if(loss) Messages::Add("You jettisoned " + Format::CreditString(loss) + " worth of cargo." , Messages::Importance::High); } void ShipInfoPanel::DumpPlunder(int count) { int64_t loss = 0; count = min(count, (*shipIt)->Cargo().Get(selectedPlunder)); if(count > 0) { loss += count * selectedPlunder->Cost(); (*shipIt)->Jettison(selectedPlunder, count); info.Update(**shipIt, player); if(loss) Messages::Add("You jettisoned " + Format::CreditString(loss) + " worth of cargo." , Messages::Importance::High); } } void ShipInfoPanel::DumpCommodities(int count) { int64_t loss = 0; count = min(count, (*shipIt)->Cargo().Get(selectedCommodity)); if(count > 0) { int64_t basis = player.GetBasis(selectedCommodity, count); loss += basis; player.AdjustBasis(selectedCommodity, -basis); (*shipIt)->Jettison(selectedCommodity, count); info.Update(**shipIt, player); if(loss) Messages::Add("You jettisoned " + Format::CreditString(loss) + " worth of cargo." , Messages::Importance::High); } } void ShipInfoPanel::Disown() { // Make sure a ship really is selected. if(shipIt == panelState.Ships().end() || shipIt->get() == player.Flagship()) return; const auto ship = shipIt; if(shipIt != panelState.Ships().begin()) --shipIt; player.DisownShip(ship->get()); panelState.Disown(ship); UpdateInfo(); }
0
endless-sky-master
endless-sky-master/source/MissionPanel.cpp
/* MissionPanel.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "MissionPanel.h" #include "text/alignment.hpp" #include "Command.h" #include "CoreStartData.h" #include "Dialog.h" #include "text/DisplayText.h" #include "FillShader.h" #include "text/Font.h" #include "text/FontSet.h" #include "text/Format.h" #include "GameData.h" #include "Information.h" #include "Interface.h" #include "LineShader.h" #include "Mission.h" #include "Planet.h" #include "PlayerInfo.h" #include "PointerShader.h" #include "Preferences.h" #include "RingShader.h" #include "Screen.h" #include "Ship.h" #include "Sprite.h" #include "SpriteSet.h" #include "SpriteShader.h" #include "System.h" #include "text/truncate.hpp" #include "UI.h" #include <algorithm> #include <cmath> #include <sstream> using namespace std; namespace { constexpr int SIDE_WIDTH = 280; // Hovering over sort buttons for this many frames activates the tooltip. const int HOVER_TIME = 60; // Check if the mission involves the given system, bool Involves(const Mission &mission, const System *system) { if(!system) return false; if(mission.Destination()->IsInSystem(system)) return true; for(const System *waypoint : mission.Waypoints()) if(waypoint == system) return true; for(const Planet *stopover : mission.Stopovers()) if(stopover->IsInSystem(system)) return true; return false; } size_t MaxDisplayedMissions(bool onRight) { return static_cast<unsigned>(max(0, static_cast<int>(floor((Screen::Height() - (onRight ? 160. : 190.)) / 20.)))); } // Compute the required scroll amount for the given list of jobs/missions. void DoScroll(const list<Mission> &missionList, const list<Mission>::const_iterator &it, double &sideScroll, bool checkVisibility) { // We don't need to scroll at all if the selection must be within the viewport. The current // scroll could be non-zero if missions were added/aborted, so return the delta that will reset it. const auto maxViewable = MaxDisplayedMissions(checkVisibility); const auto missionCount = missionList.size(); if(missionCount < maxViewable) sideScroll = 0; else { const auto countBefore = static_cast<size_t>(checkVisibility ? count_if(missionList.begin(), it, [](const Mission &m) { return m.IsVisible(); }) : distance(missionList.begin(), it)); const auto maximumScroll = (missionCount - maxViewable) * 20.; const auto pageScroll = maxViewable * 20.; const auto desiredScroll = countBefore * 20.; const auto bottomOfPage = sideScroll + pageScroll; if(desiredScroll < sideScroll) { // Scroll upwards. sideScroll = desiredScroll; } else if(desiredScroll > bottomOfPage) { // Scroll downwards (but not so far that the list's bottom sprite comes upwards further than needed). sideScroll = min(maximumScroll, sideScroll + (desiredScroll - bottomOfPage)); } } } } // Open the missions panel directly. MissionPanel::MissionPanel(PlayerInfo &player) : MapPanel(player), available(player.AvailableJobs()), accepted(player.Missions()), availableIt(player.AvailableJobs().begin()), acceptedIt(player.AvailableJobs().empty() ? accepted.begin() : accepted.end()) { // Re-do job sorting since something could have changed player.SortAvailable(); while(acceptedIt != accepted.end() && !acceptedIt->IsVisible()) ++acceptedIt; wrap.SetWrapWidth(380); wrap.SetFont(FontSet::Get(14)); wrap.SetAlignment(Alignment::JUSTIFIED); // Select the first available or accepted mission in the currently selected // system, or along the travel plan. if(!FindMissionForSystem(selectedSystem) && player.HasTravelPlan()) { const auto &tp = player.TravelPlan(); for(auto it = tp.crbegin(); it != tp.crend(); ++it) if(FindMissionForSystem(*it)) break; } SetSelectedScrollAndCenter(true); } // Switch to the missions panel from another map panel. MissionPanel::MissionPanel(const MapPanel &panel) : MapPanel(panel), available(player.AvailableJobs()), accepted(player.Missions()), availableIt(player.AvailableJobs().begin()), acceptedIt(player.AvailableJobs().empty() ? accepted.begin() : accepted.end()), availableScroll(0), acceptedScroll(0), dragSide(0) { // Re-do job sorting since something could have changed player.SortAvailable(); // In this view, always color systems based on player reputation. commodity = SHOW_REPUTATION; while(acceptedIt != accepted.end() && !acceptedIt->IsVisible()) ++acceptedIt; wrap.SetWrapWidth(380); wrap.SetFont(FontSet::Get(14)); wrap.SetAlignment(Alignment::JUSTIFIED); // Select the first available or accepted mission in the currently selected // system, or along the travel plan. if(!FindMissionForSystem(selectedSystem) && !(player.GetSystem() != selectedSystem && FindMissionForSystem(player.GetSystem())) && player.HasTravelPlan()) { const auto &tp = player.TravelPlan(); for(auto it = tp.crbegin(); it != tp.crend(); ++it) if(FindMissionForSystem(*it)) break; } SetSelectedScrollAndCenter(); } void MissionPanel::Step() { MapPanel::Step(); if(GetUI()->IsTop(this) && player.GetPlanet() && player.GetDate() >= player.StartData().GetDate() + 12) DoHelp("map advanced"); DoHelp("jobs"); } void MissionPanel::Draw() { MapPanel::Draw(); // Update the tooltip timer [0-60]. hoverSortCount += hoverSort >= 0 ? (hoverSortCount < HOVER_TIME) : (hoverSortCount ? -1 : 0); const Set<Color> &colors = GameData::Colors(); const Color &routeColor = *colors.Get("mission route"); const Ship *flagship = player.Flagship(); const double jumpRange = flagship ? flagship->JumpNavigation().JumpRange() : 0.; const System *previous = nullptr; const System *next = selectedSystem; for(; distance.Days(next) > 0; next = previous) { previous = distance.Route(next); bool isJump, isWormhole, isMappable; if(!GetTravelInfo(previous, next, jumpRange, isJump, isWormhole, isMappable, nullptr)) break; if(isWormhole && !isMappable) continue; Point from = Zoom() * (previous->Position() + center); Point to = Zoom() * (next->Position() + center); const Point unit = (to - from).Unit(); from += LINK_OFFSET * unit; to -= LINK_OFFSET * unit; // Non-hyperspace jumps are drawn with a dashed line. if(isJump) LineShader::DrawDashed(from, to, unit, 5.f, routeColor, 11., 4.); else LineShader::Draw(from, to, 5.f, routeColor); } const Color &availableColor = *colors.Get("available back"); const Color &unavailableColor = *colors.Get("unavailable back"); const Color &currentColor = *colors.Get("active back"); const Color &blockedColor = *colors.Get("blocked back"); if(availableIt != available.end() && availableIt->Destination()) DrawMissionSystem(*availableIt, CanAccept() ? availableColor : unavailableColor); if(acceptedIt != accepted.end() && acceptedIt->Destination()) DrawMissionSystem(*acceptedIt, IsSatisfied(*acceptedIt) ? currentColor : blockedColor); Point pos; if(player.GetPlanet()) { pos = DrawPanel( Screen::TopLeft() + Point(0., -availableScroll), "Missions available here:", available.size(), true); DrawList(available, pos, availableIt, true); } pos = DrawPanel( Screen::TopRight() + Point(-SIDE_WIDTH, -acceptedScroll), "Your current missions:", AcceptedVisible()); DrawList(accepted, pos, acceptedIt); // Now that the mission lists and map elements are drawn, draw the top-most UI elements. DrawKey(); DrawMissionInfo(); DrawTooltips(); FinishDrawing("is missions"); } // Only override the ones you need; the default action is to return false. bool MissionPanel::KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) { if(command.Has(Command::HELP)) { DoHelp("jobs", true); DoHelp("map advanced", true); } else if(key == 'a' && CanAccept()) { Accept((mod & KMOD_CTRL)); return true; } else if(key == 'A' || (key == 'a' && (mod & KMOD_SHIFT))) { if(acceptedIt != accepted.end() && acceptedIt->IsVisible()) GetUI()->Push(new Dialog(this, &MissionPanel::AbortMission, "Abort mission \"" + acceptedIt->Name() + "\"?")); return true; } else if(key == SDLK_LEFT && availableIt == available.end()) { // Switch to the first mission in the "available missions" list. acceptedIt = accepted.end(); availableIt = available.begin(); } else if(key == SDLK_RIGHT && acceptedIt == accepted.end() && AcceptedVisible()) { // Switch to the first mission in the "accepted missions" list. availableIt = available.end(); acceptedIt = accepted.begin(); while(acceptedIt != accepted.end() && !acceptedIt->IsVisible()) ++acceptedIt; } else if(key == SDLK_UP) { SelectAnyMission(); // Select the previous mission, which may be at the end of the list. if(availableIt != available.end()) { // All available missions are, by definition, visible. if(availableIt == available.begin()) availableIt = available.end(); --availableIt; } else if(acceptedIt != accepted.end()) { // Skip over any invisible, accepted missions. do { if(acceptedIt == accepted.begin()) acceptedIt = accepted.end(); --acceptedIt; } while(!acceptedIt->IsVisible()); } } else if(key == SDLK_DOWN) { if(SelectAnyMission()) { // A mission was just auto-selected. Nothing else to do here. } else if(availableIt != available.end()) { ++availableIt; if(availableIt == available.end()) availableIt = available.begin(); } else if(acceptedIt != accepted.end()) { do { ++acceptedIt; if(acceptedIt == accepted.end()) acceptedIt = accepted.begin(); } while(!acceptedIt->IsVisible()); } } else return MapPanel::KeyDown(key, mod, command, isNewPress); // To reach here, we changed the selected mission. Scroll the active // mission list, update the selected system, and pan the map. SetSelectedScrollAndCenter(); return true; } bool MissionPanel::Click(int x, int y, int clicks) { dragSide = 0; if(x > Screen::Right() - 80 && y > Screen::Bottom() - 50) return DoKey('p'); if(x < Screen::Left() + SIDE_WIDTH) { // Panel header if(y + static_cast<int>(availableScroll) < Screen::Top() + 30) { dragSide = -1; if(y + static_cast<int>(availableScroll) < Screen::Top() + 10) { // empty space return false; } // Sorter buttons else if(hoverSort >= 0) { if(hoverSort == 0) player.ToggleSortSeparateDeadline(); else if(hoverSort == 1) player.ToggleSortSeparatePossible(); else if(hoverSort == 2) { player.NextAvailableSortType(); tooltip.clear(); } else if(hoverSort == 3) player.ToggleSortAscending(); return true; } return false; } // Available missions unsigned index = max(0, (y + static_cast<int>(availableScroll) - 36 - Screen::Top()) / 20); if(index < available.size()) { const auto lastAvailableIt = availableIt; availableIt = available.begin(); while(index--) ++availableIt; acceptedIt = accepted.end(); dragSide = -1; if(availableIt == lastAvailableIt) { CycleInvolvedSystems(*availableIt); return true; } SetSelectedScrollAndCenter(); return true; } } else if(x >= Screen::Right() - SIDE_WIDTH) { // Accepted missions int index = max(0, (y + static_cast<int>(acceptedScroll) - 36 - Screen::Top()) / 20); if(index < AcceptedVisible()) { const auto lastAcceptedIt = acceptedIt; acceptedIt = accepted.begin(); while(index || !acceptedIt->IsVisible()) { index -= acceptedIt->IsVisible(); ++acceptedIt; } availableIt = available.end(); dragSide = 1; if(lastAcceptedIt == acceptedIt) { CycleInvolvedSystems(*acceptedIt); return true; } SetSelectedScrollAndCenter(); return true; } } // Figure out if a system was clicked on. Point click = Point(x, y) / Zoom() - center; const System *system = nullptr; for(const auto &it : GameData::Systems()) if(it.second.IsValid() && click.Distance(it.second.Position()) < 10. && (player.HasSeen(it.second) || &it.second == specialSystem)) { system = &it.second; break; } if(system) { Select(system); int options = available.size() + accepted.size(); // If you just aborted your last mission, it is possible that neither // iterator is valid. In that case, start over from the beginning. if(availableIt == available.end() && acceptedIt == accepted.end()) { if(!available.empty()) availableIt = available.begin(); else acceptedIt = accepted.begin(); } // When clicking a new system, select the first available mission // (instead of continuing from wherever the iterator happens to be) if((availableIt != available.end() && !Involves(*availableIt, system)) || (acceptedIt != accepted.end() && !Involves(*acceptedIt, system))) { auto firstExistingIt = find_if(available.begin(), available.end(), [&system](const Mission &m) { return Involves(m, system); }); if(firstExistingIt != available.end()) { availableIt = firstExistingIt; acceptedIt = accepted.end(); } else { firstExistingIt = find_if(accepted.begin(), accepted.end(), [&system](const Mission &m) { return m.IsVisible() && Involves(m, system); }); if(firstExistingIt != accepted.end()) { availableIt = available.end(); acceptedIt = firstExistingIt; } } } else while(options--) { if(availableIt != available.end()) { ++availableIt; if(availableIt == available.end()) { if(!accepted.empty()) acceptedIt = accepted.begin(); else availableIt = available.begin(); } } else if(acceptedIt != accepted.end()) { ++acceptedIt; if(acceptedIt == accepted.end()) { if(!available.empty()) availableIt = available.begin(); else acceptedIt = accepted.begin(); } } if(acceptedIt != accepted.end() && !acceptedIt->IsVisible()) continue; if(availableIt != available.end() && Involves(*availableIt, system)) break; if(acceptedIt != accepted.end() && Involves(*acceptedIt, system)) break; } // Make sure invisible missions are never selected, even if there were // no other missions in this system. if(acceptedIt != accepted.end() && !acceptedIt->IsVisible()) acceptedIt = accepted.end(); // Scroll the relevant panel so that the mission highlighted is visible. if(availableIt != available.end()) DoScroll(available, availableIt, availableScroll, false); else if(acceptedIt != accepted.end()) DoScroll(accepted, acceptedIt, acceptedScroll, true); } return true; } bool MissionPanel::Drag(double dx, double dy) { if(dragSide < 0) { availableScroll = max(0., min(available.size() * 20. + 190. - Screen::Height(), availableScroll - dy)); } else if(dragSide > 0) { acceptedScroll = max(0., min(accepted.size() * 20. + 160. - Screen::Height(), acceptedScroll - dy)); } else MapPanel::Drag(dx, dy); return true; } // Check to see if the mouse is over either of the mission lists. bool MissionPanel::Hover(int x, int y) { dragSide = 0; int oldSort = hoverSort; hoverSort = -1; unsigned index = max(0, (y + static_cast<int>(availableScroll) - 36 - Screen::Top()) / 20); if(x < Screen::Left() + SIDE_WIDTH) { if(index < available.size()) { dragSide = -1; // Hovering over sort buttons if(y + static_cast<int>(availableScroll) < Screen::Top() + 30 && y >= Screen::Top() + 10 && x >= Screen::Left() + SIDE_WIDTH - 110) { hoverSort = (x - Screen::Left() - SIDE_WIDTH + 110) / 30; if(hoverSort > 3) hoverSort = -1; } } } else if(x >= Screen::Right() - SIDE_WIDTH) { if(static_cast<int>(index) < AcceptedVisible()) dragSide = 1; } if(oldSort != hoverSort) tooltip.clear(); return dragSide || MapPanel::Hover(x, y); } bool MissionPanel::Scroll(double dx, double dy) { if(dragSide) return Drag(0., dy * Preferences::ScrollSpeed()); return MapPanel::Scroll(dx, dy); } void MissionPanel::SetSelectedScrollAndCenter(bool immediate) { // Auto select the destination system for the current mission. if(availableIt != available.end()) { selectedSystem = availableIt->Destination()->GetSystem(); DoScroll(available, availableIt, availableScroll, false); } else if(acceptedIt != accepted.end()) { selectedSystem = acceptedIt->Destination()->GetSystem(); DoScroll(accepted, acceptedIt, acceptedScroll, true); } // Center on the selected system. CenterOnSystem(selectedSystem, immediate); cycleInvolvedIndex = 0; } void MissionPanel::DrawKey() const { const Sprite *back = SpriteSet::Get("ui/mission key"); SpriteShader::Draw(back, Screen::BottomLeft() + .5 * Point(back->Width(), -back->Height())); const Font &font = FontSet::Get(14); Point angle = Point(1., 1.).Unit(); const int ROWS = 5; Point pos(Screen::Left() + 10., Screen::Bottom() - ROWS * 20. + 5.); Point pointerOff(5., 5.); Point textOff(8., -.5 * font.Height()); const Set<Color> &colors = GameData::Colors(); const Color &bright = *colors.Get("bright"); const Color &dim = *colors.Get("dim"); const Color COLOR[ROWS] = { *colors.Get("available job"), *colors.Get("unavailable job"), *colors.Get("active mission"), *colors.Get("blocked mission"), *colors.Get("waypoint") }; static const string LABEL[ROWS] = { "Available job; can accept", "Too little space to accept", "Active job; go here to complete", "Has unfinished requirements", "Waypoint you must visit" }; int selected = -1; if(availableIt != available.end()) selected = 0 + !CanAccept(); if(acceptedIt != accepted.end() && acceptedIt->Destination()) selected = 2 + !IsSatisfied(*acceptedIt); for(int i = 0; i < ROWS; ++i) { PointerShader::Draw(pos + pointerOff, angle, 10.f, 18.f, 0.f, COLOR[i]); font.Draw(LABEL[i], pos + textOff, i == selected ? bright : dim); pos.Y() += 20.; } } // Highlight the systems associated with the given mission (i.e. destination and // waypoints) by drawing colored rings around them. void MissionPanel::DrawMissionSystem(const Mission &mission, const Color &color) const { auto toVisit = set<const System *>{mission.Waypoints()}; for(const Planet *planet : mission.Stopovers()) toVisit.insert(planet->GetSystem()); auto hasVisited = set<const System *>{mission.VisitedWaypoints()}; for(const Planet *planet : mission.VisitedStopovers()) hasVisited.insert(planet->GetSystem()); const Color &waypoint = *GameData::Colors().Get("waypoint back"); const Color &visited = *GameData::Colors().Get("faint"); double zoom = Zoom(); auto drawRing = [&](const System *system, const Color &drawColor) { RingShader::Add(zoom * (system->Position() + center), 22.f, 20.5f, drawColor); }; RingShader::Bind(); { // Draw a colored ring around the destination system. drawRing(mission.Destination()->GetSystem(), color); // Draw bright rings around systems that still need to be visited. for(const System *system : toVisit) drawRing(system, waypoint); // Draw faint rings around systems already visited for this mission. for(const System *system : hasVisited) drawRing(system, visited); } RingShader::Unbind(); } // Draw the background for the lists of available and accepted missions (based on pos). Point MissionPanel::DrawPanel(Point pos, const string &label, int entries, bool sorter) const { const Color &back = *GameData::Colors().Get("map side panel background"); const Color &text = *GameData::Colors().Get("medium"); const Color separatorLine = text.Opaque(); const Color &title = *GameData::Colors().Get("bright"); const Color &highlight = *GameData::Colors().Get("dim"); // Draw the panel. Point size(SIDE_WIDTH, 20 * entries + 40); FillShader::Fill(pos + .5 * size, size, back); // Edges: const Sprite *bottom = SpriteSet::Get("ui/bottom edge"); Point edgePos = pos + Point(.5 * size.X(), size.Y()); Point bottomOff(0., .5 * bottom->Height()); SpriteShader::Draw(bottom, edgePos + bottomOff); const Sprite *left = SpriteSet::Get("ui/left edge"); const Sprite *right = SpriteSet::Get("ui/right edge"); double dy = .5 * left->Height(); Point leftOff(-.5 * (size.X() + left->Width()), 0.); Point rightOff(.5 * (size.X() + right->Width()), 0.); while(dy && edgePos.Y() > Screen::Top()) { edgePos.Y() -= dy; SpriteShader::Draw(left, edgePos + leftOff); SpriteShader::Draw(right, edgePos + rightOff); edgePos.Y() -= dy; } const Font &font = FontSet::Get(14); pos += Point(10., 10. + (20. - font.Height()) * .5); // Panel sorting const Sprite *rush[2] = { SpriteSet::Get("ui/sort rush include"), SpriteSet::Get("ui/sort rush separate") }; const Sprite *acceptable[2] = { SpriteSet::Get("ui/sort unacceptable include"), SpriteSet::Get("ui/sort unacceptable separate") }; const Sprite *sortIcon[4] = { SpriteSet::Get("ui/sort abc"), SpriteSet::Get("ui/sort pay"), SpriteSet::Get("ui/sort speed"), SpriteSet::Get("ui/sort convenient") }; const Sprite *arrow[2] = { SpriteSet::Get("ui/sort descending"), SpriteSet::Get("ui/sort ascending") }; // Draw Sorting Columns if(entries && sorter) { SpriteShader::Draw(arrow[player.ShouldSortAscending()], pos + Point(SIDE_WIDTH - 15., 7.5)); SpriteShader::Draw(sortIcon[player.GetAvailableSortType()], pos + Point(SIDE_WIDTH - 45., 7.5)); SpriteShader::Draw(acceptable[player.ShouldSortSeparatePossible()], pos + Point(SIDE_WIDTH - 75., 7.5)); SpriteShader::Draw(rush[player.ShouldSortSeparateDeadline()], pos + Point(SIDE_WIDTH - 105., 7.5)); if(hoverSort >= 0) FillShader::Fill(pos + Point(SIDE_WIDTH - 105. + 30 * hoverSort, 7.5), Point(22., 16.), highlight); } // Panel title font.Draw(label, pos, title); FillShader::Fill( pos + Point(.5 * size.X() - 5., 15.), Point(size.X() - 10., 1.), separatorLine); pos.Y() += 5.; return pos; } Point MissionPanel::DrawList(const list<Mission> &list, Point pos, const std::list<Mission>::const_iterator &selectIt, bool separateDeadlineOrPossible) const { const Font &font = FontSet::Get(14); const Color &highlight = *GameData::Colors().Get("faint"); const Color &unselected = *GameData::Colors().Get("medium"); const Color &selected = *GameData::Colors().Get("bright"); const Color &dim = *GameData::Colors().Get("dim"); const Sprite *fast = SpriteSet::Get("ui/fast forward"); bool separated = false; for(auto it = list.begin(); it != list.end(); ++it) { if(!it->IsVisible()) continue; pos.Y() += 20.; if(separateDeadlineOrPossible && !separated && ((player.ShouldSortSeparateDeadline() && it->Deadline()) || (player.ShouldSortSeparatePossible() && !it->CanAccept(player)))) { pos.Y() += 8.; separated = true; } bool isSelected = it == selectIt; if(isSelected) FillShader::Fill( pos + Point(.5 * SIDE_WIDTH - 5., 8.), Point(SIDE_WIDTH - 10., 20.), highlight); if(it->Deadline()) SpriteShader::Draw(fast, pos + Point(-4., 8.)); bool canAccept = (&list == &available ? it->CanAccept(player) : IsSatisfied(*it)); font.Draw({it->Name(), {SIDE_WIDTH - 11, Truncate::BACK}}, pos, (!canAccept ? dim : isSelected ? selected : unselected)); } return pos; } void MissionPanel::DrawMissionInfo() { Information info; // The "accept / abort" button text and activation depends on what mission, // if any, is selected, and whether missions are available. if(CanAccept()) info.SetCondition("can accept"); else if(acceptedIt != accepted.end()) info.SetCondition("can abort"); info.SetString("cargo free", to_string(player.Cargo().Free()) + " tons"); info.SetString("bunks free", to_string(player.Cargo().BunksFree()) + " bunks"); info.SetString("today", player.GetDate().ToString()); GameData::Interfaces().Get("mission")->Draw(info, this); // If a mission is selected, draw its descriptive text. if(availableIt != available.end()) wrap.Wrap(availableIt->Description()); else if(acceptedIt != accepted.end()) wrap.Wrap(acceptedIt->Description()); else return; wrap.Draw(Point(-190., Screen::Bottom() - 213.), *GameData::Colors().Get("bright")); } void MissionPanel::DrawTooltips() { if(hoverSort < 0 || hoverSortCount < HOVER_TIME) return; // Create the tooltip text. if(tooltip.empty()) { if(hoverSort == 0) tooltip = "Filter out missions with a deadline"; else if(hoverSort == 1) tooltip = "Filter out missions that you can't accept"; else if(hoverSort == 2) { switch(player.GetAvailableSortType()) { case 0: tooltip = "Sort alphabetically"; break; case 1: tooltip = "Sort by payment"; break; case 2: tooltip = "Sort by distance"; break; case 3: tooltip = "Sort by convenience: " "Prioritize missions going to a planet or system that is already a destination of one of your missions"; break; } } else if(hoverSort == 3) tooltip = "Sort direction"; hoverText.Wrap(tooltip); } if(!tooltip.empty()) { // Add 10px margin to all sides of the text. Point size(hoverText.WrapWidth(), hoverText.Height() - hoverText.ParagraphBreak()); size += Point(20., 20.); Point topLeft = Point(Screen::Left() + SIDE_WIDTH - 120. + 30 * hoverSort, Screen::Top() + 30.); // Draw the background fill and the tooltip text. FillShader::Fill(topLeft + .5 * size, size, *GameData::Colors().Get("tooltip background")); hoverText.Draw(topLeft + Point(10., 10.), *GameData::Colors().Get("medium")); } } bool MissionPanel::CanAccept() const { if(availableIt == available.end()) return false; return availableIt->CanAccept(player); } void MissionPanel::Accept(bool force) { const Mission &toAccept = *availableIt; int cargoToSell = 0; if(toAccept.CargoSize()) cargoToSell = toAccept.CargoSize() - player.Cargo().Free(); int crewToFire = 0; if(toAccept.Passengers()) crewToFire = toAccept.Passengers() - player.Cargo().BunksFree(); if(cargoToSell > 0 || crewToFire > 0) { if(force) { MakeSpaceAndAccept(); return; } ostringstream out; if(cargoToSell > 0 && crewToFire > 0) out << "You must fire " << crewToFire << " of your flagship's non-essential crew members and sell " << Format::CargoString(cargoToSell, "ordinary commodities") << " to make room for this mission. Continue?"; else if(crewToFire > 0) out << "You must fire " << crewToFire << " of your flagship's non-essential crew members to make room for this mission. Continue?"; else out << "You must sell " << Format::CargoString(cargoToSell, "ordinary commodities") << " to make room for this mission. Continue?"; GetUI()->Push(new Dialog(this, &MissionPanel::MakeSpaceAndAccept, out.str())); return; } ++availableIt; player.AcceptJob(toAccept, GetUI()); cycleInvolvedIndex = 0; if(available.empty()) return; if(availableIt == available.end()) --availableIt; // Check if any other jobs are available with the same destination. Prefer // jobs that also have the same destination planet. if(toAccept.Destination()) { const Planet *planet = toAccept.Destination(); const System *system = planet->GetSystem(); bool stillLooking = true; // Updates availableIt if matching system found, returns true if planet also matches. auto SelectNext = [this, planet, system, &stillLooking](list<Mission>::const_iterator &it) -> bool { if(it->Destination() && it->Destination()->IsInSystem(system)) { if(it->Destination() == planet) { availableIt = it; return true; } else if(stillLooking) { stillLooking = false; availableIt = it; } } return false; }; const list<Mission>::const_iterator startHere = availableIt; for(auto it = startHere; it != available.end(); ++it) if(SelectNext(it)) return; for(auto it = startHere; it != available.begin(); ) if(SelectNext(--it)) return; } } void MissionPanel::MakeSpaceAndAccept() { const Mission &toAccept = *availableIt; int cargoToSell = toAccept.CargoSize() - player.Cargo().Free(); int crewToFire = toAccept.Passengers() - player.Cargo().BunksFree(); if(crewToFire > 0) player.Flagship()->AddCrew(-crewToFire); for(const auto &it : player.Cargo().Commodities()) { if(cargoToSell <= 0) break; int toSell = min(cargoToSell, it.second); int64_t price = player.GetSystem()->Trade(it.first); int64_t basis = player.GetBasis(it.first, toSell); player.AdjustBasis(it.first, -basis); player.Cargo().Remove(it.first, toSell); player.Accounts().AddCredits(toSell * price); cargoToSell -= toSell; } player.UpdateCargoCapacities(); Accept(); } void MissionPanel::AbortMission() { if(acceptedIt != accepted.end()) { const Mission &toAbort = *acceptedIt; ++acceptedIt; player.RemoveMission(Mission::ABORT, toAbort, GetUI()); if(acceptedIt == accepted.end() && !accepted.empty()) --acceptedIt; if(acceptedIt != accepted.end() && !acceptedIt->IsVisible()) acceptedIt = accepted.end(); } } int MissionPanel::AcceptedVisible() const { int count = 0; for(const Mission &mission : accepted) count += mission.IsVisible(); return count; } bool MissionPanel::FindMissionForSystem(const System *system) { if(!system) return false; acceptedIt = accepted.end(); for(availableIt = available.begin(); availableIt != available.end(); ++availableIt) if(availableIt->Destination()->IsInSystem(system)) return true; for(acceptedIt = accepted.begin(); acceptedIt != accepted.end(); ++acceptedIt) if(acceptedIt->IsVisible() && acceptedIt->Destination()->IsInSystem(system)) return true; return false; } bool MissionPanel::SelectAnyMission() { if(availableIt == available.end() && acceptedIt == accepted.end()) { // No previous selected mission, so select the first job/mission for any system. if(!available.empty()) availableIt = available.begin(); else { acceptedIt = accepted.begin(); while(acceptedIt != accepted.end() && !acceptedIt->IsVisible()) ++acceptedIt; } return availableIt != available.end() || acceptedIt != accepted.end(); } return false; } void MissionPanel::CycleInvolvedSystems(const Mission &mission) { cycleInvolvedIndex++; int index = 0; for(const System *waypoint : mission.Waypoints()) if(++index == cycleInvolvedIndex) { CenterOnSystem(waypoint); return; } for(const Planet *stopover : mission.Stopovers()) if(++index == cycleInvolvedIndex) { CenterOnSystem(stopover->GetSystem()); return; } cycleInvolvedIndex = 0; CenterOnSystem(mission.Destination()->GetSystem()); }
0
endless-sky-master
endless-sky-master/source/Government.h
/* Government.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef GOVERNMENT_H_ #define GOVERNMENT_H_ #include "Color.h" #include "ExclusiveItem.h" #include "LocationFilter.h" #include "RaidFleet.h" #include <limits> #include <map> #include <set> #include <string> #include <utility> #include <vector> class Conversation; class DataNode; class Fleet; class Phrase; class Planet; class PlayerInfo; class Outfit; class Ship; class System; // Class representing a government. Each ship belongs to some government, and // attacking that ship will provoke its ally governments and reduce your // reputation with them, but increase your reputation with that ship's enemies. // The ships for each government are identified by drawing them with a different // color "swizzle." Some government's ships can also be easier or harder to // bribe than others. class Government { public: // Default constructor. Government(); // Load a government's definition from a file. void Load(const DataNode &node); // Get the display name of this government. const std::string &GetName() const; // Set / Get the name used for this government in the data files. void SetName(const std::string &trueName); const std::string &GetTrueName() const; // Get the color swizzle to use for ships of this government. int GetSwizzle() const; // Get the color to use for displaying this government on the map. const Color &GetColor() const; // Get the government's initial disposition toward other governments or // toward the player. double AttitudeToward(const Government *other) const; double InitialPlayerReputation() const; // Get the amount that your reputation changes for the given offense against the given government. // The given value should be a combination of one or more ShipEvent values. // Returns 0 if the Government is null. double PenaltyFor(int eventType, const Government *other) const; // In order to successfully bribe this government you must pay them this // fraction of your fleet's value. (Zero means they cannot be bribed.) double GetBribeFraction() const; // This government will fine you the given fraction of the maximum fine for // carrying illegal cargo or outfits. Zero means they will not fine you. double GetFineFraction() const; bool Trusts(const Government *other) const; // A government might not exercise the ability to perform scans or fine // the player in every system. bool CanEnforce(const System *system) const; bool CanEnforce(const Planet *planet) const; // Get the conversation that will be shown if this government gives a death // sentence to the player (for carrying highly illegal cargo). const Conversation *DeathSentence() const; // Get a hail message (which depends on whether this is an enemy government // and if the ship is disabled). std::string GetHail(bool isDisabled) const; // Find out if this government speaks a different language. const std::string &Language() const; // Find out if this government should send custom hails even if the player does not know its language. bool SendUntranslatedHails() const; // Pirate raids in this government's systems use these fleet definitions. If // it is empty, there are no pirate raids. // The second attribute denotes the minimal and maximal attraction required for the fleet to appear. const std::vector<RaidFleet> &RaidFleets() const; // Check if, according to the politics stored by GameData, this government is // an enemy of the given government right now. bool IsEnemy(const Government *other) const; // Check if this government is an enemy of the player. bool IsEnemy() const; // Below are shortcut functions which actually alter the game state in the // Politics object, but are provided as member functions here for clearer syntax. // Check if this is the player government. bool IsPlayer() const; // Commit the given "offense" against this government (which may not // actually consider it to be an offense). This may result in temporary // hostilities (if the even type is PROVOKE), or a permanent change to your // reputation. void Offend(int eventType, int count = 1) const; // Bribe this government to be friendly to you for one day. void Bribe() const; // Check to see if the player has done anything they should be fined for. // Each government can only fine you once per day. std::string Fine(PlayerInfo &player, int scan = 0, const Ship *target = nullptr, double security = 1.) const; // Check to see if the items are condemnable (atrocities) or warrant a fine. bool Condemns(const Outfit *outfit) const; bool Condemns(const Ship *ship) const; // Returns the fine for given item for this government. int Fines(const Outfit *outfit) const; int Fines(const Ship *ship) const; // Check if given ship has illegal outfits or cargo. bool FinesContents(const Ship *ship) const; // Get or set the player's reputation with this government. double Reputation() const; double ReputationMax() const; double ReputationMin() const; void AddReputation(double value) const; void SetReputation(double value) const; // Get the government's crew attack/defense values double CrewAttack() const; double CrewDefense() const; bool IsProvokedOnScan() const; // Determine if ships from this government can travel to the given system or planet. bool IsRestrictedFrom(const System &system) const; bool IsRestrictedFrom(const Planet &planet) const; private: unsigned id; std::string name; std::string displayName; int swizzle = 0; ExclusiveItem<Color> color; std::vector<double> attitudeToward; std::set<const Government *> trusted; std::map<unsigned, std::map<int, double>> customPenalties; double initialPlayerReputation = 0.; double reputationMax = std::numeric_limits<double>::max(); double reputationMin = std::numeric_limits<double>::lowest(); std::map<int, double> penaltyFor; std::map<const Outfit*, int> illegalOutfits; std::map<std::string, int> illegalShips; std::map<const Outfit*, bool> atrocityOutfits; std::map<std::string, bool> atrocityShips; double bribe = 0.; double fine = 1.; std::vector<LocationFilter> enforcementZones; LocationFilter travelRestrictions; const Conversation *deathSentence = nullptr; const Phrase *friendlyHail = nullptr; const Phrase *friendlyDisabledHail = nullptr; const Phrase *hostileHail = nullptr; const Phrase *hostileDisabledHail = nullptr; std::string language; bool sendUntranslatedHails = false; std::vector<RaidFleet> raidFleets; double crewAttack = 1.; double crewDefense = 2.; bool provokedOnScan = false; // If a government appears in this set, and the reputation with this government is affected by actions, // and events performed against that government, use the penalties that government applies for the // action instead of this governments own penalties. std::set<unsigned> useForeignPenaltiesFor; }; #endif
0
endless-sky-master
endless-sky-master/source/StellarObject.h
/* StellarObject.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef STELLAR_OBJECT_H_ #define STELLAR_OBJECT_H_ #include "Body.h" #include "Hazard.h" #include "RandomEvent.h" class Planet; class Ship; // Class representing a planet, star, moon, or other large object in space. This // does not store the details of what is on that object, if anything; that is // handled by the Planet class. Each object's position depends on what it is // orbiting around and how far away it is from that object. Each day, all the // objects in each system move slightly in their orbits. class StellarObject : public Body { public: StellarObject(); // Functions provided by the Body base class: // bool HasSprite() const; // int Width() const; // int Height() const; // Frame GetFrame(int step = -1) const; // const Point &Position() const; // const Point &Velocity() const; // const Angle &Facing() const; // Point Unit() const; // Get the radius of this planet, i.e. how close you must be to land. double Radius() const; // Determine if this object represents a planet with valid data. bool HasValidPlanet() const; // Get this object's planet, if any. It may or may not be fully defined. const Planet *GetPlanet() const; // Only planets that you can land on have names. const std::string &Name() const; // If it is impossible to land on this planet, get the message // explaining why (e.g. too hot, too cold, etc.). const std::string &LandingMessage() const; // Get the radar color to be used for displaying this object. int RadarType(const Ship *ship) const; // Check if this is a star. bool IsStar() const; // Check if this is a station. bool IsStation() const; // Check if this is a moon. bool IsMoon() const; // Get this object's parent index (in the System's vector of objects). int Parent() const; // This object's system hazards. const std::vector<RandomEvent<Hazard>> &Hazards() const; // Find out how far this object is from its parent. double Distance() const; private: const Planet *planet; double distance; double speed; double offset; std::vector<RandomEvent<Hazard>> hazards; int parent; const std::string *message; bool isStar; bool isStation; bool isMoon; // Let System handle setting all the values of an Object. friend class System; }; #endif
0
endless-sky-master
endless-sky-master/source/main.cpp
/* main.cpp Copyright (c) 2014 by Michael Zahniser Main function for Endless Sky, a space exploration and combat RPG. Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Audio.h" #include "Command.h" #include "Conversation.h" #include "ConversationPanel.h" #include "DataFile.h" #include "DataNode.h" #include "Files.h" #include "text/Font.h" #include "FrameTimer.h" #include "GameData.h" #include "GameLoadingPanel.h" #include "GameWindow.h" #include "Logger.h" #include "MenuPanel.h" #include "Panel.h" #include "PlayerInfo.h" #include "Plugins.h" #include "Preferences.h" #include "PrintData.h" #include "Screen.h" #include "SpriteSet.h" #include "SpriteShader.h" #include "Test.h" #include "TestContext.h" #include "UI.h" #include <chrono> #include <iostream> #include <map> #include <thread> #include <cassert> #include <future> #include <stdexcept> #include <string> #ifdef _WIN32 #define STRICT #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <mmsystem.h> #endif namespace { // The delay in frames when debugging the integration tests. constexpr int UI_DELAY = 60; } using namespace std; void PrintHelp(); void PrintVersion(); void GameLoop(PlayerInfo &player, const Conversation &conversation, const string &testToRun, bool debugMode); Conversation LoadConversation(); void PrintTestsTable(); #ifdef _WIN32 void InitConsole(); #endif // Entry point for the EndlessSky executable int main(int argc, char *argv[]) { // Handle command-line arguments #ifdef _WIN32 if(argc > 1) InitConsole(); #endif Conversation conversation; bool debugMode = false; bool loadOnly = false; bool printTests = false; bool printData = false; bool noTestMute = false; string testToRunName; // Ensure that we log errors to the errors.txt file. Logger::SetLogErrorCallback([](const string &errorMessage) { Files::LogErrorToFile(errorMessage); }); for(const char *const *it = argv + 1; *it; ++it) { string arg = *it; if(arg == "-h" || arg == "--help") { PrintHelp(); return 0; } else if(arg == "-v" || arg == "--version") { PrintVersion(); return 0; } else if(arg == "-t" || arg == "--talk") conversation = LoadConversation(); else if(arg == "-d" || arg == "--debug") debugMode = true; else if(arg == "-p" || arg == "--parse-save") loadOnly = true; else if(arg == "--test" && *++it) testToRunName = *it; else if(arg == "--tests") printTests = true; else if(arg == "--nomute") noTestMute = true; } printData = PrintData::IsPrintDataArgument(argv); Files::Init(argv); try { // Load plugin preferences before game data if any. Plugins::LoadSettings(); // Begin loading the game data. bool isConsoleOnly = loadOnly || printTests || printData; future<void> dataLoading = GameData::BeginLoad(isConsoleOnly, debugMode); // If we are not using the UI, or performing some automated task, we should load // all data now. (Sprites and sounds can safely be deferred.) if(isConsoleOnly || !testToRunName.empty()) dataLoading.wait(); if(!testToRunName.empty() && !GameData::Tests().Has(testToRunName)) { Logger::LogError("Test \"" + testToRunName + "\" not found."); return 1; } if(printData) { PrintData::Print(argv); return 0; } if(printTests) { PrintTestsTable(); return 0; } PlayerInfo player; if(loadOnly) { // Set the game's initial internal state. GameData::FinishLoading(); // Reference check the universe, as known to the player. If no player found, // then check the default state of the universe. if(!player.LoadRecent()) GameData::CheckReferences(); cout << "Parse completed." << endl; return 0; } assert(!isConsoleOnly && "Attempting to use UI when only data was loaded!"); // On Windows, make sure that the sleep timer has at least 1 ms resolution // to avoid irregular frame rates. #ifdef _WIN32 timeBeginPeriod(1); #endif Preferences::Load(); // Load global conditions: DataFile globalConditions(Files::Config() + "global conditions.txt"); for(const DataNode &node : globalConditions) if(node.Token(0) == "conditions") GameData::GlobalConditions().Load(node); if(!GameWindow::Init()) return 1; GameData::LoadShaders(); // Show something other than a blank window. GameWindow::Step(); Audio::Init(GameData::Sources()); if(!testToRunName.empty() && !noTestMute) { Audio::SetVolume(0); } // This is the main loop where all the action begins. GameLoop(player, conversation, testToRunName, debugMode); } catch(Test::known_failure_tag) { // This is not an error. Simply exit successfully. } catch(const runtime_error &error) { Audio::Quit(); bool doPopUp = testToRunName.empty(); GameWindow::ExitWithError(error.what(), doPopUp); return 1; } // Remember the window state and preferences if quitting normally. Preferences::Set("maximized", GameWindow::IsMaximized()); Preferences::Set("fullscreen", GameWindow::IsFullscreen()); Screen::SetRaw(GameWindow::Width(), GameWindow::Height()); Preferences::Save(); Plugins::Save(); Audio::Quit(); GameWindow::Quit(); return 0; } void GameLoop(PlayerInfo &player, const Conversation &conversation, const string &testToRunName, bool debugMode) { // gamePanels is used for the main panel where you fly your spaceship. // All other game content related dialogs are placed on top of the gamePanels. // If there are both menuPanels and gamePanels, then the menuPanels take // priority over the gamePanels. The gamePanels will not be shown until // the stack of menuPanels is empty. UI gamePanels; // menuPanels is used for the panels related to pilot creation, preferences, // game loading and game saving. UI menuPanels; // Whether the game data is done loading. This is used to trigger any // tests to run. bool dataFinishedLoading = false; menuPanels.Push(new GameLoadingPanel(player, conversation, gamePanels, dataFinishedLoading)); bool showCursor = true; int cursorTime = 0; int frameRate = 60; FrameTimer timer(frameRate); bool isPaused = false; bool isFastForward = false; int testDebugUIDelay = UI_DELAY; // If fast forwarding, keep track of whether the current frame should be drawn. int skipFrame = 0; // Limit how quickly full-screen mode can be toggled. int toggleTimeout = 0; // Data to track progress of testing if/when a test is running. TestContext testContext; if(!testToRunName.empty()) testContext = TestContext(GameData::Tests().Get(testToRunName)); // IsDone becomes true when the game is quit. while(!menuPanels.IsDone()) { if(toggleTimeout) --toggleTimeout; chrono::steady_clock::time_point start = chrono::steady_clock::now(); // Handle any events that occurred in this frame. SDL_Event event; while(SDL_PollEvent(&event)) { UI &activeUI = (menuPanels.IsEmpty() ? gamePanels : menuPanels); // If the mouse moves, reset the cursor movement timeout. if(event.type == SDL_MOUSEMOTION) cursorTime = 0; if(debugMode && event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_BACKQUOTE) { isPaused = !isPaused; } else if(event.type == SDL_KEYDOWN && menuPanels.IsEmpty() && Command(event.key.keysym.sym).Has(Command::MENU) && !gamePanels.IsEmpty() && gamePanels.Top()->IsInterruptible()) { // User pressed the Menu key. menuPanels.Push(shared_ptr<Panel>( new MenuPanel(player, gamePanels))); } else if(event.type == SDL_QUIT) { menuPanels.Quit(); } else if(event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) { // The window has been resized. Adjust the raw screen size // and the OpenGL viewport to match. GameWindow::AdjustViewport(); } else if(event.type == SDL_KEYDOWN && !toggleTimeout && (Command(event.key.keysym.sym).Has(Command::FULLSCREEN) || (event.key.keysym.sym == SDLK_RETURN && (event.key.keysym.mod & KMOD_ALT)))) { toggleTimeout = 30; Preferences::ToggleScreenMode(); } else if(activeUI.Handle(event)) { // The UI handled the event. } else if(event.type == SDL_KEYDOWN && !event.key.repeat && (Command(event.key.keysym.sym).Has(Command::FASTFORWARD))) { isFastForward = !isFastForward; } } SDL_Keymod mod = SDL_GetModState(); Font::ShowUnderlines(mod & KMOD_ALT); // In full-screen mode, hide the cursor if inactive for ten seconds, // but only if the player is flying around in the main view. bool inFlight = (menuPanels.IsEmpty() && gamePanels.Root() == gamePanels.Top()); ++cursorTime; bool shouldShowCursor = (!GameWindow::IsFullscreen() || cursorTime < 600 || !inFlight); if(shouldShowCursor != showCursor) { showCursor = shouldShowCursor; SDL_ShowCursor(showCursor); } // Switch off fast-forward if the player is not in flight or flight-related screen // (for example when the boarding dialog shows up or when the player lands). The player // can switch fast-forward on again when flight is resumed. bool allowFastForward = !gamePanels.IsEmpty() && gamePanels.Top()->AllowsFastForward(); if(Preferences::Has("Interrupt fast-forward") && !inFlight && isFastForward && !allowFastForward) isFastForward = false; // Tell all the panels to step forward, then draw them. ((!isPaused && menuPanels.IsEmpty()) ? gamePanels : menuPanels).StepAll(); // All manual events and processing done. Handle any test inputs and events if we have any. const Test *runningTest = testContext.CurrentTest(); if(runningTest && dataFinishedLoading) { // When flying around, all test processing must be handled in the // thread-safe section of Engine. When not flying around (and when no // Engine exists), then it is safe to execute the tests from here. auto mainPanel = gamePanels.Root(); if(!isPaused && inFlight && menuPanels.IsEmpty() && mainPanel) mainPanel->SetTestContext(testContext); else if(debugMode && testDebugUIDelay > 0) --testDebugUIDelay; else { // The command will be ignored, since we only support commands // from within the engine at the moment. Command ignored; runningTest->Step(testContext, player, ignored); // Reset the visual delay. testDebugUIDelay = UI_DELAY; } // Skip drawing 29 out of every 30 in-flight frames during testing to speedup testing (unless debug mode is set). // We don't skip UI-frames to ensure we test the UI code more. if(inFlight && !debugMode) { skipFrame = (skipFrame + 1) % 30; if(skipFrame) continue; } else skipFrame = 0; } // Caps lock slows the frame rate in debug mode. // Slowing eases in and out over a couple of frames. else if((mod & KMOD_CAPS) && inFlight && debugMode) { if(frameRate > 10) { frameRate = max(frameRate - 5, 10); timer.SetFrameRate(frameRate); } } else { if(frameRate < 60) { frameRate = min(frameRate + 5, 60); timer.SetFrameRate(frameRate); } if(isFastForward && inFlight) { skipFrame = (skipFrame + 1) % 3; if(skipFrame) continue; } } Audio::Step(); // Events in this frame may have cleared out the menu, in which case // we should draw the game panels instead: (menuPanels.IsEmpty() ? gamePanels : menuPanels).DrawAll(); if(isFastForward) SpriteShader::Draw(SpriteSet::Get("ui/fast forward"), Screen::TopLeft() + Point(10., 10.)); GameWindow::Step(); // When we perform automated testing, then we run the game by default as quickly as possible. // Except when debug-mode is set. if(!testContext.CurrentTest() || debugMode) timer.Wait(); // If the player ended this frame in-game, count the elapsed time as played time. if(menuPanels.IsEmpty()) player.AddPlayTime(chrono::steady_clock::now() - start); } // If player quit while landed on a planet, save the game if there are changes. if(player.GetPlanet() && gamePanels.CanSave()) player.Save(); } void PrintHelp() { cerr << endl; cerr << "Command line options:" << endl; cerr << " -h, --help: print this help message." << endl; cerr << " -v, --version: print version information." << endl; cerr << " -t, --talk: read and display a conversation from STDIN." << endl; cerr << " -r, --resources <path>: load resources from given directory." << endl; cerr << " -c, --config <path>: save user's files to given directory." << endl; cerr << " -d, --debug: turn on debugging features (e.g. Caps Lock slows down instead of speeds up)." << endl; cerr << " -p, --parse-save: load the most recent saved game and inspect it for content errors." << endl; cerr << " --tests: print table of available tests, then exit." << endl; cerr << " --test <name>: run given test from resources directory." << endl; cerr << " --nomute: don't mute the game while running tests." << endl; PrintData::Help(); cerr << endl; cerr << "Report bugs to: <https://github.com/endless-sky/endless-sky/issues>" << endl; cerr << "Home page: <https://endless-sky.github.io>" << endl; cerr << endl; } void PrintVersion() { cerr << endl; cerr << "Endless Sky ver. 0.10.5-alpha" << endl; cerr << "License GPLv3+: GNU GPL version 3 or later: <https://gnu.org/licenses/gpl.html>" << endl; cerr << "This is free software: you are free to change and redistribute it." << endl; cerr << "There is NO WARRANTY, to the extent permitted by law." << endl; cerr << endl; cerr << GameWindow::SDLVersions() << endl; cerr << endl; } Conversation LoadConversation() { Conversation conversation; DataFile file(cin); for(const DataNode &node : file) if(node.Token(0) == "conversation") { conversation.Load(node); break; } map<string, string> subs = { {"<bunks>", "[N]"}, {"<cargo>", "[N tons of Commodity]"}, {"<commodity>", "[Commodity]"}, {"<date>", "[Day Mon Year]"}, {"<day>", "[The Nth of Month]"}, {"<destination>", "[Planet in the Star system]"}, {"<fare>", "[N passengers]"}, {"<first>", "[First]"}, {"<last>", "[Last]"}, {"<origin>", "[Origin Planet]"}, {"<passengers>", "[your passengers]"}, {"<planet>", "[Planet]"}, {"<ship>", "[Ship]"}, {"<system>", "[Star]"}, {"<tons>", "[N tons]"} }; return conversation.Instantiate(subs); } // This prints out the list of tests that are available and their status // (active/missing feature/known failure).. void PrintTestsTable() { for(auto &it : GameData::Tests()) if(it.second.GetStatus() != Test::Status::PARTIAL && it.second.GetStatus() != Test::Status::BROKEN) cout << it.second.Name() << '\n'; cout.flush(); } #ifdef _WIN32 void InitConsole() { const int UNINITIALIZED = -2; bool redirectStdout = _fileno(stdout) == UNINITIALIZED; bool redirectStderr = _fileno(stderr) == UNINITIALIZED; bool redirectStdin = _fileno(stdin) == UNINITIALIZED; // Bail if stdin, stdout, and stderr are already initialized (e.g. writing to a file) if(!redirectStdout && !redirectStderr && !redirectStdin) return; // Bail if we fail to attach to the console if(!AttachConsole(ATTACH_PARENT_PROCESS) && !AllocConsole()) return; // Perform console redirection. if(redirectStdout) { FILE *fstdout = nullptr; freopen_s(&fstdout, "CONOUT$", "w", stdout); if(fstdout) setvbuf(stdout, nullptr, _IOFBF, 4096); } if(redirectStderr) { FILE *fstderr = nullptr; freopen_s(&fstderr, "CONOUT$", "w", stderr); if(fstderr) setvbuf(stderr, nullptr, _IOLBF, 1024); } if(redirectStdin) { FILE *fstdin = nullptr; freopen_s(&fstdin, "CONIN$", "r", stdin); if(fstdin) setvbuf(stdin, nullptr, _IONBF, 0); } } #endif
0
endless-sky-master
endless-sky-master/source/Fleet.cpp
/* Fleet.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Fleet.h" #include "DataNode.h" #include "GameData.h" #include "Government.h" #include "Logger.h" #include "Phrase.h" #include "Planet.h" #include "Random.h" #include "Ship.h" #include "ShipJumpNavigation.h" #include "StellarObject.h" #include "System.h" #include <algorithm> #include <cmath> #include <functional> #include <iterator> using namespace std; namespace { // Generate an offset magnitude that will sample from an annulus (planets) // or a circle (systems without inhabited planets). double OffsetFrom(pair<Point, double> &center) { // If the center has a radius, then position ships further away. double minimumOffset = center.second ? 1. : 0.; // Since it is sensible that ships would be nearer to the object of // interest on average, do not apply the sqrt(rand) correction. return (Random::Real() + minimumOffset) * 400. + 2. * center.second; } } // Construct and Load() at the same time. Fleet::Fleet(const DataNode &node) { Load(node); } void Fleet::Load(const DataNode &node) { if(node.Size() >= 2) fleetName = node.Token(1); // If Load() has already been called once on this fleet, any subsequent // calls will replace the variants instead of adding to them. bool resetVariants = !variants.empty(); for(const DataNode &child : node) { // The "add" and "remove" keywords should never be alone on a line, and // are only valid with "variant" or "personality" definitions. bool add = (child.Token(0) == "add"); bool remove = (child.Token(0) == "remove"); bool hasValue = (child.Size() >= 2); if((add || remove) && (!hasValue || (child.Token(1) != "variant" && child.Token(1) != "personality"))) { child.PrintTrace("Warning: Skipping invalid \"" + child.Token(0) + "\" tag:"); continue; } // If this line is an add or remove, the key is the token at index 1. const string &key = child.Token(add || remove); if(key == "government" && hasValue) government = GameData::Governments().Get(child.Token(1)); else if(key == "names" && hasValue) names = GameData::Phrases().Get(child.Token(1)); else if(key == "fighters" && (hasValue || child.HasChildren())) { if(hasValue) fighterNames = GameData::Phrases().Get(child.Token(1)); for(const DataNode &grand : child) { const string &fighterKey = grand.Token(0); if(fighterKey == "names" && grand.Size() >= 2) fighterNames = GameData::Phrases().Get(grand.Token(1)); else if(fighterKey == "personality") fighterPersonality.Load(grand); else grand.PrintTrace("Skipping unrecognized attribute:"); } } else if(key == "cargo settings" && child.HasChildren()) cargo.Load(child); // Allow certain individual cargo settings to be direct children // of Fleet for backwards compatibility. else if(key == "cargo" || key == "commodities" || key == "outfitters") cargo.LoadSingle(child); else if(key == "personality") personality.Load(child); else if(key == "variant" && !remove) { if(resetVariants && !add) { resetVariants = false; variants.clear(); } int weight = (child.Size() >= add + 2) ? max<int>(1, child.Value(add + 1)) : 1; variants.emplace_back(weight, child); } else if(key == "variant") { // If given a full definition of one of this fleet's variant members, remove the variant. Variant toRemove(child); int count = erase(variants, toRemove); if(!count) child.PrintTrace("Warning: Did not find matching variant for specified operation:"); } else child.PrintTrace("Skipping unrecognized attribute:"); } if(variants.empty()) node.PrintTrace("Warning: " + (fleetName.empty() ? "unnamed fleet" : "Fleet \"" + fleetName + "\"") + " contains no variants:"); } bool Fleet::IsValid(bool requireGovernment) const { // Generally, a government is required for a fleet to be valid. if(requireGovernment && !government) return false; if(names && names->IsEmpty()) return false; if(fighterNames && fighterNames->IsEmpty()) return false; // Any variant a fleet could choose should be valid. if(any_of(variants.begin(), variants.end(), [](const Variant &v) noexcept -> bool { return !v.IsValid(); })) return false; return true; } void Fleet::RemoveInvalidVariants() { int total = variants.TotalWeight(); int count = erase_if(variants, [](const Variant &v) noexcept -> bool { return !v.IsValid(); }); if(!count) return; Logger::LogError("Warning: " + (fleetName.empty() ? "unnamed fleet" : "fleet \"" + fleetName + "\"") + ": Removing " + to_string(count) + " invalid " + (count > 1 ? "variants" : "variant") + " (" + to_string(total - variants.TotalWeight()) + " of " + to_string(total) + " weight)"); } // Get the government of this fleet. const Government *Fleet::GetGovernment() const { return government; } // Choose a fleet to be created during flight, and have it enter the system via jump or planetary departure. void Fleet::Enter(const System &system, list<shared_ptr<Ship>> &ships, const Planet *planet) const { if(variants.empty() || personality.IsDerelict()) return; // Pick a fleet variant to instantiate. const vector<const Ship *> &variantShips = variants.Get().Ships(); if(variantShips.empty()) return; // Figure out what system the fleet is starting in, where it is going, and // what position it should start from in the system. const System *source = &system; const System *target = &system; Point position; double radius = 1000.; // The chosen stellar object the fleet will depart from, if any. const StellarObject *object = nullptr; // Only pick a random entry point for this fleet if a source planet was not specified. if(!planet) { // Where this fleet can come from depends on whether it is friendly to any // planets in this system and whether it has jump drives. vector<const System *> linkVector; // Find out what the "best" jump method the fleet has is. Assume that if the // others don't have that jump method, they are being carried as fighters. // That is, content creators should avoid creating fleets with a mix of jump // drives and hyperdrives. bool hasJump = false; bool hasHyper = false; double jumpDistance = System::DEFAULT_NEIGHBOR_DISTANCE; for(const Ship *ship : variantShips) { if(ship->JumpNavigation().HasJumpDrive()) { hasJump = true; jumpDistance = ship->JumpNavigation().JumpRange(); break; } if(ship->JumpNavigation().HasHyperdrive()) hasHyper = true; } const bool unrestricted = personality.IsUnrestricted(); // Don't try to make a fleet "enter" from another system if none of the // ships have jump drives. if(hasJump || hasHyper) { bool isWelcomeHere = !system.GetGovernment()->IsEnemy(government); for(const System *neighbor : (hasJump ? system.JumpNeighbors(jumpDistance) : system.Links())) { if(!unrestricted && government->IsRestrictedFrom(*neighbor)) continue; // If this ship is not "welcome" in the current system, prefer to have // it enter from a system that is friendly to it. (This is for realism, // so attack fleets don't come from what ought to be a safe direction.) if(isWelcomeHere || neighbor->GetGovernment()->IsEnemy(government)) linkVector.push_back(neighbor); else linkVector.insert(linkVector.end(), 8, neighbor); } } // Find all the inhabited planets this fleet could take off from. vector<const StellarObject *> stellarVector; if(!personality.IsSurveillance()) for(const StellarObject &object : system.Objects()) if(object.HasValidPlanet() && object.GetPlanet()->IsInhabited() && (unrestricted || !government->IsRestrictedFrom(*object.GetPlanet())) && !object.GetPlanet()->GetGovernment()->IsEnemy(government)) stellarVector.push_back(&object); // If there is nowhere for this fleet to come from, don't create it. size_t options = linkVector.size() + stellarVector.size(); if(!options) { // Prefer to launch from inhabited planets, but launch from // uninhabited ones if there is no other option. for(const StellarObject &object : system.Objects()) if(object.HasValidPlanet() && (unrestricted || !government->IsRestrictedFrom(*object.GetPlanet())) && !object.GetPlanet()->GetGovernment()->IsEnemy(government)) stellarVector.push_back(&object); options = stellarVector.size(); if(!options) return; } // Choose a random planet or star system to come from. size_t choice = Random::Int(options); // If a planet is chosen, also pick a system to travel to after taking off. if(choice >= linkVector.size()) { object = stellarVector[choice - linkVector.size()]; planet = object->GetPlanet(); if(!linkVector.empty()) target = linkVector[Random::Int(linkVector.size())]; } // We are entering this system via hyperspace, not taking off from a planet. else source = linkVector[choice]; } auto placed = Instantiate(variantShips); // Carry all ships that can be carried, as they don't need to be positioned // or checked to see if they can access a particular planet. for(auto &ship : placed) PlaceFighter(ship, placed); // Find the stellar object for this planet if necessary, and place the ships there. if(planet) { if(!object) { // Search the stellar object associated with the given planet. // If there are many possible candidates (for example for ringworlds), // then choose a random one. vector<const StellarObject *> stellarObjects; for(const auto &object : system.Objects()) if(object.GetPlanet() == planet) stellarObjects.push_back(&object); // If the source planet isn't in the source for some reason, bail out. if(stellarObjects.empty()) { // Log this error. Logger::LogError("Fleet::Enter: Unable to find valid stellar object for planet \"" + planet->TrueName() + "\" in system \"" + system.Name() + "\""); return; } object = stellarObjects[Random::Int(stellarObjects.size())]; } // To take off from the planet, all non-carried ships must be able to access it. if(planet->IsUnrestricted() || all_of(placed.cbegin(), placed.cend(), [&](const shared_ptr<Ship> &ship) { return ship->GetParent() || planet->IsAccessible(ship.get()); })) { position = object->Position(); radius = object->Radius(); } // The chosen planet could not be departed from by all ships in the variant. else { // If there are no departure paths, then there are no arrival paths either. if(source == target) return; // Otherwise, have the fleet arrive here from the target system. std::swap(source, target); planet = nullptr; } } // Place all the ships in the chosen fleet variant. shared_ptr<Ship> flagship; for(shared_ptr<Ship> &ship : placed) { // If this is a carried fighter, no need to position it. if(ship->GetParent()) continue; Angle angle = Angle::Random(360.); Point pos = position + angle.Unit() * (Random::Real() * radius); ships.push_front(ship); ship->SetSystem(source); ship->SetPlanet(planet); if(source == &system) ship->Place(pos, angle.Unit(), angle); else { // Place the ship stationary and pointed in the right direction. angle = Angle(system.Position() - source->Position()); ship->Place(pos, Point(), angle); } if(target != source) ship->SetTargetSystem(target); if(flagship) ship->SetParent(flagship); else flagship = ship; cargo.SetCargo(&*ship); } } // Place one of the variants in the given system, already "in action." If the carried flag is set, // only uncarried ships will be added to the list (as any carriables will be stored in bays). void Fleet::Place(const System &system, list<shared_ptr<Ship>> &ships, bool carried, bool addCargo) const { if(variants.empty()) return; // Pick a fleet variant to instantiate. const vector<const Ship *> &variantShips = variants.Get().Ships(); if(variantShips.empty()) return; // Determine where the fleet is going to or coming from. auto center = ChooseCenter(system); // Place all the ships in the chosen fleet variant. shared_ptr<Ship> flagship; vector<shared_ptr<Ship>> placed = Instantiate(variantShips); for(shared_ptr<Ship> &ship : placed) { // If this is a fighter and someone can carry it, no need to position it. if(carried && PlaceFighter(ship, placed)) continue; Angle angle = Angle::Random(); Point pos = center.first + Angle::Random().Unit() * OffsetFrom(center); double velocity = 0; if(!ship->GetPersonality().IsDerelict()) velocity = Random::Real() * ship->MaxVelocity(); else ship->Disable(); ships.push_front(ship); ship->SetSystem(&system); ship->Place(pos, velocity * angle.Unit(), angle); if(flagship) ship->SetParent(flagship); else flagship = ship; if(addCargo) cargo.SetCargo(&*ship); } } // Do the randomization to make a ship enter or be in the given system. const System *Fleet::Enter(const System &system, Ship &ship, const System *source) { bool unrestricted = ship.GetPersonality().IsUnrestricted(); bool canEnter = (source != nullptr || unrestricted || any_of(system.Links().begin(), system.Links().end(), [&ship](const System *link) noexcept -> bool { return !ship.GetGovernment()->IsRestrictedFrom(*link); } )); if(!canEnter || system.Links().empty() || (source && !system.Links().count(source))) { Place(system, ship); return &system; } // Choose which system this ship is coming from. if(!source) { vector<const System *> validSystems; const Government *gov = ship.GetGovernment(); for(const System *link : system.Links()) if(unrestricted || !gov->IsRestrictedFrom(*link)) validSystems.emplace_back(link); auto it = validSystems.cbegin(); advance(it, Random::Int(validSystems.size())); source = *it; } Angle angle = Angle::Random(); Point pos = angle.Unit() * Random::Real() * 1000.; ship.Place(pos, angle.Unit(), angle); ship.SetSystem(source); ship.SetTargetSystem(&system); return source; } void Fleet::Place(const System &system, Ship &ship) { // Choose a random inhabited object in the system to spawn around. auto center = ChooseCenter(system); Point pos = center.first + Angle::Random().Unit() * OffsetFrom(center); double velocity = ship.IsDisabled() ? 0. : Random::Real() * ship.MaxVelocity(); ship.SetSystem(&system); Angle angle = Angle::Random(); ship.Place(pos, velocity * angle.Unit(), angle); } int64_t Fleet::Strength() const { return variants.Average(std::mem_fn(&Variant::Strength)); } // Obtain a positional reference and the radius of the object at that position (e.g. a planet). // Spaceport status can be modified during normal gameplay, so this information is not cached. pair<Point, double> Fleet::ChooseCenter(const System &system) { auto centers = vector<pair<Point, double>>(); for(const StellarObject &object : system.Objects()) if(object.HasValidPlanet() && object.GetPlanet()->IsInhabited()) centers.emplace_back(object.Position(), object.Radius()); if(centers.empty()) return {Point(), 0.}; return centers[Random::Int(centers.size())]; } vector<shared_ptr<Ship>> Fleet::Instantiate(const vector<const Ship *> &ships) const { vector<shared_ptr<Ship>> placed; for(const Ship *model : ships) { // At least one of this variant's ships is valid, but we should avoid spawning any that are not defined. if(!model->IsValid()) { Logger::LogError("Warning: Skipping invalid ship model \"" + model->TrueModelName() + "\" in fleet \"" + fleetName + "\"."); continue; } // Copy the model instance into a new instance. auto ship = make_shared<Ship>(*model); bool canBeCarried = ship->CanBeCarried(); const Phrase *phrase = ((canBeCarried && fighterNames) ? fighterNames : names); if(phrase) ship->SetName(phrase->Get()); ship->SetGovernment(government); if(canBeCarried && fighterPersonality.IsDefined()) ship->SetPersonality(fighterPersonality); else ship->SetPersonality(personality); placed.push_back(ship); } return placed; } bool Fleet::PlaceFighter(shared_ptr<Ship> fighter, vector<shared_ptr<Ship>> &placed) const { if(!fighter->CanBeCarried()) return false; for(const shared_ptr<Ship> &parent : placed) if(parent->Carry(fighter)) return true; return false; }
0
endless-sky-master
endless-sky-master/source/StartConditionsPanel.cpp
/* StartConditionsPanel.cpp Copyright (c) 2020-2021 by FranchuFranchu <fff999abc999@gmail.com> Copyright (c) 2021 by Benjamin Hauch Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "StartConditionsPanel.h" #include "Command.h" #include "ConversationPanel.h" #include "text/DisplayText.h" #include "FillShader.h" #include "text/Font.h" #include "text/FontSet.h" #include "GameData.h" #include "Information.h" #include "Interface.h" #include "text/layout.hpp" #include "MainPanel.h" #include "Planet.h" #include "PlayerInfo.h" #include "Preferences.h" #include "Rectangle.h" #include "Ship.h" #include "ShipyardPanel.h" #include "StarField.h" #include "StartConditions.h" #include "System.h" #include "text/truncate.hpp" #include "UI.h" #include <algorithm> using namespace std; StartConditionsPanel::StartConditionsPanel(PlayerInfo &player, UI &gamePanels, const StartConditionsList &allScenarios, const Panel *parent) : player(player), gamePanels(gamePanels), parent(parent), bright(*GameData::Colors().Get("bright")), medium(*GameData::Colors().Get("medium")), selectedBackground(*GameData::Colors().Get("faint")), description(FontSet::Get(14)) { // Extract from all start scenarios those that are visible to the player. for(const auto &scenario : allScenarios) if(scenario.Visible(GameData::GlobalConditions())) { scenarios.emplace_back(scenario); scenarios.back().SetState(GameData::GlobalConditions()); } startIt = scenarios.begin(); const Interface *startConditionsMenu = GameData::Interfaces().Find("start conditions menu"); if(startConditionsMenu) { // Ideally, we want the content of the boxes to be drawn in Interface.cpp. // However, we'd need a way to specify arbitrarily extensible lists there. // We also would need to a way to specify truncation for such a list. // Such a list would also have to be scrollable. descriptionBox = startConditionsMenu->GetBox("start description"); entriesContainer = startConditionsMenu->GetBox("start entry list"); entryBox = startConditionsMenu->GetBox("start entry item bounds"); entryTextPadding = startConditionsMenu->GetBox("start entry text padding").Dimensions(); } const Rectangle firstRectangle = Rectangle::FromCorner(entriesContainer.TopLeft(), entryBox.Dimensions()); const auto startCount = scenarios.size(); startConditionsClickZones.reserve(startCount); for(size_t i = 0; i < startCount; ++i) startConditionsClickZones.emplace_back(firstRectangle + Point(0, i * entryBox.Height()), scenarios.begin() + i); description.SetWrapWidth(descriptionBox.Width()); Select(startIt); } void StartConditionsPanel::Draw() { glClear(GL_COLOR_BUFFER_BIT); GameData::Background().Draw(Point(), Point()); GameData::Interfaces().Get("menu background")->Draw(info, this); GameData::Interfaces().Get("start conditions menu")->Draw(info, this); GameData::Interfaces().Get("menu start info")->Draw(info, this); // Rather than blink list items in & out of existence, fade them in/out over half the entry height. const double fadeDistance = .5 * entryBox.Height(); const double fadeInY = entriesContainer.Top() - fadeDistance + entryTextPadding.Y(); const double fadeOutY = fadeInY + entriesContainer.Height(); // Start at the top left of the list and offset by the text margins and scroll. auto pos = entriesContainer.TopLeft() - Point(0., entriesScroll); const Font &font = FontSet::Get(14); for(auto it = scenarios.begin(); it != scenarios.end(); ++it, pos += Point(0., entryBox.Height())) { // Any scenario wholly outside the bounds can be skipped. const auto zone = Rectangle::FromCorner(pos, entryBox.Dimensions()); if(!(entriesContainer.Contains(zone.TopLeft()) || entriesContainer.Contains(zone.BottomRight()))) continue; // Partially visible entries should fade in or out. double opacity = entriesContainer.Contains(zone) ? 1. : min(1., max(0., min(pos.Y() - fadeInY, fadeOutY - pos.Y()) / fadeDistance)); bool isHighlighted = it == startIt || (hasHover && zone.Contains(hoverPoint)); if(it == startIt) FillShader::Fill(zone.Center(), zone.Dimensions(), selectedBackground.Additive(opacity)); const auto name = DisplayText(it->GetDisplayName(), Truncate::BACK); font.Draw(name, pos + entryTextPadding, (isHighlighted ? bright : medium).Transparent(opacity)); } // TODO: Prevent lengthy descriptions from overflowing. description.Draw(descriptionBox.TopLeft(), bright); } bool StartConditionsPanel::KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool /* isNewPress */) { if(key == 'b' || key == SDLK_ESCAPE || command.Has(Command::MENU) || (key == 'w' && (mod & (KMOD_CTRL | KMOD_GUI)))) GetUI()->Pop(this); else if(!scenarios.empty() && (key == SDLK_UP || key == SDLK_DOWN || key == SDLK_PAGEUP || key == SDLK_PAGEDOWN)) { // Move up / down an entry, or a page. If at the bottom / top, wrap around. const ptrdiff_t magnitude = (key == SDLK_UP || key == SDLK_DOWN) ? 1 : entriesContainer.Height() / entryBox.Height() - 1; if(key == SDLK_UP || key == SDLK_PAGEUP) { if(startIt == scenarios.begin()) startIt = scenarios.end() - 1; else startIt -= min(magnitude, distance(scenarios.begin(), startIt)); } else { if(startIt + 1 == scenarios.end()) startIt = scenarios.begin(); else startIt += min(magnitude, distance(startIt, scenarios.end() - 1)); } Select(startIt); } else if(startIt != scenarios.end() && (key == 's' || key == 'n' || key == SDLK_KP_ENTER || key == SDLK_RETURN) && info.HasCondition("unlocked start")) { player.New(*startIt); ConversationPanel *panel = new ConversationPanel( player, startIt->GetConversation()); GetUI()->Push(panel); panel->SetCallback(this, &StartConditionsPanel::OnConversationEnd); } else return false; return true; } bool StartConditionsPanel::Click(int x, int y, int /* clicks */) { // When the user clicks, clear the hovered state. hasHover = false; // Only clicks within the list of scenarios should have an effect. if(!entriesContainer.Contains(Point(x, y))) return false; for(const auto &it : startConditionsClickZones) if(it.Contains(Point(x, y + entriesScroll))) { if(startIt != it.Value()) Select(it.Value()); return true; } return false; } bool StartConditionsPanel::Hover(int x, int y) { hasHover = true; hoverPoint = Point(x, y); return true; } bool StartConditionsPanel::Drag(double /* dx */, double dy) { if(entriesContainer.Contains(hoverPoint)) { entriesScroll = max(0., min(entriesScroll - dy, scenarios.size() * entryBox.Height() - entriesContainer.Height())); } else if(descriptionBox.Contains(hoverPoint)) { descriptionScroll = 0.; // TODO: When #4123 gets merged, re-add scrolling support to the description. // Right now it's pointless because it would make the text overflow. } else return false; return true; } bool StartConditionsPanel::Scroll(double /* dx */, double dy) { return Drag(0., dy * Preferences::ScrollSpeed()); } // Transition from the completed "new pilot" conversation into the actual game. void StartConditionsPanel::OnConversationEnd(int) { gamePanels.Reset(); gamePanels.CanSave(true); gamePanels.Push(new MainPanel(player)); // Tell the main panel to re-draw itself (and pop up the planet panel). gamePanels.StepAll(); // If the starting conditions don't specify any ships, let the player buy one. if(player.Ships().empty()) { gamePanels.Push(new ShipyardPanel(player)); gamePanels.StepAll(); } if(parent) GetUI()->Pop(parent); GetUI()->Pop(GetUI()->Root().get()); GetUI()->Pop(this); } // Scroll the selected starting condition into view, if necessary. void StartConditionsPanel::ScrollToSelected() { // If there are fewer starts than there are displayable starts, never scroll. const double entryHeight = entryBox.Height(); const int maxDisplayedRows = entriesContainer.Height() / entryHeight; const auto startCount = scenarios.size(); if(static_cast<int>(startCount) < maxDisplayedRows) { entriesScroll = 0.; return; } // Otherwise, scroll the minimum of the desired amount and the amount that // brings the scrolled-to edge within view. const auto countBefore = static_cast<size_t>(distance(scenarios.begin(), startIt)); const double maxScroll = (startCount - maxDisplayedRows) * entryHeight; const double pageScroll = maxDisplayedRows * entryHeight; const double desiredScroll = countBefore * entryHeight; const double bottomOfPage = entriesScroll + pageScroll; if(desiredScroll < entriesScroll) { // Scroll upwards. entriesScroll = desiredScroll; } else if(desiredScroll + entryHeight > bottomOfPage) { // Scroll downwards (but not so far that we overscroll). entriesScroll = min(maxScroll, entriesScroll + entryHeight + desiredScroll - bottomOfPage); } } // Update the UI to reflect the given starting scenario. void StartConditionsPanel::Select(StartConditionsList::iterator it) { // Clear the displayed information. info = Information(); startIt = it; if(startIt == scenarios.end()) { // The only time we should be here is if there are no scenarios at all. description.Wrap("No valid starting scenarios were defined!\n\n" "Make sure you installed Endless Sky (and any plugins) properly."); return; } // Update the information summary. info.SetCondition("chosen start"); if(startIt->IsUnlocked()) info.SetCondition("unlocked start"); if(startIt->GetThumbnail()) info.SetSprite("thumbnail", startIt->GetThumbnail()); info.SetString("name", startIt->GetDisplayName()); info.SetString("description", startIt->GetDescription()); info.SetString("planet", startIt->GetPlanetName()); info.SetString("system", startIt->GetSystemName()); info.SetString("date", startIt->GetDateString()); info.SetString("credits", startIt->GetCredits()); info.SetString("debt", startIt->GetDebt()); // Update the displayed description text. descriptionScroll = 0; description.Wrap(startIt->GetDescription()); // Scroll the selected scenario into view. ScrollToSelected(); }
0
endless-sky-master
endless-sky-master/source/MapPanel.h
/* MapPanel.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef MAP_PANEL_H_ #define MAP_PANEL_H_ #include "Panel.h" #include "Color.h" #include "DistanceMap.h" #include "Point.h" #include "text/WrappedText.h" #include <map> #include <string> #include <utility> #include <vector> class Angle; class Government; class Mission; class Planet; class PlayerInfo; class System; // This class provides the base class for both the "map details" panel and the // missions panel, and handles drawing of the underlying starmap and coloring // the systems based on a selected criterion. It also handles finding and // drawing routes in between systems. class MapPanel : public Panel { public: // Enumeration for how the systems should be colored: static const int SHOW_SHIPYARD = -1; static const int SHOW_OUTFITTER = -2; static const int SHOW_VISITED = -3; static const int SHOW_SPECIAL = -4; static const int SHOW_GOVERNMENT = -5; static const int SHOW_REPUTATION = -6; static const int SHOW_DANGER = -7; static const float OUTER; static const float INNER; static const float LINK_WIDTH; static const float LINK_OFFSET; class SystemTooltipData { public: // Number of ships that are in flight unsigned activeShips = 0; // Number of ships that are parked unsigned parkedShips = 0; // Maps planet to number of outfits on that planet std::map<const Planet *, unsigned> outfits; }; public: explicit MapPanel(PlayerInfo &player, int commodity = SHOW_REPUTATION, const System *special = nullptr); virtual void Step() override; virtual void Draw() override; // Draw map mode buttons, escort/storage tooltips, and the non-routable system warning. void FinishDrawing(const std::string &buttonCondition); static void DrawMiniMap(const PlayerInfo &player, float alpha, const System *const jump[2], int step); // Map panels allow fast-forward to stay active. bool AllowsFastForward() const noexcept final; protected: // Only override the ones you need; the default action is to return false. virtual bool KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) override; virtual bool Click(int x, int y, int clicks) override; virtual bool Hover(int x, int y) override; virtual bool Drag(double dx, double dy) override; virtual bool Scroll(double dx, double dy) override; // Get the color mapping for various system attributes. static Color MapColor(double value); static Color ReputationColor(double reputation, bool canLand, bool hasDominated); static Color GovernmentColor(const Government *government); static Color DangerColor(double danger); static Color UninhabitedColor(); static Color UnexploredColor(); virtual double SystemValue(const System *system) const; void Select(const System *system); void Find(const std::string &name); double Zoom() const; // Check whether the NPC and waypoint conditions of the given mission have // been satisfied. bool IsSatisfied(const Mission &mission) const; static bool IsSatisfied(const PlayerInfo &player, const Mission &mission); // Returns if previous->next can be done with a known travel type. bool GetTravelInfo(const System *previous, const System *next, double jumpRange, bool &isJump, bool &isWormhole, bool &isMappable, Color *wormholeColor) const; protected: PlayerInfo &player; DistanceMap distance; // The system in which the player is located. const System &playerSystem; // The (non-null) system which is currently selected. const System *selectedSystem; // The selected planet, if any. const Planet *selectedPlanet = nullptr; // A system associated with a dialog or conversation. const System *specialSystem; double playerJumpDistance; Point center; Point recenterVector; int recentering = 0; int commodity; int step = 0; std::string buttonCondition; // Distance from the screen center to the nearest owned system, // for use in determining which governments are in the legend. std::map<const Government *, double> closeGovernments; // Systems in which your (active and parked) escorts and stored outfits are located. std::map<const System *, SystemTooltipData> escortSystems; // Center the view on the given system (may actually be slightly offset // to account for panels on the screen). void CenterOnSystem(const System *system, bool immediate = false); // Cache the map layout, so it doesn't have to be re-calculated every frame. // The cache must be updated when the coloring mode changes. void UpdateCache(); // For tooltips: int hoverCount = 0; const System *hoverSystem = nullptr; std::string tooltip; WrappedText hoverText; // An X offset in pixels to be applied to the selected system UI if something // else gets in the way of its default position. int selectedSystemOffset = 0; private: void DrawTravelPlan(); // Display the name of and distance to the selected system. void DrawSelectedSystem(); // Indicate which other systems have player escorts. void DrawEscorts(); void DrawWormholes(); void DrawLinks(); // Draw systems in accordance to the set commodity color scheme. void DrawSystems(); void DrawNames(); void DrawMissions(); void DrawPointer(const System *system, unsigned &systemCount, const Color &color, bool bigger = false); static void DrawPointer(Point position, unsigned &systemCount, const Color &color, bool drawBack = true, bool bigger = false); private: // This is the coloring mode currently used in the cache. int cachedCommodity = -10; class Node { public: Node(const Point &position, const Color &color, const std::string &name, const Color &nameColor, const Government *government) : position(position), color(color), name(name), nameColor(nameColor), government(government) {} Point position; Color color; std::string name; Color nameColor; const Government *government; }; std::vector<Node> nodes; class Link { public: Link(const Point &start, const Point &end, const Color &color) : start(start), end(end), color(color) {} Point start; Point end; Color color; }; std::vector<Link> links; }; #endif
0
endless-sky-master
endless-sky-master/source/NPC.h
/* NPC.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef NPC_H_ #define NPC_H_ #include "Conversation.h" #include "EsUuid.h" #include "ExclusiveItem.h" #include "Fleet.h" #include "FleetCargo.h" #include "LocationFilter.h" #include "NPCAction.h" #include "Personality.h" #include "Phrase.h" #include <list> #include <map> #include <memory> #include <string> class DataNode; class DataWriter; class Government; class Mission; class Planet; class PlayerInfo; class Ship; class ShipEvent; class System; class UI; // An NPC is a ship associated with a mission. Certain required actions are // associated with each NPC, such as boarding it, killing it, or making sure it // is not boarded or killed. NPCs also have different "behaviors," such as // staying in the system they started in, or attacking only the player's ships. class NPC { public: enum class Trigger : int_fast8_t { // Triggers corresponding directly to ShipEvents. ASSIST, SCAN_CARGO, SCAN_OUTFITS, PROVOKE, DISABLE, BOARD, CAPTURE, DESTROY, // Can be triggered by either the CAPTURE or DESTROY events. KILL }; public: NPC() = default; // Copying an NPC instance isn't allowed. NPC(const NPC &) = delete; NPC &operator=(const NPC &) = delete; NPC(NPC &&) noexcept = default; NPC &operator=(NPC &&) noexcept = default; ~NPC() noexcept = default; // Construct and Load() at the same time. explicit NPC(const DataNode &node); void Load(const DataNode &node); // Note: the Save() function can assume this is an instantiated mission, not // a template, so fleets will be replaced by individual ships already. void Save(DataWriter &out) const; // Determine if this NPC or NPC template uses well-defined data. // Returns the reason the NPC is not valid, or an empty string if valid. std::string Validate(bool asTemplate = false) const; const EsUuid &UUID() const noexcept; // Update or check spawning and despawning for this NPC. void UpdateSpawning(const PlayerInfo &player); bool ShouldSpawn() const; // Get the ships associated with this set of NPCs. const std::list<std::shared_ptr<Ship>> Ships() const; // Handle the given ShipEvent. void Do(const ShipEvent &event, PlayerInfo &player, UI *ui = nullptr, const Mission *caller = nullptr, bool isVisible = true); // Determine if the NPC is in a successful state, assuming the player is in the given system. // (By default, a despawnable NPC has succeeded and is not actually checked.) bool HasSucceeded(const System *playerSystem, bool ignoreIfDespawnable = true) const; // Check if the NPC is supposed to be accompanied and is not. bool IsLeftBehind(const System *playerSystem) const; // Determine if the NPC is in a failed state. A failed state is irrecoverable, except for // NPCs which would despawn upon the player's next landing. bool HasFailed() const; // Create a copy of this NPC but with the fleets replaced by the actual // ships they represent, wildcards in the conversation text replaced, etc. NPC Instantiate(std::map<std::string, std::string> &subs, const System *origin, const System *destination, int jumps, int64_t payload) const; private: // Handle any NPC mission actions that may have been triggered by a ShipEvent. void DoActions(const ShipEvent &event, bool newEvent, PlayerInfo &player, UI *ui, const Mission *caller); private: // The government of the ships in this NPC: const Government *government = nullptr; Personality personality; // The cargo ships in this NPC will be able to carry. FleetCargo cargo; bool overrideFleetCargo = false; EsUuid uuid; // Start out in a location matching this filter, or in a particular system: LocationFilter location; const System *system = nullptr; bool isAtDestination = false; // Start out landed on this planet. const Planet *planet = nullptr; // Dialog or conversation to show when all requirements for this NPC are met: std::string dialogText; ExclusiveItem<Phrase> dialogPhrase; ExclusiveItem<Conversation> conversation; // Conditions that must be met in order for this NPC to be placed or despawned: ConditionSet toSpawn; ConditionSet toDespawn; // Once true, the NPC will be spawned on takeoff and its success state will influence // the parent mission's ability to be completed. bool passedSpawnConditions = false; // Once true, the NPC will be despawned on landing and it will no longer contribute to // the parent mission's ability to be completed or failed. bool passedDespawnConditions = false; // Whether we have actually checked spawning conditions yet. (This // will generally be true, except when reloading a save.) bool checkedSpawnConditions = false; // The ships may be listed individually or referred to as a fleet, and may // be customized or just refer to stock objects: std::list<std::shared_ptr<Ship>> ships; std::list<const Ship *> stockShips; std::list<std::string> shipNames; std::list<ExclusiveItem<Fleet>> fleets; // This must be done to each ship in this set to complete the mission: int succeedIf = 0; int failIf = 0; bool mustEvade = false; bool mustAccompany = false; // The ShipEvent actions that have been done to each ship. std::map<const Ship *, int> shipEvents; // The NPCActions that this NPC can run on certain events/triggers. std::map<Trigger, NPCAction> npcActions; }; #endif
0
endless-sky-master
endless-sky-master/source/Mask.h
/* Mask.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef MASK_H_ #define MASK_H_ #include "Angle.h" #include "Point.h" #include <vector> class ImageBuffer; // Class representing the outline of an object, with functions for checking if a // line segment intersects that object or if a point is within a certain distance. // The outline is represented in polygonal form, which allows intersection tests // to be done much more efficiently than if we were testing individual pixels in // the image itself. class Mask { public: // Construct a mask from the alpha channel of an RGBA-formatted image. void Create(const ImageBuffer &image, int frame = 0); // Check whether a mask was successfully generated from the image. bool IsLoaded() const; // Check if this mask intersects the given line segment (from sA to vA). If // it does, return the fraction of the way along the segment where the // intersection occurs. The sA should be relative to this object's center, // while vA should be relative to sA. // If this object contains the given point, the return value is 0. If there // is no collision, the return value is 1. double Collide(Point sA, Point vA, Angle facing) const; // Check whether the mask contains the given point. bool Contains(Point point, Angle facing) const; // Find out whether this object (rotated and scaled as represented by the given // unit vector) is touching a ring defined by the given inner and outer ranges. bool WithinRing(Point point, Angle facing, double inner, double outer) const; // Find out how close the given point is to the mask. double Range(Point point, Angle facing) const; // Get the maximum distance from the center of this mask. double Radius() const; // Get the individual outlines that comprise this mask. const std::vector<std::vector<Point>> &Outlines() const; // Scale all the points in the mask. Mask operator*(double scale) const; friend Mask operator*(double scale, const Mask &mask); private: double Intersection(Point sA, Point vA) const; bool Contains(Point point) const; private: std::vector<std::vector<Point>> outlines; double radius = 0.; }; #endif
0
endless-sky-master
endless-sky-master/source/SpriteShader.cpp
/* SpriteShader.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "SpriteShader.h" #include "Point.h" #include "Screen.h" #include "Shader.h" #include "Sprite.h" #include <sstream> #include <vector> #ifdef ES_GLES // ES_GLES always uses the shader, not this, so use a dummy value to compile. // (the correct value is usually 0x8E46, so don't use that) #define GL_TEXTURE_SWIZZLE_RGBA 0xBEEF #endif using namespace std; namespace { Shader shader; GLint scaleI; GLint texI; GLint swizzleMaskI; GLint useSwizzleMaskI; GLint frameI; GLint frameCountI; GLint positionI; GLint transformI; GLint blurI; GLint clipI; GLint alphaI; GLint swizzlerI; GLuint vao; GLuint vbo; const int SWIZZLES = 29; } // Initialize the shaders. void SpriteShader::Init() { static const char *vertexCode = "// vertex sprite shader\n" "precision mediump float;\n" "uniform vec2 scale;\n" "uniform vec2 position;\n" "uniform mat2 transform;\n" "uniform vec2 blur;\n" "uniform float clip;\n" "in vec2 vert;\n" "out vec2 fragTexCoord;\n" "void main() {\n" " vec2 blurOff = 2.f * vec2(vert.x * abs(blur.x), vert.y * abs(blur.y));\n" " gl_Position = vec4((transform * (vert + blurOff) + position) * scale, 0, 1);\n" " vec2 texCoord = vert + vec2(.5, .5);\n" " fragTexCoord = vec2(texCoord.x, min(clip, texCoord.y)) + blurOff;\n" "}\n"; static const char *fragmentCode = "// fragment sprite shader\n" "precision mediump float;\n" #ifdef ES_GLES "precision mediump sampler2DArray;\n" #endif "uniform sampler2DArray tex;\n" "uniform sampler2DArray swizzleMask;\n" "uniform int useSwizzleMask;\n" "uniform float frame;\n" "uniform float frameCount;\n" "uniform vec2 blur;\n" "uniform int swizzler;\n" "uniform float alpha;\n" "const int range = 5;\n" "in vec2 fragTexCoord;\n" "out vec4 finalColor;\n" "void main() {\n" " float first = floor(frame);\n" " float second = mod(ceil(frame), frameCount);\n" " float fade = frame - first;\n" " vec4 color;\n" " if(blur.x == 0.f && blur.y == 0.f)\n" " {\n" " if(fade != 0.f)\n" " color = mix(\n" " texture(tex, vec3(fragTexCoord, first)),\n" " texture(tex, vec3(fragTexCoord, second)), fade);\n" " else\n" " color = texture(tex, vec3(fragTexCoord, first));\n" " }\n" " else\n" " {\n" " color = vec4(0., 0., 0., 0.);\n" " const float divisor = float(range * (range + 2) + 1);\n" " for(int i = -range; i <= range; ++i)\n" " {\n" " float scale = float(range + 1 - abs(i)) / divisor;\n" " vec2 coord = fragTexCoord + (blur * float(i)) / float(range);\n" " if(fade != 0.f)\n" " color += scale * mix(\n" " texture(tex, vec3(coord, first)),\n" " texture(tex, vec3(coord, second)), fade);\n" " else\n" " color += scale * texture(tex, vec3(coord, first));\n" " }\n" " }\n" " vec4 swizzleColor;\n" " switch (swizzler) {\n" // 0 red + yellow markings (republic) " case 0:\n" " swizzleColor = color.rgba;\n" " break;\n" // 1 red + magenta markings " case 1:\n" " swizzleColor = color.rbga;\n" " break;\n" // 2 green + yellow (free worlds) " case 2:\n" " swizzleColor = color.grba;\n" " break;\n" // 3 green + cyan " case 3:\n" " swizzleColor = color.brga;\n" " break;\n" // 4 blue + magenta (syndicate) " case 4:\n" " swizzleColor = color.gbra;\n" " break;\n" // 5 blue + cyan (merchant) " case 5:\n" " swizzleColor = color.bgra;\n" " break;\n" // 6 red and black (pirate) " case 6:\n" " swizzleColor = color.gbba;\n" " break;\n" // 7 pure red " case 7:\n" " swizzleColor = color.rbba;\n" " break;\n" // 8 faded red " case 8:\n" " swizzleColor = color.rgga;\n" " break;\n" // 9 pure black " case 9:\n" " swizzleColor = color.bbba;\n" " break;\n" // 10 faded black " case 10:\n" " swizzleColor = color.ggga;\n" " break;\n" // 11 pure white " case 11:\n" " swizzleColor = color.rrra;\n" " break;\n" // 12 darkened blue " case 12:\n" " swizzleColor = color.bbga;\n" " break;\n" // 13 pure blue " case 13:\n" " swizzleColor = color.bbra;\n" " break;\n" // 14 faded blue " case 14:\n" " swizzleColor = color.ggra;\n" " break;\n" // 15 darkened cyan " case 15:\n" " swizzleColor = color.bgga;\n" " break;\n" // 16 pure cyan " case 16:\n" " swizzleColor = color.brra;\n" " break;\n" // 17 faded cyan " case 17:\n" " swizzleColor = color.grra;\n" " break;\n" // 18 darkened green " case 18:\n" " swizzleColor = color.bgba;\n" " break;\n" // 19 pure green " case 19:\n" " swizzleColor = color.brba;\n" " break;\n" // 20 faded green " case 20:\n" " swizzleColor = color.grga;\n" " break;\n" // 21 darkened yellow " case 21:\n" " swizzleColor = color.ggba;\n" " break;\n" // 22 pure yellow " case 22:\n" " swizzleColor = color.rrba;\n" " break;\n" // 23 faded yellow " case 23:\n" " swizzleColor = color.rrga;\n" " break;\n" // 24 darkened magenta " case 24:\n" " swizzleColor = color.gbga;\n" " break;\n" // 25 pure magenta " case 25:\n" " swizzleColor = color.rbra;\n" " break;\n" // 26 faded magenta " case 26:\n" " swizzleColor = color.rgra;\n" " break;\n" // 27 red only (cloaked) " case 27:\n" " swizzleColor = vec4(color.b, 0.f, 0.f, color.a);\n" " break;\n" // 28 black only (outline) " case 28:\n" " swizzleColor = vec4(0.f, 0.f, 0.f, color.a);\n" " break;\n" " }\n" " if(useSwizzleMask > 0)\n" " {\n" " float factor = texture(swizzleMask, vec3(fragTexCoord, first)).r;\n" " color = color * factor + swizzleColor * (1.0 - factor);\n" " }\n" " else\n" " color = swizzleColor;\n" " finalColor = color * alpha;\n" "}\n"; shader = Shader(vertexCode, fragmentCode); scaleI = shader.Uniform("scale"); texI = shader.Uniform("tex"); frameI = shader.Uniform("frame"); frameCountI = shader.Uniform("frameCount"); positionI = shader.Uniform("position"); transformI = shader.Uniform("transform"); blurI = shader.Uniform("blur"); clipI = shader.Uniform("clip"); alphaI = shader.Uniform("alpha"); swizzlerI = shader.Uniform("swizzler"); swizzleMaskI = shader.Uniform("swizzleMask"); useSwizzleMaskI = shader.Uniform("useSwizzleMask"); // Generate the vertex data for drawing sprites. glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); GLfloat vertexData[] = { -.5f, -.5f, -.5f, .5f, .5f, -.5f, .5f, .5f }; glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glEnableVertexAttribArray(shader.Attrib("vert")); glVertexAttribPointer(shader.Attrib("vert"), 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); // unbind the VBO and VAO glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void SpriteShader::Draw(const Sprite *sprite, const Point &position, float zoom, int swizzle, float frame) { if(!sprite) return; Bind(); Add(Prepare(sprite, position, zoom, swizzle, frame)); Unbind(); } SpriteShader::Item SpriteShader::Prepare(const Sprite *sprite, const Point &position, float zoom, int swizzle, float frame) { if(!sprite) return {}; Item item; item.texture = sprite->Texture(); item.swizzleMask = sprite->SwizzleMask(); item.frame = frame; item.frameCount = sprite->Frames(); // Position. item.position[0] = static_cast<float>(position.X()); item.position[1] = static_cast<float>(position.Y()); // Rotation (none) and scale. item.transform[0] = sprite->Width() * zoom; item.transform[3] = sprite->Height() * zoom; // Swizzle. item.swizzle = swizzle; return item; } void SpriteShader::Bind() { glUseProgram(shader.Object()); glBindVertexArray(vao); GLfloat scale[2] = {2.f / Screen::Width(), -2.f / Screen::Height()}; glUniform2fv(scaleI, 1, scale); } void SpriteShader::Add(const Item &item, bool withBlur) { glUniform1i(texI, 0); glBindTexture(GL_TEXTURE_2D_ARRAY, item.texture); glUniform1i(swizzleMaskI, 1); // Don't mask full color swizzles that always apply to the whole ship sprite. glUniform1i(useSwizzleMaskI, item.swizzle >= 27 ? 0 : item.swizzleMask); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D_ARRAY, item.swizzleMask); glActiveTexture(GL_TEXTURE0); glUniform1f(frameI, item.frame); glUniform1f(frameCountI, item.frameCount); glUniform2fv(positionI, 1, item.position); glUniformMatrix2fv(transformI, 1, false, item.transform); // Special case: check if the blur should be applied or not. static const float UNBLURRED[2] = {0.f, 0.f}; glUniform2fv(blurI, 1, withBlur ? item.blur : UNBLURRED); glUniform1f(clipI, item.clip); glUniform1f(alphaI, item.alpha); // Bounds check for the swizzle value: int swizzle = (static_cast<size_t>(item.swizzle) >= SWIZZLES ? 0 : item.swizzle); // Set the color swizzle. glUniform1i(swizzlerI, swizzle); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } void SpriteShader::Unbind() { // Reset the swizzle. glUniform1i(swizzlerI, 0); glBindVertexArray(0); glUseProgram(0); }
0
endless-sky-master
endless-sky-master/source/CollisionSet.cpp
/* CollisionSet.cpp Copyright (c) 2016 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "CollisionSet.h" #include "Body.h" #include "Government.h" #include "Logger.h" #include "Mask.h" #include "Point.h" #include "Projectile.h" #include "Ship.h" #include <algorithm> #include <cstdlib> #include <numeric> #include <set> #include <string> using namespace std; namespace { // Maximum allowed projectile velocity. constexpr int MAX_VELOCITY = 450000; // Velocity used for any projectiles with v > MAX_VELOCITY constexpr int USED_MAX_VELOCITY = MAX_VELOCITY - 1; // Warn the user only once about too-large projectile velocities. bool warned = false; // Keep track of the closest collision found so far. If an external "closest // hit" value was given, there is no need to check collisions farther out // than that. class Closest { public: explicit Closest(double closestHit) : closest_dist(closestHit) , closest_body(nullptr) {} void TryNearer(double new_closest, Body *new_body) { if(new_closest >= closest_dist) return; closest_dist = new_closest; closest_body = new_body; } double GetClosestDistance() const { return closest_dist; } Body *GetClosestBody() const { return closest_body; } private: double closest_dist; Body *closest_body; }; } // Initialize a collision set. The cell size and cell count should both be // powers of two; otherwise, they are rounded down to a power of two. CollisionSet::CollisionSet(unsigned cellSize, unsigned cellCount) { // Right shift amount to convert from (x, y) location to grid (x, y). SHIFT = 0u; while(cellSize >>= 1u) ++SHIFT; CELL_SIZE = (1u << SHIFT); CELL_MASK = CELL_SIZE - 1u; // Number of grid rows and columns. CELLS = 1u; while(cellCount >>= 1u) CELLS <<= 1; WRAP_MASK = CELLS - 1u; // Just in case Clear() isn't called before objects are added: Clear(0); } // Clear all objects in the set. void CollisionSet::Clear(int step) { this->step = step; added.clear(); sorted.clear(); counts.clear(); all.clear(); // The counts vector starts with two sentinel slots that will be used in the // course of performing the radix sort. counts.resize(CELLS * CELLS + 2u, 0u); } // Add an object to the set. void CollisionSet::Add(Body &body) { // Calculate the range of (x, y) grid coordinates this object covers. int minX = static_cast<int>(body.Position().X() - body.Radius()) >> SHIFT; int minY = static_cast<int>(body.Position().Y() - body.Radius()) >> SHIFT; int maxX = static_cast<int>(body.Position().X() + body.Radius()) >> SHIFT; int maxY = static_cast<int>(body.Position().Y() + body.Radius()) >> SHIFT; // Add a pointer to this object in every grid cell it occupies. for(int y = minY; y <= maxY; ++y) { auto gy = y & WRAP_MASK; for(int x = minX; x <= maxX; ++x) { auto gx = x & WRAP_MASK; added.emplace_back(&body, all.size(), x, y); ++counts[gy * CELLS + gx + 2]; } } // Also save a pointer to this object irrespective of its grid location. all.emplace_back(&body); } // Finish adding objects (and organize them into the final lookup table). void CollisionSet::Finish() { // Perform a partial sum to convert the counts of items in each bin into the // index of the output element where that bin begins. partial_sum(counts.begin(), counts.end(), counts.begin()); // Allocate space for a sorted copy of the vector. sorted.resize(added.size()); // Now, perform a radix sort. for(const Entry &entry : added) { auto gx = entry.x & WRAP_MASK; auto gy = entry.y & WRAP_MASK; auto index = gy * CELLS + gx + 1; sorted[counts[index]++] = entry; } // Now, counts[index] is where a certain bin begins. // Initialize 'seen' with 0 seen.clear(); seen.resize(all.size()); seenEpoch = 0; } // Get the first object that collides with the given projectile. If a // "closest hit" value is given, update that value. Body *CollisionSet::Line(const Projectile &projectile, double *closestHit) const { // What objects the projectile hits depends on its government. const Government *pGov = projectile.GetGovernment(); // Convert the start and end coordinates to integers. Point from = projectile.Position(); Point to = from + projectile.Velocity(); return Line(from, to, closestHit, pGov, projectile.Target()); } // Check for collisions with a line, which may be a projectile's current // position or its entire expected trajectory (for the auto-firing AI). Body *CollisionSet::Line(const Point &from, const Point &to, double *closestHit, const Government *pGov, const Body *target) const { const int x = from.X(); const int y = from.Y(); const int endX = to.X(); const int endY = to.Y(); // Figure out which grid cell the line starts and ends in. int gx = x >> SHIFT; int gy = y >> SHIFT; const int endGX = endX >> SHIFT; const int endGY = endY >> SHIFT; Closest closer_result(closestHit ? *closestHit : 1.); // Special case, very common: the projectile is contained in one grid cell. // In this case, all the complicated code below can be skipped. if(gx == endGX && gy == endGY) { // Examine all objects in the current grid cell. const auto index = (gy & WRAP_MASK) * CELLS + (gx & WRAP_MASK); vector<Entry>::const_iterator it = sorted.begin() + counts[index]; vector<Entry>::const_iterator end = sorted.begin() + counts[index + 1]; for( ; it != end; ++it) { // Skip objects that were put in this same grid cell only because // of the cell coordinates wrapping around. if(it->x != gx || it->y != gy) continue; // Check if this projectile can hit this object. If either the // projectile or the object has no government, it will always hit. const Government *iGov = it->body->GetGovernment(); if(it->body != target && iGov && pGov && !iGov->IsEnemy(pGov)) continue; const Mask &mask = it->body->GetMask(step); Point offset = from - it->body->Position(); const double range = mask.Collide(offset, to - from, it->body->Facing()); closer_result.TryNearer(range, it->body); } if(closer_result.GetClosestDistance() < 1. && closestHit) *closestHit = closer_result.GetClosestDistance(); return closer_result.GetClosestBody(); } const Point pVelocity = (to - from); if(pVelocity.Length() > MAX_VELOCITY) { // Cap projectile velocity to prevent integer overflows. if(!warned) { Logger::LogError("Warning: maximum projectile velocity is " + to_string(MAX_VELOCITY)); warned = true; } Point newEnd = from + pVelocity.Unit() * USED_MAX_VELOCITY; return Line(from, newEnd, closestHit, pGov, target); } // When stepping from one grid cell to the next, we'll go in this direction. const int stepX = (x <= endX ? 1 : -1); const int stepY = (y <= endY ? 1 : -1); // Calculate the slope of the line, shifted so it is positive in both axes. const uint64_t mx = abs(endX - x); const uint64_t my = abs(endY - y); // Behave as if each grid cell has this width and height. This guarantees // that we only need to work with integer coordinates. const uint64_t scale = max<uint64_t>(mx, 1) * max<uint64_t>(my, 1); const uint64_t fullScale = CELL_SIZE * scale; // Get the "remainder" distance that we must travel in x and y in order to // reach the next grid cell. These ensure we only check grid cells which the // line will pass through. uint64_t rx = scale * (x & CELL_MASK); uint64_t ry = scale * (y & CELL_MASK); if(stepX > 0) rx = fullScale - rx; if(stepY > 0) ry = fullScale - ry; ++seenEpoch; while(true) { // Examine all objects in the current grid cell. auto i = (gy & WRAP_MASK) * CELLS + (gx & WRAP_MASK); vector<Entry>::const_iterator it = sorted.begin() + counts[i]; vector<Entry>::const_iterator end = sorted.begin() + counts[i + 1]; for( ; it != end; ++it) { // Skip objects that were put in this same grid cell only because // of the cell coordinates wrapping around. if(it->x != gx || it->y != gy) continue; if(seen[it->seenIndex] == seenEpoch) continue; seen[it->seenIndex] = seenEpoch; // Check if this projectile can hit this object. If either the // projectile or the object has no government, it will always hit. const Government *iGov = it->body->GetGovernment(); if(it->body != target && iGov && pGov && !iGov->IsEnemy(pGov)) continue; const Mask &mask = it->body->GetMask(step); Point offset = from - it->body->Position(); const double range = mask.Collide(offset, to - from, it->body->Facing()); closer_result.TryNearer(range, it->body); } // Check if we've found a collision or reached the final grid cell. if(closer_result.GetClosestBody() || (gx == endGX && gy == endGY)) break; // If not, move to the next one. Check whether rx / mx < ry / my. const int64_t diff = rx * my - ry * mx; if(!diff) { // The line is exactly intersecting a corner. rx = fullScale; ry = fullScale; // Make sure we don't step past the end grid. if(gx == endGX && gy + stepY == endGY) break; if(gy == endGY && gx + stepX == endGX) break; gx += stepX; gy += stepY; } else if(diff < 0) { // Because of the scale used, the rx coordinate is always divisible // by mx, so this will always come out even. The mx will always be // nonzero because otherwise, the comparison would have been false. ry -= my * (rx / mx); rx = fullScale; gx += stepX; } else { // Calculate how much x distance remains until the edge of the cell // after moving forward to the edge in the y direction. rx -= mx * (ry / my); ry = fullScale; gy += stepY; } } if(closer_result.GetClosestDistance() < 1. && closestHit) *closestHit = closer_result.GetClosestDistance(); return closer_result.GetClosestBody(); } // Get all objects within the given range of the given point. const vector<Body *> &CollisionSet::Circle(const Point &center, double radius) const { return Ring(center, 0., radius); } // Get all objects touching a ring with a given inner and outer range // centered at the given point. const vector<Body *> &CollisionSet::Ring(const Point &center, double inner, double outer) const { // Calculate the range of (x, y) grid coordinates this ring covers. const int minX = static_cast<int>(center.X() - outer) >> SHIFT; const int minY = static_cast<int>(center.Y() - outer) >> SHIFT; const int maxX = static_cast<int>(center.X() + outer) >> SHIFT; const int maxY = static_cast<int>(center.Y() + outer) >> SHIFT; ++seenEpoch; result.clear(); for(int y = minY; y <= maxY; ++y) { const auto gy = y & WRAP_MASK; for(int x = minX; x <= maxX; ++x) { const auto gx = x & WRAP_MASK; const auto index = gy * CELLS + gx; vector<Entry>::const_iterator it = sorted.begin() + counts[index]; vector<Entry>::const_iterator end = sorted.begin() + counts[index + 1]; for( ; it != end; ++it) { // Skip objects that were put in this same grid cell only because // of the cell coordinates wrapping around. if(it->x != x || it->y != y) continue; if(seen[it->seenIndex] == seenEpoch) continue; seen[it->seenIndex] = seenEpoch; const Mask &mask = it->body->GetMask(step); Point offset = center - it->body->Position(); const double length = offset.Length(); if((length <= outer && length >= inner) || mask.WithinRing(offset, it->body->Facing(), inner, outer)) result.push_back(it->body); } } } return result; } const vector<Body *> &CollisionSet::All() const { return all; }
0
endless-sky-master
endless-sky-master/source/Variant.cpp
/* Variant.cpp Copyright (c) 2022 by Amazinite Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Variant.h" #include "DataNode.h" #include "GameData.h" #include "Ship.h" #include <algorithm> using namespace std; Variant::Variant(const DataNode &node) { Load(node); } void Variant::Load(const DataNode &node) { if(node.Token(0) == "variant" && node.Size() >= 2) weight = max<int>(1, node.Value(1)); else if(node.Token(0) == "add" && node.Size() >= 3) weight = max<int>(1, node.Value(2)); for(const DataNode &child : node) { int n = 1; if(child.Size() >= 2 && child.Value(1) >= 1.) n = child.Value(1); ships.insert(ships.end(), n, GameData::Ships().Get(child.Token(0))); } } // Determine if this variant template uses well-defined data. bool Variant::IsValid() const { // At least one valid ship is enough to make the variant valid. if(any_of(ships.begin(), ships.end(), [](const Ship *const s) noexcept -> bool { return s->IsValid(); })) return true; return false; } int Variant::Weight() const { return weight; } const vector<const Ship *> &Variant::Ships() const { return ships; } // The strength of a variant is the sum of the strength of its ships. int64_t Variant::Strength() const { int64_t strength = 0; for(const Ship *ship : ships) strength += ship->Strength(); return strength; } bool Variant::operator==(const Variant &other) const { // Are the ships of other a permutation of this variant's? if(other.ships.size() != ships.size() || !is_permutation(ships.begin(), ships.end(), other.ships.begin())) return false; // If all checks have passed, these variants are equal. return true; } bool Variant::operator!=(const Variant &other) const { return !(*this == other); }
0
endless-sky-master
endless-sky-master/source/Depreciation.h
/* Depreciation.h Copyright (c) 2016 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef DEPRECIATION_H_ #define DEPRECIATION_H_ #include <cstdint> #include <map> #include <memory> #include <string> #include <vector> class DataNode; class DataWriter; class Outfit; class Ship; // Class for tracking depreciation records, by storing the day on which a given // outfit or ship was purchased. Any ship or outfit for which no record exists, // for example because it is plunder, counts as full depreciated. class Depreciation { public: // What fraction of its cost a fully depreciated item has left: static double Full(); public: // Load or save depreciation records. Multiple records may be saved in the // player info, under different names (e.g. fleet and stock depreciation). void Load(const DataNode &node); void Save(DataWriter &out, int day) const; // Check if any records have been loaded. bool IsLoaded() const; // If no records have been loaded, initialize with an entire fleet. void Init(const std::vector<std::shared_ptr<Ship>> &fleet, int day); // Add a ship, and all its outfits, to the depreciation record. void Buy(const Ship &ship, int day, Depreciation *source = nullptr, bool chassisOnly = false); // Add a single outfit to the depreciation record. void Buy(const Outfit *outfit, int day, Depreciation *source = nullptr); // Get the value of an entire fleet. int64_t Value(const std::vector<std::shared_ptr<Ship>> &fleet, int day, bool chassisOnly = false) const; // Get the value of a ship, along with all its outfits. int64_t Value(const Ship &ship, int day) const; // Get the value just of the chassis of a ship. int64_t Value(const Ship *ship, int day, int count = 1) const; // Get the value of an outfit. int64_t Value(const Outfit *outfit, int day, int count = 1) const; private: // "Sell" an item, removing it from the given record and returning the base // day for its depreciation. int Sell(std::map<int, int> &record) const; // Calculate depreciation: double Depreciate(const std::map<int, int> &record, int day, int count = 1) const; double Depreciate(int age) const; // Depreciation of an item for which no record exists. If buying, items // default to no depreciation. When selling, they default to full. double DefaultDepreciation() const; private: // This depreciation record is either a planet's stock or a player's fleet. // If it's the stock, it sells you the most depreciated item first, and once // it runs out of depreciated items all the rest have full price. If it is // your fleet, you sell the least depreciated items first. bool isStock = true; // Check if any data has been loaded. bool isLoaded = false; std::map<const Ship *, std::map<int, int>> ships; std::map<const Outfit *, std::map<int, int>> outfits; }; #endif
0
endless-sky-master
endless-sky-master/source/Files.cpp
/* Files.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Files.h" #include "File.h" #include "Logger.h" #include <SDL2/SDL.h> #if defined _WIN32 #include "text/Utf8.h" #define STRICT #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <dirent.h> #include <sys/stat.h> #include <unistd.h> #include <utime.h> #endif #include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <mutex> #include <stdexcept> using namespace std; namespace { string resources; string config; string dataPath; string imagePath; string soundPath; string savePath; string testPath; File errorLog; // Convert windows-style directory separators ('\\') to standard '/'. #if defined _WIN32 void FixWindowsSlashes(string &path) { for(char &c : path) if(c == '\\') c = '/'; } #endif // Open the given folder in a separate window. void OpenFolder(const string &path) { #if SDL_VERSION_ATLEAST(2, 0, 14) if(SDL_OpenURL(("file://" + path).c_str())) Logger::LogError("Warning: SDL_OpenURL failed with \"" + string(SDL_GetError()) + "\""); #elif defined(__linux__) // Some supported distributions do not have an up-to-date SDL. cout.flush(); if(int result = WEXITSTATUS(system(("xdg-open file://" + path).c_str()))) Logger::LogError("Warning: xdg-open failed with error code " + to_string(result) + "."); #else #warning SDL 2.0.14 or higher is needed for opening folders! Logger::LogError("Warning: No handler found to open \"" + path + "\" in a new window."); #endif } } void Files::Init(const char * const *argv) { // Parse the command line arguments to see if the user has specified // different directories to use. for(const char * const *it = argv + 1; *it; ++it) { string arg = *it; if((arg == "-r" || arg == "--resources") && *++it) resources = *it; else if((arg == "-c" || arg == "--config") && *++it) config = *it; } if(resources.empty()) { // Find the path to the resource directory. This will depend on the // operating system, and can be overridden by a command line argument. char *str = SDL_GetBasePath(); if(!str) throw runtime_error("Unable to get path to resource directory!"); resources = str; SDL_free(str); } #if defined _WIN32 FixWindowsSlashes(resources); #endif if(resources.back() != '/') resources += '/'; #if defined __linux__ || defined __FreeBSD__ || defined __DragonFly__ // Special case, for Linux: the resource files are not in the same place as // the executable, but are under the same prefix (/usr or /usr/local). static const string LOCAL_PATH = "/usr/local/"; static const string STANDARD_PATH = "/usr/"; static const string RESOURCE_PATH = "share/games/endless-sky/"; if(!resources.compare(0, LOCAL_PATH.length(), LOCAL_PATH)) resources = LOCAL_PATH + RESOURCE_PATH; else if(!resources.compare(0, STANDARD_PATH.length(), STANDARD_PATH)) resources = STANDARD_PATH + RESOURCE_PATH; #endif // If the resources are not here, search in the directories containing this // one. This allows, for example, a Mac app that does not actually have the // resources embedded within it. while(!Exists(resources + "credits.txt")) { size_t pos = resources.rfind('/', resources.length() - 2); if(pos == string::npos || pos == 0) throw runtime_error("Unable to find the resource directories!"); resources.erase(pos + 1); } dataPath = resources + "data/"; imagePath = resources + "images/"; soundPath = resources + "sounds/"; if(config.empty()) { // Create the directory for the saved games, preferences, etc., if necessary. char *str = SDL_GetPrefPath(nullptr, "endless-sky"); if(!str) throw runtime_error("Unable to get path to config directory!"); config = str; SDL_free(str); } #ifdef _WIN32 FixWindowsSlashes(config); #endif if(config.back() != '/') config += '/'; if(!Exists(config)) throw runtime_error("Unable to create config directory!"); savePath = config + "saves/"; CreateFolder(savePath); // Create the "plugins" directory if it does not yet exist, so that it is // clear to the user where plugins should go. CreateFolder(config + "plugins/"); // Check that all the directories exist. if(!Exists(dataPath) || !Exists(imagePath) || !Exists(soundPath)) throw runtime_error("Unable to find the resource directories!"); if(!Exists(savePath)) throw runtime_error("Unable to create save directory!"); if(!Exists(config + "plugins/")) throw runtime_error("Unable to create plugins directory!"); } const string &Files::Resources() { return resources; } const string &Files::Config() { return config; } const string &Files::Data() { return dataPath; } const string &Files::Images() { return imagePath; } const string &Files::Sounds() { return soundPath; } const string &Files::Saves() { return savePath; } const string &Files::Tests() { return testPath; } vector<string> Files::List(string directory) { if(directory.empty() || directory.back() != '/') directory += '/'; vector<string> list; #if defined _WIN32 WIN32_FIND_DATAW ffd; HANDLE hFind = FindFirstFileW(Utf8::ToUTF16(directory + '*').c_str(), &ffd); if(!hFind) return list; do { if(ffd.cFileName[0] == '.') continue; if(!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) list.push_back(directory + Utf8::ToUTF8(ffd.cFileName)); } while(FindNextFileW(hFind, &ffd)); FindClose(hFind); #else DIR *dir = opendir(directory.c_str()); if(!dir) return list; while(true) { dirent *ent = readdir(dir); if(!ent) break; // Skip dotfiles (including "." and ".."). if(ent->d_name[0] == '.') continue; string name = directory + ent->d_name; // Don't assume that this operating system's implementation of dirent // includes the t_type field; in particular, on Windows it will not. struct stat buf; stat(name.c_str(), &buf); bool isRegularFile = S_ISREG(buf.st_mode); if(isRegularFile) list.push_back(name); } closedir(dir); #endif sort(list.begin(), list.end()); return list; } // Get a list of any directories in the given directory. vector<string> Files::ListDirectories(string directory) { if(directory.empty() || directory.back() != '/') directory += '/'; vector<string> list; #if defined _WIN32 WIN32_FIND_DATAW ffd; HANDLE hFind = FindFirstFileW(Utf8::ToUTF16(directory + '*').c_str(), &ffd); if(!hFind) return list; do { if(ffd.cFileName[0] == '.') continue; if(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) list.push_back(directory + Utf8::ToUTF8(ffd.cFileName) + '/'); } while(FindNextFileW(hFind, &ffd)); FindClose(hFind); #else DIR *dir = opendir(directory.c_str()); if(!dir) return list; while(true) { dirent *ent = readdir(dir); if(!ent) break; // Skip dotfiles (including "." and ".."). if(ent->d_name[0] == '.') continue; string name = directory + ent->d_name; // Don't assume that this operating system's implementation of dirent // includes the t_type field; in particular, on Windows it will not. struct stat buf; stat(name.c_str(), &buf); bool isDirectory = S_ISDIR(buf.st_mode); if(isDirectory) { if(name.back() != '/') name += '/'; list.push_back(name); } } closedir(dir); #endif sort(list.begin(), list.end()); return list; } vector<string> Files::RecursiveList(const string &directory) { vector<string> list; RecursiveList(directory, &list); sort(list.begin(), list.end()); return list; } void Files::RecursiveList(string directory, vector<string> *list) { if(directory.empty() || directory.back() != '/') directory += '/'; #if defined _WIN32 WIN32_FIND_DATAW ffd; HANDLE hFind = FindFirstFileW(Utf8::ToUTF16(directory + '*').c_str(), &ffd); if(hFind == INVALID_HANDLE_VALUE) return; do { if(ffd.cFileName[0] == '.') continue; if(!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) list->push_back(directory + Utf8::ToUTF8(ffd.cFileName)); else RecursiveList(directory + Utf8::ToUTF8(ffd.cFileName) + '/', list); } while(FindNextFileW(hFind, &ffd)); FindClose(hFind); #else DIR *dir = opendir(directory.c_str()); if(!dir) return; while(true) { dirent *ent = readdir(dir); if(!ent) break; // Skip dotfiles (including "." and ".."). if(ent->d_name[0] == '.') continue; string name = directory + ent->d_name; // Don't assume that this operating system's implementation of dirent // includes the t_type field; in particular, on Windows it will not. struct stat buf; stat(name.c_str(), &buf); bool isRegularFile = S_ISREG(buf.st_mode); bool isDirectory = S_ISDIR(buf.st_mode); if(isRegularFile) list->push_back(name); else if(isDirectory) RecursiveList(name + '/', list); } closedir(dir); #endif } bool Files::Exists(const string &filePath) { #if defined _WIN32 struct _stat buf; return !_wstat(Utf8::ToUTF16(filePath).c_str(), &buf); #else struct stat buf; return !stat(filePath.c_str(), &buf); #endif } time_t Files::Timestamp(const string &filePath) { #if defined _WIN32 struct _stat buf; _wstat(Utf8::ToUTF16(filePath).c_str(), &buf); #else struct stat buf; stat(filePath.c_str(), &buf); #endif return buf.st_mtime; } void Files::Copy(const string &from, const string &to) { #if defined _WIN32 CopyFileW(Utf8::ToUTF16(from).c_str(), Utf8::ToUTF16(to).c_str(), false); #else Write(to, Read(from)); // Preserve the timestamps of the original file. struct stat buf; if(stat(from.c_str(), &buf)) Logger::LogError("Error: Cannot stat \"" + from + "\"."); else { struct utimbuf times; times.actime = buf.st_atime; times.modtime = buf.st_mtime; if(utime(to.c_str(), &times)) Logger::LogError("Error: Failed to preserve the timestamps for \"" + to + "\"."); } #endif } void Files::Move(const string &from, const string &to) { #if defined _WIN32 MoveFileExW(Utf8::ToUTF16(from).c_str(), Utf8::ToUTF16(to).c_str(), MOVEFILE_REPLACE_EXISTING); #else rename(from.c_str(), to.c_str()); #endif } void Files::Delete(const string &filePath) { #if defined _WIN32 DeleteFileW(Utf8::ToUTF16(filePath).c_str()); #else unlink(filePath.c_str()); #endif } // Get the filename from a path. string Files::Name(const string &path) { // string::npos = -1, so if there is no '/' in the path this will // return the entire string, i.e. path.substr(0). return path.substr(path.rfind('/') + 1); } FILE *Files::Open(const string &path, bool write) { #if defined _WIN32 FILE *file = nullptr; _wfopen_s(&file, Utf8::ToUTF16(path).c_str(), write ? L"w" : L"rb"); return file; #else return fopen(path.c_str(), write ? "wb" : "rb"); #endif } string Files::Read(const string &path) { File file(path); return Read(file); } string Files::Read(FILE *file) { string result; if(!file) return result; // Find the remaining number of bytes in the file. size_t start = ftell(file); fseek(file, 0, SEEK_END); size_t size = ftell(file) - start; // Reserve one extra byte because DataFile appends a '\n' to the end of each // file it reads, and that's the most common use of this function. result.reserve(size + 1); result.resize(size); fseek(file, start, SEEK_SET); // Read the file data. size_t bytes = fread(&result[0], 1, result.size(), file); if(bytes != result.size()) throw runtime_error("Error reading file!"); return result; } void Files::Write(const string &path, const string &data) { File file(path, true); Write(file, data); } void Files::Write(FILE *file, const string &data) { if(!file) return; fwrite(&data[0], 1, data.size(), file); } void Files::CreateFolder(const std::string &path) { if(Exists(path)) return; #ifdef _WIN32 CreateDirectoryW(Utf8::ToUTF16(path).c_str(), nullptr); #else mkdir(path.c_str(), 0700); #endif } // Open this user's plugins directory in their native file explorer. void Files::OpenUserPluginFolder() { OpenFolder(Config() + "plugins"); } void Files::LogErrorToFile(const string &message) { if(!errorLog) { errorLog = File(config + "errors.txt", true); if(!errorLog) { cerr << "Unable to create \"errors.txt\" " << (config.empty() ? "in current directory" : "in \"" + config + "\"") << endl; return; } } Write(errorLog, message); fwrite("\n", 1, 1, errorLog); fflush(errorLog); }
0
endless-sky-master
endless-sky-master/source/Fleet.h
/* Fleet.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef FLEET_H_ #define FLEET_H_ #include "FleetCargo.h" #include "Personality.h" #include "Sale.h" #include "Variant.h" #include "WeightedList.h" #include <list> #include <memory> #include <set> #include <string> #include <utility> #include <vector> class DataNode; class Government; class Outfit; class Phrase; class Planet; class Ship; class System; // A fleet represents a collection of ships that may enter a system or be used // as NPCs in a mission. Each fleet contains one or more "variants," each of // which can occur with a different probability, and each of those variants // lists one or more ships. All the ships in a fleet share a certain government, // AI personality, and set of friendly and hostile "hail" messages, and the ship // names are chosen based on a given random "phrase" generator. class Fleet { public: Fleet() = default; // Construct and Load() at the same time. Fleet(const DataNode &node); void Load(const DataNode &node); // Determine if this fleet template uses well-defined data. bool IsValid(bool requireGovernment = true) const; // Ensure any variant selected during gameplay will have at least one ship to spawn. void RemoveInvalidVariants(); // Get the government of this fleet. const Government *GetGovernment() const; // Choose a fleet to be created during flight, and have it enter the system via jump or planetary departure. void Enter(const System &system, std::list<std::shared_ptr<Ship>> &ships, const Planet *planet = nullptr) const; // Place a fleet in the given system, already "in action." If the carried flag is set, only // uncarried ships will be added to the list (as any carriables will be stored in bays). void Place(const System &system, std::list<std::shared_ptr<Ship>> &ships, bool carried = true, bool addCargo = true) const; // Do the randomization to make a ship enter or be in the given system. // Return the system that was chosen for the ship to enter from. static const System *Enter(const System &system, Ship &ship, const System *source = nullptr); static void Place(const System &system, Ship &ship); int64_t Strength() const; private: static std::pair<Point, double> ChooseCenter(const System &system); std::vector<std::shared_ptr<Ship>> Instantiate(const std::vector<const Ship *> &ships) const; bool PlaceFighter(std::shared_ptr<Ship> fighter, std::vector<std::shared_ptr<Ship>> &placed) const; private: std::string fleetName; const Government *government = nullptr; const Phrase *names = nullptr; const Phrase *fighterNames = nullptr; WeightedList<Variant> variants; // The cargo ships in this fleet will carry. FleetCargo cargo; Personality personality; Personality fighterPersonality; }; #endif
0
endless-sky-master
endless-sky-master/source/Wormhole.h
/* Wormhole.h Copyright (c) 2021 by quyykk Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef WORMHOLE_H_ #define WORMHOLE_H_ #include "Color.h" #include "ExclusiveItem.h" #include <string> #include <unordered_map> class DataNode; class Planet; class System; // Class representing a wormhole in a planet. class Wormhole { public: // Define the constructor to set "linkColor" to the desired default color. Wormhole(); // Load a wormhole's description from a file. void Load(const DataNode &node); // Load a wormhole from a given planet. void LoadFromPlanet(const Planet &planet); // Check if this wormhole has been defined. bool IsValid() const; // Returns the planet corresponding to this wormhole. const Planet *GetPlanet() const; // Returns this wormhole's name. const std::string &Name() const; // Whether this wormhole's link appears on the map. bool IsMappable() const; // Returns this wormhole's arrow color. // The link color will be a dimmed version of this one. const Color *GetLinkColor() const; // Whether this wormhole was auto-generated. This is used to // update this wormhole in game events that update the corresponding // planet. bool IsAutogenerated() const; const System &WormholeSource(const System &to) const; const System &WormholeDestination(const System &from) const; const std::unordered_map<const System *, const System *> &Links() const; void SetPlanet(const Planet &planet); private: // Generate any links from the planet. void GenerateLinks(); private: bool isDefined = false; bool isAutogenerated = false; const Planet *planet = nullptr; std::string name = "???"; bool mappable = false; ExclusiveItem<Color> linkColor; std::unordered_map<const System *, const System *> links; }; #endif
0
endless-sky-master
endless-sky-master/source/Distribution.h
/* Distribution.h Copyright (c) 2022 by DeBlister Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef DISTRIBUTION_H_ #define DISTRIBUTION_H_ #include <utility> class Angle; // A class which generates an angle of inaccuracy for a projectile // given its inaccuracy value and type. class Distribution { public: enum class Type { Narrow = 0, Medium = 1, Wide = 2, Uniform = 3, Triangular = 4 }; public: // Generate an angle that gets projectile heading // when combined with hardpoint aim. static Angle GenerateInaccuracy(double value, std::pair<Type, bool> distribution); }; #endif
0
endless-sky-master
endless-sky-master/source/ConversationPanel.cpp
/* ConversationPanel.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ConversationPanel.h" #include "text/alignment.hpp" #include "BoardingPanel.h" #include "Color.h" #include "Command.h" #include "Conversation.h" #include "text/DisplayText.h" #include "FillShader.h" #include "text/Font.h" #include "text/FontSet.h" #include "text/Format.h" #include "GameData.h" #include "Government.h" #include "MapDetailPanel.h" #include "PlayerInfo.h" #include "Point.h" #include "Preferences.h" #include "Screen.h" #include "shift.h" #include "Ship.h" #include "Sprite.h" #include "SpriteSet.h" #include "SpriteShader.h" #include "UI.h" #if defined _WIN32 #include "Files.h" #endif #include <iterator> using namespace std; namespace { #if defined _WIN32 size_t PATH_LENGTH; #endif // Width of the conversation text. const int WIDTH = 540; // Margin on either side of the text. const int MARGIN = 20; } // Constructor. ConversationPanel::ConversationPanel(PlayerInfo &player, const Conversation &conversation, const Mission *caller, const System *system, const shared_ptr<Ship> &ship, bool useTransactions) : player(player), caller(caller), useTransactions(useTransactions), conversation(conversation), scroll(0.), system(system), ship(ship) { #if defined _WIN32 PATH_LENGTH = Files::Saves().size(); #endif // These substitutions need to be applied on the fly as each paragraph of // text is prepared for display. subs["<first>"] = player.FirstName(); subs["<last>"] = player.LastName(); if(ship) subs["<ship>"] = ship->Name(); else if(player.Flagship()) subs["<ship>"] = player.Flagship()->Name(); // Start a PlayerInfo transaction to prevent saves during the conversation // from recording partial results. if(useTransactions) player.StartTransaction(); // Begin at the start of the conversation. Goto(0); } void ConversationPanel::SetCallback(function<void(int)> fun) { callback = std::move(fun); } // Draw this panel. void ConversationPanel::Draw() { // Dim out everything outside this panel. DrawBackdrop(); // Draw the panel itself, stretching from top to bottom of the screen on // the left side. The edge sprite contains 10 pixels of the margin; the rest // of the margin is included in the filled rectangle drawn here: const Color &back = *GameData::Colors().Get("conversation background"); double boxWidth = WIDTH + 2. * MARGIN - 10.; FillShader::Fill( Point(Screen::Left() + .5 * boxWidth, 0.), Point(boxWidth, Screen::Height()), back); const Sprite *edgeSprite = SpriteSet::Get("ui/right edge"); if(edgeSprite->Height()) { // If the screen is high enough, the edge sprite should repeat. double spriteHeight = edgeSprite->Height(); Point pos( Screen::Left() + boxWidth + .5 * edgeSprite->Width(), Screen::Top() + .5 * spriteHeight); for( ; pos.Y() - .5 * spriteHeight < Screen::Bottom(); pos.Y() += spriteHeight) SpriteShader::Draw(edgeSprite, pos); } // Get the font and colors we'll need for drawing everything. const Font &font = FontSet::Get(14); const Color &selectionColor = *GameData::Colors().Get("faint"); const Color &dim = *GameData::Colors().Get("dim"); const Color &gray = *GameData::Colors().Get("medium"); const Color &bright = *GameData::Colors().Get("bright"); const Color &dark = *GameData::Colors().Get("dark"); // Figure out where we should start drawing. Point point( Screen::Left() + MARGIN, Screen::Top() + MARGIN + scroll); // Draw all the conversation text up to this point. for(const Paragraph &it : text) point = it.Draw(point, gray); // Draw whatever choices are being presented. if(node < 0) { // The conversation has already ended. Draw a "done" button. static const string done = "[done]"; int width = font.Width(done); int height = font.Height(); Point off(Screen::Left() + MARGIN + WIDTH - width, point.Y()); font.Draw(done, off, bright); // Handle clicks on this button. AddZone(Rectangle::FromCorner(off, Point(width, height)), [this](){ this->Exit(); }); } else if(choices.empty()) { // This conversation node is prompting the player to enter their name. Point fieldSize(150, 20); const auto layout = Layout(fieldSize.X() - 10, Truncate::FRONT); for(int side = 0; side < 2; ++side) { Point center = point + Point(side ? 420 : 190, 7); Point unselected = point + Point(side ? 190 : 420, 7); // Handle mouse clicks in whatever field is not selected. if(side != choice) { AddZone(Rectangle(center, fieldSize), [this, side](){ this->ClickName(side); }); continue; } // Color selected text box, or flicker if user attempts an error. FillShader::Fill(center, fieldSize, (flickerTime % 6 > 3) ? dim : selectionColor); if(flickerTime) --flickerTime; // Fill non-selected text box with dimmer color. FillShader::Fill(unselected, fieldSize, dark); // Draw the text cursor. center.X() += font.FormattedWidth({choice ? lastName : firstName, layout}) - 67; FillShader::Fill(center, Point(1., 16.), dim); } font.Draw("First name:", point + Point(40, 0), dim); font.Draw({firstName, layout}, point + Point(120, 0), choice ? gray : bright); font.Draw("Last name:", point + Point(270, 0), dim); font.Draw({lastName, layout}, point + Point(350, 0), choice ? bright : gray); // Draw the OK button, and remember its location. static const string ok = "[ok]"; int width = font.Width(ok); int height = font.Height(); Point off(Screen::Left() + MARGIN + WIDTH - width, point.Y()); font.Draw(ok, off, bright); // Handle clicks on this button. AddZone(Rectangle::FromCorner(off, Point(width, height)), SDLK_RETURN); } else { string label = "0:"; int index = 0; for(const auto &it : choices) { ++label[0]; const auto &paragraph = it.first; Point center = point + paragraph.Center(); Point size(WIDTH, paragraph.Height()); auto zone = Rectangle::FromCorner(point, size); // If the mouse is hovering over this choice then we need to highlight it. if(isHovering && zone.Contains(hoverPoint)) choice = index; if(index == choice) FillShader::Fill(center + Point(-5, 0), size + Point(30, 0), selectionColor); AddZone(zone, [this, index](){ this->ClickChoice(index); }); ++index; font.Draw(label, point + Point(-15, 0), dim); point = paragraph.Draw(point, bright); } } // Store the total height of the text. maxScroll = min(0., Screen::Top() - (point.Y() - scroll) + font.Height() + 15.); // Reset the hover flag. If the mouse is still moving than the flag will be set in the next frame. isHovering = false; } // Handle key presses. bool ConversationPanel::KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) { // Map popup happens when you press the map key, unless the name text entry // fields are currently active. The name text entry fields are active if // choices is empty and we aren't at the end of the conversation. if(command.Has(Command::MAP) && (!choices.empty() || node < 0)) GetUI()->Push(new MapDetailPanel(player, system)); if(node < 0) { // If the conversation has ended, the only possible action is to exit. if(isNewPress && (key == SDLK_RETURN || key == SDLK_KP_ENTER || key == 'd')) { Exit(); return true; } return false; } if(choices.empty()) { // Right now we're asking the player to enter their name. string &name = (choice ? lastName : firstName); string &otherName = (choice ? firstName : lastName); // Allow editing the text. The tab key toggles to the other entry field, // as does the return key if the other field is still empty. if(key >= ' ' && key <= '~') { // Apply the shift or caps lock key. char c = ((mod & KMOD_SHIFT) ? SHIFT[key] : key); // Caps lock should shift letters, but not any other keys. if((mod & KMOD_CAPS) && c >= 'a' && c <= 'z') c += 'A' - 'a'; // Don't allow characters that can't be used in a file name. static const string FORBIDDEN = "/\\?*:|\"<>~"; // Prevent the name from being so large that it cannot be saved. // Most path components can be at most 255 bytes. size_t MAX_NAME_LENGTH = 250; #if defined _WIN32 MAX_NAME_LENGTH -= PATH_LENGTH; #endif if(FORBIDDEN.find(c) == string::npos && (name.size() + otherName.size()) < MAX_NAME_LENGTH) name += c; else flickerTime = 18; } else if((key == SDLK_DELETE || key == SDLK_BACKSPACE) && !name.empty()) name.erase(name.size() - 1); else if(key == '\t' || ((key == SDLK_RETURN || key == SDLK_KP_ENTER) && otherName.empty())) choice = !choice; else if((key == SDLK_RETURN || key == SDLK_KP_ENTER) && (firstName.empty() || lastName.empty())) flickerTime = 18; else if((key == SDLK_RETURN || key == SDLK_KP_ENTER) && !firstName.empty() && !lastName.empty()) { // Display the name the player entered. string name = "\t\tName: " + firstName + " " + lastName + ".\n"; text.emplace_back(name); player.SetName(firstName, lastName); subs["<first>"] = player.FirstName(); subs["<last>"] = player.LastName(); Goto(node + 1); } else return false; return true; } // Let the player select choices by using the arrow keys and then pressing // return, or by pressing a number key. if(key == SDLK_UP && choice > 0) --choice; else if(key == SDLK_DOWN && choice + 1 < static_cast<int>(choices.size())) ++choice; else if((key == SDLK_RETURN || key == SDLK_KP_ENTER) && isNewPress && choice < static_cast<int>(choices.size())) Goto(conversation.NextNodeForChoice(node, MapChoice(choice)), choice); else if(key >= '1' && key < static_cast<SDL_Keycode>('1' + choices.size())) Goto(conversation.NextNodeForChoice(node, MapChoice(key - '1')), key - '1'); else if(key >= SDLK_KP_1 && key < static_cast<SDL_Keycode>(SDLK_KP_1 + choices.size())) Goto(conversation.NextNodeForChoice(node, MapChoice(key - SDLK_KP_1)), key - SDLK_KP_1); else return false; return true; } // Allow scrolling by click and drag. bool ConversationPanel::Drag(double dx, double dy) { scroll = min(0., max(maxScroll, scroll + dy)); return true; } // Handle the scroll wheel. bool ConversationPanel::Scroll(double dx, double dy) { return Drag(0., dy * Preferences::ScrollSpeed()); } // Handle selecting choices by hovering with the mouse. bool ConversationPanel::Hover(int x, int y) { hoverPoint = Point(x, y); isHovering = true; return true; } // The player just selected the given choice. void ConversationPanel::Goto(int index, int selectedChoice) { const ConditionsStore &conditions = player.Conditions(); Format::ConditionGetter getter = [&conditions](const std::string &str, size_t start, size_t length) -> int64_t { return conditions.Get(str.substr(start, length)); }; if(index) { // Add the chosen option to the text. if(selectedChoice >= 0 && selectedChoice < static_cast<int>(choices.size())) text.emplace_back(next(choices.begin(), selectedChoice)->first); // Scroll to the start of the new text, unless the conversation ended. if(index >= 0) { scroll = -11; for(const Paragraph &it : text) scroll -= it.Height(); } } // We'll need to reload the choices from whatever new node we arrive at. choices.clear(); node = index; // Not every conversation node allows a choice. Move forward through the // nodes until we encounter one that does, or the conversation ends. while(node >= 0 && !conversation.HasAnyChoices(player.Conditions(), node)) { int choice = 0; // Skip empty choices. if(conversation.IsChoice(node)) { node = conversation.StepToNextNode(node); continue; } if(conversation.IsBranch(node)) { // Branch nodes change the flow of the conversation based on the // player's condition variables rather than player input. choice = !conversation.Conditions(node).Test(player.Conditions()); } else if(conversation.IsAction(node)) { // Action nodes are able to perform various actions, e.g. changing // the player's conditions, granting payments, triggering events, // and more. They are not allowed to spawn additional UI elements. conversation.GetAction(node).Do(player, nullptr, caller); } else if(conversation.ShouldDisplayNode(player.Conditions(), node)) { // This is an ordinary conversation node which should be displayed. // Perform any necessary text replacement, and add the text to the display. string altered = Format::ExpandConditions(Format::Replace(conversation.Text(node), subs), getter); text.emplace_back(altered, conversation.Scene(node), text.empty()); } else { // This conversation node should not be displayed, so skip its goto. node = conversation.StepToNextNode(node); continue; } node = conversation.NextNodeForChoice(node, choice); } // Display whatever choices are being offered to the player. for(int i = 0; i < conversation.Choices(node); ++i) if(conversation.ShouldDisplayNode(player.Conditions(), node, i)) { string altered = Format::ExpandConditions(Format::Replace(conversation.Text(node, i), subs), getter); choices.emplace_back(Paragraph(altered), i); } // This is a safeguard in case of logic errors, to ensure we don't set the player name. if(choices.empty() && conversation.Choices(node) != 0) { node = Conversation::DECLINE; } this->choice = 0; } // Exit this panel and do whatever needs to happen next. void ConversationPanel::Exit() { // Finish the PlayerInfo transaction so any changes get saved again. if(useTransactions) player.FinishTransaction(); GetUI()->Pop(this); // Some conversations may be offered from an NPC, e.g. an assisting or // boarding mission's `on offer`, or from completing a mission's NPC // block (e.g. scanning or boarding or killing all required targets). if(node == Conversation::DIE || node == Conversation::EXPLODE) player.Die(node, ship); else if(ship) { // A forced-launch ending (LAUNCH, FLEE, or DEPART) destroys any NPC. if(Conversation::RequiresLaunch(node)) ship->Destroy(); // Only show the BoardingPanel for a hostile NPC that is being boarded. // (NPC completion conversations can result from non-boarding events.) // TODO: Is there a better / more robust boarding check than relative position? else if((node != Conversation::ACCEPT || player.CaptureOverriden(ship)) && ship->GetGovernment()->IsEnemy() && !ship->IsDestroyed() && ship->IsDisabled() && ship->Position().Distance(player.Flagship()->Position()) <= 1.) GetUI()->Push(new BoardingPanel(player, ship)); } // Call the exit response handler to manage the conversation's effect // on the player's missions, or force takeoff from a planet. if(callback) callback(node); } // The player just clicked one of the two name entry text fields. void ConversationPanel::ClickName(int side) { choice = side; } // The player just clicked on a conversation choice. void ConversationPanel::ClickChoice(int index) { Goto(conversation.NextNodeForChoice(node, MapChoice(index)), index); } // Given an index into the list of displayed choices (i.e. not including // conditionally-skipped choices), return its "raw index" in the conversation // (i.e. including conditionally-skipped choices) int ConversationPanel::MapChoice(int n) const { if(n < 0 || n >= static_cast<int>(choices.size())) return 0; else return next(choices.cbegin(), n)->second; } // Paragraph constructor. ConversationPanel::Paragraph::Paragraph(const string &text, const Sprite *scene, bool isFirst) : scene(scene), isFirst(isFirst) { wrap.SetAlignment(Alignment::JUSTIFIED); wrap.SetWrapWidth(WIDTH); wrap.SetFont(FontSet::Get(14)); wrap.Wrap(text); } // Get the height of this paragraph (including any "scene" image). int ConversationPanel::Paragraph::Height() const { int height = wrap.Height(); if(scene) height += 20 * !isFirst + scene->Height() + 20; return height; } // Get the center point of this paragraph. Point ConversationPanel::Paragraph::Center() const { return Point(.5 * WIDTH, .5 * (Height() - wrap.ParagraphBreak())); } // Draw this paragraph, and return the point that the next paragraph below it // should be drawn at. Point ConversationPanel::Paragraph::Draw(Point point, const Color &color) const { if(scene) { Point offset(WIDTH / 2, 20 * !isFirst + scene->Height() / 2); SpriteShader::Draw(scene, point + offset); point.Y() += 20 * !isFirst + scene->Height() + 20; } wrap.Draw(point, color); point.Y() += wrap.Height(); return point; }
0
endless-sky-master
endless-sky-master/source/pi.h
/* pi.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef PI_H_ #define PI_H_ // Constants to replace M_PI (which is not available on all operating systems). constexpr double PI = 3.14159265358979323846; constexpr double TO_RAD = PI / 180.; constexpr double TO_DEG = 180. / PI; #endif
0
endless-sky-master
endless-sky-master/source/ConditionsStore.cpp
/* ConditionsStore.cpp Copyright (c) 2020-2022 by Peter van der Meer Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ConditionsStore.h" #include "DataNode.h" #include "DataWriter.h" #include "Logger.h" #include <utility> using namespace std; // Default constructor ConditionsStore::DerivedProvider::DerivedProvider(const string &name, bool isPrefixProvider) : name(name), isPrefixProvider(isPrefixProvider) { } void ConditionsStore::DerivedProvider::SetGetFunction(function<int64_t(const string &)> newGetFun) { getFunction = std::move(newGetFun); } void ConditionsStore::DerivedProvider::SetHasFunction(function<bool(const string &)> newHasFun) { hasFunction = std::move(newHasFun); } void ConditionsStore::DerivedProvider::SetSetFunction(function<bool(const string &, int64_t)> newSetFun) { setFunction = std::move(newSetFun); } void ConditionsStore::DerivedProvider::SetEraseFunction(function<bool(const string &)> newEraseFun) { eraseFunction = std::move(newEraseFun); } ConditionsStore::ConditionEntry::operator int64_t() const { if(!provider) return value; const string &key = fullKey.empty() ? provider->name : fullKey; return provider->getFunction(key); } ConditionsStore::ConditionEntry &ConditionsStore::ConditionEntry::operator=(int64_t val) { if(!provider) value = val; else { const string &key = fullKey.empty() ? provider->name : fullKey; provider->setFunction(key, val); } return *this; } ConditionsStore::ConditionEntry &ConditionsStore::ConditionEntry::operator++() { if(!provider) ++value; else { const string &key = fullKey.empty() ? provider->name : fullKey; provider->setFunction(key, provider->getFunction(key) + 1); } return *this; } ConditionsStore::ConditionEntry &ConditionsStore::ConditionEntry::operator--() { if(!provider) --value; else { const string &key = fullKey.empty() ? provider->name : fullKey; provider->setFunction(key, provider->getFunction(key) - 1); } return *this; } ConditionsStore::ConditionEntry &ConditionsStore::ConditionEntry::operator+=(int64_t val) { if(!provider) value += val; else { const string &key = fullKey.empty() ? provider->name : fullKey; provider->setFunction(key, provider->getFunction(key) + val); } return *this; } ConditionsStore::ConditionEntry &ConditionsStore::ConditionEntry::operator-=(int64_t val) { if(!provider) value -= val; else { const string &key = fullKey.empty() ? provider->name : fullKey; provider->setFunction(key, provider->getFunction(key) - val); } return *this; } // Constructor with loading primary conditions from datanode. ConditionsStore::ConditionsStore(const DataNode &node) { Load(node); } // Constructor where a number of initial manually-set values are set. ConditionsStore::ConditionsStore(initializer_list<pair<string, int64_t>> initialConditions) { for(const auto &it : initialConditions) Set(it.first, it.second); } // Constructor where a number of initial manually-set values are set. ConditionsStore::ConditionsStore(const map<string, int64_t> &initialConditions) { for(const auto &it : initialConditions) Set(it.first, it.second); } void ConditionsStore::Load(const DataNode &node) { for(const DataNode &child : node) Set(child.Token(0), (child.Size() >= 2) ? child.Value(1) : 1); } void ConditionsStore::Save(DataWriter &out) const { out.Write("conditions"); out.BeginChild(); for(const auto &it : storage) { // We don't need to save derived conditions that have a provider. if(it.second.provider) continue; // If the condition's value is 0, don't write it at all. if(!it.second.value) continue; // If the condition's value is 1, don't bother writing the 1. if(it.second.value == 1) out.Write(it.first); else out.Write(it.first, it.second.value); } out.EndChild(); } // Get a condition from the Conditions-Store. Retrieves both conditions // that were directly set (primary conditions) as well as conditions // derived from other data-structures (derived conditions). int64_t ConditionsStore::Get(const string &name) const { const ConditionEntry *ce = GetEntry(name); if(!ce) return 0; if(!ce->provider) return ce->value; return ce->provider->getFunction(name); } bool ConditionsStore::Has(const string &name) const { const ConditionEntry *ce = GetEntry(name); if(!ce) return false; if(!ce->provider) return true; return ce->provider->hasFunction(name); } // Returns a pair where the boolean indicates if the game has this condition set, // and an int64_t which contains the value if the condition was set. pair<bool, int64_t> ConditionsStore::HasGet(const string &name) const { const ConditionEntry *ce = GetEntry(name); if(!ce) return make_pair(false, 0); if(!ce->provider) return make_pair(true, ce->value); bool has = ce->provider->hasFunction(name); int64_t val = 0; if(has) val = ce->provider->getFunction(name); return make_pair(has, val); } // Add a value to a condition. Returns true on success, false on failure. bool ConditionsStore::Add(const string &name, int64_t value) { // This code performers 2 lookups of the condition, once for get and // once for set. This might be optimized to a single lookup in a // later version of the code. return Set(name, Get(name) + value); } // Set a value for a condition, either for the local value, or by performing // a set on the provider. bool ConditionsStore::Set(const string &name, int64_t value) { ConditionEntry *ce = GetEntry(name); if(!ce) { (storage[name]).value = value; return true; } if(!ce->provider) { ce->value = value; return true; } return ce->provider->setFunction(name, value); } // Erase a condition completely, either the local value or by performing // an erase on the provider. bool ConditionsStore::Erase(const string &name) { ConditionEntry *ce = GetEntry(name); if(!ce) return true; if(!(ce->provider)) { storage.erase(name); return true; } return ce->provider->eraseFunction(name); } ConditionsStore::ConditionEntry &ConditionsStore::operator[](const string &name) { // Search for an exact match and return it if it exists. auto it = storage.find(name); if(it != storage.end()) return it->second; // Check for a prefix provider. ConditionEntry *ceprov = GetEntry(name); // If no prefix provider is found, then just create a new value entry. if(ceprov == nullptr) return storage[name]; // Found a matching prefixed entry provider, but no exact match for the entry itself, // let's create the exact match based on the prefix provider. ConditionEntry &ce = storage[name]; ce.provider = ceprov->provider; ce.fullKey = name; return ce; } // Build a provider for a given prefix. ConditionsStore::DerivedProvider &ConditionsStore::GetProviderPrefixed(const string &prefix) { auto it = providers.emplace(std::piecewise_construct, std::forward_as_tuple(prefix), std::forward_as_tuple(prefix, true)); DerivedProvider *provider = &(it.first->second); if(!provider->isPrefixProvider) { Logger::LogError("Error: Rewriting named provider \"" + prefix + "\" to prefixed provider."); provider->isPrefixProvider = true; } if(VerifyProviderLocation(prefix, provider)) { storage[prefix].provider = provider; // Check if any matching later entries within the prefixed range use the same provider. auto checkIt = storage.find(prefix); while(checkIt != storage.end() && (0 == checkIt->first.compare(0, prefix.length(), prefix))) { ConditionEntry &ce = checkIt->second; if(ce.provider != provider) { ce.provider = provider; ce.fullKey = checkIt->first; throw runtime_error("Replacing condition entries matching prefixed provider \"" + prefix + "\"."); } ++checkIt; } } return *provider; } // Build a provider for the condition identified by the given name. ConditionsStore::DerivedProvider &ConditionsStore::GetProviderNamed(const string &name) { auto it = providers.emplace(std::piecewise_construct, std::forward_as_tuple(name), std::forward_as_tuple(name, false)); DerivedProvider *provider = &(it.first->second); if(provider->isPrefixProvider) Logger::LogError("Error: Retrieving prefixed provider \"" + name + "\" as named provider."); else if(VerifyProviderLocation(name, provider)) storage[name].provider = provider; return *provider; } // Helper to completely remove all data and linked condition-providers from the store. void ConditionsStore::Clear() { storage.clear(); providers.clear(); } // Helper for testing; check how many primary conditions are registered. int64_t ConditionsStore::PrimariesSize() const { int64_t result = 0; for(const auto &it : storage) { // We only count primary conditions; conditions that don't have a provider. if(it.second.provider) continue; ++result; } return result; } ConditionsStore::ConditionEntry *ConditionsStore::GetEntry(const string &name) { // Avoid code-duplication between const and non-const function. return const_cast<ConditionsStore::ConditionEntry *>(const_cast<const ConditionsStore *>(this)->GetEntry(name)); } const ConditionsStore::ConditionEntry *ConditionsStore::GetEntry(const string &name) const { if(storage.empty()) return nullptr; // Perform a single search for values, named providers, and prefixed providers. auto it = storage.upper_bound(name); if(it == storage.begin()) return nullptr; --it; // The entry is matching if we have an exact string match. if(name == it->first) return &(it->second); // The entry is also matching when we have a prefix entry and the prefix part in the provider matches. DerivedProvider *provider = it->second.provider; if(provider && provider->isPrefixProvider && !name.compare(0, provider->name.length(), provider->name)) return &(it->second); // And otherwise we don't have a match. return nullptr; } // Helper function to check if we can safely add a provider with the given name. bool ConditionsStore::VerifyProviderLocation(const string &name, DerivedProvider *provider) const { auto it = storage.upper_bound(name); if(it == storage.begin()) return true; --it; const ConditionEntry &ce = it->second; // If we find the provider we are trying to add, then it apparently // was safe to add the entry since it was already added before. if(ce.provider == provider) return true; if(!ce.provider && it->first == name) { Logger::LogError("Error: overwriting primary condition \"" + name + "\" with derived provider."); return true; } if(ce.provider && ce.provider->isPrefixProvider && 0 == name.compare(0, ce.provider->name.length(), ce.provider->name)) throw runtime_error("Error: not adding provider for \"" + name + "\"" ", because it is within range of prefixed derived provider \"" + ce.provider->name + "\"."); return true; }
0
endless-sky-master
endless-sky-master/source/Weapon.cpp
/* Weapon.cpp Copyright (c) 2015 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Weapon.h" #include "Audio.h" #include "DataNode.h" #include "Effect.h" #include "GameData.h" #include "Outfit.h" #include "SpriteSet.h" #include <algorithm> using namespace std; // Load from a "weapon" node, either in an outfit or in a ship (explosion). void Weapon::LoadWeapon(const DataNode &node) { isWeapon = true; bool isClustered = false; calculatedDamage = false; doesDamage = false; bool safeRangeOverriden = false; bool disabledDamageSet = false; bool minableDamageSet = false; bool relativeDisabledDamageSet = false; bool relativeMinableDamageSet = false; for(const DataNode &child : node) { const string &key = child.Token(0); if(key == "stream") isStreamed = true; else if(key == "cluster") isClustered = true; else if(key == "safe") isSafe = true; else if(key == "phasing") isPhasing = true; else if(key == "no damage scaling") isDamageScaled = false; else if(key == "parallel") isParallel = true; else if(key == "gravitational") isGravitational = true; else if(child.Size() < 2) child.PrintTrace("Skipping weapon attribute with no value specified:"); else if(key == "sprite") sprite.LoadSprite(child); else if(key == "hardpoint sprite") hardpointSprite.LoadSprite(child); else if(key == "sound") sound = Audio::Get(child.Token(1)); else if(key == "ammo") { int usage = (child.Size() >= 3) ? child.Value(2) : 1; ammo = make_pair(GameData::Outfits().Get(child.Token(1)), max(0, usage)); } else if(key == "icon") icon = SpriteSet::Get(child.Token(1)); else if(key == "fire effect") { int count = (child.Size() >= 3) ? child.Value(2) : 1; fireEffects[GameData::Effects().Get(child.Token(1))] += count; } else if(key == "live effect") { int count = (child.Size() >= 3) ? child.Value(2) : 1; liveEffects[GameData::Effects().Get(child.Token(1))] += count; } else if(key == "hit effect") { int count = (child.Size() >= 3) ? child.Value(2) : 1; hitEffects[GameData::Effects().Get(child.Token(1))] += count; } else if(key == "target effect") { int count = (child.Size() >= 3) ? child.Value(2) : 1; targetEffects[GameData::Effects().Get(child.Token(1))] += count; } else if(key == "die effect") { int count = (child.Size() >= 3) ? child.Value(2) : 1; dieEffects[GameData::Effects().Get(child.Token(1))] += count; } else if(key == "submunition") { submunitions.emplace_back( GameData::Outfits().Get(child.Token(1)), (child.Size() >= 3) ? child.Value(2) : 1); for(const DataNode &grand : child) { if((grand.Size() >= 2) && (grand.Token(0) == "facing")) submunitions.back().facing = Angle(grand.Value(1)); else if((grand.Size() >= 3) && (grand.Token(0) == "offset")) submunitions.back().offset = Point(grand.Value(1), grand.Value(2)); else child.PrintTrace("Skipping unknown or incomplete submunition attribute:"); } } else if(key == "inaccuracy") { inaccuracy = child.Value(1); for(const DataNode &grand : child) { for(int j = 0; j < grand.Size(); ++j) { const string &token = grand.Token(j); if(token == "inverted") inaccuracyDistribution.second = true; else if(token == "triangular") inaccuracyDistribution.first = Distribution::Type::Triangular; else if(token == "uniform") inaccuracyDistribution.first = Distribution::Type::Uniform; else if(token == "narrow") inaccuracyDistribution.first = Distribution::Type::Narrow; else if(token == "medium") inaccuracyDistribution.first = Distribution::Type::Medium; else if(token == "wide") inaccuracyDistribution.first = Distribution::Type::Wide; else grand.PrintTrace("Skipping unknown distribution attribute:"); } } } else { double value = child.Value(1); if(key == "lifetime") lifetime = max(0., value); else if(key == "random lifetime") randomLifetime = max(0., value); else if(key == "fade out") fadeOut = max(0., value); else if(key == "reload") reload = max(1., value); else if(key == "burst reload") burstReload = max(1., value); else if(key == "burst count") burstCount = max(1., value); else if(key == "homing") homing = value; else if(key == "missile strength") missileStrength = max(0., value); else if(key == "anti-missile") antiMissile = max(0., value); else if(key == "velocity") velocity = value; else if(key == "random velocity") randomVelocity = value; else if(key == "acceleration") acceleration = value; else if(key == "drag") drag = value; else if(key == "hardpoint offset") { // A single value specifies the y-offset, while two values // specifies an x & y offset, e.g. for an asymmetric hardpoint. // The point is specified in traditional XY orientation, but must // be inverted along the y-dimension for internal use. if(child.Size() == 2) hardpointOffset = Point(0., -value); else if(child.Size() == 3) hardpointOffset = Point(value, -child.Value(2)); else child.PrintTrace("Unsupported \"" + key + "\" specification:"); } else if(key == "turn") turn = value; else if(key == "turret turn") turretTurn = value; else if(key == "tracking") tracking = max(0., min(1., value)); else if(key == "optical tracking") opticalTracking = max(0., min(1., value)); else if(key == "infrared tracking") infraredTracking = max(0., min(1., value)); else if(key == "radar tracking") radarTracking = max(0., min(1., value)); else if(key == "firing energy") firingEnergy = value; else if(key == "firing force") firingForce = value; else if(key == "firing fuel") firingFuel = value; else if(key == "firing heat") firingHeat = value; else if(key == "firing hull") firingHull = value; else if(key == "firing shields") firingShields = value; else if(key == "firing ion") firingIon = value; else if(key == "firing scramble") firingScramble = value; else if(key == "firing slowing") firingSlowing = value; else if(key == "firing disruption") firingDisruption = value; else if(key == "firing discharge") firingDischarge = value; else if(key == "firing corrosion") firingCorrosion = value; else if(key == "firing leak") firingLeak = value; else if(key == "firing burn") firingBurn = value; else if(key == "relative firing energy") relativeFiringEnergy = value; else if(key == "relative firing heat") relativeFiringHeat = value; else if(key == "relative firing fuel") relativeFiringFuel = value; else if(key == "relative firing hull") relativeFiringHull = value; else if(key == "relative firing shields") relativeFiringShields = value; else if(key == "split range") splitRange = max(0., value); else if(key == "trigger radius") triggerRadius = max(0., value); else if(key == "blast radius") blastRadius = max(0., value); else if(key == "safe range override") { safeRange = max(0., value); safeRangeOverriden = true; } else if(key == "shield damage") damage[SHIELD_DAMAGE] = value; else if(key == "hull damage") damage[HULL_DAMAGE] = value; else if(key == "disabled damage") { damage[DISABLED_DAMAGE] = value; disabledDamageSet = true; } else if(key == "minable damage") { damage[MINABLE_DAMAGE] = value; minableDamageSet = true; } else if(key == "fuel damage") damage[FUEL_DAMAGE] = value; else if(key == "heat damage") damage[HEAT_DAMAGE] = value; else if(key == "energy damage") damage[ENERGY_DAMAGE] = value; else if(key == "ion damage") damage[ION_DAMAGE] = value; else if(key == "scrambling damage") damage[WEAPON_JAMMING_DAMAGE] = value; else if(key == "disruption damage") damage[DISRUPTION_DAMAGE] = value; else if(key == "slowing damage") damage[SLOWING_DAMAGE] = value; else if(key == "discharge damage") damage[DISCHARGE_DAMAGE] = value; else if(key == "corrosion damage") damage[CORROSION_DAMAGE] = value; else if(key == "leak damage") damage[LEAK_DAMAGE] = value; else if(key == "burn damage") damage[BURN_DAMAGE] = value; else if(key == "relative shield damage") damage[RELATIVE_SHIELD_DAMAGE] = value; else if(key == "relative hull damage") damage[RELATIVE_HULL_DAMAGE] = value; else if(key == "relative disabled damage") { damage[RELATIVE_DISABLED_DAMAGE] = value; relativeDisabledDamageSet = true; } else if(key == "relative minable damage") { damage[RELATIVE_MINABLE_DAMAGE] = value; relativeMinableDamageSet = true; } else if(key == "relative fuel damage") damage[RELATIVE_FUEL_DAMAGE] = value; else if(key == "relative heat damage") damage[RELATIVE_HEAT_DAMAGE] = value; else if(key == "relative energy damage") damage[RELATIVE_ENERGY_DAMAGE] = value; else if(key == "hit force") damage[HIT_FORCE] = value; else if(key == "piercing") piercing = max(0., value); else if(key == "range override") rangeOverride = max(0., value); else if(key == "velocity override") velocityOverride = max(0., value); else if(key == "damage dropoff") { hasDamageDropoff = true; double maxDropoff = (child.Size() >= 3) ? child.Value(2) : 0.; damageDropoffRange = make_pair(max(0., value), maxDropoff); } else if(key == "dropoff modifier") damageDropoffModifier = max(0., value); else child.PrintTrace("Unrecognized weapon attribute: \"" + key + "\":"); } } // Disabled damage defaults to hull damage instead of 0. if(!disabledDamageSet) damage[DISABLED_DAMAGE] = damage[HULL_DAMAGE]; if(!relativeDisabledDamageSet) damage[RELATIVE_DISABLED_DAMAGE] = damage[RELATIVE_HULL_DAMAGE]; // Minable damage defaults to hull damage instead of 0. if(!minableDamageSet) damage[MINABLE_DAMAGE] = damage[HULL_DAMAGE]; if(!relativeMinableDamageSet) damage[RELATIVE_MINABLE_DAMAGE] = damage[RELATIVE_HULL_DAMAGE]; // Sanity checks: if(burstReload > reload) burstReload = reload; if(damageDropoffRange.first > damageDropoffRange.second) damageDropoffRange.second = Range(); // Weapons of the same type will alternate firing (streaming) rather than // firing all at once (clustering) if the weapon is not an anti-missile and // is not vulnerable to anti-missile, or has the "stream" attribute. isStreamed |= !(MissileStrength() || AntiMissile()); isStreamed &= !isClustered; // Support legacy missiles with no tracking type defined: if(homing && !tracking && !opticalTracking && !infraredTracking && !radarTracking) { tracking = 1.; node.PrintTrace("Warning: Deprecated use of \"homing\" without use of \"[optical|infrared|radar] tracking.\""); } // Convert the "live effect" counts from occurrences per projectile lifetime // into chance of occurring per frame. if(lifetime <= 0) liveEffects.clear(); for(auto it = liveEffects.begin(); it != liveEffects.end(); ) { if(!it->second) it = liveEffects.erase(it); else { it->second = max(1, lifetime / it->second); ++it; } } // Only when the weapon is not safe and has a blast radius is safeRange needed, // except if it is already overridden. if(!isSafe && blastRadius > 0 && !safeRangeOverriden) safeRange = (blastRadius + triggerRadius); } bool Weapon::IsWeapon() const { return isWeapon; } // Get assets used by this weapon. const Body &Weapon::WeaponSprite() const { return sprite; } const Body &Weapon::HardpointSprite() const { return hardpointSprite; } const Sound *Weapon::WeaponSound() const { return sound; } const Outfit *Weapon::Ammo() const { return ammo.first; } int Weapon::AmmoUsage() const { return ammo.second; } bool Weapon::IsParallel() const { return isParallel; } const Sprite *Weapon::Icon() const { return icon; } // Effects to be created at the start or end of the weapon's lifetime. const map<const Effect *, int> &Weapon::FireEffects() const { return fireEffects; } const map<const Effect *, int> &Weapon::LiveEffects() const { return liveEffects; } const map<const Effect *, int> &Weapon::HitEffects() const { return hitEffects; } const map<const Effect *, int> &Weapon::TargetEffects() const { return targetEffects; } const map<const Effect *, int> &Weapon::DieEffects() const { return dieEffects; } const vector<Weapon::Submunition> &Weapon::Submunitions() const { return submunitions; } double Weapon::TotalLifetime() const { if(rangeOverride) return rangeOverride / WeightedVelocity(); if(totalLifetime < 0.) { totalLifetime = 0.; for(const auto &it : submunitions) totalLifetime = max(totalLifetime, it.weapon->TotalLifetime()); totalLifetime += lifetime; } return totalLifetime; } double Weapon::Range() const { return (rangeOverride > 0) ? rangeOverride : WeightedVelocity() * TotalLifetime(); } // Calculate the fraction of full damage that this weapon deals given the // distance that the projectile traveled if it has a damage dropoff range. double Weapon::DamageDropoff(double distance) const { double minDropoff = damageDropoffRange.first; double maxDropoff = damageDropoffRange.second; if(distance <= minDropoff) return 1.; if(distance >= maxDropoff) return damageDropoffModifier; // Damage modification is linear between the min and max dropoff points. double slope = (1 - damageDropoffModifier) / (minDropoff - maxDropoff); return slope * (distance - minDropoff) + 1; } // Return the weapon's damage dropoff at maximum range. double Weapon::MaxDropoff() const { return damageDropoffModifier; } // Return the ranges at which the weapon's damage dropoff begins and ends. const pair<double, double> &Weapon::DropoffRanges() const { return damageDropoffRange; } // Legacy support: allow turret outfits with no turn rate to specify a // default turnrate. void Weapon::SetTurretTurn(double rate) { turretTurn = rate; } double Weapon::TotalDamage(int index) const { if(!calculatedDamage) { calculatedDamage = true; for(int i = 0; i < DAMAGE_TYPES; ++i) { for(const auto &it : submunitions) damage[i] += it.weapon->TotalDamage(i) * it.count; doesDamage |= (damage[i] > 0.); } } return damage[index]; } pair<Distribution::Type, bool> Weapon::InaccuracyDistribution() const { return inaccuracyDistribution; } double Weapon::Inaccuracy() const { return inaccuracy; }
0
endless-sky-master
endless-sky-master/source/FillShader.cpp
/* FillShader.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "FillShader.h" #include "Color.h" #include "Point.h" #include "Screen.h" #include "Shader.h" #include <stdexcept> namespace { Shader shader; GLint scaleI; GLint centerI; GLint sizeI; GLint colorI; GLuint vao; GLuint vbo; } void FillShader::Init() { static const char *vertexCode = "// vertex fill shader\n" "uniform vec2 scale;\n" "uniform vec2 center;\n" "uniform vec2 size;\n" "in vec2 vert;\n" "void main() {\n" " gl_Position = vec4((center + vert * size) * scale, 0, 1);\n" "}\n"; static const char *fragmentCode = "// fragment fill shader\n" "precision mediump float;\n" "uniform vec4 color;\n" "out vec4 finalColor;\n" "void main() {\n" " finalColor = color;\n" "}\n"; shader = Shader(vertexCode, fragmentCode); scaleI = shader.Uniform("scale"); centerI = shader.Uniform("center"); sizeI = shader.Uniform("size"); colorI = shader.Uniform("color"); // Generate the vertex data for drawing sprites. glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); GLfloat vertexData[] = { -.5f, -.5f, .5f, -.5f, -.5f, .5f, .5f, .5f }; glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glEnableVertexAttribArray(shader.Attrib("vert")); glVertexAttribPointer(shader.Attrib("vert"), 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); // unbind the VBO and VAO glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void FillShader::Fill(const Point &center, const Point &size, const Color &color) { if(!shader.Object()) throw std::runtime_error("FillShader: Draw() called before Init()."); glUseProgram(shader.Object()); glBindVertexArray(vao); GLfloat scale[2] = {2.f / Screen::Width(), -2.f / Screen::Height()}; glUniform2fv(scaleI, 1, scale); GLfloat centerV[2] = {static_cast<float>(center.X()), static_cast<float>(center.Y())}; glUniform2fv(centerI, 1, centerV); GLfloat sizeV[2] = {static_cast<float>(size.X()), static_cast<float>(size.Y())}; glUniform2fv(sizeI, 1, sizeV); glUniform4fv(colorI, 1, color.Get()); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); glUseProgram(0); }
0
endless-sky-master
endless-sky-master/source/AsteroidField.cpp
/* AsteroidField.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "AsteroidField.h" #include "DrawList.h" #include "Mask.h" #include "Minable.h" #include "Projectile.h" #include "Random.h" #include "Screen.h" #include "SpriteSet.h" #include <algorithm> #include <cmath> #include <cstdlib> using namespace std; namespace { constexpr double WRAP = 4096.; constexpr unsigned CELL_SIZE = 256u; constexpr unsigned CELL_COUNT = WRAP / CELL_SIZE; } // Constructor, to set up the collision set parameters. AsteroidField::AsteroidField() : asteroidCollisions(CELL_SIZE, CELL_COUNT), minableCollisions(CELL_SIZE, CELL_COUNT) { } // Clear the list of asteroids. void AsteroidField::Clear() { asteroids.clear(); minables.clear(); } // Add a new asteroid to the list, using the sprite with the given name. void AsteroidField::Add(const string &name, int count, double energy) { const Sprite *sprite = SpriteSet::Get("asteroid/" + name + "/spin"); for(int i = 0; i < count; ++i) asteroids.emplace_back(sprite, energy); } void AsteroidField::Add(const Minable *minable, int count, double energy, const WeightedList<double> &belts) { // Double check that the given asteroid is defined. if(!minable || !minable->GetMask().IsLoaded()) return; // Place copies of the given minable asteroid throughout the system. for(int i = 0; i < count; ++i) { minables.emplace_back(new Minable(*minable)); minables.back()->Place(energy, belts.Get()); } } // Move all the asteroids forward one step. void AsteroidField::Step(vector<Visual> &visuals, list<shared_ptr<Flotsam>> &flotsam, int step) { asteroidCollisions.Clear(step); for(Asteroid &asteroid : asteroids) { asteroidCollisions.Add(asteroid); asteroid.Step(); } asteroidCollisions.Finish(); // Step through the minables. Since they are destructible, we may need to // remove them from the list. minableCollisions.Clear(step); auto it = minables.begin(); while(it != minables.end()) { if((*it)->Move(visuals, flotsam)) { minableCollisions.Add(**it); ++it; } else it = minables.erase(it); } minableCollisions.Finish(); } // Draw the asteroids, centered on the given location. void AsteroidField::Draw(DrawList &draw, const Point &center, double zoom) const { for(const Asteroid &asteroid : asteroids) asteroid.Draw(draw, center, zoom); for(const shared_ptr<Minable> &minable : minables) draw.Add(*minable); } // Check if the given projectile collides with any asteroids. Body *AsteroidField::Collide(const Projectile &projectile, double *closestHit) { Body *hit = nullptr; // First, check for collisions with ordinary asteroids, which are tiled. // Rather than tiling the collision set, tile the projectile. Point from = projectile.Position(); Point to = from + projectile.Velocity(); // Map the projectile to a position within the wrap square. Point minimum = Point(min(from.X(), to.X()), min(from.Y(), to.Y())); Point maximum = from + to - minimum; Point grid = WRAP * Point(floor(maximum.X() / WRAP), floor(maximum.Y() / WRAP)); from -= grid; to -= grid; // The projectile's bounding rectangle now overlaps the wrap square. If it // extends outside that square, it does so only on the low end (assuming no // projectile has a length longer than the wrap distance). If it does extend // outside the square, it must be "tiled" once in that direction. int tileX = 1 + (minimum.X() < grid.X()); int tileY = 1 + (minimum.Y() < grid.Y()); for(int y = 0; y < tileY; ++y) for(int x = 0; x < tileX; ++x) { Point offset = Point(x, y) * WRAP; Body *body = asteroidCollisions.Line(from + offset, to + offset, closestHit); if(body) hit = body; } // Now, check for collisions with minable asteroids. Because this is the // very last collision check to be done, if a minable asteroid is the // closest hit, it really is what the projectile struck - that is, we are // not going to later find a ship or something else that is closer. Body *body = minableCollisions.Line(projectile, closestHit); if(body) { hit = body; reinterpret_cast<Minable *>(body)->TakeDamage(projectile); } return hit; } // Get the list of minable asteroids. const list<shared_ptr<Minable>> &AsteroidField::Minables() const { return minables; } // Construct an asteroid with the given sprite and "energy level." AsteroidField::Asteroid::Asteroid(const Sprite *sprite, double energy) { // Energy level determines how fast the asteroid rotates. SetSprite(sprite); SetFrameRate(Random::Real() * 4. * energy + 5.); // Pick a random position within the wrapped square. position = Point(Random::Real() * WRAP, Random::Real() * WRAP); // In addition to the "spin" inherent in the animation, the asteroid should // spin in screen coordinates. This makes the animation more interesting // because every time it comes back to the same frame it is pointing in a // new direction, so the asteroids don't all appear to be spinning on // exactly the same axis. angle = Angle::Random(); spin = Angle::Random(energy) - Angle::Random(energy); // The asteroid's velocity is also determined by the energy level. velocity = angle.Unit() * Random::Real() * energy; // Store how big an area the asteroid can cover, so we can figure out when // it is potentially on screen. size = Point(1., 1.) * Radius(); } // Move the asteroid forward one time step. void AsteroidField::Asteroid::Step() { angle += spin; position += velocity; // Keep the position within the wrap square. if(position.X() < 0.) position = Point(position.X() + WRAP, position.Y()); else if(position.X() >= WRAP) position = Point(position.X() - WRAP, position.Y()); if(position.Y() < 0.) position = Point(position.X(), position.Y() + WRAP); else if(position.Y() >= WRAP) position = Point(position.X(), position.Y() - WRAP); } // Draw any instances of this asteroid that are on screen. void AsteroidField::Asteroid::Draw(DrawList &draw, const Point &center, double zoom) const { // Any object within this range must be drawn. Point topLeft = center + (Screen::TopLeft() - size) / zoom; Point bottomRight = center + (Screen::BottomRight() + size) / zoom; // Figure out the position of the first instance of this asteroid that is to // the right of and below the top left corner of the screen. double startX = fmod(position.X() - topLeft.X(), WRAP); startX += topLeft.X() + WRAP * (startX < 0.); double startY = fmod(position.Y() - topLeft.Y(), WRAP); startY += topLeft.Y() + WRAP * (startY < 0.); // Draw any instances of this asteroid that are on screen. for(double y = startY; y < bottomRight.Y(); y += WRAP) for(double x = startX; x < bottomRight.X(); x += WRAP) draw.Add(*this, Point(x, y)); }
0
endless-sky-master
endless-sky-master/source/Government.cpp
/* Government.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Government.h" #include "Conversation.h" #include "DataNode.h" #include "Fleet.h" #include "GameData.h" #include "Outfit.h" #include "Phrase.h" #include "Politics.h" #include "Ship.h" #include "ShipEvent.h" #include <algorithm> using namespace std; namespace { // Load ShipEvent strings and corresponding numerical values into a map. void PenaltyHelper(const DataNode &node, map<int, double> &penalties) { for(const DataNode &child : node) if(child.Size() >= 2) { const string &key = child.Token(0); if(key == "assist") penalties[ShipEvent::ASSIST] = child.Value(1); else if(key == "disable") penalties[ShipEvent::DISABLE] = child.Value(1); else if(key == "board") penalties[ShipEvent::BOARD] = child.Value(1); else if(key == "capture") penalties[ShipEvent::CAPTURE] = child.Value(1); else if(key == "destroy") penalties[ShipEvent::DESTROY] = child.Value(1); else if(key == "scan") { penalties[ShipEvent::SCAN_OUTFITS] = child.Value(1); penalties[ShipEvent::SCAN_CARGO] = child.Value(1); } else if(key == "provoke") penalties[ShipEvent::PROVOKE] = child.Value(1); else if(key == "atrocity") penalties[ShipEvent::ATROCITY] = child.Value(1); else child.PrintTrace("Skipping unrecognized attribute:"); } else child.PrintTrace("Skipping unrecognized attribute:"); } // Determine the penalty for the given ShipEvent based on the values in the given map. double PenaltyHelper(int eventType, const map<int, double> &penalties) { double penalty = 0.; for(const auto &it : penalties) if(eventType & it.first) penalty += it.second; return penalty; } unsigned nextID = 0; } // Default constructor. Government::Government() { // Default penalties: penaltyFor[ShipEvent::ASSIST] = -0.1; penaltyFor[ShipEvent::DISABLE] = 0.5; penaltyFor[ShipEvent::BOARD] = 0.3; penaltyFor[ShipEvent::CAPTURE] = 1.; penaltyFor[ShipEvent::DESTROY] = 1.; penaltyFor[ShipEvent::SCAN_OUTFITS] = 0.; penaltyFor[ShipEvent::SCAN_CARGO] = 0.; penaltyFor[ShipEvent::PROVOKE] = 0.; penaltyFor[ShipEvent::ATROCITY] = 10.; id = nextID++; } // Load a government's definition from a file. void Government::Load(const DataNode &node) { if(node.Size() >= 2) { name = node.Token(1); if(displayName.empty()) displayName = name; } // For the following keys, if this data node defines a new value for that // key, the old values should be cleared (unless using the "add" keyword). set<string> shouldOverwrite = {"raid"}; for(const DataNode &child : node) { bool remove = child.Token(0) == "remove"; bool add = child.Token(0) == "add"; if((add || remove) && child.Size() < 2) { child.PrintTrace("Skipping " + child.Token(0) + " with no key given:"); continue; } const string &key = child.Token((add || remove) ? 1 : 0); int valueIndex = (add || remove) ? 2 : 1; bool hasValue = child.Size() > valueIndex; // Check for conditions that require clearing this key's current value. // "remove <key>" means to clear the key's previous contents. // "remove <key> <value>" means to remove just that value from the key. bool removeAll = (remove && !hasValue); // If this is the first entry for the given key, and we are not in "add" // or "remove" mode, its previous value should be cleared. bool overwriteAll = (!add && !remove && shouldOverwrite.count(key)); if(removeAll || overwriteAll) { if(key == "provoked on scan") provokedOnScan = false; else if(key == "travel restrictions") travelRestrictions = LocationFilter{}; else if(key == "reputation") { for(const DataNode &grand : child) { const string &grandKey = grand.Token(0); if(grandKey == "max") reputationMax = numeric_limits<double>::max(); else if(grandKey == "min") reputationMin = numeric_limits<double>::lowest(); } } else if(key == "raid") raidFleets.clear(); else if(key == "display name") displayName = name; else if(key == "death sentence") deathSentence = nullptr; else if(key == "friendly hail") friendlyHail = nullptr; else if(key == "friendly disabled hail") friendlyDisabledHail = nullptr; else if(key == "hostile hail") hostileHail = nullptr; else if(key == "hostile disabled hail") hostileDisabledHail = nullptr; else if(key == "language") language.clear(); else if(key == "send untranslated hails") sendUntranslatedHails = false; else if(key == "trusted") trusted.clear(); else if(key == "enforces") enforcementZones.clear(); else if(key == "custom penalties for") customPenalties.clear(); else if(key == "foreign penalties for") useForeignPenaltiesFor.clear(); else if(key == "illegals") { illegalOutfits.clear(); illegalShips.clear(); } else if(key == "atrocities") { atrocityOutfits.clear(); atrocityShips.clear(); } else child.PrintTrace("Cannot \"remove\" the given key:"); // If not in "overwrite" mode, move on to the next node. if(overwriteAll) shouldOverwrite.erase(key); else continue; } if(key == "raid") RaidFleet::Load(raidFleets, child, remove, valueIndex); // Handle the attributes which cannot have a value removed. else if(remove) child.PrintTrace("Cannot \"remove\" a specific value from the given key:"); else if(key == "attitude toward") { for(const DataNode &grand : child) { if(grand.Size() >= 2) { const Government *gov = GameData::Governments().Get(grand.Token(0)); attitudeToward.resize(nextID, 0.); attitudeToward[gov->id] = grand.Value(1); } else grand.PrintTrace("Skipping unrecognized attribute:"); } } else if(key == "reputation") { for(const DataNode &grand : child) { const string &grandKey = grand.Token(0); bool hasGrandValue = grand.Size() >= 2; if(grandKey == "player reputation" && hasGrandValue) initialPlayerReputation = add ? initialPlayerReputation + child.Value(valueIndex) : child.Value(valueIndex); else if(grandKey == "max" && hasGrandValue) reputationMax = add ? reputationMax + grand.Value(valueIndex) : grand.Value(valueIndex); else if(grandKey == "min" && hasGrandValue) reputationMin = add ? reputationMin + grand.Value(valueIndex) : grand.Value(valueIndex); else grand.PrintTrace("Skipping unrecognized attribute:"); } } else if(key == "trusted") { bool clearTrusted = !trusted.empty(); for(const DataNode &grand : child) { bool remove = grand.Token(0) == "remove"; bool add = grand.Token(0) == "add"; if((add || remove) && grand.Size() < 2) { grand.PrintTrace("Warning: Skipping invalid \"" + child.Token(0) + "\" tag:"); continue; } if(clearTrusted && !add && !remove) { trusted.clear(); clearTrusted = false; } const Government *gov = GameData::Governments().Get(grand.Token(remove || add)); if(gov) { if(remove) trusted.erase(gov); else trusted.insert(gov); } else grand.PrintTrace("Skipping unrecognized government:"); } } else if(key == "penalty for") PenaltyHelper(child, penaltyFor); else if(key == "custom penalties for") for(const DataNode &grand : child) { if(grand.Token(0) == "remove" && grand.Size() >= 2) customPenalties[GameData::Governments().Get(grand.Token(1))->id].clear(); else { auto &pens = customPenalties[GameData::Governments().Get(grand.Token(0))->id]; PenaltyHelper(grand, pens); } } else if(key == "illegals") { if(!add) { illegalOutfits.clear(); illegalShips.clear(); } for(const DataNode &grand : child) if(grand.Size() >= 2) { if(grand.Token(0) == "remove") { if(grand.Size() >= 3 && grand.Token(1) == "ship") { if(!illegalShips.erase(grand.Token(2))) grand.PrintTrace("Invalid remove, ship not found in existing illegals:"); } else if(!illegalOutfits.erase(GameData::Outfits().Get(grand.Token(1)))) grand.PrintTrace("Invalid remove, outfit not found in existing illegals:"); } else if(grand.Token(0) == "ignore") { if(grand.Size() >= 3 && grand.Token(1) == "ship") illegalShips[grand.Token(2)] = 0; else illegalOutfits[GameData::Outfits().Get(grand.Token(1))] = 0; } else if(grand.Size() >= 3 && grand.Token(0) == "ship") illegalShips[grand.Token(1)] = grand.Value(2); else illegalOutfits[GameData::Outfits().Get(grand.Token(0))] = grand.Value(1); } } else if(key == "atrocities") { if(!add) { atrocityOutfits.clear(); atrocityShips.clear(); } for(const DataNode &grand : child) if(grand.Size() >= 2) { if(grand.Token(0) == "remove") { if(grand.Size() >= 3 && grand.Token(1) == "ship") { if(!atrocityShips.erase(grand.Token(2))) grand.PrintTrace("Invalid remove, ship not found in existing atrocities:"); } else if(!atrocityOutfits.erase(GameData::Outfits().Get(grand.Token(1)))) grand.PrintTrace("Invalid remove, outfit not found in existing atrocities:"); } else if(grand.Token(0) == "ignore") { if(grand.Size() >= 3 && grand.Token(1) == "ship") atrocityShips[grand.Token(2)] = false; else atrocityOutfits[GameData::Outfits().Get(grand.Token(1))] = false; } else if(grand.Token(0) == "ship") atrocityShips[grand.Token(1)] = true; } else atrocityOutfits[GameData::Outfits().Get(grand.Token(0))] = true; } else if(key == "enforces" && child.HasChildren()) enforcementZones.emplace_back(child); else if(key == "provoked on scan") provokedOnScan = true; else if(key == "travel restrictions" && child.HasChildren()) { if(add) travelRestrictions.Load(child); else travelRestrictions = LocationFilter(child); } else if(key == "foreign penalties for") for(const DataNode &grand : child) useForeignPenaltiesFor.insert(GameData::Governments().Get(grand.Token(0))->id); else if(key == "send untranslated hails") sendUntranslatedHails = true; else if(!hasValue) child.PrintTrace("Error: Expected key to have a value:"); else if(key == "player reputation") initialPlayerReputation = add ? initialPlayerReputation + child.Value(valueIndex) : child.Value(valueIndex); else if(key == "crew attack") crewAttack = max(0., add ? child.Value(valueIndex) + crewAttack : child.Value(valueIndex)); else if(key == "crew defense") crewDefense = max(0., add ? child.Value(valueIndex) + crewDefense : child.Value(valueIndex)); else if(key == "bribe") bribe = add ? bribe + child.Value(valueIndex) : child.Value(valueIndex); else if(key == "fine") fine = add ? fine + child.Value(valueIndex) : child.Value(valueIndex); else if(add) child.PrintTrace("Error: Unsupported use of add:"); else if(key == "display name") displayName = child.Token(valueIndex); else if(key == "swizzle") swizzle = child.Value(valueIndex); else if(key == "color") { if(child.Size() >= 3 + valueIndex) color = ExclusiveItem<Color>(Color(child.Value(valueIndex), child.Value(valueIndex + 1), child.Value(valueIndex + 2))); else if(child.Size() >= 1 + valueIndex) color = ExclusiveItem<Color>(GameData::Colors().Get(child.Token(valueIndex))); } else if(key == "death sentence") deathSentence = GameData::Conversations().Get(child.Token(valueIndex)); else if(key == "friendly hail") friendlyHail = GameData::Phrases().Get(child.Token(valueIndex)); else if(key == "friendly disabled hail") friendlyDisabledHail = GameData::Phrases().Get(child.Token(valueIndex)); else if(key == "hostile hail") hostileHail = GameData::Phrases().Get(child.Token(valueIndex)); else if(key == "hostile disabled hail") hostileDisabledHail = GameData::Phrases().Get(child.Token(valueIndex)); else if(key == "language") language = child.Token(valueIndex); else if(key == "enforces" && child.Token(valueIndex) == "all") { enforcementZones.clear(); child.PrintTrace("Warning: Deprecated use of \"enforces all\". Use \"remove enforces\" instead:"); } else child.PrintTrace("Skipping unrecognized attribute:"); } // Ensure reputation minimum is not above the // maximum, and set reputation again to enforce limtis. if(reputationMin > reputationMax) reputationMin = reputationMax; SetReputation(Reputation()); // Default to the standard disabled hail messages. if(!friendlyDisabledHail) friendlyDisabledHail = GameData::Phrases().Get("friendly disabled"); if(!hostileDisabledHail) hostileDisabledHail = GameData::Phrases().Get("hostile disabled"); } // Get the display name of this government. const string &Government::GetName() const { return displayName; } // Set / Get the name used for this government in the data files. void Government::SetName(const string &trueName) { this->name = trueName; } const string &Government::GetTrueName() const { return name; } // Get the color swizzle to use for ships of this government. int Government::GetSwizzle() const { return swizzle; } // Get the color to use for displaying this government on the map. const Color &Government::GetColor() const { return *color; } // Get the government's initial disposition toward other governments or // toward the player. double Government::AttitudeToward(const Government *other) const { if(!other) return 0.; if(other == this) return 1.; if(attitudeToward.size() <= other->id) return 0.; return attitudeToward[other->id]; } double Government::InitialPlayerReputation() const { return initialPlayerReputation; } // Get the amount that your reputation changes for the given offense against the given government. // The given value should be a combination of one or more ShipEvent values. // Returns 0 if the Government is null. double Government::PenaltyFor(int eventType, const Government *other) const { if(!other) return 0.; if(other == this) return PenaltyHelper(eventType, penaltyFor); const int id = other->id; const auto &penalties = useForeignPenaltiesFor.count(id) ? other->penaltyFor : penaltyFor; const auto it = customPenalties.find(id); if(it == customPenalties.end()) return PenaltyHelper(eventType, penalties); map<int, double> tempPenalties = penalties; for(const auto &penalty : it->second) tempPenalties[penalty.first] = penalty.second; return PenaltyHelper(eventType, tempPenalties); } // In order to successfully bribe this government you must pay them this // fraction of your fleet's value. (Zero means they cannot be bribed.) double Government::GetBribeFraction() const { return bribe; } double Government::GetFineFraction() const { return fine; } bool Government::Trusts(const Government *government) const { return government == this || trusted.count(government); } // Returns true if this government has no enforcement restrictions, or if the // indicated system matches at least one enforcement zone. bool Government::CanEnforce(const System *system) const { for(const LocationFilter &filter : enforcementZones) if(filter.Matches(system)) return true; return enforcementZones.empty(); } // Returns true if this government has no enforcement restrictions, or if the // indicated planet matches at least one enforcement zone. bool Government::CanEnforce(const Planet *planet) const { for(const LocationFilter &filter : enforcementZones) if(filter.Matches(planet)) return true; return enforcementZones.empty(); } const Conversation *Government::DeathSentence() const { return deathSentence; } // Get a hail message (which depends on whether this is an enemy government // and if the ship is disabled). string Government::GetHail(bool isDisabled) const { const Phrase *phrase = nullptr; if(IsEnemy()) phrase = isDisabled ? hostileDisabledHail : hostileHail; else phrase = isDisabled ? friendlyDisabledHail : friendlyHail; return phrase ? phrase->Get() : ""; } // Find out if this government speaks a different language. const string &Government::Language() const { return language; } // Find out if this government should send custom hails even if the player does not know its language. bool Government::SendUntranslatedHails() const { return sendUntranslatedHails; } // Pirate raids in this government's systems use these fleet definitions. If // it is empty, there are no pirate raids. // The second attribute denotes the minimal and maximal attraction required for the fleet to appear. const vector<RaidFleet> &Government::RaidFleets() const { return raidFleets; } // Check if, according to the politics stored by GameData, this government is // an enemy of the given government right now. bool Government::IsEnemy(const Government *other) const { return GameData::GetPolitics().IsEnemy(this, other); } // Check if this government is an enemy of the player. bool Government::IsEnemy() const { return GameData::GetPolitics().IsEnemy(this, GameData::PlayerGovernment()); } // Check if this is the player government. bool Government::IsPlayer() const { return (this == GameData::PlayerGovernment()); } // Commit the given "offense" against this government (which may not // actually consider it to be an offense). This may result in temporary // hostilities (if the even type is PROVOKE), or a permanent change to your // reputation. void Government::Offend(int eventType, int count) const { return GameData::GetPolitics().Offend(this, eventType, count); } // Bribe this government to be friendly to you for one day. void Government::Bribe() const { GameData::GetPolitics().Bribe(this); } // Check to see if the player has done anything they should be fined for. // Each government can only fine you once per day. string Government::Fine(PlayerInfo &player, int scan, const Ship *target, double security) const { return GameData::GetPolitics().Fine(player, this, scan, target, security); } bool Government::Condemns(const Outfit *outfit) const { const auto isAtrocity = atrocityOutfits.find(outfit); bool found = isAtrocity != atrocityOutfits.cend(); return (found && isAtrocity->second) || (!found && outfit->Get("atrocity") > 0.); } bool Government::Condemns(const Ship *ship) const { const auto isAtrocity = atrocityShips.find(ship->TrueModelName()); bool found = isAtrocity != atrocityShips.cend(); return (found && isAtrocity->second) || (!found && ship->BaseAttributes().Get("atrocity") > 0.); } int Government::Fines(const Outfit *outfit) const { // If this government doesn't fine anything it won't fine this outfit. if(!fine) return 0; for(const auto &it : illegalOutfits) if(it.first == outfit) return it.second; return outfit->Get("illegal"); } int Government::Fines(const Ship *ship) const { // If this government doesn't fine anything it won't fine this ship. if(!fine) return 0; for(const auto &it : illegalShips) if(it.first == ship->TrueModelName()) return it.second; return ship->BaseAttributes().Get("illegal"); } bool Government::FinesContents(const Ship *ship) const { for(auto &it : ship->Outfits()) if(this->Fines(it.first) || this->Condemns(it.first)) return true; return ship->Cargo().IllegalCargoFine(this); } // Get or set the player's reputation with this government. double Government::Reputation() const { return GameData::GetPolitics().Reputation(this); } double Government::ReputationMax() const { return reputationMax; } double Government::ReputationMin() const { return reputationMin; } void Government::AddReputation(double value) const { GameData::GetPolitics().AddReputation(this, value); } void Government::SetReputation(double value) const { GameData::GetPolitics().SetReputation(this, value); } double Government::CrewAttack() const { return crewAttack; } double Government::CrewDefense() const { return crewDefense; } bool Government::IsProvokedOnScan() const { return provokedOnScan; } bool Government::IsRestrictedFrom(const System &system) const { return !travelRestrictions.IsEmpty() && travelRestrictions.Matches(&system); } bool Government::IsRestrictedFrom(const Planet &planet) const { return !travelRestrictions.IsEmpty() && travelRestrictions.Matches(&planet); }
0
endless-sky-master
endless-sky-master/source/Ship.h
/* Ship.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef SHIP_H_ #define SHIP_H_ #include "Body.h" #include "Angle.h" #include "Armament.h" #include "CargoHold.h" #include "Command.h" #include "EsUuid.h" #include "FireCommand.h" #include "Outfit.h" #include "Personality.h" #include "Point.h" #include "Port.h" #include "ship/ShipAICache.h" #include "ShipJumpNavigation.h" #include <list> #include <map> #include <memory> #include <set> #include <string> #include <vector> class DamageDealt; class DataNode; class DataWriter; class Effect; class Flotsam; class Government; class Minable; class Phrase; class Planet; class PlayerInfo; class Projectile; class StellarObject; class System; class Visual; // Class representing a ship (either a model for sale or an instance of it). A // ship's information can be saved to a file, so that it can later be read back // in exactly the same state. The same class is used for the player's ship as // for all other ships, so their capabilities are exactly the same within the // limits of what the AI knows how to command them to do. class Ship : public Body, public std::enable_shared_from_this<Ship> { public: class Bay { public: Bay(double x, double y, std::string category) : point(x * .5, y * .5), category(std::move(category)) {} Bay(Bay &&) = default; Bay &operator=(Bay &&) = default; ~Bay() = default; // Copying a bay does not copy the ship inside it. Bay(const Bay &b) : point(b.point), category(b.category), side(b.side), facing(b.facing), launchEffects(b.launchEffects) {} Bay &operator=(const Bay &b) { return *this = Bay(b); } Point point; std::shared_ptr<Ship> ship; std::string category; uint8_t side = 0; static const uint8_t INSIDE = 0; static const uint8_t OVER = 1; static const uint8_t UNDER = 2; // The angle at which the carried ship will depart, relative to the carrying ship. Angle facing; // The launch effect(s) to be simultaneously played when the bay's ship launches. std::vector<const Effect *> launchEffects; }; class EnginePoint : public Point { public: EnginePoint(double x, double y, double zoom) : Point(x, y), zoom(zoom) {} uint8_t side = 0; static const uint8_t UNDER = 0; static const uint8_t OVER = 1; uint8_t steering = 0; static const uint8_t NONE = 0; static const uint8_t LEFT = 1; static const uint8_t RIGHT = 2; double zoom; Angle facing; Angle gimbal; }; public: // Functions provided by the Body base class: // bool HasSprite() const; // const Sprite *GetSprite() const; // int Width() const; // int Height() const; // int GetSwizzle() const; // Frame GetFrame(int step = -1) const; // const Mask &GetMask(int step = -1) const; // const Point &Position() const; // const Point &Velocity() const; // const Angle &Facing() const; // Point Unit() const; // double Zoom() const; // const Government *GetGovernment() const; Ship() = default; // Construct and Load() at the same time. Ship(const DataNode &node); // Load data for a type of ship: void Load(const DataNode &node); // When loading a ship, some of the outfits it lists may not have been // loaded yet. So, wait until everything has been loaded, then call this. void FinishLoading(bool isNewInstance); // Check that this ship model and all its outfits have been loaded. bool IsValid() const; // Save a full description of this ship, as currently configured. void Save(DataWriter &out) const; const EsUuid &UUID() const noexcept; // Explicitly set this ship's ID. void SetUUID(const EsUuid &id); // Get the name of this particular ship. const std::string &Name() const; // Set / Get the name of this model of ship. void SetTrueModelName(const std::string &model); const std::string &TrueModelName() const; const std::string &DisplayModelName() const; const std::string &PluralModelName() const; // Get the name of this ship as a variant. const std::string &VariantName() const; // Get the generic noun (e.g. "ship") to be used when describing this ship. const std::string &Noun() const; // Get this ship's description. const std::string &Description() const; // Get the shipyard thumbnail for this ship. const Sprite *Thumbnail() const; // Get this ship's cost. int64_t Cost() const; int64_t ChassisCost() const; int64_t Strength() const; // Get the attraction and deterrance of this ship, for pirate raids. // This is only useful for the player's ships. double Attraction() const; double Deterrence() const; // Check if this ship is configured in such a way that it would be difficult // or impossible to fly. std::vector<std::string> FlightCheck() const; void SetPosition(Point position); // When creating a new ship, you must set the following: void Place(Point position = Point(), Point velocity = Point(), Angle angle = Angle(), bool isDeparting = true); void SetName(const std::string &name); void SetSystem(const System *system); void SetPlanet(const Planet *planet); void SetGovernment(const Government *government); void SetIsSpecial(bool special = true); bool IsSpecial() const; // If a ship belongs to the player, the player can give it commands. void SetIsYours(bool yours = true); bool IsYours() const; // A parked ship stays on a planet and requires no daily salary payments. void SetIsParked(bool parked = true); bool IsParked() const; // The player can selectively deploy their carried ships, rather than just all / none. void SetDeployOrder(bool shouldDeploy = true); bool HasDeployOrder() const; // Access the ship's personality, which affects how the AI behaves. const Personality &GetPersonality() const; void SetPersonality(const Personality &other); // Get a random hail message, or set the object used to generate them. If no // object is given the government's default will be used. const Phrase *GetHailPhrase() const; void SetHailPhrase(const Phrase &phrase); std::string GetHail(std::map<std::string, std::string> &&subs) const; bool CanSendHail(const PlayerInfo &player, bool allowUntranslated = false) const; // Access the ship's AI cache, containing the range and expected AI behavior for this ship. ShipAICache &GetAICache(); void UpdateCaches(); // Set the commands for this ship to follow this timestep. void SetCommands(const Command &command); void SetCommands(const FireCommand &firingCommand); const Command &Commands() const; const FireCommand &FiringCommands() const noexcept; // Move this ship. A ship may create effects as it moves, in particular if // it is in the process of blowing up. void Move(std::vector<Visual> &visuals, std::list<std::shared_ptr<Flotsam>> &flotsam); // Launch any ships that are ready to launch. void Launch(std::list<std::shared_ptr<Ship>> &ships, std::vector<Visual> &visuals); // Check if this ship is boarding another ship. If it is, it either plunders // it or, if this is a player ship, returns the ship it is plundering so a // plunder dialog can be displayed. std::shared_ptr<Ship> Board(bool autoPlunder, bool nonDocking); // Scan the target, if able and commanded to. Return a ShipEvent bitmask // giving the types of scan that succeeded. int Scan(const PlayerInfo &player); // Find out what fraction of the scan is complete. double CargoScanFraction() const; double OutfitScanFraction() const; // Fire any weapons that are ready to fire. If an anti-missile is ready, // instead of firing here this function returns true and it can be fired if // collision detection finds a missile in range. bool Fire(std::vector<Projectile> &projectiles, std::vector<Visual> &visuals); // Fire an anti-missile. Returns true if the missile was killed. bool FireAntiMissile(const Projectile &projectile, std::vector<Visual> &visuals); // Get the system this ship is in. Set to nullptr if the ship is being carried. const System *GetSystem() const; // Get the system this ship is in. If being carried, gets the parent's system. const System *GetActualSystem() const; // If the ship is landed, get the planet it has landed on. const Planet *GetPlanet() const; // Check the status of this ship. bool IsCapturable() const; bool IsTargetable() const; bool IsOverheated() const; bool IsDisabled() const; bool IsBoarding() const; bool IsLanding() const; bool IsFleeing() const; // Check if this ship is currently able to begin landing on its target. bool CanLand() const; // Check if some condition is keeping this ship from acting. (That is, it is // landing, hyperspacing, cloaking, disabled, or under-crewed.) bool CannotAct() const; // Get the degree to which this ship is cloaked. 1 means invisible and // impossible to hit or target; 0 means fully visible. double Cloaking() const; // Check if this ship is entering (rather than leaving) hyperspace. bool IsEnteringHyperspace() const; // Check if this ship is entering or leaving hyperspace. bool IsHyperspacing() const; int GetHyperspacePercentage() const; // Check if this ship is hyperspacing, specifically via a jump drive. bool IsUsingJumpDrive() const; // Check if this ship is currently able to enter hyperspace to it target. bool IsReadyToJump(bool waitingIsReady = false) const; // Get this ship's custom swizzle. int CustomSwizzle() const; // Check if the ship is thrusting. If so, the engine sound should be played. bool IsThrusting() const; bool IsReversing() const; bool IsSteering() const; // The direction that the ship is steering. If positive, the ship is steering right. // If negative, the ship is steering left. double SteeringDirection() const; // Get the points from which engine flares should be drawn. const std::vector<EnginePoint> &EnginePoints() const; const std::vector<EnginePoint> &ReverseEnginePoints() const; const std::vector<EnginePoint> &SteeringEnginePoints() const; // Make a ship disabled or destroyed, or bring back a destroyed ship. void Disable(); void Destroy(); void SelfDestruct(); void Restore(); bool IsDamaged() const; // Check if this ship has been destroyed. bool IsDestroyed() const; // Recharge and repair this ship (e.g. because it has landed). void Recharge(int rechargeType = Port::RechargeType::All, bool hireCrew = true); // Check if this ship is able to give the given ship enough fuel to jump. bool CanRefuel(const Ship &other) const; // Give the other ship enough fuel for it to jump. double TransferFuel(double amount, Ship *to); // Mark this ship as property of the given ship. Returns the number of crew transferred from the capturer. int WasCaptured(const std::shared_ptr<Ship> &capturer); // Clear all orders and targets this ship has (after capture or transfer of control). void ClearTargetsAndOrders(); // Get characteristics of this ship, as a fraction between 0 and 1. double Shields() const; double Hull() const; double Fuel() const; double Energy() const; // A ship's heat is generally between 0 and 1, but if it receives // heat damage the value can increase above 1. double Heat() const; // Get the ship's "health," where <=0 is disabled and 1 means full health. double Health() const; // Get the hull fraction at which this ship is disabled. double DisabledHull() const; // Get the maximum shield and hull values of the ship, accounting for multipliers. double MaxShields() const; double MaxHull() const; // Get the actual shield level of the ship. double ShieldLevel() const; // Get how disrupted this ship's shields are. double DisruptionLevel() const; // Get the (absolute) amount of hull that needs to be damaged until the // ship becomes disabled. Returns 0 if the ships hull is already below the // disabled threshold. double HullUntilDisabled() const; // Returns the remaining damage timer, for the damage overlay. int DamageOverlayTimer() const; // Get this ship's jump navigation, which contains information about how // much it costs for this ship to jump, how far it can jump, and its possible // jump methods. const ShipJumpNavigation &JumpNavigation() const; // Get the number of jumps this ship can make before running out of fuel. // This depends on how much fuel it has and what sort of hyperdrive it uses. // This does not show accurate number of jumps remaining beyond 1. // If followParent is false, this ship will not follow the parent. int JumpsRemaining(bool followParent = true) const; bool NeedsFuel(bool followParent = true) const; // Get the amount of fuel missing for the next jump (smart refueling) double JumpFuelMissing() const; // Get the heat level at idle. double IdleHeat() const; // Get the heat dissipation, in heat units per heat unit per frame. double HeatDissipation() const; // Get the maximum heat level, in heat units (not temperature). double MaximumHeat() const; // Calculate the multiplier for cooling efficiency. double CoolingEfficiency() const; // Calculate the drag on this ship. The drag can be no greater than the mass. double Drag() const; // Calculate the drag force that this ship experiences. The drag force is the drag // divided by the mass, up to a value of 1. double DragForce() const; // Access how many crew members this ship has or needs. int Crew() const; int RequiredCrew() const; // Get the reputational value of this ship's crew, which depends // on its crew size and "crew equivalent" attribute. int CrewValue() const; void AddCrew(int count); // Check if this is a ship that can be used as a flagship. bool CanBeFlagship() const; // Get this ship's movement characteristics. double Mass() const; double InertialMass() const; double TurnRate() const; double Acceleration() const; double MaxVelocity() const; double ReverseAcceleration() const; double MaxReverseVelocity() const; // This ship just got hit by a weapon. Take damage according to the // DamageDealt from that weapon. The return value is a ShipEvent type, // which may be a combination of PROVOKED, DISABLED, and DESTROYED. // Create any target effects as sparks. int TakeDamage(std::vector<Visual> &visuals, const DamageDealt &damage, const Government *sourceGovernment); // Apply a force to this ship, accelerating it. This might be from a weapon // impact, or from firing a weapon, for example. void ApplyForce(const Point &force, bool gravitational = false); // Check if this ship has bays to carry other ships. bool HasBays() const; // Check how many bays are not occupied at present. This does not check // whether one of your escorts plans to use that bay. int BaysFree(const std::string &category) const; // Check how many bays this ship has of a given category. int BaysTotal(const std::string &category) const; // Check if this ship has a bay free for the given other ship, and the // bay is not reserved for one of its existing escorts. bool CanCarry(const Ship &ship) const; // Check if this is a ship of a type that can be carried. bool CanBeCarried() const; // Move the given ship into one of the bays, if possible. bool Carry(const std::shared_ptr<Ship> &ship); // Empty the bays. If the carried ships are not special ships that are // saved in the player data, they will be deleted. Otherwise, they become // visible as ships landed on the same planet as their parent. void UnloadBays(); // Get a list of any ships this ship is carrying. const std::vector<Bay> &Bays() const; // Adjust the positions and velocities of any visible carried fighters or // drones. If any are visible, return true. bool PositionFighters() const; // Get cargo information. CargoHold &Cargo(); const CargoHold &Cargo() const; // Display box effects from jettisoning this much cargo. void Jettison(const std::string &commodity, int tons, bool wasAppeasing = false); void Jettison(const Outfit *outfit, int count, bool wasAppeasing = false); // Get the current attributes of this ship. const Outfit &Attributes() const; // Get the attributes of this ship chassis before any outfits were added. const Outfit &BaseAttributes() const; // Get the list of all outfits installed in this ship. const std::map<const Outfit *, int> &Outfits() const; // Find out how many outfits of the given type this ship contains. int OutfitCount(const Outfit *outfit) const; // Add or remove outfits. (To remove, pass a negative number.) void AddOutfit(const Outfit *outfit, int count); // Get the list of weapons. Armament &GetArmament(); const std::vector<Hardpoint> &Weapons() const; // Check if we are able to fire the given weapon (i.e. there is enough // energy, ammo, and fuel to fire it). bool CanFire(const Weapon *weapon) const; // Fire the given weapon (i.e. deduct whatever energy, ammo, or fuel it uses // and add whatever heat it generates). Assume that CanFire() is true. void ExpendAmmo(const Weapon &weapon); // Each ship can have a target system (to travel to), a target planet (to // land on) and a target ship (to move to, and attack if hostile). std::shared_ptr<Ship> GetTargetShip() const; std::shared_ptr<Ship> GetShipToAssist() const; const StellarObject *GetTargetStellar() const; // Get ship's target system (it should always be one jump / wormhole pass away). const System *GetTargetSystem() const; // Mining target. std::shared_ptr<Minable> GetTargetAsteroid() const; std::shared_ptr<Flotsam> GetTargetFlotsam() const; // Mark this ship as fleeing. void SetFleeing(bool fleeing = true); // Set this ship's targets. void SetTargetShip(const std::shared_ptr<Ship> &ship); void SetShipToAssist(const std::shared_ptr<Ship> &ship); void SetTargetStellar(const StellarObject *object); // Set ship's target system (it should always be one jump / wormhole pass away). void SetTargetSystem(const System *system); // Mining target. void SetTargetAsteroid(const std::shared_ptr<Minable> &asteroid); void SetTargetFlotsam(const std::shared_ptr<Flotsam> &flotsam); bool CanPickUp(const Flotsam &flotsam) const; // Manage escorts. When you set this ship's parent, it will automatically // register itself as an escort of that ship, and unregister itself from any // previous parent it had. void SetParent(const std::shared_ptr<Ship> &ship); std::shared_ptr<Ship> GetParent() const; const std::vector<std::weak_ptr<Ship>> &GetEscorts() const; // How many AI steps has this ship been lingering? int GetLingerSteps() const; // The AI wants the ship to linger for one AI step. void Linger(); private: // Various steps of Ship::Move: // Check if this ship has been in a different system from the player for so // long that it should be "forgotten." Also eliminate ships that have no // system set because they just entered a fighter bay. Clear the hyperspace // targets of ships that can't enter hyperspace. bool StepFlags(); // Step ship destruction logic. Returns 1 if the ship has been destroyed, -1 if it is being // destroyed, or 0 otherwise. int StepDestroyed(std::vector<Visual> &visuals, std::list<std::shared_ptr<Flotsam>> &flotsam); void DoGeneration(); void DoPassiveEffects(std::vector<Visual> &visuals, std::list<std::shared_ptr<Flotsam>> &flotsam); void DoJettison(std::list<std::shared_ptr<Flotsam>> &flotsam); void DoCloakDecision(); // Step hyperspace enter/exit logic. Returns true if ship is hyperspacing in or out. bool DoHyperspaceLogic(std::vector<Visual> &visuals); // Step landing logic. Returns true if the ship is landing or departing. bool DoLandingLogic(); void DoInitializeMovement(); void StepPilot(); void DoMovement(bool &isUsingAfterburner); void StepTargeting(); void DoEngineVisuals(std::vector<Visual> &visuals, bool isUsingAfterburner); // Add or remove a ship from this ship's list of escorts. void AddEscort(Ship &ship); void RemoveEscort(const Ship &ship); // Get the hull amount at which this ship is disabled. double MinimumHull() const; // Create one of this ship's explosions, within its mask. The explosions can // either stay over the ship, or spread out if this is the final explosion. void CreateExplosion(std::vector<Visual> &visuals, bool spread = false); // Place a "spark" effect, like ionization or disruption. void CreateSparks(std::vector<Visual> &visuals, const std::string &name, double amount); void CreateSparks(std::vector<Visual> &visuals, const Effect *effect, double amount); // Calculate the attraction and deterrance of this ship, for pirate raids. // This is only useful for the player's ships. double CalculateAttraction() const; double CalculateDeterrence() const; private: // Protected member variables of the Body class: // Point position; // Point velocity; // Angle angle; // double zoom; // int swizzle; // const Government *government; // Characteristics of the chassis: bool isDefined = false; const Ship *base = nullptr; std::string trueModelName; std::string displayModelName; std::string pluralModelName; std::string variantName; std::string noun; std::string description; const Sprite *thumbnail = nullptr; // Characteristics of this particular ship: EsUuid uuid; std::string name; bool canBeCarried = false; int forget = 0; bool isInSystem = true; // "Special" ships cannot be forgotten, and if they land on a planet, they // continue to exist and refuel instead of being deleted. bool isSpecial = false; bool isYours = false; bool isParked = false; bool shouldDeploy = false; bool isOverheated = false; bool isDisabled = false; bool isBoarding = false; bool hasBoarded = false; bool isFleeing = false; bool isThrusting = false; bool isReversing = false; bool isSteering = false; double steeringDirection = 0.; bool neverDisabled = false; bool isCapturable = true; bool isInvisible = false; int customSwizzle = -1; double cloak = 0.; double cloakDisruption = 0.; // Cached values for figuring out when anti-missile is in range. double antiMissileRange = 0.; double weaponRadius = 0.; // Cargo and outfit scanning takes time. double cargoScan = 0.; double outfitScan = 0.; double attraction = 0.; double deterrence = 0.; // Number of AI steps this ship has spent lingering int lingerSteps = 0; Command commands; FireCommand firingCommands; Personality personality; const Phrase *hail = nullptr; ShipAICache aiCache; // Installed outfits, cargo, etc.: Outfit attributes; Outfit baseAttributes; bool addAttributes = false; const Outfit *explosionWeapon = nullptr; std::map<const Outfit *, int> outfits; CargoHold cargo; std::list<std::shared_ptr<Flotsam>> jettisoned; std::vector<Bay> bays; // Cache the mass of carried ships to avoid repeatedly recomputing it. double carriedMass = 0.; std::vector<EnginePoint> enginePoints; std::vector<EnginePoint> reverseEnginePoints; std::vector<EnginePoint> steeringEnginePoints; Armament armament; // Various energy levels: double shields = 0.; double hull = 0.; double fuel = 0.; double energy = 0.; double heat = 0.; // Accrued "ion damage" that will affect this ship's energy over time. double ionization = 0.; // Accrued "scrambling damage" that will affect this ship's weaponry over time. double scrambling = 0.; // Accrued "disruption damage" that will affect this ship's shield effectiveness over time. double disruption = 0.; // Accrued "slowing damage" that will affect this ship's movement over time. double slowness = 0.; // Accrued "discharge damage" that will affect this ship's shields over time. double discharge = 0.; // Accrued "corrosion damage" that will affect this ship's hull over time. double corrosion = 0.; // Accrued "leak damage" that will affect this ship's fuel over time. double leakage = 0.; // Accrued "burn damage" that will affect this ship's heat over time. double burning = 0.; // Delays for shield generation and hull repair. int shieldDelay = 0; int hullDelay = 0; // Number of frames the damage overlay should be displayed, if any. int damageOverlayTimer = 0; // Acceleration can be created by engines, firing weapons, or weapon impacts. Point acceleration; int crew = 0; int pilotError = 0; int pilotOkay = 0; // Current status of this particular ship: const System *currentSystem = nullptr; // A Ship can be locked into one of three special states: landing, // hyperspacing, and exploding. Each one must track some special counters: const Planet *landingPlanet = nullptr; ShipJumpNavigation navigation; int hyperspaceCount = 0; const System *hyperspaceSystem = nullptr; bool isUsingJumpDrive = false; double hyperspaceFuelCost = 0.; Point hyperspaceOffset; // The hull may spring a "leak" (venting atmosphere, flames, blood, etc.) // when the ship is dying. class Leak { public: Leak(const Effect *effect = nullptr) : effect(effect) {} const Effect *effect = nullptr; Point location; Angle angle; int openPeriod = 60; int closePeriod = 60; }; std::vector<Leak> leaks; std::vector<Leak> activeLeaks; // Explosions that happen when the ship is dying: std::map<const Effect *, int> explosionEffects; unsigned explosionRate = 0; unsigned explosionCount = 0; unsigned explosionTotal = 0; std::map<const Effect *, int> finalExplosions; // Target ships, planets, systems, etc. std::weak_ptr<Ship> targetShip; std::weak_ptr<Ship> shipToAssist; const StellarObject *targetPlanet = nullptr; const System *targetSystem = nullptr; std::weak_ptr<Minable> targetAsteroid; std::weak_ptr<Flotsam> targetFlotsam; // Links between escorts and parents. std::vector<std::weak_ptr<Ship>> escorts; std::weak_ptr<Ship> parent; bool removeBays = false; }; #endif
0
endless-sky-master
endless-sky-master/source/LogbookPanel.cpp
/* LogbookPanel.cpp Copyright (c) 2017 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "LogbookPanel.h" #include "text/alignment.hpp" #include "Color.h" #include "text/DisplayText.h" #include "FillShader.h" #include "text/Font.h" #include "text/FontSet.h" #include "GameData.h" #include "text/layout.hpp" #include "PlayerInfo.h" #include "Preferences.h" #include "Screen.h" #include "Sprite.h" #include "SpriteSet.h" #include "SpriteShader.h" #include "UI.h" #include "text/WrappedText.h" #include <algorithm> #include <set> using namespace std; namespace { const double SIDEBAR_WIDTH = 100.; const double TEXT_WIDTH = 400.; const double PAD = 10.; const double WIDTH = SIDEBAR_WIDTH + TEXT_WIDTH; const double LINE_HEIGHT = 25.; // The minimum distance in pixels between the selected month and the edge of the screen before the month gets centered const double MINIMUM_SELECTION_DISTANCE = LINE_HEIGHT * 3; const double GAP = 30.; const string MONTH[] = { " January", " February", " March", " April", " May", " June", " July", " August", " September", " October", " November", " December"}; } LogbookPanel::LogbookPanel(PlayerInfo &player) : player(player) { SetInterruptible(false); if(!player.Logbook().empty()) { selectedDate = (--player.Logbook().end())->first; selectedName = MONTH[selectedDate.Month() - 1]; } Update(); } // Draw this panel. void LogbookPanel::Draw() { // Dim out everything outside this panel. DrawBackdrop(); // Draw the panel. The sidebar should be slightly darker than the rest. const Color &sideColor = *GameData::Colors().Get("logbook sidebar"); FillShader::Fill( Point(Screen::Left() + .5 * SIDEBAR_WIDTH, 0.), Point(SIDEBAR_WIDTH, Screen::Height()), sideColor); const Color &backColor = *GameData::Colors().Get("logbook background"); FillShader::Fill( Point(Screen::Left() + SIDEBAR_WIDTH + .5 * TEXT_WIDTH, 0.), Point(TEXT_WIDTH, Screen::Height()), backColor); const Color &lineColor = *GameData::Colors().Get("logbook line"); FillShader::Fill( Point(Screen::Left() + SIDEBAR_WIDTH - .5, 0.), Point(1., Screen::Height()), lineColor); const Sprite *edgeSprite = SpriteSet::Get("ui/right edge"); if(edgeSprite->Height()) { // If the screen is high enough, the edge sprite should repeat. double spriteHeight = edgeSprite->Height(); Point pos( Screen::Left() + WIDTH + .5 * edgeSprite->Width(), Screen::Top() + .5 * spriteHeight); for( ; pos.Y() - .5 * spriteHeight < Screen::Bottom(); pos.Y() += spriteHeight) SpriteShader::Draw(edgeSprite, pos); } // Colors to be used for drawing the log. const Font &font = FontSet::Get(14); const Color &dim = *GameData::Colors().Get("dim"); const Color &medium = *GameData::Colors().Get("medium"); const Color &bright = *GameData::Colors().Get("bright"); // Draw the sidebar. // The currently selected sidebar item should be highlighted. This is how // big the highlight rectangle is. Point highlightSize(SIDEBAR_WIDTH - 4., LINE_HEIGHT); Point highlightOffset = Point(4. - PAD, 0.) + .5 * highlightSize; Point textOffset(0., .5 * (LINE_HEIGHT - font.Height())); // Start at this point on the screen: Point pos = Screen::TopLeft() + Point(PAD, PAD - categoryScroll); for(size_t i = 0; i < contents.size(); ++i) { if(selectedDate ? dates[i].Month() == selectedDate.Month() : selectedName == contents[i]) { FillShader::Fill(pos + highlightOffset - Point(1., 0.), highlightSize + Point(0., 2.), lineColor); FillShader::Fill(pos + highlightOffset, highlightSize, backColor); } font.Draw(contents[i], pos + textOffset, dates[i].Month() ? medium : bright); pos.Y() += LINE_HEIGHT; } maxCategoryScroll = max(0., maxCategoryScroll + pos.Y() - Screen::Bottom()); // Parameters for drawing the main text: WrappedText wrap(font); wrap.SetAlignment(Alignment::JUSTIFIED); wrap.SetWrapWidth(TEXT_WIDTH - 2. * PAD); // Draw the main text. pos = Screen::TopLeft() + Point(SIDEBAR_WIDTH + PAD, PAD + .5 * (LINE_HEIGHT - font.Height()) - scroll); // Branch based on whether this is an ordinary log month or a special page. auto pit = player.SpecialLogs().find(selectedName); if(selectedDate && begin != end) { const auto layout = Layout(static_cast<int>(TEXT_WIDTH - 2. * PAD), Alignment::RIGHT); for(auto it = begin; it != end; ++it) { string date = it->first.ToString(); font.Draw({date, layout}, pos + Point(0., textOffset.Y()), dim); pos.Y() += LINE_HEIGHT; wrap.Wrap(it->second); wrap.Draw(pos, medium); pos.Y() += wrap.Height() + GAP; } } else if(!selectedDate && pit != player.SpecialLogs().end()) { for(const auto &it : pit->second) { font.Draw(it.first, pos + textOffset, bright); pos.Y() += LINE_HEIGHT; wrap.Wrap(it.second); wrap.Draw(pos, medium); pos.Y() += wrap.Height() + GAP; } } maxScroll = max(0., scroll + pos.Y() - Screen::Bottom()); } bool LogbookPanel::KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) { if(key == 'd' || key == SDLK_ESCAPE || (key == 'w' && (mod & (KMOD_CTRL | KMOD_GUI)))) GetUI()->Pop(this); else if(key == SDLK_PAGEUP || key == SDLK_PAGEDOWN) { double direction = (key == SDLK_PAGEUP) - (key == SDLK_PAGEDOWN); Drag(0., (Screen::Height() - 100.) * direction); } else if(key == SDLK_HOME || key == SDLK_END) { double direction = (key == SDLK_HOME) - (key == SDLK_END); Drag(0., maxScroll * direction); } else if(key == SDLK_UP || key == SDLK_DOWN) { // Find the index of the currently selected line. size_t i = 0; for( ; i < contents.size(); ++i) if(contents[i] == selectedName) break; if(i == contents.size()) return true; if(key == SDLK_DOWN) { ++i; if(i >= contents.size()) i = 0; } else if(i) { --i; // Skip the entry that is just the currently selected year. if(dates[i] && !dates[i].Month()) { // If this is the very top of the list, don't move the selection // up. (That is, you can't select the year heading line.) if(i) --i; else ++i; } } else i = contents.size() - 1; if(contents[i] != selectedName) { selectedDate = dates[i]; selectedName = contents[i]; scroll = 0.; Update(key == SDLK_UP); // Find our currently selected item again for(i = 0 ; i < contents.size(); ++i) if(contents[i] == selectedName) break; if(i == contents.size()) return true; // Check if it's too far down or up int position = i * LINE_HEIGHT - categoryScroll; // If it's out of bounds, recenter it if(position < MINIMUM_SELECTION_DISTANCE || position > (Screen::Height() - MINIMUM_SELECTION_DISTANCE)) categoryScroll = position - (Screen::Height() / 2); categoryScroll = max(categoryScroll, 0.); } } return true; } bool LogbookPanel::Click(int x, int y, int clicks) { x -= Screen::Left(); y -= Screen::Top(); if(x < SIDEBAR_WIDTH) { size_t index = (y - PAD + categoryScroll) / LINE_HEIGHT; if(index < contents.size()) { selectedDate = dates[index]; selectedName = contents[index]; scroll = 0.; // If selecting a different year, select the first month in that // year. Update(false); } } else if(x > WIDTH) GetUI()->Pop(this); return true; } bool LogbookPanel::Drag(double dx, double dy) { if((hoverPoint.X() - Screen::Left()) > SIDEBAR_WIDTH) scroll = max(0., min(maxScroll, scroll - dy)); else categoryScroll = max(0., min(maxCategoryScroll, categoryScroll - dy)); return true; } bool LogbookPanel::Scroll(double dx, double dy) { return Drag(0., dy * Preferences::ScrollSpeed()); } bool LogbookPanel::Hover(int x, int y) { hoverPoint = Point(x, y); return true; } void LogbookPanel::Update(bool selectLast) { contents.clear(); dates.clear(); for(const auto &it : player.SpecialLogs()) { contents.emplace_back(it.first); dates.emplace_back(); } // The logbook should never be opened if it has no entries, but just in case: if(player.Logbook().empty()) { begin = end = player.Logbook().end(); return; } // Check what years and months have entries for them. set<int> years; set<int> months; for(const auto &it : player.Logbook()) { years.insert(it.first.Year()); if(it.first.Year() == selectedDate.Year() && it.first.Month() >= 1 && it.first.Month() <= 12) months.insert(it.first.Month()); } // Generate the table of contents. for(int year : years) { contents.emplace_back(to_string(year)); dates.emplace_back(0, 0, year); if(selectedDate && year == selectedDate.Year()) for(int month : months) { contents.emplace_back(MONTH[month - 1]); dates.emplace_back(0, month, year); } } // If a special category is selected, bail out here. if(!selectedDate) { begin = end = player.Logbook().end(); return; } // Make sure a month is selected, within the current year. if(!selectedDate.Month()) { selectedDate = Date(0, selectLast ? *--months.end() : *months.begin(), selectedDate.Year()); selectedName = MONTH[selectedDate.Month() - 1]; } // Get the range of entries that include the selected month. begin = player.Logbook().lower_bound(Date(0, selectedDate.Month(), selectedDate.Year())); end = player.Logbook().lower_bound(Date(32, selectedDate.Month(), selectedDate.Year())); }
0
endless-sky-master
endless-sky-master/source/StartConditions.cpp
/* StartConditions.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "StartConditions.h" #include "DataNode.h" #include "text/Format.h" #include "GameData.h" #include "Logger.h" #include "Planet.h" #include "Ship.h" #include "Sprite.h" #include "SpriteSet.h" #include "System.h" #include <algorithm> #include <sstream> using namespace std; namespace { // A default string to return if somehow the current state does not exist in the state map. static const string ILLEGAL = "(ILLEGAL STATE)"; } StartConditions::StartConditions(const DataNode &node) { Load(node); } void StartConditions::Load(const DataNode &node) { // When a plugin modifies an existing starting condition, default to // clearing the previously-defined description text. The plugin may // amend it by using "add description" StartInfo &unlocked = infoByState[StartState::UNLOCKED]; bool clearDescription = !unlocked.description.empty(); for(const DataNode &child : node) { // Check for the "add" or "remove" keyword. bool add = (child.Token(0) == "add"); bool remove = (child.Token(0) == "remove"); if((add || remove) && child.Size() < 2) { child.PrintTrace("Skipping " + child.Token(0) + " with no key given:"); continue; } // Determine if the child is a "core" or "UNLOCKED state" attribute. Removal of such attributes // is handled below. if(!remove && (CoreStartData::LoadChild(child, add) || LoadStateChild(child, unlocked, clearDescription, add))) continue; // Otherwise, we should try to parse it. const string &key = child.Token((add || remove) ? 1 : 0); int valueIndex = (add || remove) ? 2 : 1; bool hasValue = (child.Size() > valueIndex); const string &value = child.Token(hasValue ? valueIndex : 0); if(remove) { if(key == "name") unlocked.name.clear(); else if(key == "description") unlocked.description.clear(); else if(key == "thumbnail") unlocked.thumbnail = nullptr; else if(key == "ships") ships.clear(); else if(key == "ship" && hasValue) ships.erase(remove_if(ships.begin(), ships.end(), [&value](const Ship &s) noexcept -> bool { return s.TrueModelName() == value; }), ships.end()); else if(key == "conversation") conversation = ExclusiveItem<Conversation>(); else if(key == "to" && hasValue) { if(value == "display") toDisplay = ConditionSet(); else if(value == "reveal") toReveal = ConditionSet(); else if(value == "unlock") toUnlock = ConditionSet(); else child.PrintTrace("Skipping unrecognized attribute:"); } else if(key == "conditions") conditions = ConditionSet(); else child.PrintTrace("Skipping unsupported use of \"remove\":"); } else if(key == "ship" && hasValue) { // TODO: support named stock ships. // Assume that child nodes introduce a full ship definition. Even without child nodes, // Ship::Load + Ship::FinishLoading will create the expected ship instance if there is // a 3rd token (i.e. this will be treated as though it were a ship variant definition, // without making the variant available to the rest of GameData). if(child.HasChildren() || child.Size() >= add + 3) ships.emplace_back(child); // If there's only 2 tokens & there's no child nodes, the created instance would be ill-formed. else child.PrintTrace("Skipping unsupported use of a \"stock\" ship (a full definition is required):"); } else if(key == "conversation" && child.HasChildren() && !add) conversation = ExclusiveItem<Conversation>(Conversation(child)); else if(key == "conversation" && hasValue && !child.HasChildren()) conversation = ExclusiveItem<Conversation>(GameData::Conversations().Get(value)); else if(add) child.PrintTrace("Skipping unsupported use of \"add\":"); // Only global conditions are supported in these ConditionSets. The global conditions are accessed directly, // and therefore do not need the "global: " prefix. else if(key == "to" && hasValue) { if(value == "display") toDisplay.Load(child); else if(value == "reveal") toReveal.Load(child); else if(value == "unlock") toUnlock.Load(child); else child.PrintTrace("Skipping unrecognized attribute:"); } else if(key == "on" && hasValue) { // The HIDDEN state contains no information. The UNLOCKED StateInfo is a child of the root node // instead of an "on" node. if(value == "display") LoadState(child, StartState::DISPLAYED); else if(value == "reveal") LoadState(child, StartState::REVEALED); } else conditions.Add(child); } // The unlocked state must have at least some information. if(unlocked.description.empty()) unlocked.description = "(No description provided.)"; if(unlocked.name.empty()) unlocked.name = "(Unnamed start)"; // If the REVEALED or DISPLAYED states are missing information, fill them in with "???". // Also use the UNLOCKED state thumbnail if the other states are missing one. FillState(StartState::REVEALED, unlocked.thumbnail); FillState(StartState::DISPLAYED, unlocked.thumbnail); // If no identifier is supplied, the creator would like this starting scenario to be isolated from // other plugins. Thus, use an unguessable, non-reproducible identifier, this item's memory address. if(identifier.empty() && node.Size() >= 2) identifier = node.Token(1); else if(identifier.empty()) { stringstream addr; addr << unlocked.name << " " << this; identifier = addr.str(); } } // Finish loading the ship definitions. void StartConditions::FinishLoading() { for(Ship &ship : ships) ship.FinishLoading(true); // The UNLOCKED StartInfo should always display the correct information. Therefore, we get the // planet and system names now. If we had gotten these during Load, the planet and system provided // may now be invalid, meaning the CoreStartData would actually send the start to New Boston instead // of what was displayed. StartInfo &unlocked = infoByState[StartState::UNLOCKED]; unlocked.planet = GetPlanet().Name(); unlocked.system = GetSystem().Name(); unlocked.date = GetDate().ToString(); unlocked.credits = Format::Credits(GetAccounts().Credits()); unlocked.debt = Format::Credits(GetAccounts().TotalDebt()); string reason = GetConversation().Validate(); if(!GetConversation().IsValidIntro() || !reason.empty()) Logger::LogError("Warning: The start scenario \"" + Identifier() + "\" (named \"" + unlocked.name + "\") has an invalid starting conversation." + (reason.empty() ? "" : "\n\t" + std::move(reason))); } bool StartConditions::IsValid() const { // A start must specify a valid system. if(!system || !system->IsValid()) return false; // A start must specify a valid planet in its specified system. if(!planet || !planet->IsValid() || planet->GetSystem() != system) return false; // A start must reference a valid "intro" conversation, either stock or custom. if(!GetConversation().IsValidIntro() || !GetConversation().Validate().empty()) return false; // All ship models must be valid. if(any_of(ships.begin(), ships.end(), [](const Ship &it) noexcept -> bool { return !it.IsValid(); })) return false; return true; } const ConditionSet &StartConditions::GetConditions() const noexcept { return conditions; } const vector<Ship> &StartConditions::Ships() const noexcept { return ships; } const Conversation &StartConditions::GetConversation() const { return *conversation; } const Sprite *StartConditions::GetThumbnail() const noexcept { // The state we ask for should always be present in the map, but just in case it isn't, // make sure we're not accessing out of bound information. auto it = infoByState.find(state); return it == infoByState.end() ? nullptr : it->second.thumbnail; } const string &StartConditions::GetDisplayName() const noexcept { auto it = infoByState.find(state); return it == infoByState.end() ? ILLEGAL : it->second.name; } const string &StartConditions::GetDescription() const noexcept { auto it = infoByState.find(state); return it == infoByState.end() ? ILLEGAL : it->second.description; } const string &StartConditions::GetPlanetName() const noexcept { auto it = infoByState.find(state); return it == infoByState.end() ? ILLEGAL : it->second.planet; } const string &StartConditions::GetSystemName() const noexcept { auto it = infoByState.find(state); return it == infoByState.end() ? ILLEGAL : it->second.system; } const string &StartConditions::GetDateString() const noexcept { auto it = infoByState.find(state); return it == infoByState.end() ? ILLEGAL : it->second.date; } const string &StartConditions::GetCredits() const noexcept { auto it = infoByState.find(state); return it == infoByState.end() ? ILLEGAL : it->second.credits; } const string &StartConditions::GetDebt() const noexcept { auto it = infoByState.find(state); return it == infoByState.end() ? ILLEGAL : it->second.debt; } bool StartConditions::Visible(const ConditionsStore &conditionsStore) const { return toDisplay.Test(conditionsStore); } void StartConditions::SetState(const ConditionsStore &conditionsStore) { if(toDisplay.Test(conditionsStore)) { if(toReveal.Test(conditionsStore)) { if(toUnlock.Test(conditionsStore)) state = StartState::UNLOCKED; else state = StartState::REVEALED; } else state = StartState::DISPLAYED; } else state = StartState::HIDDEN; } bool StartConditions::IsUnlocked() const { return state == StartState::UNLOCKED; } void StartConditions::LoadState(const DataNode &node, StartState state) { StartInfo &info = infoByState[state]; bool clearDescription = !info.description.empty(); for(const auto &child : node) LoadStateChild(child, info, clearDescription, false); } bool StartConditions::LoadStateChild(const DataNode &child, StartInfo &info, bool &clearDescription, bool isAdd) { const string &key = child.Token(isAdd ? 1 : 0); int valueIndex = (isAdd) ? 2 : 1; bool hasValue = (child.Size() > valueIndex); const string &value = child.Token(hasValue ? valueIndex : 0); if(key == "name" && hasValue) info.name = value; else if(key == "description" && hasValue) { if(clearDescription) { info.description.clear(); clearDescription = false; } info.description += value + "\n"; } else if(key == "thumbnail" && hasValue) info.thumbnail = SpriteSet::Get(value); else if(key == "system" && hasValue) info.system = value; else if(key == "planet" && hasValue) info.planet = value; else if(key == "date" && hasValue) info.date = value; else if(key == "credits" && hasValue) info.credits = value; else if(key == "debt" && hasValue) info.debt = value; else return false; return true; } void StartConditions::FillState(StartState fillState, const Sprite *thumbnail) { StartInfo &fill = infoByState[fillState]; if(!fill.thumbnail) fill.thumbnail = thumbnail; if(fill.name.empty()) fill.name = "???"; if(fill.description.empty()) fill.description = "???"; if(fill.system.empty()) fill.system = "???"; if(fill.planet.empty()) fill.planet = "???"; if(fill.date.empty()) fill.date = "???"; if(fill.credits.empty()) fill.credits = "???"; if(fill.debt.empty()) fill.debt = "???"; }
0
endless-sky-master
endless-sky-master/source/StellarObject.cpp
/* StellarObject.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "StellarObject.h" #include "GameData.h" #include "Government.h" #include "Planet.h" #include "Politics.h" #include "Radar.h" #include <algorithm> using namespace std; // Object default constructor. StellarObject::StellarObject() : planet(nullptr), distance(0.), speed(0.), offset(0.), parent(-1), message(nullptr), isStar(false), isStation(false), isMoon(false) { // Unlike ships and projectiles, stellar objects are not drawn shrunk to half size, // because they do not need to be so sharp. zoom = 2.; } // Get the radius of this planet, i.e. how close you must be to land. double StellarObject::Radius() const { double radius = -1.; if(HasSprite()) radius = .5 * min(Width(), Height()); // Special case: stars may have a huge cloud around them, but only count the // core of the cloud as part of the radius. if(isStar) radius = min(radius, 80.); return radius; } bool StellarObject::HasValidPlanet() const { return planet && planet->IsValid(); } const Planet *StellarObject::GetPlanet() const { return planet; } // Only planets that you can land on have names. const string &StellarObject::Name() const { static const string UNKNOWN = "???"; return (planet && !planet->Name().empty()) ? planet->Name() : UNKNOWN; } // If it is impossible to land on this planet, get the message // explaining why (e.g. too hot, too cold, etc.). const string &StellarObject::LandingMessage() const { // Check if there's a custom message for this sprite type. if(GameData::HasLandingMessage(GetSprite())) return GameData::LandingMessage(GetSprite()); static const string EMPTY; return (message ? *message : EMPTY); } // Get the color to be used for displaying this object. int StellarObject::RadarType(const Ship *ship) const { if(IsStar()) return Radar::STAR; else if(!planet || !planet->IsAccessible(ship)) return Radar::INACTIVE; else if(planet->IsWormhole()) return Radar::ANOMALOUS; else if(GameData::GetPolitics().HasDominated(planet)) return Radar::PLAYER; else if(planet->CanLand()) return Radar::FRIENDLY; else if(!planet->GetGovernment()->IsEnemy()) return Radar::UNFRIENDLY; return Radar::HOSTILE; } // Check if this is a star. bool StellarObject::IsStar() const { return isStar; } // Check if this is a station. bool StellarObject::IsStation() const { return isStation; } // Check if this is a moon. bool StellarObject::IsMoon() const { return isMoon; } // Get this object's parent index (in the System's vector of objects). int StellarObject::Parent() const { return parent; } // Find out how far this object is from its parent. double StellarObject::Distance() const { return distance; } const vector<RandomEvent<Hazard>> &StellarObject::Hazards() const { return hazards; }
0
endless-sky-master
endless-sky-master/source/Conversation.h
/* Conversation.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef CONVERSATION_H_ #define CONVERSATION_H_ #include "ConditionSet.h" #include "ConditionsStore.h" #include "GameAction.h" #include <map> #include <string> #include <utility> #include <vector> class DataNode; class DataWriter; class Sprite; // Class representing a conversation, generally occurring when the player is asked to // accept or decline a mission. The conversation can take different paths depending // on what responses you choose, leading you to accept, decline, or (rarely) to be // killed. A conversation can also branch based on various condition flags that // are set for the player, or even trigger various changes to the game's state. class Conversation { public: // The possible outcomes of a conversation: static const int ACCEPT = -1; static const int DECLINE = -2; static const int DEFER = -3; // These 3 options force the player to TakeOff (if landed), or cause // the boarded NPCs to explode, in addition to respectively duplicating // the above mission outcomes. static const int LAUNCH = -4; static const int FLEE = -5; static const int DEPART = -6; // The player may simply die (if landed on a planet or captured while // in space), or the flagship might also explode. static const int DIE = -7; static const int EXPLODE = -8; // Check whether the given conversation outcome is one that forces the // player to immediately depart. static bool RequiresLaunch(int outcome); public: Conversation() = default; // Construct and Load() at the same time. Conversation(const DataNode &node); // Read or write to files. void Load(const DataNode &node); void Save(DataWriter &out) const; // Check if any data is loaded in this conversation object. bool IsEmpty() const noexcept; // Check if this conversation includes a name prompt. bool IsValidIntro() const noexcept; // Check if the actions in this conversation are valid. std::string Validate() const; // Generate a new conversation from this template, filling in any text // substitutions and instantiating any actions. Conversation Instantiate(std::map<std::string, std::string> &subs, int jumps = 0, int payload = 0) const; // The beginning of the conversation is node 0. Some nodes have choices for // the user to select; others just automatically continue to another node. // Nodes may also display images or include conditional branches. bool IsChoice(int node) const; // Some choices have conditions in each option. If all options are disabled, // the choice cannot be shown. bool HasAnyChoices(const ConditionsStore &vars, int node) const; // If the given node is a choice node, check how many choices it offers. int Choices(int node) const; // Check if the given conversation node is a conditional branch. bool IsBranch(int node) const; // Check if the given conversation node performs an action. bool IsAction(int node) const; const ConditionSet &Conditions(int node) const; const GameAction &GetAction(int node) const; const std::string &Text(int node, int element = 0) const; const Sprite *Scene(int node) const; // Find out where the conversation goes if the given option is chosen. int NextNodeForChoice(int node, int element = 0) const; // Go to the next node of the conversation, ignoring any choices. int StepToNextNode(int node) const; // Returns whether the given node should be displayed. // Returns false if: // - The node (or element) is out of range. // - The node is not a choice node, and element is non-zero. // - The node (or element) has conditions and those conditions are not met. // and true otherwise. bool ShouldDisplayNode(const ConditionsStore &vars, int node, int element = 0) const; // Returns true if the given node index is in the range of valid nodes for // this Conversation. // Note: This function only considers actual Conversation nodes to be valid // choices. The negative "outcome" values (ACCEPT, DEFER, etc.) are special // sentinel values, rather than indices of Conversation nodes, and are // therefore considered invalid by this function. bool NodeIsValid(int node) const; // Returns true if the given node index is in the range of valid nodes for // this Conversation *and* the given element index is in the range of valid // elements for the given node. bool ElementIsValid(int node, int element) const; private: // This serves multiple purposes: // - In a regular text node, there's exactly one of these. It contains the // text data, the index of the next node to unconditionally visit, and, // optionally, a condition set which, if not met, prevents the text from // being displayed (without affecting which node is processed next). // - In a choice node, there's one of these for each possible choice, // containing the text to display, the node the choice leads to, and, // optionally, the conditions under which to offer the choice. // - In a branch node, there's two of these. The first one contains the // condition for the branch. If the condition is met, the "next" member // of the first element is followed. If it's not met, it's the second // element whose "next" member is followed. class Element { public: explicit Element(std::string text, int next) : text(std::move(text)), next(next) {} // The text to display: std::string text; // The next node to visit: int next; // Conditions for displaying the text: ConditionSet conditions; }; // The conversation is a network of "nodes" that you travel between by // making choices (or by automatic branches that depend on the condition // variable values for the current player). class Node { public: // Construct a new node. Each paragraph of conversation that involves no // choice can be merged into what came before it, to simplify things. explicit Node(bool isChoice = false) noexcept : isChoice(isChoice), canMergeOnto(!isChoice) {} // The condition expressions that determine the next node to load, or // whether to display. ConditionSet conditions; // Tasks performed when this node is reached. GameAction actions; // See Element's comment above for what this actually entails. std::vector<Element> elements; // This distinguishes "choice" nodes from "branch" or text nodes. If // this value is false, a one-element node is considered text, and a // node with more than one element is considered a "branch". bool isChoice; // Keep track of whether it's possible to merge future nodes onto this. bool canMergeOnto; // Image that should be shown along with this text. const Sprite *scene = nullptr; }; private: // Parse the children of the given node to see if they contain any "gotos" // or "conditions." If so, link them up properly. Return true if gotos or // conditions were found. bool LoadDestinations(const DataNode &node); // Parse the children to see if there is a condition. bool HasDisplayRestriction(const DataNode &node); // Add a label, pointing to whatever node is created next. void AddLabel(const std::string &label, const DataNode &node); // Set up a "goto". Depending on whether the named label has been seen yet // or not, it is either resolved immediately or added to the unresolved set. void Goto(const std::string &label, int node, int element = 0); // Add an "empty" node. It will contain one empty line of text, with its // goto link set to fall through to the next node. void AddNode(); private: // While parsing the conversation, keep track of what labels link to what // nodes. If a name appears in a goto before that label appears, remember // what node and what element it appeared at in order to link it up later. std::map<std::string, int> labels; std::multimap<std::string, std::pair<int, int>> unresolved; // The actual conversation data: std::vector<Node> nodes; }; #endif
0
endless-sky-master
endless-sky-master/source/GameWindow.h
/* GameWindow.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef GAMEWINDOW_H_ #define GAMEWINDOW_H_ #include "Preferences.h" #include <string> // This class is a collection of global functions for handling SDL_Windows. class GameWindow { public: static std::string SDLVersions(); static bool Init(); static void Quit(); // Paint the next frame in the main window. static void Step(); // Ensure the proper icon is set on the main window. static void SetIcon(); // Handle resize events of the main window. static void AdjustViewport(); // Attempt to set the game's VSync setting. static bool SetVSync(Preferences::VSync state); // Last known windowed-mode width & height. static int Width(); static int Height(); static bool IsMaximized(); static bool IsFullscreen(); static void ToggleFullscreen(); // Print the error message in the terminal, error file, and message box. // Checks for video system errors and records those as well. static void ExitWithError(const std::string& message, bool doPopUp = true); }; #endif
0
endless-sky-master
endless-sky-master/source/LoadPanel.cpp
/* LoadPanel.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "LoadPanel.h" #include "Color.h" #include "Command.h" #include "ConversationPanel.h" #include "DataFile.h" #include "Dialog.h" #include "text/DisplayText.h" #include "Files.h" #include "FillShader.h" #include "text/Font.h" #include "text/FontSet.h" #include "GameData.h" #include "Information.h" #include "Interface.h" #include "text/layout.hpp" #include "MainPanel.h" #include "MaskManager.h" #include "PlayerInfo.h" #include "Preferences.h" #include "Rectangle.h" #include "StarField.h" #include "StartConditionsPanel.h" #include "text/truncate.hpp" #include "UI.h" #include "opengl.h" #include <algorithm> #include <cstdlib> #include <stdexcept> #include <utility> using namespace std; namespace { // Return a pair containing settings to use for time formatting. pair<pair<string, string>, size_t> TimestampFormatString(Preferences::DateFormat fmt) { // pair<string, string>: Linux (1st) and Windows (2nd) format strings // size_t: BUF_SIZE if(fmt == Preferences::DateFormat::YMD) return make_pair(make_pair("%F %T", "%F %T"), 26); if(fmt == Preferences::DateFormat::MDY) return make_pair(make_pair("%-I:%M %p on %b %-d, %Y", "%#I:%M %p on %b %#d, %Y"), 25); if(fmt == Preferences::DateFormat::DMY) return make_pair(make_pair("%-I:%M %p on %-d %b %Y", "%#I:%M %p on %#d %b %Y"), 24); // Return YYYY-MM-DD by default. return make_pair(make_pair("%F %T", "%F %T"), 26); } // Convert a time_t to a human-readable time and date. string TimestampString(time_t timestamp) { pair<pair<string, string>, size_t> fmt = TimestampFormatString(Preferences::GetDateFormat()); char* buf = static_cast<char*>(std::malloc(fmt.second)); #ifdef _WIN32 tm date; localtime_s(&date, &timestamp); auto str = string(buf, strftime(buf, fmt.second, fmt.first.second.c_str(), &date)); #else const tm *date = localtime(&timestamp); auto str = string(buf, strftime(buf, fmt.second, fmt.first.first.c_str(), date)); #endif std::free(buf); return str; } // Extract the date from this pilot's most recent save. string FileDate(const string &filename) { string date = "0000-00-00"; DataFile file(filename); for(const DataNode &node : file) if(node.Token(0) == "date") { int year = node.Value(3); int month = node.Value(2); int day = node.Value(1); date[0] += (year / 1000) % 10; date[1] += (year / 100) % 10; date[2] += (year / 10) % 10; date[3] += year % 10; date[5] += (month / 10) % 10; date[6] += month % 10; date[8] += (day / 10) % 10; date[9] += day % 10; break; } return date; } // Only show tooltips if the mouse has hovered in one place for this amount // of time. const int HOVER_TIME = 60; } LoadPanel::LoadPanel(PlayerInfo &player, UI &gamePanels) : player(player), gamePanels(gamePanels), selectedPilot(player.Identifier()), pilotBox(GameData::Interfaces().Get("load menu")->GetBox("pilots")), snapshotBox(GameData::Interfaces().Get("load menu")->GetBox("snapshots")) { // If you have a player loaded, and the player is on a planet, make sure // the player is saved so that any snapshot you create will be of the // player's current state, rather than one planet ago. Only do this if the // game is paused and 'dirty', i.e. the "main panel" is not on top, and we // actually were using the loaded save. if(player.GetPlanet() && !player.IsDead() && !gamePanels.IsTop(&*gamePanels.Root()) && gamePanels.CanSave()) player.Save(); UpdateLists(); } void LoadPanel::Draw() { glClear(GL_COLOR_BUFFER_BIT); GameData::Background().Draw(Point(), Point()); const Font &font = FontSet::Get(14); Information info; if(loadedInfo.IsLoaded()) { info.SetString("pilot", loadedInfo.Name()); if(loadedInfo.ShipSprite()) { info.SetSprite("ship sprite", loadedInfo.ShipSprite()); info.SetString("ship", loadedInfo.ShipName()); } if(!loadedInfo.GetSystem().empty()) info.SetString("system", loadedInfo.GetSystem()); if(!loadedInfo.GetPlanet().empty()) info.SetString("planet", loadedInfo.GetPlanet()); info.SetString("credits", loadedInfo.Credits()); info.SetString("date", loadedInfo.GetDate()); info.SetString("playtime", loadedInfo.GetPlayTime()); } else info.SetString("pilot", "No Pilot Loaded"); if(!selectedPilot.empty()) info.SetCondition("pilot selected"); if(!player.IsDead() && player.IsLoaded() && !selectedPilot.empty()) info.SetCondition("pilot alive"); if(selectedFile.find('~') != string::npos) info.SetCondition("snapshot selected"); if(loadedInfo.IsLoaded()) info.SetCondition("pilot loaded"); const Interface *loadPanel = GameData::Interfaces().Get("load menu"); GameData::Interfaces().Get("menu background")->Draw(info, this); loadPanel->Draw(info, this); GameData::Interfaces().Get("menu player info")->Draw(info, this); // Draw the list of pilots. { // The list has space for 14 entries. Alpha should be 100% for Y = -157 to // 103, and fade to 0 at 10 pixels beyond that. const Point topLeft = pilotBox.TopLeft(); Point currentTopLeft = topLeft + Point(0, -sideScroll); const double top = topLeft.Y(); const double bottom = top + pilotBox.Height(); const double hTextPad = loadPanel->GetValue("pilot horizontal text pad"); const double fadeOut = loadPanel->GetValue("pilot fade out"); for(const auto &it : files) { const Point drawPoint = currentTopLeft; currentTopLeft += Point(0., 20.); if(drawPoint.Y() < top - fadeOut) continue; if(drawPoint.Y() > bottom - fadeOut) continue; const double width = pilotBox.Width(); Rectangle zone(drawPoint + Point(width / 2., 10.), Point(width, 20.)); const Point textPoint(drawPoint.X() + hTextPad, zone.Center().Y() - font.Height() / 2); bool isHighlighted = (it.first == selectedPilot || (hasHover && zone.Contains(hoverPoint))); double alpha = min((drawPoint.Y() - (top - fadeOut)) * .1, (bottom - fadeOut - drawPoint.Y()) * .1); alpha = max(alpha, 0.); alpha = min(alpha, 1.); if(it.first == selectedPilot) FillShader::Fill(zone.Center(), zone.Dimensions(), Color(.1 * alpha, 0.)); const int textWidth = pilotBox.Width() - 2. * hTextPad; font.Draw({it.first, {textWidth, Truncate::BACK}}, textPoint, Color((isHighlighted ? .7 : .5) * alpha, 0.)); } } // The hover count "decays" over time if not hovering over a saved game. if(hoverCount) --hoverCount; string hoverText; // Draw the list of snapshots for the selected pilot. if(!selectedPilot.empty() && files.count(selectedPilot)) { const Point topLeft = snapshotBox.TopLeft(); Point currentTopLeft = topLeft + Point(0, -centerScroll); const double top = topLeft.Y(); const double bottom = top + snapshotBox.Height(); const double hTextPad = loadPanel->GetValue("snapshot horizontal text pad"); const double fadeOut = loadPanel->GetValue("snapshot fade out"); for(const auto &it : files.find(selectedPilot)->second) { const Point drawPoint = currentTopLeft; currentTopLeft += Point(0., 20.); if(drawPoint.Y() < top - fadeOut) continue; if(drawPoint.Y() > bottom - fadeOut) continue; const string &file = it.first; Rectangle zone(drawPoint + Point(snapshotBox.Width() / 2., 10.), Point(snapshotBox.Width(), 20.)); const Point textPoint(drawPoint.X() + hTextPad, zone.Center().Y() - font.Height() / 2); bool isHovering = (hasHover && zone.Contains(hoverPoint)); bool isHighlighted = (file == selectedFile || isHovering); if(isHovering) { hoverCount = min(HOVER_TIME, hoverCount + 2); if(hoverCount == HOVER_TIME) hoverText = TimestampString(it.second); } double alpha = min((drawPoint.Y() - (top - fadeOut)) * .1, (bottom - fadeOut - drawPoint.Y()) * .1); alpha = max(alpha, 0.); alpha = min(alpha, 1.); if(file == selectedFile) FillShader::Fill(zone.Center(), zone.Dimensions(), Color(.1 * alpha, 0.)); size_t pos = file.find('~') + 1; const string name = file.substr(pos, file.size() - 4 - pos); const int textWidth = snapshotBox.Width() - 2. * hTextPad; font.Draw({name, {textWidth, Truncate::BACK}}, textPoint, Color((isHighlighted ? .7 : .5) * alpha, 0.)); } } if(!hoverText.empty()) { Point boxSize(font.Width(hoverText) + 20., 30.); FillShader::Fill(hoverPoint + .5 * boxSize, boxSize, *GameData::Colors().Get("tooltip background")); font.Draw(hoverText, hoverPoint + Point(10., 10.), *GameData::Colors().Get("medium")); } } bool LoadPanel::KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) { if(key == 'n') { // If no player is loaded, the "Enter Ship" button becomes "New Pilot." // Request that the player chooses a start scenario. // StartConditionsPanel also handles the case where there's no scenarios. GetUI()->Push(new StartConditionsPanel(player, gamePanels, GameData::StartOptions(), this)); } else if(key == 'd' && !selectedPilot.empty()) { GetUI()->Push(new Dialog(this, &LoadPanel::DeletePilot, "Are you sure you want to delete the selected pilot, \"" + loadedInfo.Name() + "\", and all their saved games?\n\n(This will permanently delete the pilot data.)\n" + "Confirm the name of the pilot you want to delete.", [this](const string &pilot) { return pilot == loadedInfo.Name(); })); } else if(key == 'a' && !player.IsDead() && player.IsLoaded()) { auto it = files.find(selectedPilot); if(it == files.end() || it->second.empty() || it->second.front().first.size() < 4) return false; nameToConfirm.clear(); string lastSave = Files::Saves() + it->second.front().first; GetUI()->Push(new Dialog(this, &LoadPanel::SnapshotCallback, "Enter a name for this snapshot, or use the most recent save's date:", FileDate(lastSave))); } else if(key == 'R' && !selectedFile.empty()) { string fileName = selectedFile.substr(selectedFile.rfind('/') + 1); if(!(fileName == selectedPilot + ".txt")) GetUI()->Push(new Dialog(this, &LoadPanel::DeleteSave, "Are you sure you want to delete the selected saved game file, \"" + selectedFile + "\"?")); } else if((key == 'l' || key == 'e') && !selectedPilot.empty()) { // Is the selected file a snapshot or the pilot's main file? string fileName = selectedFile.substr(selectedFile.rfind('/') + 1); if(fileName == selectedPilot + ".txt") LoadCallback(); else GetUI()->Push(new Dialog(this, &LoadPanel::LoadCallback, "If you load this snapshot, it will overwrite your current game. " "Any progress will be lost, unless you have saved other snapshots. " "Are you sure you want to do that?")); } else if(key == 'b' || command.Has(Command::MENU) || (key == 'w' && (mod & (KMOD_CTRL | KMOD_GUI)))) GetUI()->Pop(this); else if((key == SDLK_DOWN || key == SDLK_UP) && !files.empty()) { auto pit = files.find(selectedPilot); if(sideHasFocus) { auto it = files.begin(); int index = 0; for( ; it != files.end(); ++it, ++index) if(it->first == selectedPilot) break; if(key == SDLK_DOWN) { const int lastVisibleIndex = (sideScroll / 20.) + 13.; if(index >= lastVisibleIndex) sideScroll += 20.; ++it; if(it == files.end()) { it = files.begin(); sideScroll = 0.; } } else { const int firstVisibleIndex = sideScroll / 20.; if(index <= firstVisibleIndex) sideScroll -= 20.; if(it == files.begin()) { it = files.end(); sideScroll = max(0., 20. * files.size() - 280.); } --it; } selectedPilot = it->first; selectedFile = it->second.front().first; centerScroll = 0.; } else if(pit != files.end()) { auto it = pit->second.begin(); int index = 0; for( ; it != pit->second.end(); ++it, ++index) if(it->first == selectedFile) break; if(key == SDLK_DOWN) { ++it; const int lastVisibleIndex = (centerScroll / 20.) + 13.; if(index >= lastVisibleIndex) centerScroll += 20.; if(it == pit->second.end()) { it = pit->second.begin(); centerScroll = 0.; } } else { const int firstVisibleIndex = centerScroll / 20.; if(index <= firstVisibleIndex) centerScroll -= 20.; if(it == pit->second.begin()) { it = pit->second.end(); centerScroll = max(0., 20. * pit->second.size() - 280.); } --it; } selectedFile = it->first; } loadedInfo.Load(Files::Saves() + selectedFile); } else if(key == SDLK_LEFT) sideHasFocus = true; else if(key == SDLK_RIGHT) sideHasFocus = false; else return false; return true; } bool LoadPanel::Click(int x, int y, int clicks) { // When the user clicks, clear the hovered state. hasHover = false; const Point click(x, y); if(pilotBox.Contains(click)) { int selected = (y + sideScroll - pilotBox.Top()) / 20; int i = 0; for(const auto &it : files) if(i++ == selected && selectedPilot != it.first) { selectedPilot = it.first; selectedFile = it.second.front().first; centerScroll = 0; } } else if(snapshotBox.Contains(click)) { int selected = (y + centerScroll - snapshotBox.Top()) / 20; int i = 0; auto filesIt = files.find(selectedPilot); if(filesIt == files.end()) return true; for(const auto &it : filesIt->second) if(i++ == selected) { const bool sameSelected = selectedFile == it.first; selectedFile = it.first; if(sameSelected && clicks > 1) KeyDown('l', 0, Command(), true); break; } } else return false; if(!selectedFile.empty()) loadedInfo.Load(Files::Saves() + selectedFile); return true; } bool LoadPanel::Hover(int x, int y) { if(x >= pilotBox.Left() && x < pilotBox.Right()) sideHasFocus = true; else if(x >= snapshotBox.Left() && x < snapshotBox.Right()) sideHasFocus = false; hasHover = true; hoverPoint = Point(x, y); // Tooltips should not pop up unless the mouse stays in one place for the // full hover time. Otherwise, every time the user scrubs the mouse over the // list, tooltips will appear after one second. if(hoverCount < HOVER_TIME) hoverCount = 0; return true; } bool LoadPanel::Drag(double dx, double dy) { auto it = files.find(selectedPilot); if(sideHasFocus) sideScroll = max(0., min(20. * files.size() - 280., sideScroll - dy)); else if(!selectedPilot.empty() && it != files.end()) centerScroll = max(0., min(20. * it->second.size() - 280., centerScroll - dy)); return true; } bool LoadPanel::Scroll(double dx, double dy) { return Drag(0., dy * Preferences::ScrollSpeed()); } void LoadPanel::UpdateLists() { files.clear(); vector<string> fileList = Files::List(Files::Saves()); for(const string &path : fileList) { // Skip any files that aren't text files. if(path.compare(path.length() - 4, 4, ".txt")) continue; string fileName = Files::Name(path); // The file name is either "Pilot Name.txt" or "Pilot Name~SnapshotTitle.txt". size_t pos = fileName.find('~'); const bool isSnapshot = (pos != string::npos); if(!isSnapshot) pos = fileName.size() - 4; string pilotName = fileName.substr(0, pos); auto &savesList = files[pilotName]; savesList.emplace_back(fileName, Files::Timestamp(path)); // Ensure that the main save for this pilot, not a snapshot, is first in the list. if(!isSnapshot) swap(savesList.front(), savesList.back()); } for(auto &it : files) { // Don't include the first item in the sort if this pilot has a non-snapshot save. auto start = it.second.begin(); if(start->first.find('~') == string::npos) ++start; sort(start, it.second.end(), [](const pair<string, time_t> &a, const pair<string, time_t> &b) -> bool { return a.second > b.second || (a.second == b.second && a.first < b.first); } ); } if(!files.empty()) { if(selectedPilot.empty()) selectedPilot = files.begin()->first; if(selectedFile.empty()) { auto it = files.find(selectedPilot); if(it != files.end()) { selectedFile = it->second.front().first; loadedInfo.Load(Files::Saves() + selectedFile); } } } } // Snapshot name callback. void LoadPanel::SnapshotCallback(const string &name) { auto it = files.find(selectedPilot); if(it == files.end() || it->second.empty() || it->second.front().first.size() < 4) return; string from = Files::Saves() + it->second.front().first; string suffix = name.empty() ? FileDate(from) : name; string extension = "~" + suffix + ".txt"; // If a file with this name already exists, make sure the player // actually wants to overwrite it. string to = from.substr(0, from.size() - 4) + extension; if(Files::Exists(to) && suffix != nameToConfirm) { nameToConfirm = suffix; GetUI()->Push(new Dialog(this, &LoadPanel::SnapshotCallback, "Warning: \"" + suffix + "\" is being used for an existing snapshot.\nOverwrite it?", suffix)); } else WriteSnapshot(from, to); } // This name is the one to be used, even if it already exists. void LoadPanel::WriteSnapshot(const string &sourceFile, const string &snapshotName) { // Copy the autosave to a new, named file. Files::Copy(sourceFile, snapshotName); if(Files::Exists(snapshotName)) { UpdateLists(); selectedFile = Files::Name(snapshotName); loadedInfo.Load(Files::Saves() + selectedFile); } else GetUI()->Push(new Dialog("Error: unable to create the file \"" + snapshotName + "\".")); } // Load snapshot callback. void LoadPanel::LoadCallback() { // First, make sure the previous MainPanel has been deleted, so // its background thread is no longer running. gamePanels.Reset(); gamePanels.CanSave(true); player.Load(loadedInfo.Path()); // Scale any new masks that might have been added by the newly loaded save file. GameData::GetMaskManager().ScaleMasks(); GetUI()->PopThrough(GetUI()->Root().get()); gamePanels.Push(new MainPanel(player)); // It takes one step to figure out the planet panel should be created, and // another step to actually place it. So, take two steps to avoid a flicker. gamePanels.StepAll(); gamePanels.StepAll(); } void LoadPanel::DeletePilot(const string &) { loadedInfo.Clear(); if(selectedPilot == player.Identifier()) player.Clear(); auto it = files.find(selectedPilot); if(it == files.end()) return; bool failed = false; for(const auto &fit : it->second) { string path = Files::Saves() + fit.first; Files::Delete(path); failed |= Files::Exists(path); } if(failed) GetUI()->Push(new Dialog("Deleting pilot files failed.")); sideHasFocus = true; selectedPilot.clear(); selectedFile.clear(); UpdateLists(); } void LoadPanel::DeleteSave() { loadedInfo.Clear(); string pilot = selectedPilot; string path = Files::Saves() + selectedFile; Files::Delete(path); if(Files::Exists(path)) GetUI()->Push(new Dialog("Deleting snapshot file failed.")); sideHasFocus = true; selectedPilot.clear(); UpdateLists(); auto it = files.find(pilot); if(it != files.end() && !it->second.empty()) { selectedFile = it->second.front().first; selectedPilot = pilot; loadedInfo.Load(Files::Saves() + selectedFile); sideHasFocus = false; } }
0
endless-sky-master
endless-sky-master/source/GameWindow.cpp
/* GameWindow.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "GameWindow.h" #include "Files.h" #include "ImageBuffer.h" #include "Logger.h" #include "Screen.h" #include "opengl.h" #include <SDL2/SDL.h> #include <cstring> #include <sstream> #include <string> using namespace std; namespace { SDL_Window *mainWindow = nullptr; SDL_GLContext context = nullptr; int width = 0; int height = 0; bool supportsAdaptiveVSync = false; // Logs SDL errors and returns true if found bool checkSDLerror() { string message = SDL_GetError(); if(!message.empty()) { Logger::LogError("(SDL message: \"" + message + "\")"); SDL_ClearError(); return true; } return false; } } string GameWindow::SDLVersions() { SDL_version built; SDL_version linked; SDL_VERSION(&built); SDL_GetVersion(&linked); auto toString = [](const SDL_version &v) -> string { return to_string(v.major) + "." + to_string(v.minor) + "." + to_string(v.patch); }; return "Compiled against SDL v" + toString(built) + "\nUsing SDL v" + toString(linked); } bool GameWindow::Init() { #ifdef _WIN32 // Tell Windows this process is high dpi aware and doesn't need to get scaled. SDL_SetHint(SDL_HINT_WINDOWS_DPI_AWARENESS, "permonitorv2"); #elif defined(__linux__) // Set the class name for the window on Linux. Used to set the application icon. // This sets it for both X11 and Wayland. setenv("SDL_VIDEO_X11_WMCLASS", "io.github.endless_sky.endless_sky", true); #endif // This needs to be called before any other SDL commands. if(SDL_Init(SDL_INIT_VIDEO) != 0) { checkSDLerror(); return false; } // Get details about the current display. SDL_DisplayMode mode; if(SDL_GetCurrentDisplayMode(0, &mode)) { ExitWithError("Unable to query monitor resolution!"); return false; } if(mode.refresh_rate && mode.refresh_rate < 60) Logger::LogError("Warning: low monitor frame rate detected (" + to_string(mode.refresh_rate) + ")." " The game will run more slowly."); // Make the window just slightly smaller than the monitor resolution. int minWidth = 640; int minHeight = 480; int maxWidth = mode.w; int maxHeight = mode.h; if(maxWidth < minWidth || maxHeight < minHeight) { ExitWithError("Monitor resolution is too small!"); return false; } int windowWidth = maxWidth - 100; int windowHeight = maxHeight - 100; // Decide how big the window should be. if(Screen::RawWidth() && Screen::RawHeight()) { // Load the previously saved window dimensions. windowWidth = min(windowWidth, Screen::RawWidth()); windowHeight = min(windowHeight, Screen::RawHeight()); } // Settings that must be declared before the window creation. Uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI; if(Preferences::ScreenModeSetting() == "fullscreen") flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; else if(Preferences::Has("maximized")) flags |= SDL_WINDOW_MAXIMIZED; // The main window spawns visibly at this point. mainWindow = SDL_CreateWindow("Endless Sky", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, flags); if(!mainWindow) { ExitWithError("Unable to create window!"); return false; } // Settings that must be declared before the context creation. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); #ifdef _WIN32 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #endif #ifdef ES_GLES SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); #else SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #endif SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); context = SDL_GL_CreateContext(mainWindow); if(!context) { ExitWithError("Unable to create OpenGL context! Check if your system supports OpenGL 3.0."); return false; } if(SDL_GL_MakeCurrent(mainWindow, context)) { ExitWithError("Unable to set the current OpenGL context!"); return false; } // Initialize GLEW. #if !defined(__APPLE__) && !defined(ES_GLES) glewExperimental = GL_TRUE; GLenum err = glewInit(); #ifdef GLEW_ERROR_NO_GLX_DISPLAY if(err != GLEW_OK && err != GLEW_ERROR_NO_GLX_DISPLAY) #else if(err != GLEW_OK) #endif { ExitWithError("Unable to initialize GLEW!"); return false; } #endif // Check that the OpenGL version is high enough. const char *glVersion = reinterpret_cast<const char *>(glGetString(GL_VERSION)); if(!glVersion || !*glVersion) { ExitWithError("Unable to query the OpenGL version!"); return false; } const char *glslVersion = reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION)); if(!glslVersion || !*glslVersion) { ostringstream out; out << "Unable to query the GLSL version. OpenGL version is " << glVersion << "."; ExitWithError(out.str()); return false; } if(*glVersion < '3') { ostringstream out; out << "Endless Sky requires OpenGL version 3.0 or higher." << endl; out << "Your OpenGL version is " << glVersion << ", GLSL version " << glslVersion << "." << endl; out << "Please update your graphics drivers."; ExitWithError(out.str()); return false; } // OpenGL settings glClearColor(0.f, 0.f, 0.0f, 1.f); glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // Check for support of various graphical features. supportsAdaptiveVSync = OpenGL::HasAdaptiveVSyncSupport(); // Enable the user's preferred VSync state, otherwise update to an available // value (e.g. if an external program is forcing a particular VSync state). if(!SetVSync(Preferences::VSyncState())) Preferences::ToggleVSync(); // Make sure the screen size and view-port are set correctly. AdjustViewport(); #ifndef __APPLE__ // On OS X, setting the window icon will cause that same icon to be used // in the dock and the application switcher. That's not something we // want, because the ".icns" icon that is used automatically is prettier. SetIcon(); #endif return true; } // Clean up the SDL context, window, and shut down SDL. void GameWindow::Quit() { // Make sure the cursor is visible. SDL_ShowCursor(true); // Clean up in the reverse order that everything is launched. //#ifndef _WIN32 // Under windows, this cleanup code causes intermittent crashes. if(context) SDL_GL_DeleteContext(context); //#endif if(mainWindow) SDL_DestroyWindow(mainWindow); SDL_Quit(); } void GameWindow::Step() { SDL_GL_SwapWindow(mainWindow); } void GameWindow::SetIcon() { if(!mainWindow) return; // Load the icon file. ImageBuffer buffer; if(!buffer.Read(Files::Resources() + "icon.png")) return; if(!buffer.Pixels() || !buffer.Width() || !buffer.Height()) return; // Convert the icon to an SDL surface. SDL_Surface *surface = SDL_CreateRGBSurfaceFrom(buffer.Pixels(), buffer.Width(), buffer.Height(), 32, 4 * buffer.Width(), 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); if(surface) { SDL_SetWindowIcon(mainWindow, surface); SDL_FreeSurface(surface); } } void GameWindow::AdjustViewport() { if(!mainWindow) return; // Get the window's size in screen coordinates. int windowWidth, windowHeight; SDL_GetWindowSize(mainWindow, &windowWidth, &windowHeight); // Only save the window size when not in fullscreen mode. if(!GameWindow::IsFullscreen()) { width = windowWidth; height = windowHeight; } // Round the window size up to a multiple of 2, even if this // means one pixel of the display will be clipped. int roundWidth = (windowWidth + 1) & ~1; int roundHeight = (windowHeight + 1) & ~1; Screen::SetRaw(roundWidth, roundHeight); // Find out the drawable dimensions. If this is a high- DPI display, this // may be larger than the window. int drawWidth, drawHeight; SDL_GL_GetDrawableSize(mainWindow, &drawWidth, &drawHeight); Screen::SetHighDPI(drawWidth > windowWidth || drawHeight > windowHeight); // Set the viewport to go off the edge of the window, if necessary, to get // everything pixel-aligned. drawWidth = (drawWidth * roundWidth) / windowWidth; drawHeight = (drawHeight * roundHeight) / windowHeight; glViewport(0, 0, drawWidth, drawHeight); } // Attempts to set the requested SDL Window VSync to the given state. Returns false // if the operation could not be completed successfully. bool GameWindow::SetVSync(Preferences::VSync state) { if(!context) return false; const int originalState = SDL_GL_GetSwapInterval(); int interval = 1; switch(state) { case Preferences::VSync::adaptive: interval = -1; break; case Preferences::VSync::off: interval = 0; break; case Preferences::VSync::on: interval = 1; break; default: return false; } // Do not attempt to enable adaptive VSync when unsupported, // as this can crash older video drivers. if(interval == -1 && !supportsAdaptiveVSync) return false; if(SDL_GL_SetSwapInterval(interval) == -1) { checkSDLerror(); SDL_GL_SetSwapInterval(originalState); return false; } return SDL_GL_GetSwapInterval() == interval; } // Last window width, in windowed mode. int GameWindow::Width() { return width; } // Last window height, in windowed mode. int GameWindow::Height() { return height; } bool GameWindow::IsMaximized() { return (SDL_GetWindowFlags(mainWindow) & SDL_WINDOW_MAXIMIZED); } bool GameWindow::IsFullscreen() { return (SDL_GetWindowFlags(mainWindow) & SDL_WINDOW_FULLSCREEN_DESKTOP); } void GameWindow::ToggleFullscreen() { // This will generate a window size change event, // no need to adjust the viewport here. if(IsFullscreen()) { SDL_SetWindowFullscreen(mainWindow, 0); SDL_SetWindowSize(mainWindow, width, height); } else SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP); } void GameWindow::ExitWithError(const string &message, bool doPopUp) { // Print the error message in the terminal and the error file. Logger::LogError(message); checkSDLerror(); // Show the error message in a message box. if(doPopUp) { SDL_MessageBoxData box; box.flags = SDL_MESSAGEBOX_ERROR; box.window = nullptr; box.title = "Endless Sky: Error"; box.message = message.c_str(); box.colorScheme = nullptr; SDL_MessageBoxButtonData button; button.flags = SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT; button.buttonid = 0; button.text = "OK"; box.numbuttons = 1; box.buttons = &button; int result = 0; SDL_ShowMessageBox(&box, &result); } GameWindow::Quit(); }
0
endless-sky-master
endless-sky-master/source/Politics.h
/* Politics.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef POLITICS_H_ #define POLITICS_H_ #include <map> #include <set> #include <string> class Government; class Planet; class PlayerInfo; class Ship; // This class represents the current state of relationships between governments // in the game, and in particular the relationship of each government to the // player. The player has a reputation with each government, which is affected // by what they do for a government or its allies or enemies. class Politics { public: // Reset to the initial political state defined in the game data. void Reset(); bool IsEnemy(const Government *first, const Government *second) const; // Commit the given "offense" against the given government (which may not // actually consider it to be an offense). This may result in temporary // hostilities (if the event type is PROVOKE), or a permanent change to your // reputation. void Offend(const Government *gov, int eventType, int count = 1); // Bribe the given government to be friendly to you for one day. void Bribe(const Government *gov); // Check if the given ship can land on the given planet. bool CanLand(const Ship &ship, const Planet *planet) const; // Check if the player can land on the given planet. bool CanLand(const Planet *planet) const; bool CanUseServices(const Planet *planet) const; // Bribe a planet to let the player's ships land there. void BribePlanet(const Planet *planet, bool fullAccess); void DominatePlanet(const Planet *planet, bool dominate = true); bool HasDominated(const Planet *planet) const; // Check to see if the player has done anything they should be fined for. // Each government can only fine you once per day. std::string Fine(PlayerInfo &player, const Government *gov, int scan, const Ship *target, double security); // Get or set your reputation with the given government. double Reputation(const Government *gov) const; void AddReputation(const Government *gov, double value); void SetReputation(const Government *gov, double value); // Reset any temporary effects (typically because a day has passed). void ResetDaily(); private: // attitude[target][other] stores how much an action toward the given target // government will affect your reputation with the given other government. // The relationships need not be perfectly symmetrical. For example, just // because Republic ships will help a merchant under attack does not mean // that merchants will come to the aid of Republic ships. std::map<const Government *, double> reputationWith; std::set<const Government *> provoked; std::set<const Government *> bribed; std::map<const Planet *, bool> bribedPlanets; std::set<const Planet *> dominatedPlanets; std::set<const Government *> fined; }; #endif
0
endless-sky-master
endless-sky-master/source/BatchShader.cpp
/* BatchShader.cpp Copyright (c) 2017 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "BatchShader.h" #include "Screen.h" #include "Shader.h" #include "Sprite.h" using namespace std; namespace { Shader shader; // Uniforms: GLint scaleI; GLint frameCountI; // Vertex data: GLint vertI; GLint texCoordI; GLint alphaI; GLuint vao; GLuint vbo; } // Initialize the shaders. void BatchShader::Init() { static const char *vertexCode = "// vertex batch shader\n" "uniform vec2 scale;\n" "in vec2 vert;\n" "in vec3 texCoord;\n" "in float alpha;\n" "out vec3 fragTexCoord;\n" "out float fragAlpha;\n" "void main() {\n" " gl_Position = vec4(vert * scale, 0, 1);\n" " fragTexCoord = texCoord;\n" " fragAlpha = alpha;\n" "}\n"; static const char *fragmentCode = "// fragment batch shader\n" "precision mediump float;\n" #ifdef ES_GLES "precision mediump sampler2DArray;\n" #endif "uniform sampler2DArray tex;\n" "uniform float frameCount;\n" "in vec3 fragTexCoord;\n" "in float fragAlpha;\n" "out vec4 finalColor;\n" "void main() {\n" " float first = floor(fragTexCoord.z);\n" " float second = mod(ceil(fragTexCoord.z), frameCount);\n" " float fade = fragTexCoord.z - first;\n" " finalColor = mix(\n" " texture(tex, vec3(fragTexCoord.xy, first)),\n" " texture(tex, vec3(fragTexCoord.xy, second)), fade);\n" " finalColor *= vec4(fragAlpha);\n" "}\n"; // Compile the shaders. shader = Shader(vertexCode, fragmentCode); // Get the indices of the uniforms and attributes. scaleI = shader.Uniform("scale"); frameCountI = shader.Uniform("frameCount"); vertI = shader.Attrib("vert"); texCoordI = shader.Attrib("texCoord"); alphaI = shader.Attrib("alpha"); // Make sure we're using texture 0. glUseProgram(shader.Object()); glUniform1i(shader.Uniform("tex"), 0); glUseProgram(0); // Generate the buffer for uploading the batch vertex data. glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); // In this VAO, enable the two vertex arrays and specify their byte offsets. constexpr auto stride = 6 * sizeof(float); glEnableVertexAttribArray(vertI); glVertexAttribPointer(vertI, 2, GL_FLOAT, GL_FALSE, stride, nullptr); // The 3 texture fields (s, t, frame) come after the x,y pixel fields. auto textureOffset = reinterpret_cast<const GLvoid *>(2 * sizeof(float)); glEnableVertexAttribArray(texCoordI); glVertexAttribPointer(texCoordI, 3, GL_FLOAT, GL_FALSE, stride, textureOffset); // The alpha value. auto alphaOffset = reinterpret_cast<const GLvoid *>(5 * sizeof(float)); glEnableVertexAttribArray(alphaI); glVertexAttribPointer(alphaI, 1, GL_FLOAT, GL_FALSE, stride, alphaOffset); // Unbind the buffer and the VAO, but leave the vertex attrib arrays enabled // in the VAO so they will be used when it is bound. glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void BatchShader::Bind() { glUseProgram(shader.Object()); glBindVertexArray(vao); // Bind the vertex buffer so we can upload data to it. glBindBuffer(GL_ARRAY_BUFFER, vbo); // Set up the screen scale. GLfloat scale[2] = {2.f / Screen::Width(), -2.f / Screen::Height()}; glUniform2fv(scaleI, 1, scale); } void BatchShader::Add(const Sprite *sprite, bool isHighDPI, const vector<float> &data) { // Do nothing if there are no sprites to draw. if(data.empty()) return; // First, bind the proper texture. glBindTexture(GL_TEXTURE_2D_ARRAY, sprite->Texture(isHighDPI)); // The shader also needs to know how many frames the texture has. glUniform1f(frameCountI, sprite->Frames()); // Upload the vertex data. glBufferData(GL_ARRAY_BUFFER, sizeof(float) * data.size(), data.data(), GL_STREAM_DRAW); // Draw all the vertices. glDrawArrays(GL_TRIANGLE_STRIP, 0, data.size() / 6); } void BatchShader::Unbind() { // Unbind everything in reverse order. glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glUseProgram(0); }
0
endless-sky-master
endless-sky-master/source/Planet.cpp
/* Planet.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Planet.h" #include "DataNode.h" #include "text/Format.h" #include "GameData.h" #include "Government.h" #include "Logger.h" #include "PlayerInfo.h" #include "Politics.h" #include "Random.h" #include "Ship.h" #include "ShipEvent.h" #include "SpriteSet.h" #include "System.h" #include "Wormhole.h" #include <algorithm> using namespace std; namespace { const string WORMHOLE = "wormhole"; const string PLANET = "planet"; // Planet attributes in the form "requires: <attribute>" restrict the ability of ships to land // unless the ship has all required attributes. void SetRequiredAttributes(const set<string> &attributes, set<string> &required) { static const string PREFIX = "requires: "; static const string PREFIX_END = "requires:!"; required.clear(); for_each(attributes.lower_bound(PREFIX), attributes.lower_bound(PREFIX_END), [&](const string &attribute) { required.emplace_hint(required.cend(), attribute.substr(PREFIX.length())); }); } } // Load a planet's description from a file. void Planet::Load(const DataNode &node, Set<Wormhole> &wormholes) { if(node.Size() < 2) return; name = node.Token(1); // The planet's name is needed to save references to this object, so a // flag is used to test whether Load() was called at least once for it. isDefined = true; // If this planet has been loaded before, these sets of items should be // reset instead of appending to them: set<string> shouldOverwrite = {"attributes", "description", "spaceport", "port"}; for(const DataNode &child : node) { // Check for the "add" or "remove" keyword. bool add = (child.Token(0) == "add"); bool remove = (child.Token(0) == "remove"); if((add || remove) && child.Size() < 2) { child.PrintTrace("Skipping " + child.Token(0) + " with no key given:"); continue; } // Get the key and value (if any). const string &key = child.Token((add || remove) ? 1 : 0); int valueIndex = (add || remove) ? 2 : 1; bool hasValue = (child.Size() > valueIndex); const string &value = child.Token(hasValue ? valueIndex : 0); // Check for conditions that require clearing this key's current value. // "remove <key>" means to clear the key's previous contents. // "remove <key> <value>" means to remove just that value from the key. bool removeAll = (remove && !hasValue); // "<key> clear" is the deprecated way of writing "remove <key>." removeAll |= (!add && !remove && hasValue && value == "clear"); // If this is the first entry for the given key, and we are not in "add" // or "remove" mode, its previous value should be cleared. bool overwriteAll = (!add && !remove && !removeAll && shouldOverwrite.count(key)); // Clear the data of the given type. if(removeAll || overwriteAll) { // Clear the data of the given type. if(key == "music") music.clear(); else if(key == "attributes") attributes.clear(); else if(key == "description") description.clear(); else if(key == "port" || key == "spaceport") { port = Port(); // Overwriting either port or spaceport counts as overwriting the other. if(overwriteAll) { shouldOverwrite.erase("port"); shouldOverwrite.erase("spaceport"); } } else if(key == "shipyard") shipSales.clear(); else if(key == "outfitter") outfitSales.clear(); else if(key == "government") government = nullptr; else if(key == "required reputation") requiredReputation = 0.; else if(key == "bribe") bribe = 0.; else if(key == "security") security = 0.; else if(key == "tribute") tribute = 0; else if(key == "wormhole") wormhole = nullptr; // If not in "overwrite" mode, move on to the next node. if(overwriteAll) shouldOverwrite.erase(key); else continue; } if(key == "port") port.Load(child); // Handle the attributes which can be "removed." else if(!hasValue) { child.PrintTrace("Error: Expected key to have a value:"); continue; } else if(key == "attributes") { if(remove) for(int i = valueIndex; i < child.Size(); ++i) attributes.erase(child.Token(i)); else for(int i = valueIndex; i < child.Size(); ++i) attributes.insert(child.Token(i)); } else if(key == "shipyard") { if(remove) shipSales.erase(GameData::Shipyards().Get(value)); else shipSales.insert(GameData::Shipyards().Get(value)); } else if(key == "outfitter") { if(remove) outfitSales.erase(GameData::Outfitters().Get(value)); else outfitSales.insert(GameData::Outfitters().Get(value)); } // Handle the attributes which cannot be "removed." else if(remove) { child.PrintTrace("Error: Cannot \"remove\" a specific value from the given key:"); continue; } else if(key == "landscape") landscape = SpriteSet::Get(value); else if(key == "music") music = value; else if(key == "description" || key == "spaceport") { const bool isDescription = key == "description"; if(!isDescription) port.LoadDefaultSpaceport(); string &text = isDescription ? description : port.Description(); if(!text.empty() && !value.empty() && value[0] > ' ') text += '\t'; text += value; text += '\n'; } else if(key == "government") government = GameData::Governments().Get(value); else if(key == "required reputation") requiredReputation = child.Value(valueIndex); else if(key == "bribe") bribe = child.Value(valueIndex); else if(key == "security") { customSecurity = true; security = child.Value(valueIndex); } else if(key == "tribute") { tribute = child.Value(valueIndex); bool resetFleets = !defenseFleets.empty(); for(const DataNode &grand : child) { if(grand.Token(0) == "threshold" && grand.Size() >= 2) defenseThreshold = grand.Value(1); else if(grand.Token(0) == "fleet") { if(grand.Size() >= 2 && !grand.HasChildren()) { // Allow only one "tribute" node to define the tribute fleets. if(resetFleets) { defenseFleets.clear(); resetFleets = false; } defenseFleets.insert(defenseFleets.end(), grand.Size() >= 3 ? grand.Value(2) : 1, GameData::Fleets().Get(grand.Token(1)) ); } else grand.PrintTrace("Skipping unsupported tribute fleet definition:"); } else grand.PrintTrace("Skipping unrecognized tribute attribute:"); } } else if(key == "wormhole") { wormhole = wormholes.Get(value); wormhole->SetPlanet(*this); } else child.PrintTrace("Skipping unrecognized attribute:"); } // For reverse compatibility, if this planet has a spaceport but it was not custom loaded, // and the planet has the "uninhabited" attribute, replace the spaceport with a special-case // uninhabited spaceport. if(attributes.count("uninhabited") && HasNamedPort() && !port.CustomLoaded()) port.LoadUninhabitedSpaceport(); // Apply any auto-attributes to this planet depending on what it has. static const vector<string> AUTO_ATTRIBUTES = { "spaceport", "port", "shipyard", "outfitter", "service: trading", "service: jobs", "service: bank", "service: crew", "service: missions", "recharges: shields", "recharges: hull", "recharges: energy", "recharges: fuel", "spaceport news", }; bool autoValues[14] = { port.HasService(Port::ServicesType::All) && port.CanRecharge(Port::RechargeType::All) && port.HasNews() && HasNamedPort(), HasNamedPort(), !shipSales.empty(), !outfitSales.empty(), port.HasService(Port::ServicesType::Trading), port.HasService(Port::ServicesType::JobBoard), port.HasService(Port::ServicesType::Bank), port.HasService(Port::ServicesType::HireCrew), port.HasService(Port::ServicesType::OffersMissions), port.CanRecharge(Port::RechargeType::Shields), port.CanRecharge(Port::RechargeType::Hull), port.CanRecharge(Port::RechargeType::Energy), port.CanRecharge(Port::RechargeType::Fuel), port.HasNews(), }; for(unsigned i = 0; i < AUTO_ATTRIBUTES.size(); ++i) { if(autoValues[i]) attributes.insert(AUTO_ATTRIBUTES[i]); else attributes.erase(AUTO_ATTRIBUTES[i]); } // Precalculate commonly used values that can only change due to Load(). inhabited = (HasServices() || requiredReputation || !defenseFleets.empty()) && !attributes.count("uninhabited"); SetRequiredAttributes(Attributes(), requiredAttributes); } // Legacy wormhole do not have an associated Wormhole object so // we must auto generate one if we detect such legacy wormhole. void Planet::FinishLoading(Set<Wormhole> &wormholes) { // If this planet is in multiple systems, then it is a wormhole. if(!wormhole && systems.size() > 1) { wormhole = wormholes.Get(TrueName()); wormhole->LoadFromPlanet(*this); Logger::LogError("Warning: deprecated automatic generation of wormhole \"" + name + "\" from a multi-system planet."); } // If the wormhole was autogenerated we need to update it to // match the planet's state. else if(wormhole && wormhole->IsAutogenerated()) wormhole->LoadFromPlanet(*this); } // Test if this planet has been loaded (vs. just referred to). It must also be located in // at least one system, and all systems that claim it must themselves be valid. bool Planet::IsValid() const { return isDefined && !systems.empty() && all_of(systems.begin(), systems.end(), [](const System *s) noexcept -> bool { return s->IsValid(); }); } // Get the name of the planet. const string &Planet::Name() const { return IsWormhole() ? wormhole->Name() : name; } void Planet::SetName(const string &name) { this->name = name; } // Get the name used for this planet in the data files. const string &Planet::TrueName() const { return name; } // Get the planet's descriptive text. const string &Planet::Description() const { return description; } // Get the landscape sprite. const Sprite *Planet::Landscape() const { return landscape; } // Get the name of the ambient audio to play on this planet. const string &Planet::MusicName() const { return music; } // Get the list of "attributes" of the planet. const set<string> &Planet::Attributes() const { return attributes; } // Get planet's noun descriptor from attributes const string &Planet::Noun() const { if(IsWormhole()) return WORMHOLE; for(const string &attribute : attributes) if(attribute == "moon" || attribute == "station") return attribute; return PLANET; } // Check whether this planet's port is named. bool Planet::HasNamedPort() const { return !port.Name().empty(); } // Get this planet's port. const Port &Planet::GetPort() const { return port; } // Check whether there are port services (such as trading, jobs, banking, and hiring) // available on this planet. bool Planet::HasServices() const { return port.HasServices(); } // Check if this planet is inhabited (i.e. it has a spaceport, and does not // have the "uninhabited" attribute). bool Planet::IsInhabited() const { return inhabited; } // Check if this planet has a shipyard. bool Planet::HasShipyard() const { return !Shipyard().empty(); } // Get the list of ships in the shipyard. const Sale<Ship> &Planet::Shipyard() const { shipyard.clear(); for(const Sale<Ship> *sale : shipSales) shipyard.Add(*sale); return shipyard; } // Check if this planet has an outfitter. bool Planet::HasOutfitter() const { return !Outfitter().empty(); } // Get the list of outfits available from the outfitter. const Sale<Outfit> &Planet::Outfitter() const { outfitter.clear(); for(const Sale<Outfit> *sale : outfitSales) outfitter.Add(*sale); return outfitter; } // Get this planet's government. Most planets follow the government of the system they are in. const Government *Planet::GetGovernment() const { return government ? government : systems.empty() ? nullptr : GetSystem()->GetGovernment(); } // You need this good a reputation with this system's government to land here. double Planet::RequiredReputation() const { return requiredReputation; } // This is what fraction of your fleet's value you must pay as a bribe in // order to land on this planet. (If zero, you cannot bribe it.) double Planet::GetBribeFraction() const { return bribe; } // This is how likely the planet's authorities are to notice if you are // doing something illegal. double Planet::Security() const { return security; } bool Planet::HasCustomSecurity() const { return customSecurity; } const System *Planet::GetSystem() const { return (systems.empty() ? nullptr : systems.front()); } // Check if this planet is in the given system. Note that wormholes may be // in more than one system. bool Planet::IsInSystem(const System *system) const { return (find(systems.begin(), systems.end(), system) != systems.end()); } void Planet::SetSystem(const System *system) { if(find(systems.begin(), systems.end(), system) == systems.end()) systems.push_back(system); } // Remove the given system from the list of systems this planet is in. This // must be done when game events rearrange the planets in a system. void Planet::RemoveSystem(const System *system) { auto it = find(systems.begin(), systems.end(), system); if(it != systems.end()) systems.erase(it); } const vector<const System *> &Planet::Systems() const { return systems; } // Check if this is a wormhole (that is, it appears in multiple systems). bool Planet::IsWormhole() const { return wormhole; } const Wormhole *Planet::GetWormhole() const { return wormhole; } // Check if the given ship has all the attributes necessary to allow it to // land on this planet. bool Planet::IsAccessible(const Ship *ship) const { // If this is a wormhole that leads to an inaccessible system, no ship can land here. if(wormhole && ship && ship->GetSystem() && wormhole->WormholeDestination(*ship->GetSystem()).Inaccessible()) return false; // If there are no required attributes, then any ship may land here. if(IsUnrestricted()) return true; if(!ship) return false; const auto &shipAttributes = ship->Attributes(); return all_of(requiredAttributes.cbegin(), requiredAttributes.cend(), [&](const string &attr) -> bool { return shipAttributes.Get(attr); }); } // Check if this planet has any required attributes that restrict landability. bool Planet::IsUnrestricted() const { return requiredAttributes.empty(); } // Below are convenience functions which access the game state in Politics, // but do so with a less convoluted syntax: bool Planet::HasFuelFor(const Ship &ship) const { return !IsWormhole() && port.CanRecharge(Port::RechargeType::Fuel) && CanLand(ship); } bool Planet::CanLand(const Ship &ship) const { return IsAccessible(&ship) && GameData::GetPolitics().CanLand(ship, this); } bool Planet::CanLand() const { return GameData::GetPolitics().CanLand(this); } Planet::Friendliness Planet::GetFriendliness() const { if(GameData::GetPolitics().HasDominated(this)) return Friendliness::DOMINATED; else if(GetGovernment()->IsEnemy()) return Friendliness::HOSTILE; else if(CanLand()) return Friendliness::FRIENDLY; else return Friendliness::RESTRICTED; } bool Planet::CanUseServices() const { return GameData::GetPolitics().CanUseServices(this); } void Planet::Bribe(bool fullAccess) const { GameData::GetPolitics().BribePlanet(this, fullAccess); } // Demand tribute, and get the planet's response. string Planet::DemandTribute(PlayerInfo &player) const { const auto &playerTribute = player.GetTribute(); if(playerTribute.find(this) != playerTribute.end()) return "We are already paying you as much as we can afford."; if(!tribute || defenseFleets.empty()) return "Please don't joke about that sort of thing."; if(player.Conditions().Get("combat rating") < defenseThreshold) return "You're not worthy of our time."; // The player is scary enough for this planet to take notice. Check whether // this is the first demand for tribute, or not. if(!isDefending) { isDefending = true; set<const Government *> toProvoke; for(const auto &fleet : defenseFleets) toProvoke.insert(fleet->GetGovernment()); for(const auto &gov : toProvoke) if(gov) gov->Offend(ShipEvent::PROVOKE); // Terrorizing a planet is not taken lightly by it or its allies. // TODO: Use a distinct event type for the domination system and // expose syntax for controlling its impact on the targeted government // and those that know it. GetGovernment()->Offend(ShipEvent::ATROCITY); return "Our defense fleet will make short work of you."; } // The player has already demanded tribute. Have they defeated the entire defense fleet? bool isDefeated = (defenseDeployed == defenseFleets.size()); for(const shared_ptr<Ship> &ship : defenders) if(!ship->IsDisabled() && !ship->IsYours()) { isDefeated = false; break; } if(!isDefeated) return "We're not ready to surrender yet."; player.SetTribute(this, tribute); return "We surrender. We will pay you " + Format::CreditString(tribute) + " per day to leave us alone."; } // While being tributed, attempt to spawn the next specified defense fleet. void Planet::DeployDefense(list<shared_ptr<Ship>> &ships) const { if(!isDefending || Random::Int(60) || defenseDeployed == defenseFleets.size()) return; auto end = defenders.begin(); if(defenseFleets[defenseDeployed]->IsValid()) defenseFleets[defenseDeployed]->Enter(*GetSystem(), defenders, this); else Logger::LogError("Warning: skipped an incomplete defense fleet of planet \"" + name + "\"."); ships.insert(ships.begin(), defenders.begin(), end); // All defenders use a special personality. Personality defenderPersonality = Personality::Defender(); Personality fighterPersonality = Personality::DefenderFighter(); for(auto it = defenders.begin(); it != end; ++it) { (**it).SetPersonality(defenderPersonality); if((**it).HasBays()) for(auto bay = (**it).Bays().begin(); bay != (**it).Bays().end(); ++bay) if(bay->ship) bay->ship->SetPersonality(fighterPersonality); } ++defenseDeployed; } void Planet::ResetDefense() const { isDefending = false; defenseDeployed = 0; defenders.clear(); } bool Planet::IsDefending() const { return isDefending; }
0
endless-sky-master
endless-sky-master/source/Account.h
/* Account.h Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef ACCOUNT_H_ #define ACCOUNT_H_ #include "Mortgage.h" #include <cstdint> #include <map> #include <string> #include <vector> class DataNode; class DataWriter; // Class representing all your assets and liabilities and tracking their change // over time. class Account { public: // Load or save account data. void Load(const DataNode &node, bool clearFirst); void Save(DataWriter &out) const; // Get or change the player's credits. int64_t Credits() const; void AddCredits(int64_t value); void PayExtra(int mortgage, int64_t amount); // Step forward one day, and return a string summarizing payments made. std::string Step(int64_t assets, int64_t salaries, int64_t maintenance); // Structural income. const std::map<std::string, int64_t> &SalariesIncome() const; int64_t SalariesIncomeTotal() const; void SetSalaryIncome(const std::string &name, int64_t amount); // Overdue crew salaries: int64_t CrewSalariesOwed() const; void PaySalaries(int64_t amount); // Overdue maintenance costs: int64_t MaintenanceDue() const; void PayMaintenance(int64_t amount); // Liabilities: const std::vector<Mortgage> &Mortgages() const; void AddMortgage(int64_t principal); void AddFine(int64_t amount); int64_t Prequalify() const; // Assets: int64_t NetWorth() const; // Find out the player's credit rating. int CreditScore() const; // Get the total amount owed for "Mortgage", "Fine", or both. int64_t TotalDebt(const std::string &type = "") const; private: int64_t YearlyRevenue() const; private: int64_t credits = 0; // Regular income from salaries paid to the player. std::map<std::string, int64_t> salariesIncome; // If back salaries and maintenance cannot be paid, they pile up rather // than being ignored. int64_t crewSalariesOwed = 0; int64_t maintenanceDue = 0; // Your credit score determines the interest rate on your mortgages. int creditScore = 400; std::vector<Mortgage> mortgages; // History of the player's net worth. This is used to calculate your average // daily income, which is used to calculate how big a mortgage you can afford. std::vector<int64_t> history; }; #endif
0
endless-sky-master
endless-sky-master/source/Bitset.cpp
/* Bitset.cpp Copyright (c) 2021 by quyykk Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Bitset.h" #include <algorithm> using namespace std; // Returns the number of bits this bitset can hold. size_t Bitset::Size() const noexcept { return bits.size() * BITS_PER_BLOCK; } // Returns the number of bits this bitset has reserved. size_t Bitset::Capacity() const noexcept { return bits.capacity() * BITS_PER_BLOCK; } // Resizes the bitset to hold at least the specific amount of bits. void Bitset::Resize(size_t size) { bits.resize(size / BITS_PER_BLOCK + 1); } // Clears the bitset. After this call this bitset is empty. void Bitset::Clear() noexcept { bits.clear(); } // Whether the given bitset has any bits that are also set in this bitset. bool Bitset::Intersects(const Bitset &other) const noexcept { const auto size = min(bits.size(), other.bits.size()); for(size_t i = 0; i < size; ++i) if(bits[i] & other.bits[i]) return true; return false; } // Returns the value of the bit at the specified index. bool Bitset::Test(size_t index) const noexcept { const auto blockIndex = index / BITS_PER_BLOCK; const auto pos = index % BITS_PER_BLOCK; return bits[blockIndex] & (uint64_t(1) << pos); } // Sets the bit at the specified index. void Bitset::Set(size_t index) noexcept { const auto blockIndex = index / BITS_PER_BLOCK; const auto pos = index % BITS_PER_BLOCK; bits[blockIndex] |= (uint64_t(1) << pos); } // Resets all bits in the bitset. void Bitset::Reset() noexcept { for(auto &it : bits) it = uint64_t(0); } // Whether any bits are set. bool Bitset::Any() const noexcept { for(uint64_t block : bits) if(block) return true; return false; } // Whether no bits are set. bool Bitset::None() const noexcept { return !Any(); } // Fills the current bitset with the bits of other. void Bitset::UpdateWith(const Bitset &other) { const auto size = min(bits.size(), other.bits.size()); for(size_t i = 0; i < size; ++i) bits[i] = other.bits[i]; }
0
endless-sky-master
endless-sky-master/source/MapPlanetCard.cpp
/* MapPlanetCard.cpp Copyright (c) 2022 by Hurleveur Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "MapPlanetCard.h" #include "Color.h" #include "FillShader.h" #include "text/Font.h" #include "text/FontSet.h" #include "GameData.h" #include "Government.h" #include "Interface.h" #include "MapDetailPanel.h" #include "Planet.h" #include "Point.h" #include "PointerShader.h" #include "Screen.h" #include "SpriteShader.h" #include "StellarObject.h" #include "System.h" #include "text/WrappedText.h" using namespace std; namespace { bool hasGovernments = false; } MapPlanetCard::MapPlanetCard(const StellarObject &object, unsigned number, bool hasVisited) : number(number), hasVisited(hasVisited), planetName(object.Name()) { planet = object.GetPlanet(); hasSpaceport = planet->HasServices(); hasShipyard = planet->HasShipyard(); hasOutfitter = planet->HasOutfitter(); governmentName = planet->GetGovernment()->GetName(); string systemGovernmentName = planet->GetSystem()->GetGovernment()->GetName(); if(governmentName != "Uninhabited" && governmentName != systemGovernmentName) hasGovernments = true; if(!hasSpaceport) reputationLabel = "No Spaceport"; else { switch(planet->GetFriendliness()) { case Planet::Friendliness::FRIENDLY: reputationLabel = "Friendly"; break; case Planet::Friendliness::RESTRICTED: reputationLabel = "Restricted"; break; case Planet::Friendliness::HOSTILE: reputationLabel = "Hostile"; break; case Planet::Friendliness::DOMINATED: reputationLabel = "Dominated"; break; } } sprite = object.GetSprite(); const Interface *planetCardInterface = GameData::Interfaces().Get("map planet card"); const float planetIconMaxSize = static_cast<float>(planetCardInterface->GetValue("planet icon max size")); spriteScale = min(.5f, min(planetIconMaxSize / sprite->Width(), planetIconMaxSize / sprite->Height())); } MapPlanetCard::ClickAction MapPlanetCard::Click(int x, int y, int clicks) { ClickAction clickAction = ClickAction::NONE; // The isShown variable should have already updated by the drawing of this item. if(isShown) { const Interface *planetCardInterface = GameData::Interfaces().Get("map planet card"); // Point at which the text starts (after the top margin), at first there is the planet's name, // and then it is divided into clickable categories of the same size. const double textStart = planetCardInterface->GetValue("text start"); const double categorySize = planetCardInterface->GetValue("category size"); const double categories = planetCardInterface->GetValue("categories"); // The maximum possible size for the sprite of the planet. const double planetIconMaxSize = planetCardInterface->GetValue("planet icon max size"); // The yCoordinate refers to the center of this object. double relativeY = (y - yCoordinate); if(relativeY > 0. && relativeY < AvailableSpace()) { // The first category is the planet name and is not selectable. if(x > Screen::Left() + planetIconMaxSize && relativeY > textStart + categorySize && relativeY < textStart + categorySize * (categories + hasGovernments)) selectedCategory = (relativeY - textStart - categorySize) / categorySize; else clickAction = ClickAction::SELECTED; static const int SHOW[5] = {MapPanel::SHOW_GOVERNMENT, MapPanel::SHOW_REPUTATION, MapPanel::SHOW_SHIPYARD, MapPanel::SHOW_OUTFITTER, MapPanel::SHOW_VISITED}; if(clickAction != ClickAction::SELECTED) { // If there are no governments shown, the first category is the reputation. clickAction = static_cast<ClickAction>(SHOW[selectedCategory + !hasGovernments]); // Double clicking results in going to the shipyard/outfitter. if(clickAction == ClickAction::SHOW_SHIPYARD && clicks > 1) clickAction = ClickAction::GOTO_SHIPYARD; else if(clickAction == ClickAction::SHOW_OUTFITTER && clicks > 1) clickAction = ClickAction::GOTO_OUTFITTER; } } } isSelected = (clickAction != ClickAction::NONE); return clickAction; } bool MapPlanetCard::DrawIfFits(const Point &uiPoint) { // Need to update this before checking if the element fits. yCoordinate = uiPoint.Y(); isShown = IsShown(); if(isShown) { const Font &font = FontSet::Get(14); const Color &faint = *GameData::Colors().Get("faint"); const Color &dim = *GameData::Colors().Get("dim"); const Color &medium = *GameData::Colors().Get("medium"); const Interface *planetCardInterface = GameData::Interfaces().Get("map planet card"); // The maximum possible size for the sprite of the planet. const double planetIconMaxSize = planetCardInterface->GetValue("planet icon max size"); const auto alignLeft = Layout(planetCardInterface->GetValue("width") - planetIconMaxSize, Truncate::BACK); // Height of one MapPlanetCard element. const double height = Height(); // Point at which the text starts (after the top margin), at first there is the planet's name, // and then it is divided into clickable categories of the same size. const double textStart = planetCardInterface->GetValue("text start"); const double categorySize = planetCardInterface->GetValue("category size"); const double categories = planetCardInterface->GetValue("categories"); // Available space, limited by the space there is between the top of this item, // and the end of the panel below. const double availableBottomSpace = AvailableBottomSpace(); // The top part goes out of the screen so we can draw there. The bottom would go out of this panel. const Interface *mapInterface = GameData::Interfaces().Get("map detail panel"); auto spriteItem = SpriteShader::Prepare(sprite, Point(Screen::Left() + planetIconMaxSize / 2., uiPoint.Y() + height / 2.), spriteScale); float clip = 1.f; // Lowest point of the planet sprite. double planetBottomY = height / 2. + spriteScale * sprite->Height() / 2.; // Calculate the correct clip on the bottom of the sprite if necessary. // It is done by looking at how much space is available, // and the difference between that and the lowest point of the sprite. // Of course, the clipping needs to be done relative to the size of the sprite. if(availableBottomSpace <= planetBottomY) clip = 1.f + (availableBottomSpace - planetBottomY) / (spriteScale * sprite->Height()); spriteItem.clip = clip; spriteItem.position[1] -= (sprite->Height() * ((1.f - clip) * .5f)) * spriteScale; spriteItem.transform[3] *= clip; SpriteShader::Bind(); SpriteShader::Add(spriteItem); SpriteShader::Unbind(); // Check if drawing a category would not go out of the panel. const auto FitsCategory = [availableBottomSpace, categorySize, height] (double number) { return availableBottomSpace >= height - (categorySize * number); }; // Draw the name of the planet. if(FitsCategory(categories + hasGovernments)) font.Draw({ planetName, alignLeft }, uiPoint + Point(0, textStart), isSelected ? medium : dim); // Draw the government name, reputation, shipyard, outfitter and visited. const double margin = mapInterface->GetValue("text margin"); if(hasGovernments && FitsCategory(categories)) font.Draw(governmentName, uiPoint + Point(margin, textStart + categorySize), governmentName == "Uninhabited" ? faint : dim); if(FitsCategory(4.)) font.Draw(reputationLabel, uiPoint + Point(margin, textStart + categorySize * (1. + hasGovernments)), hasSpaceport ? medium : faint); if(FitsCategory(3.)) font.Draw("Shipyard", uiPoint + Point(margin, textStart + categorySize * (2. + hasGovernments)), hasShipyard ? medium : faint); if(FitsCategory(2.)) font.Draw("Outfitter", uiPoint + Point(margin, textStart + categorySize * (3. + hasGovernments)), hasOutfitter ? medium : faint); if(FitsCategory(1.)) font.Draw(hasVisited ? "(has been visited)" : "(not yet visited)", uiPoint + Point(margin, textStart + categorySize * (4. + hasGovernments)), dim); // Draw the arrow pointing to the selected category. if(FitsCategory(categories - (selectedCategory + 1.))) PointerShader::Draw(uiPoint + Point(margin, textStart + 8. + (selectedCategory + 1) * categorySize), Point(1., 0.), 10.f, 10.f, 0.f, medium); if(isSelected) Highlight(availableBottomSpace); } else yCoordinate = Screen::Bottom(); return isShown; } bool MapPlanetCard::IsShown() const { return AvailableSpace() > 15.; } bool MapPlanetCard::IsSelected() const { return isSelected; } double MapPlanetCard::AvailableSpace() const { return min(AvailableBottomSpace(), AvailableTopSpace()); } const Planet *MapPlanetCard::GetPlanet() const { return planet; } void MapPlanetCard::Select(bool select) { isSelected = select; } double MapPlanetCard::Height() { const Interface *planetCardInterface = GameData::Interfaces().Get("map planet card"); return planetCardInterface->GetValue("height padding") + (planetCardInterface->GetValue("categories") + hasGovernments) * planetCardInterface->GetValue("category size"); } void MapPlanetCard::ResetSize() { hasGovernments = false; } void MapPlanetCard::Highlight(double availableSpace) const { const Interface *planetCardInterface = GameData::Interfaces().Get("map planet card"); const double width = planetCardInterface->GetValue("width"); FillShader::Fill(Point(Screen::Left() + width / 2., yCoordinate + availableSpace / 2.), Point(width, availableSpace), *GameData::Colors().Get("item selected")); } double MapPlanetCard::AvailableTopSpace() const { const double height = Height(); return min(height, max(0., (number + 1) * height - MapDetailPanel::GetScroll())); } double MapPlanetCard::AvailableBottomSpace() const { const Interface *mapInterface = GameData::Interfaces().Get("map detail panel"); double maxPlanetPanelHeight = mapInterface->GetValue("max planet panel height"); return min(Height(), max(0., Screen::Top() + min(MapDetailPanel::PlanetPanelHeight(), maxPlanetPanelHeight) - yCoordinate)); }
0
endless-sky-master
endless-sky-master/source/ItemInfoDisplay.cpp
/* ItemInfoDisplay.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ItemInfoDisplay.h" #include "text/alignment.hpp" #include "Color.h" #include "FillShader.h" #include "text/FontSet.h" #include "GameData.h" #include "text/layout.hpp" #include "Rectangle.h" #include "Screen.h" #include "text/Table.h" #include <algorithm> #include <cmath> using namespace std; namespace { const int HOVER_TIME = 60; } ItemInfoDisplay::ItemInfoDisplay() { description.SetAlignment(Alignment::JUSTIFIED); description.SetWrapWidth(WIDTH - 20); description.SetFont(FontSet::Get(14)); hoverText.SetAlignment(Alignment::JUSTIFIED); hoverText.SetWrapWidth(WIDTH - 20); hoverText.SetFont(FontSet::Get(14)); } // Get the panel width. int ItemInfoDisplay::PanelWidth() { return WIDTH; } // Get the height of each of the three panels. int ItemInfoDisplay::MaximumHeight() const { return maximumHeight; } int ItemInfoDisplay::DescriptionHeight() const { return descriptionHeight; } int ItemInfoDisplay::AttributesHeight() const { return attributesHeight; } // Draw each of the panels. void ItemInfoDisplay::DrawDescription(const Point &topLeft) const { Rectangle hoverTarget = Rectangle::FromCorner(topLeft, Point(PanelWidth(), DescriptionHeight())); Color color = hoverTarget.Contains(hoverPoint) ? *GameData::Colors().Get("bright") : *GameData::Colors().Get("medium"); description.Draw(topLeft + Point(10., 12.), color); } void ItemInfoDisplay::DrawAttributes(const Point &topLeft) const { Draw(topLeft, attributeLabels, attributeValues); } void ItemInfoDisplay::DrawTooltips() const { if(!hoverCount || hoverCount-- < HOVER_TIME || !hoverText.Height()) return; Point textSize(hoverText.WrapWidth(), hoverText.Height() - hoverText.ParagraphBreak()); Point boxSize = textSize + Point(20., 20.); Point topLeft = hoverPoint; if(topLeft.X() + boxSize.X() > Screen::Right()) topLeft.X() -= boxSize.X(); if(topLeft.Y() + boxSize.Y() > Screen::Bottom()) topLeft.Y() -= boxSize.Y(); FillShader::Fill(topLeft + .5 * boxSize, boxSize, *GameData::Colors().Get("tooltip background")); hoverText.Draw(topLeft + Point(10., 10.), *GameData::Colors().Get("medium")); } // Update the location where the mouse is hovering. void ItemInfoDisplay::Hover(const Point &point) { hoverPoint = point; hasHover = true; } void ItemInfoDisplay::ClearHover() { hasHover = false; } void ItemInfoDisplay::UpdateDescription(const string &text, const vector<string> &licenses, bool isShip) { if(licenses.empty()) description.Wrap(text); else { static const string NOUN[2] = {"outfit", "ship"}; string fullText = text + "\tTo purchase this " + NOUN[isShip] + " you must have "; for(unsigned i = 0; i < licenses.size(); ++i) { bool isVoweled = false; for(const char &c : "aeiou") if(*licenses[i].begin() == c || *licenses[i].begin() == toupper(c)) isVoweled = true; if(i) { if(licenses.size() > 2) fullText += ", "; else fullText += " "; } if(i && i == licenses.size() - 1) fullText += "and "; fullText += (isVoweled ? "an " : "a ") + licenses[i] + " License"; } fullText += ".\n"; description.Wrap(fullText); } // If there is a description, pad by 10 pixels on the top and bottom. descriptionHeight = description.Height(); if(descriptionHeight) descriptionHeight += 20; } Point ItemInfoDisplay::Draw(Point point, const vector<string> &labels, const vector<string> &values) const { // Add ten pixels of padding at the top. point.Y() += 10.; // Get standard colors to draw with. const Color &labelColor = *GameData::Colors().Get("medium"); const Color &valueColor = *GameData::Colors().Get("bright"); Table table; // Use 10-pixel margins on both sides. table.AddColumn(10, {WIDTH - 20}); table.AddColumn(WIDTH - 10, {WIDTH - 20, Alignment::RIGHT}); table.SetHighlight(0, WIDTH); table.DrawAt(point); for(unsigned i = 0; i < labels.size() && i < values.size(); ++i) { if(labels[i].empty()) { table.DrawGap(10); continue; } CheckHover(table, labels[i]); table.Draw(labels[i], values[i].empty() ? valueColor : labelColor); table.Draw(values[i], valueColor); } return table.GetPoint(); } void ItemInfoDisplay::CheckHover(const Table &table, const string &label) const { if(!hasHover) return; Point distance = hoverPoint - table.GetCenterPoint(); Point radius = .5 * table.GetRowSize(); if(abs(distance.X()) < radius.X() && abs(distance.Y()) < radius.Y()) { hoverCount += 2 * (label == hover); hover = label; if(hoverCount >= HOVER_TIME) { hoverCount = HOVER_TIME; hoverText.Wrap(GameData::Tooltip(label)); } } }
0
endless-sky-master
endless-sky-master/source/Flotsam.cpp
/* Flotsam.cpp Copyright (c) 2016 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Flotsam.h" #include "Angle.h" #include "Effect.h" #include "GameData.h" #include "Outfit.h" #include "Random.h" #include "Ship.h" #include "SpriteSet.h" #include "Visual.h" #include <cmath> using namespace std; const int Flotsam::TONS_PER_BOX = 5; // Constructors for flotsam carrying either a commodity or an outfit. Flotsam::Flotsam(const string &commodity, int count, const Government *sourceGovernment) : commodity(commodity), count(count), sourceGovernment(sourceGovernment) { lifetime = Random::Int(3600) + 7200; // Scale lifetime in proportion to the expected amount per box. if(count != TONS_PER_BOX) lifetime = sqrt(count * (1. / TONS_PER_BOX)) * lifetime; } Flotsam::Flotsam(const Outfit *outfit, int count, const Government *sourceGovernment) : outfit(outfit), count(count), sourceGovernment(sourceGovernment) { // The more the outfit costs, the faster this flotsam should disappear. int lifetimeBase = 3000000000 / (outfit->Cost() * count + 1000000); lifetime = Random::Int(lifetimeBase) + lifetimeBase + 600; } // Place this flotsam, and set the given ship as its source. This is a // separate function because a ship may queue up flotsam to dump but take // several frames before it finishes dumping it all. void Flotsam::Place(const Ship &source) { this->source = &source; Place(source, Angle::Random().Unit() * (2. * Random::Real()) - 2. * source.Unit()); } // Place flotsam coming from something other than a ship. Optionally specify // the maximum relative velocity, or the exact relative velocity as a vector. void Flotsam::Place(const Body &source, double maxVelocity) { Place(source, Angle::Random().Unit() * (maxVelocity * Random::Real())); } void Flotsam::Place(const Body &source, const Point &dv) { position = source.Position(); velocity = source.Velocity() + dv; angle = Angle::Random(); spin = Angle::Random(10.); // Special case: allow a harvested outfit item to define its flotsam sprite // using the field that usually defines a secondary weapon's icon. if(outfit && outfit->FlotsamSprite()) SetSprite(outfit->FlotsamSprite()); else SetSprite(SpriteSet::Get("effect/box")); SetFrameRate(4. * (1. + Random::Real())); } // Move the object one time-step forward. void Flotsam::Move(vector<Visual> &visuals) { position += velocity; velocity *= drag; angle += spin; --lifetime; if(lifetime > 0) return; // This flotsam has reached the end of its life. const Effect *effect = GameData::Effects().Get("flotsam death"); for(int i = 0; i < 3; ++i) { Angle smokeAngle = Angle::Random(); velocity += smokeAngle.Unit() * Random::Real(); visuals.emplace_back(*effect, position, velocity, smokeAngle); } MarkForRemoval(); } // This is the one ship that cannot pick up this flotsam. const Ship *Flotsam::Source() const { return source; } // Ships from this Government should not pick up this flotsam because it // was explicitly dumped by a member of this government. const Government *Flotsam::SourceGovernment() const { return sourceGovernment; } // This is what the flotsam contains: const string &Flotsam::CommodityType() const { return commodity; } const Outfit *Flotsam::OutfitType() const { return outfit; } int Flotsam::Count() const { return count; } // This is how big one "unit" of the flotsam is (in tons). If a ship has // less than this amount of space, it can't pick up anything here. double Flotsam::UnitSize() const { return outfit ? outfit->Mass() : 1.; } // Transfer contents to the collector ship. The flotsam velocity is // stabilized in proportion to the amount being transferred. int Flotsam::TransferTo(Ship *collector) { int amount = outfit ? collector->Cargo().Add(outfit, count) : collector->Cargo().Add(commodity, count); Point relative = collector->Velocity() - velocity; double proportion = static_cast<double>(amount) / count; velocity += relative * proportion; count -= amount; // If this flotsam is now empty, remove it. if(count <= 0) MarkForRemoval(); return amount; }
0
endless-sky-master
endless-sky-master/source/Port.h
/* Port.h Copyright (c) 2023 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifndef PORT_H_ #define PORT_H_ #include <string> class DataNode; // Class representing a port on a planet and its capabilities, such as what properties // of a ship it can recharge and what services (e.g. banking, trading) it can provide. class Port { public: // The different ship properties that can be recharged by a port. class RechargeType { public: static constexpr int None = 0; static constexpr int Shields = (1 << 0); static constexpr int Hull = (1 << 1); static constexpr int Energy = (1 << 2); static constexpr int Fuel = (1 << 3); static constexpr int All = Shields | Hull | Energy | Fuel; }; // The different services available on this port. class ServicesType { public: static constexpr int None = 0; static constexpr int Trading = (1 << 0); static constexpr int JobBoard = (1 << 1); static constexpr int Bank = (1 << 2); static constexpr int HireCrew = (1 << 3); static constexpr int OffersMissions = (1 << 4); static constexpr int All = Trading | JobBoard | Bank | HireCrew | OffersMissions; }; public: // Load a port's description from a node. void Load(const DataNode &node); void LoadDefaultSpaceport(); void LoadUninhabitedSpaceport(); // Whether this port was loaded from the Load function. bool CustomLoaded() const; // Whether this port has any services available. bool HasServices() const; // Get all the possible sources that can get recharged at this port. int GetRecharges() const; const std::string &Name() const; std::string &Description(); const std::string &Description() const; // Check whether the given recharging is possible. bool CanRecharge(int type) const; // Check whether the given service is available. bool HasService(int type) const; bool HasNews() const; private: // Whether this port was loaded from the Load function. bool loaded = false; // The name of this port. std::string name; // The description of this port. Shown when clicking on the // port button on the planet panel. std::string description; // What is recharged when landing on this port. int recharge = RechargeType::None; // What services are available on this port. int services = ServicesType::None; // Whether this port has news. bool hasNews = false; }; #endif
0
endless-sky-master
endless-sky-master/source/Phrase.cpp
/* Phrase.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Phrase.h" #include "DataNode.h" #include "text/Format.h" #include "GameData.h" using namespace std; // Replace all occurrences ${phrase name} with the expanded phrase from GameData::Phrases() std::string Phrase::ExpandPhrases(const std::string &source) { string result; size_t next = 0; while(next < source.length()) { size_t var = source.find("${", next); if(var == string::npos) break; else if(var > next) result.append(source, next, var - next); next = source.find('}', var); if(next == string::npos) break; ++next; string phraseName = string{source, var + 2, next - var - 3}; const Phrase *phrase = GameData::Phrases().Find(phraseName); result.append(phrase ? phrase->Get() : phraseName); } // Optimization for most common case: no phrase in string: if(!next) return source; else if(next < source.length()) result.append(source, next, string::npos); return result; } Phrase::Phrase(const DataNode &node) { Load(node); } void Phrase::Load(const DataNode &node) { // Set the name of this phrase, so we know it has been loaded. name = node.Size() >= 2 ? node.Token(1) : "Unnamed Phrase"; // To avoid a possible parsing ambiguity, the interpolation delimiters // may not be used in a Phrase's name. if(name.find("${") != string::npos || name.find('}') != string::npos) { node.PrintTrace("Error: Phrase names may not contain '${' or '}':"); return; } sentences.emplace_back(node, this); if(sentences.back().empty()) { sentences.pop_back(); node.PrintTrace("Error: Unable to parse node:"); } } bool Phrase::IsEmpty() const { return sentences.empty(); } // Get the name associated with the node this phrase was instantiated // from, or "Unnamed Phrase" if it was anonymously defined. const string &Phrase::Name() const { return name; } // Get a random sentence's text. string Phrase::Get() const { string result; if(sentences.empty()) return result; for(const auto &part : sentences[Random::Int(sentences.size())]) { if(!part.choices.empty()) { const auto &choice = part.choices.Get(); for(const auto &element : choice) result += element.second ? element.second->Get() : element.first; } else if(!part.replacements.empty()) for(const auto &pair : part.replacements) Format::ReplaceAll(result, pair.first, pair.second); } return result; } // Inspect this phrase and all its subphrases to determine if a cyclic // reference exists between this phrase and the other. bool Phrase::ReferencesPhrase(const Phrase *other) const { if(other == this) return true; for(const auto &sentence : sentences) for(const auto &part : sentence) for(const auto &choice : part.choices) for(const auto &element : choice) if(element.second && element.second->ReferencesPhrase(other)) return true; return false; } Phrase::Choice::Choice(const DataNode &node, bool isPhraseName) { // The given datanode should not have any children. if(node.HasChildren()) node.begin()->PrintTrace("Skipping unrecognized child node:"); if(isPhraseName) { emplace_back(string{}, GameData::Phrases().Get(node.Token(0))); return; } // This node is a text string that may contain an interpolation request. const string &entry = node.Token(0); if(entry.empty()) { // A blank choice was desired. emplace_back(); return; } size_t start = 0; while(start < entry.length()) { // Determine if there is an interpolation request in this string. size_t left = entry.find("${", start); if(left == string::npos) break; size_t right = entry.find('}', left); if(right == string::npos) break; // Add the text up to the ${, and then add the contained phrase name. ++right; size_t length = right - left; auto text = string{entry, start, left - start}; auto phraseName = string{entry, left + 2, length - 3}; emplace_back(text, nullptr); emplace_back(string{}, GameData::Phrases().Get(phraseName)); start = right; } // Add the remaining text to the sequence. if(entry.length() - start > 0) emplace_back(string{entry, start, entry.length() - start}, nullptr); } // Forwarding constructor, for use with emplace/emplace_back. Phrase::Sentence::Sentence(const DataNode &node, const Phrase *parent) { Load(node, parent); } // Parse the children of the given node to populate the sentence's structure. void Phrase::Sentence::Load(const DataNode &node, const Phrase *parent) { for(const DataNode &child : node) { if(!child.HasChildren()) { child.PrintTrace("Skipping node with no children:"); continue; } emplace_back(); auto &part = back(); if(child.Token(0) == "word") for(const DataNode &grand : child) part.choices.emplace_back((grand.Size() >= 2) ? max<int>(1, grand.Value(1)) : 1, grand); else if(child.Token(0) == "phrase") for(const DataNode &grand : child) part.choices.emplace_back((grand.Size() >= 2) ? max<int>(1, grand.Value(1)) : 1, grand, true); else if(child.Token(0) == "replace") for(const DataNode &grand : child) part.replacements.emplace_back(grand.Token(0), (grand.Size() >= 2) ? grand.Token(1) : string{}); else child.PrintTrace("Skipping unrecognized attribute:"); // Require any newly added phrases have no recursive references. Any recursions // will instead yield an empty string, rather than possibly infinite text. for(auto &choice : part.choices) for(auto &element : choice) if(element.second && element.second->ReferencesPhrase(parent)) { child.PrintTrace("Warning: Replaced recursive '" + element.second->Name() + "' phrase reference with \"\":"); element.second = nullptr; } // If no words, phrases, or replaces were given, discard this part of the phrase. if(part.choices.empty() && part.replacements.empty()) pop_back(); } }
0
endless-sky-master
endless-sky-master/source/PlayerInfoPanel.cpp
/* PlayerInfoPanel.cpp Copyright (c) 2017 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "PlayerInfoPanel.h" #include "text/alignment.hpp" #include "Command.h" #include "text/Font.h" #include "text/FontSet.h" #include "text/Format.h" #include "GameData.h" #include "InfoPanelState.h" #include "Information.h" #include "Interface.h" #include "text/layout.hpp" #include "LogbookPanel.h" #include "MissionPanel.h" #include "Planet.h" #include "PlayerInfo.h" #include "Preferences.h" #include "Rectangle.h" #include "Ship.h" #include "ShipInfoPanel.h" #include "System.h" #include "text/Table.h" #include "text/truncate.hpp" #include "UI.h" #include <algorithm> #include <cmath> #include <utility> using namespace std; namespace { // Number of lines per page of the fleet listing. const int LINES_PER_PAGE = 26; // Draw a list of (string, value) pairs. void DrawList(vector<pair<int64_t, string>> &list, Table &table, const string &title, int maxCount = 0, bool drawValues = true) { if(list.empty()) return; int otherCount = list.size() - maxCount; if(otherCount > 0 && maxCount > 0) { list[maxCount - 1].second = "(" + to_string(otherCount + 1) + " Others)"; while(otherCount--) { list[maxCount - 1].first += list.back().first; list.pop_back(); } } const Color &dim = *GameData::Colors().Get("medium"); table.DrawGap(10); table.DrawUnderline(dim); table.Draw(title, *GameData::Colors().Get("bright")); table.Advance(); table.DrawGap(5); for(const auto &it : list) { table.Draw(it.second, dim); if(drawValues) table.Draw(it.first); else table.Advance(); } } bool CompareName(const shared_ptr<Ship> &lhs, const shared_ptr<Ship> &rhs) { return lhs->Name() < rhs->Name(); } bool CompareModelName(const shared_ptr<Ship> &lhs, const shared_ptr<Ship> &rhs) { return lhs->DisplayModelName() < rhs->DisplayModelName(); } bool CompareSystem(const shared_ptr<Ship> &lhs, const shared_ptr<Ship> &rhs) { // Ships (drones) with no system are sorted to the end. if(lhs->GetSystem() == nullptr) return false; else if(rhs->GetSystem() == nullptr) return true; return lhs->GetSystem()->Name() < rhs->GetSystem()->Name(); } bool CompareShields(const shared_ptr<Ship> &lhs, const shared_ptr<Ship> &rhs) { return lhs->Shields() < rhs->Shields(); } bool CompareHull(const shared_ptr<Ship> &lhs, const shared_ptr<Ship> &rhs) { return lhs->Hull() < rhs->Hull(); } bool CompareFuel(const shared_ptr<Ship> &lhs, const shared_ptr<Ship> &rhs) { return lhs->Attributes().Get("fuel capacity") * lhs->Fuel() < rhs->Attributes().Get("fuel capacity") * rhs->Fuel(); } bool CompareRequiredCrew(const shared_ptr<Ship> &lhs, const shared_ptr<Ship> &rhs) { // Parked ships are sorted to the end. if(lhs->IsParked()) return false; else if(rhs->IsParked()) return true; return lhs->RequiredCrew() < rhs->RequiredCrew(); } // A helper function for reversing the arguments of the given function F. template <InfoPanelState::ShipComparator &F> bool ReverseCompare(const shared_ptr<Ship> &lhs, const shared_ptr<Ship> &rhs) { return F(rhs, lhs); } // Reverses the argument order of the given comparator function. InfoPanelState::ShipComparator &GetReverseCompareFrom(InfoPanelState::ShipComparator &f) { if(f == &CompareName) return ReverseCompare<CompareName>; else if(f == &CompareModelName) return ReverseCompare<CompareModelName>; else if(f == &CompareSystem) return ReverseCompare<CompareSystem>; else if(f == &CompareShields) return ReverseCompare<CompareShields>; else if(f == &CompareHull) return ReverseCompare<CompareHull>; else if(f == &CompareFuel) return ReverseCompare<CompareFuel>; return ReverseCompare<CompareRequiredCrew>; } } // Table columns and their starting x positions, end x positions, alignment and sort comparator. const PlayerInfoPanel::SortableColumn PlayerInfoPanel::columns[7] = { SortableColumn("ship", 0, 217, {217, Truncate::MIDDLE}, CompareName), SortableColumn("model", 220, 347, {127, Truncate::BACK}, CompareModelName), SortableColumn("system", 350, 487, {137, Truncate::BACK}, CompareSystem), SortableColumn("shields", 550, 493, {57, Alignment::RIGHT, Truncate::BACK}, CompareShields), SortableColumn("hull", 610, 553, {57, Alignment::RIGHT, Truncate::BACK}, CompareHull), SortableColumn("fuel", 670, 613, {57, Alignment::RIGHT, Truncate::BACK}, CompareFuel), SortableColumn("crew", 730, 673, {57, Alignment::RIGHT, Truncate::BACK}, CompareRequiredCrew) }; PlayerInfoPanel::PlayerInfoPanel(PlayerInfo &player) : PlayerInfoPanel(player, InfoPanelState(player)) { } PlayerInfoPanel::PlayerInfoPanel(PlayerInfo &player, InfoPanelState panelState) : player(player), panelState(panelState) { SetInterruptible(false); } void PlayerInfoPanel::Step() { // If the player has acquired a second ship for the first time, explain to // them how to reorder and sort the ships in their fleet. if(panelState.Ships().size() > 1) DoHelp("multiple ships"); } void PlayerInfoPanel::Draw() { // Dim everything behind this panel. DrawBackdrop(); // Fill in the information for how this interface should be drawn. Information interfaceInfo; interfaceInfo.SetCondition("player tab"); if(panelState.CanEdit() && !panelState.Ships().empty()) { bool allParked = true; bool allParkedSystem = true; bool hasOtherShips = false; const Ship *flagship = player.Flagship(); const System *flagshipSystem = flagship ? flagship->GetSystem() : player.GetSystem(); for(const auto &it : panelState.Ships()) if(!it->IsDisabled() && it.get() != flagship) { allParked &= it->IsParked(); hasOtherShips = true; if(it->GetSystem() == flagshipSystem) allParkedSystem &= it->IsParked(); } if(hasOtherShips) { interfaceInfo.SetCondition(allParked ? "show unpark all" : "show park all"); interfaceInfo.SetCondition(allParkedSystem ? "show unpark system" : "show park system"); } // If ships are selected, decide whether the park or unpark button // should be shown. if(!panelState.AllSelected().empty()) { bool parkable = false; allParked = true; for(int i : panelState.AllSelected()) { const Ship &ship = *panelState.Ships()[i]; if(!ship.IsDisabled() && &ship != flagship) { allParked &= ship.IsParked(); parkable = true; } } if(parkable) { interfaceInfo.SetCondition("can park"); interfaceInfo.SetCondition(allParked ? "show unpark" : "show park"); } } // If ship order has changed by choosing a sort comparison, // show the save order button. Any manual sort by the player // is applied immediately and doesn't need this button. if(panelState.CanEdit() && panelState.CurrentSort()) interfaceInfo.SetCondition("show save order"); } interfaceInfo.SetCondition("three buttons"); if(player.HasLogs()) interfaceInfo.SetCondition("enable logbook"); // Draw the interface. const Interface *infoPanelUi = GameData::Interfaces().Get("info panel"); infoPanelUi->Draw(interfaceInfo, this); // Draw the player and fleet info sections. menuZones.clear(); DrawPlayer(infoPanelUi->GetBox("player")); DrawFleet(infoPanelUi->GetBox("fleet")); } bool PlayerInfoPanel::AllowsFastForward() const noexcept { return true; } bool PlayerInfoPanel::KeyDown(SDL_Keycode key, Uint16 mod, const Command &command, bool isNewPress) { bool control = (mod & (KMOD_CTRL | KMOD_GUI)); bool shift = (mod & KMOD_SHIFT); if(key == 'd' || key == SDLK_ESCAPE || (key == 'w' && control) || key == 'i' || command.Has(Command::INFO)) { GetUI()->Pop(this); } else if(command.Has(Command::HELP)) { if(panelState.Ships().size() > 1) DoHelp("multiple ships", true); } else if(key == 's' || key == SDLK_RETURN || key == SDLK_KP_ENTER || (control && key == SDLK_TAB)) { if(!panelState.Ships().empty()) { GetUI()->Pop(this); GetUI()->Push(new ShipInfoPanel(player, std::move(panelState))); } } else if(key == SDLK_PAGEUP || key == SDLK_PAGEDOWN) { int direction = (key == SDLK_PAGEDOWN) - (key == SDLK_PAGEUP); Scroll((LINES_PER_PAGE - 2) * direction); } else if(key == SDLK_HOME) Scroll(-static_cast<int>(player.Ships().size())); else if(key == SDLK_END) Scroll(player.Ships().size()); else if(key == SDLK_UP || key == SDLK_DOWN) { if(panelState.AllSelected().empty()) { // If no ship was selected, moving up or down selects the first or last ship. if(isNewPress) { if(key == SDLK_UP) panelState.SetSelectedIndex(panelState.Ships().size() - 1); else panelState.SetSelectedIndex(0); } } // Holding both Ctrl & Shift keys and using the arrows moves the // selected ship group up or down one row. else if(panelState.CanEdit() && !panelState.AllSelected().empty() && control && shift) { // Move based on the position of the first selected ship. An upward // movement is a shift of one, while a downward move shifts 1 and // then 1 for each ship in the contiguous selection. size_t toIndex = *panelState.AllSelected().begin(); if(key == SDLK_UP && toIndex > 0) --toIndex; else if(key == SDLK_DOWN) { int next = ++toIndex; for(const auto sel : panelState.AllSelected()) { if(sel != next) break; ++toIndex; ++next; } } // Clamp the destination index to the end of the ships list. size_t moved = panelState.AllSelected().size(); toIndex = min(panelState.Ships().size() - moved, toIndex); if(panelState.ReorderShipsTo(toIndex)) ScrollAbsolute(panelState.SelectedIndex() - 12); return true; } else { // Move the selection up or down one space. int selectedIndex = panelState.SelectedIndex() + (key == SDLK_DOWN) - (key == SDLK_UP); bool isValidIndex = static_cast<unsigned>(selectedIndex) < panelState.Ships().size(); if(selectedIndex < 0) { if(isNewPress) panelState.DeselectAll(); } else if(shift) { if(panelState.AllSelected().count(selectedIndex)) panelState.Deselect(panelState.SelectedIndex()); if(isValidIndex) panelState.SetSelectedIndex(selectedIndex); } else if(control) { // If ctrl is down, select current ship. if(isValidIndex) panelState.SetSelectedIndex(selectedIndex); } else if(isValidIndex) panelState.SelectOnly(selectedIndex); else if(isNewPress) panelState.DeselectAll(); } // Update the scroll. int selected = panelState.SelectedIndex(); if(selected >= 0) { if(selected < panelState.Scroll() + LINES_PER_PAGE && selected >= panelState.Scroll()) { // If the selected ship is on screen, do not scroll. } else if(selected == panelState.Scroll() + LINES_PER_PAGE) Scroll(1); else if(selected == panelState.Scroll() - 1) Scroll(-1); else if(key == SDLK_UP) ScrollAbsolute(selected - LINES_PER_PAGE + 1); else ScrollAbsolute(selected); } } else if(panelState.CanEdit() && (key == 'k' || (key == 'p' && shift)) && !panelState.AllSelected().empty()) { // Toggle the parked status for all selected ships. bool allParked = true; const Ship *flagship = player.Flagship(); for(int i : panelState.AllSelected()) { const Ship &ship = *panelState.Ships()[i]; if(!ship.IsDisabled() && &ship != flagship) allParked &= ship.IsParked(); } for(int i : panelState.AllSelected()) { const Ship &ship = *panelState.Ships()[i]; if(!ship.IsDisabled() && &ship != flagship) player.ParkShip(&ship, !allParked); } } else if(panelState.CanEdit() && (key == 'a') && !panelState.Ships().empty()) { // Toggle the parked status for all ships except the flagship. bool allParked = true; const Ship *flagship = player.Flagship(); for(const auto &it : panelState.Ships()) if(!it->IsDisabled() && it.get() != flagship) allParked &= it->IsParked(); for(const auto &it : panelState.Ships()) if(!it->IsDisabled() && (allParked || it.get() != flagship)) player.ParkShip(it.get(), !allParked); } else if(panelState.CanEdit() && (key == 'c') && !panelState.Ships().empty()) { // Toggle the parked status for all ships in system except the flagship. bool allParked = true; const Ship *flagship = player.Flagship(); const System *flagshipSystem = flagship ? flagship->GetSystem() : player.GetSystem(); for(const auto &it : panelState.Ships()) if(!it->IsDisabled() && it.get() != flagship && it->GetSystem() == flagshipSystem) allParked &= it->IsParked(); for(const auto &it : panelState.Ships()) if(!it->IsDisabled() && (allParked || it.get() != flagship) && it->GetSystem() == flagshipSystem) player.ParkShip(it.get(), !allParked); } // If "Save order" button is pressed. else if(panelState.CanEdit() && panelState.CurrentSort() && key == 'v') { player.SetShipOrder(panelState.Ships()); panelState.SetCurrentSort(nullptr); } else if(command.Has(Command::MAP) || key == 'm') GetUI()->Push(new MissionPanel(player)); else if(key == 'l' && player.HasLogs()) GetUI()->Push(new LogbookPanel(player)); else if(key >= '0' && key <= '9') { int group = key - '0'; if(control) { // Convert from indices into ship pointers. set<Ship *> selected; for(int i : panelState.AllSelected()) selected.insert(panelState.Ships()[i].get()); player.SetGroup(group, &selected); } else { // Convert ship pointers into indices in the ship list. set<int> added; for(Ship *ship : player.GetGroup(group)) for(size_t i = 0; i < panelState.Ships().size(); ++i) if(panelState.Ships()[i].get() == ship) added.insert(i); // If the shift key is not down, replace the current set of selected // ships with the group with the given index. if(!shift) panelState.SetSelected(added); else if(!added.empty()) { // If every single ship in this group is already selected, shift // plus the group number means to deselect all those ships. bool allWereSelected = true; for(int i : added) allWereSelected &= panelState.Deselect(i); if(!allWereSelected) { for(int i : added) panelState.Select(i); panelState.SetSelectedIndex(*added.begin()); } } ScrollAbsolute(panelState.SelectedIndex()); } } else return false; return true; } bool PlayerInfoPanel::Click(int x, int y, int clicks) { // Sort the ships if the click was on one of the column headers. Point mouse = Point(x, y); for(auto &zone : menuZones) if(zone.Contains(mouse)) { SortShips(*zone.Value()); return true; } // Do nothing if the click was not on one of the ships in the fleet list. if(hoverIndex < 0) return true; bool shift = (SDL_GetModState() & KMOD_SHIFT); bool control = (SDL_GetModState() & (KMOD_CTRL | KMOD_GUI)); if(panelState.CanEdit() && (shift || control || clicks < 2)) { // If the control+click was on an already selected ship, deselect it. if(control && panelState.AllSelected().count(hoverIndex)) panelState.Deselect(hoverIndex); else { if(control) panelState.SetSelectedIndex(hoverIndex); else if(shift) { // Select all the ships between the previous selection and this one. int start = max(0, min(panelState.SelectedIndex(), hoverIndex)); int end = max(panelState.SelectedIndex(), hoverIndex); panelState.SelectMany(start, end + 1); panelState.SetSelectedIndex(hoverIndex); } else if(panelState.AllSelected().count(hoverIndex)) { // If the click is on an already selected line, start dragging // but do not change the selection. } else panelState.SelectOnly(hoverIndex); } } else { const bool sameIndex = panelState.SelectedIndex() == hoverIndex; panelState.SelectOnly(hoverIndex); // If not landed, clicking a ship name takes you straight to its info. if(!panelState.CanEdit() || sameIndex) { GetUI()->Pop(this); GetUI()->Push(new ShipInfoPanel(player, std::move(panelState))); } } return true; } bool PlayerInfoPanel::Drag(double dx, double dy) { isDragging = true; return Hover(hoverPoint + Point(dx, dy)); } bool PlayerInfoPanel::Release(int /* x */, int /* y */) { if(!isDragging) return true; isDragging = false; // Do nothing if the block of ships has not been dragged to a valid new // location in the list, or if it's not possible to reorder the list. if(!panelState.CanEdit() || hoverIndex < 0 || hoverIndex == panelState.SelectedIndex()) return true; panelState.ReorderShipsTo(hoverIndex); return true; } void PlayerInfoPanel::DrawPlayer(const Rectangle &bounds) { // Check that the specified area is big enough. if(bounds.Width() < 250.) return; // Colors to draw with. const Color &dim = *GameData::Colors().Get("medium"); const Color &bright = *GameData::Colors().Get("bright"); // Two columns of opposite alignment are used to simulate a single visual column. Table table; const int columnWidth = 230; table.AddColumn(0, {columnWidth, Alignment::LEFT}); table.AddColumn(columnWidth, {columnWidth, Alignment::RIGHT}); table.SetUnderline(0, columnWidth); table.DrawAt(bounds.TopLeft() + Point(10., 8.)); table.DrawTruncatedPair("player:", dim, player.FirstName() + " " + player.LastName(), bright, Truncate::MIDDLE, true); table.DrawTruncatedPair("net worth:", dim, Format::CreditString(player.Accounts().NetWorth()), bright, Truncate::MIDDLE, true); table.DrawTruncatedPair("time played:", dim, Format::PlayTime(player.GetPlayTime()), bright, Truncate::MIDDLE, true); // Determine the player's combat rating. int combatExperience = player.Conditions().Get("combat rating"); int combatLevel = log(max<int64_t>(1, combatExperience)); string combatRating = GameData::Rating("combat", combatLevel); if(!combatRating.empty()) { table.DrawGap(10); table.DrawUnderline(dim); table.Draw("combat rating:", bright); table.Advance(); table.DrawGap(5); table.DrawTruncatedPair("rank:", dim, to_string(combatLevel) + " - " + combatRating, dim, Truncate::MIDDLE, false); table.DrawTruncatedPair("experience:", dim, Format::Number(combatExperience), dim, Truncate::MIDDLE, false); bool maxRank = (combatRating == GameData::Rating("combat", combatLevel + 1)); table.DrawTruncatedPair(" for next rank:", dim, maxRank ? "MAX" : Format::Number(ceil(exp(combatLevel + 1))), dim, Truncate::MIDDLE, false); } // Display the factors affecting piracy targeting the player. auto factors = player.RaidFleetFactors(); double attractionLevel = max(0., log2(max(factors.first, 0.))); double deterrenceLevel = max(0., log2(max(factors.second, 0.))); string attractionRating = GameData::Rating("cargo attractiveness", attractionLevel); string deterrenceRating = GameData::Rating("armament deterrence", deterrenceLevel); if(!attractionRating.empty() && !deterrenceRating.empty()) { double attraction = max(0., min(1., .005 * (factors.first - factors.second - 2.))); double prob = 1. - pow(1. - attraction, 10.); table.DrawGap(10); table.DrawUnderline(dim); table.Draw("piracy threat:", bright); table.Draw(to_string(lround(100 * prob)) + "%", dim); table.DrawGap(5); // Format the attraction and deterrence levels with tens places, so it // is clear which is higher even if they round to the same level. table.DrawTruncatedPair("cargo: " + attractionRating, dim, "(+" + Format::Decimal(attractionLevel, 1) + ")", dim, Truncate::MIDDLE, false); table.DrawTruncatedPair("fleet: " + deterrenceRating, dim, "(-" + Format::Decimal(deterrenceLevel, 1) + ")", dim, Truncate::MIDDLE, false); } // Other special information: vector<pair<int64_t, string>> salary; for(const auto &it : player.Accounts().SalariesIncome()) salary.emplace_back(it.second, it.first); sort(salary.begin(), salary.end()); DrawList(salary, table, "salary:", 4); vector<pair<int64_t, string>> tribute; for(const auto &it : player.GetTribute()) tribute.emplace_back(it.second, it.first->TrueName()); sort(tribute.begin(), tribute.end()); DrawList(tribute, table, "tribute:", 4); int maxRows = static_cast<int>(250. - 30. - table.GetPoint().Y()) / 20; vector<pair<int64_t, string>> licenses; for(const auto &it : player.Licenses()) licenses.emplace_back(1, it); DrawList(licenses, table, "licenses:", maxRows, false); } void PlayerInfoPanel::DrawFleet(const Rectangle &bounds) { // Check that the specified area is big enough. if(bounds.Width() < 750.) return; // Colors to draw with. const Color &back = *GameData::Colors().Get("faint"); const Color &selectedBack = *GameData::Colors().Get("dimmer"); const Color &dim = *GameData::Colors().Get("medium"); const Color &bright = *GameData::Colors().Get("bright"); const Color &elsewhere = *GameData::Colors().Get("dim"); const Color &dead = *GameData::Colors().Get("dead"); const Color &flagship = *GameData::Colors().Get("flagship"); const Color &disabled = *GameData::Colors().Get("disabled"); // Table attributes. Table table; for(const auto &col : columns) table.AddColumn(col.offset, col.layout); table.SetUnderline(0, 730); table.DrawAt(bounds.TopLeft() + Point(10., 8.)); table.DrawUnderline(dim); // Header row. const Point tablePoint = table.GetPoint(); for(const auto &column : columns) { Rectangle zone = Rectangle( tablePoint + Point((column.offset + column.endX) / 2, table.GetRowSize().Y() / 2), Point(column.layout.width, table.GetRowSize().Y()) ); // Highlight the column header if it is under the mouse // or ships are sorted according to that column. const Color &columnHeaderColor = ((!isDragging && zone.Contains(hoverPoint)) || panelState.CurrentSort() == column.shipSort) ? bright : dim; table.Draw(column.name, columnHeaderColor); menuZones.emplace_back(zone, column.shipSort); } table.DrawGap(5); // Loop through all the player's ships. int index = panelState.Scroll(); hoverIndex = -1; for(auto sit = panelState.Ships().begin() + panelState.Scroll(); sit < panelState.Ships().end(); ++sit) { // Bail out if we've used out the whole drawing area. if(!bounds.Contains(table.GetRowBounds())) break; // Check if this row is selected. if(panelState.SelectedIndex() == index) table.DrawHighlight(selectedBack); else if(panelState.AllSelected().count(index)) table.DrawHighlight(back); // Find out if the mouse is hovering over the ship Rectangle shipZone = Rectangle(table.GetCenterPoint(), table.GetRowSize()); bool isHovered = (hoverIndex == -1) && shipZone.Contains(hoverPoint); if(isHovered) hoverIndex = index; const Ship &ship = **sit; bool isElsewhere = (ship.GetSystem() != player.GetSystem()); isElsewhere |= ((ship.CanBeCarried() || ship.GetPlanet() != player.GetPlanet()) && player.GetPlanet()); bool isDead = ship.IsDestroyed(); bool isDisabled = ship.IsDisabled(); bool isFlagship = &ship == player.Flagship(); table.SetColor( isDead ? dead : isHovered ? bright : isFlagship ? flagship : isDisabled ? disabled : isElsewhere ? elsewhere : dim ); // Indent the ship name if it is a fighter or drone. table.Draw(ship.CanBeCarried() ? " " + ship.Name() : ship.Name()); table.Draw(ship.DisplayModelName()); const System *system = ship.GetSystem(); table.Draw(system ? system->Name() : ""); string shields = to_string(static_cast<int>(100. * max(0., ship.Shields()))) + "%"; table.Draw(shields); string hull = to_string(static_cast<int>(100. * max(0., ship.Hull()))) + "%"; table.Draw(hull); string fuel = to_string(static_cast<int>( ship.Attributes().Get("fuel capacity") * ship.Fuel())); table.Draw(fuel); // If this isn't the flagship, we'll remember how many crew it has, but // only the minimum number of crew need to be paid for. int crewCount = ship.Crew(); if(!isFlagship) crewCount = min(crewCount, ship.RequiredCrew()); string crew = (ship.IsParked() ? "Parked" : to_string(crewCount)); table.Draw(crew); ++index; } // Re-ordering ships in your fleet. if(isDragging) { const Font &font = FontSet::Get(14); Point pos(hoverPoint.X(), hoverPoint.Y()); for(int i : panelState.AllSelected()) { const string &name = panelState.Ships()[i]->Name(); font.Draw(name, pos + Point(1., 1.), Color(0., 1.)); font.Draw(name, pos, bright); pos.Y() += 20.; } } } // Sorts the player's fleet given a comparator function (based on column). void PlayerInfoPanel::SortShips(InfoPanelState::ShipComparator *shipComparator) { // Clicking on a sort column twice reverses the comparison. if(panelState.CurrentSort() == shipComparator) shipComparator = GetReverseCompareFrom(*shipComparator); // Save selected ships to preserve selection after sort. multiset<shared_ptr<Ship>, InfoPanelState::ShipComparator *> selectedShips(shipComparator); shared_ptr<Ship> lastSelected = panelState.SelectedIndex() == -1 ? nullptr : panelState.Ships()[panelState.SelectedIndex()]; for(int i : panelState.AllSelected()) selectedShips.insert(panelState.Ships()[i]); panelState.DeselectAll(); // Move flagship to first position for(auto &ship : panelState.Ships()) if(ship.get() == player.Flagship()) { swap(ship, *panelState.Ships().begin()); break; } stable_sort( panelState.Ships().begin() + 1, panelState.Ships().end(), shipComparator ); // Load the same selected ships from before the sort. auto it = selectedShips.begin(); for(size_t i = 0; i < panelState.Ships().size(); ++i) if(panelState.Ships()[i] == *it) { if(lastSelected == *it) panelState.SetSelectedIndex(i); else panelState.Select(i); ++it; if(it == selectedShips.end()) break; } // Ships are now sorted. panelState.SetCurrentSort(shipComparator); } bool PlayerInfoPanel::Hover(int x, int y) { return Hover(Point(x, y)); } bool PlayerInfoPanel::Hover(const Point &point) { hoverPoint = point; hoverIndex = -1; return true; } bool PlayerInfoPanel::Scroll(double /* dx */, double dy) { return Scroll(dy * -.1 * Preferences::ScrollSpeed()); } bool PlayerInfoPanel::ScrollAbsolute(int scroll) { int maxScroll = panelState.Ships().size() - LINES_PER_PAGE; int newScroll = max(0, min<int>(maxScroll, scroll)); if(panelState.Scroll() == newScroll) return false; panelState.SetScroll(newScroll); return true; } // Adjust the scroll by the given amount. Return true if it changed. bool PlayerInfoPanel::Scroll(int distance) { return ScrollAbsolute(panelState.Scroll() + distance); } PlayerInfoPanel::SortableColumn::SortableColumn( string name, double offset, double endX, Layout layout, InfoPanelState::ShipComparator *shipSort ) : name(name), offset(offset), endX(endX), layout(layout), shipSort(shipSort) { }
0
endless-sky-master
endless-sky-master/source/Logger.cpp
/* Logger.cpp Copyright (c) 2022 by Peter van der Meer Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Logger.h" #include <iostream> #include <mutex> using namespace std; namespace { function<void(const string &message)> logErrorCallback = nullptr; mutex logErrorMutex; } void Logger::SetLogErrorCallback(function<void(const string &message)> callback) { logErrorCallback = std::move(callback); } void Logger::LogError(const string &message) { lock_guard<mutex> lock(logErrorMutex); // Log by default to stderr. cerr << message << endl; // Perform additional logging through callback if any is registered. if(logErrorCallback) logErrorCallback(message); }
0
endless-sky-master
endless-sky-master/source/MaskManager.cpp
/* MaskManager.cpp Copyright (c) 2021 by Amazinite Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "MaskManager.h" #include "Logger.h" #include "Sprite.h" using namespace std; namespace { constexpr double DEFAULT = 1.; map<const Sprite *, bool> warned; string PrintScale(double s) { return to_string(100. * s) + "%"; } } // Move the given masks at 1x scale into the manager's storage. void MaskManager::SetMasks(const Sprite *sprite, vector<Mask> &&masks) { lock_guard<mutex> lock(spriteMutex); auto &scales = spriteMasks[sprite]; auto it = scales.find(DEFAULT); if(it != scales.end()) it->second.swap(masks); else scales.emplace(DEFAULT, std::move(masks)); } // Add a scale that the given sprite needs to have a mask for. void MaskManager::RegisterScale(const Sprite *sprite, double scale) { lock_guard<mutex> lock(spriteMutex); auto &scales = spriteMasks[sprite]; auto lb = scales.lower_bound(scale); if(lb == scales.end() || lb->first != scale) scales.emplace_hint(lb, scale, vector<Mask>{}); else if(!lb->second.empty()) Logger::LogError("Collision mask for sprite \"" + sprite->Name() + "\" at scale " + PrintScale(scale) + " was already generated."); } // Create the scaled versions of all masks from the 1x versions. void MaskManager::ScaleMasks() { for(auto &spriteScales : spriteMasks) { auto &scales = spriteScales.second; auto baseIt = scales.find(DEFAULT); if(baseIt == scales.end() || baseIt->second.empty()) continue; const auto &baseMasks = baseIt->second; for(auto &it : scales) { auto &masks = it.second; // Skip mask generation for scales that have already been generated previously. if(!masks.empty()) continue; masks.reserve(baseMasks.size()); for(auto &&mask : baseMasks) masks.push_back(mask * it.first); } } } // Get the masks for the given sprite at the given scale. If a // sprite has no masks, an empty mask is returned. const std::vector<Mask> &MaskManager::GetMasks(const Sprite *sprite, double scale) const { static const vector<Mask> EMPTY; const auto scalesIt = spriteMasks.find(sprite); if(scalesIt == spriteMasks.end()) { if(warned.insert(make_pair(sprite, true)).second) Logger::LogError("Warning: sprite \"" + sprite->Name() + "\": no collision masks found."); return EMPTY; } const auto &scales = scalesIt->second; const auto maskIt = scales.find(scale); if(maskIt != scales.end() && !maskIt->second.empty()) return maskIt->second; // Shouldn't happen, but just in case, print some details about the scales for this sprite (once). if(warned.insert(make_pair(sprite, true)).second) { string warning = "Warning: sprite \"" + sprite->Name() + "\": collision mask not found."; if(scales.empty()) warning += " (No scaled masks.)"; else if(maskIt != scales.end()) warning += " (No masks for scale " + PrintScale(scale) + ".)"; else { warning += "\n\t" + PrintScale(scale) + " not found in known scales:"; for(auto &&s : scales) warning += "\n\t\t" + PrintScale(s.first); } Logger::LogError(warning); } return EMPTY; }
0