1 // AIManager.cxx Based on David Luff's AIMgr:
2 // - a global management type for AI objects
4 // Written by David Culp, started October 2003.
5 // - davidculp2@comcast.net
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24 #include <simgear/sg_inlines.h>
25 #include <simgear/math/sg_geodesy.hxx>
26 #include <simgear/props/props_io.hxx>
27 #include <simgear/structure/exception.hxx>
28 #include <boost/mem_fn.hpp>
29 #include <boost/foreach.hpp>
31 #include <Main/globals.hxx>
32 #include <Airports/airport.hxx>
34 #include "AIManager.hxx"
35 #include "AIAircraft.hxx"
37 #include "AIBallistic.hxx"
38 #include "AIStorm.hxx"
39 #include "AIThermal.hxx"
40 #include "AICarrier.hxx"
41 #include "AIStatic.hxx"
42 #include "AIMultiplayer.hxx"
43 #include "AITanker.hxx"
44 #include "AIWingman.hxx"
45 #include "AIGroundVehicle.hxx"
46 #include "AIEscort.hxx"
48 FGAIManager::FGAIManager() :
49 cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
50 fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
51 cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
52 fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
57 FGAIManager::~FGAIManager()
59 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
64 root = fgGetNode("sim/ai", true);
66 enabled = root->getNode("enabled", true);
68 thermal_lift_node = fgGetNode("/environment/thermal-lift-fps", true);
69 wind_from_east_node = fgGetNode("/environment/wind-from-east-fps",true);
70 wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
72 user_latitude_node = fgGetNode("/position/latitude-deg", true);
73 user_longitude_node = fgGetNode("/position/longitude-deg", true);
74 user_altitude_node = fgGetNode("/position/altitude-ft", true);
75 user_altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
76 user_heading_node = fgGetNode("/orientation/heading-deg", true);
77 user_pitch_node = fgGetNode("/orientation/pitch-deg", true);
78 user_yaw_node = fgGetNode("/orientation/side-slip-deg", true);
79 user_roll_node = fgGetNode("/orientation/roll-deg", true);
80 user_speed_node = fgGetNode("/velocities/uBody-fps", true);
84 FGAIManager::postinit() {
85 // postinit, so that it can access the Nasal subsystem
87 if (!root->getBoolValue("scenarios-enabled", true))
90 // scenarios enabled, AI subsystem required
91 if (!enabled->getBoolValue())
92 enabled->setBoolValue(true);
94 // process all scenarios
95 std::map<string, bool> scenarios;
96 for (int i = 0 ; i < root->nChildren() ; i++) {
97 SGPropertyNode *n = root->getChild(i);
98 if (strcmp(n->getName(), "scenario"))
101 const string& name = n->getStringValue();
105 if (scenarios.find(name) != scenarios.end()) {
106 SG_LOG(SG_AI, SG_DEBUG, "won't load scenario '" << name << "' twice");
110 SG_LOG(SG_AI, SG_ALERT, "loading scenario '" << name << '\'');
111 processScenario(name);
112 scenarios[name] = true;
117 FGAIManager::reinit()
120 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
124 FGAIManager::bind() {
125 root = globals->get_props()->getNode("ai/models", true);
126 root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
127 &FGAIManager::getNumAiObjects));
131 FGAIManager::unbind() {
132 root->untie("count");
135 void FGAIManager::removeDeadItem(FGAIBase* base)
137 SGPropertyNode *props = base->_getProps();
139 props->setBoolValue("valid", false);
142 // for backward compatibility reset properties, so that aircraft,
143 // which don't know the <valid> property, keep working
144 // TODO: remove after a while
145 props->setIntValue("id", -1);
146 props->setBoolValue("radar/in-range", false);
147 props->setIntValue("refuel/tanker", false);
151 FGAIManager::update(double dt) {
152 // initialize these for finding nearest thermals
153 range_nearest = 10000.0;
156 if (!enabled->getBoolValue())
161 // partition the list into dead followed by alive
162 ai_list_iterator firstAlive =
163 std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
165 // clean up each item and finally remove from the container
166 for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
170 ai_list.erase(ai_list.begin(), firstAlive);
172 // every remaining item is alive
173 BOOST_FOREACH(FGAIBase* base, ai_list) {
174 if (base->isa(FGAIBase::otThermal)) {
175 processThermal(dt, (FGAIThermal*)base);
179 } // of live AI objects iteration
181 thermal_lift_node->setDoubleValue( strength ); // for thermals
184 /** update LOD settings of all AI/MP models */
186 FGAIManager::updateLOD(SGPropertyNode* node)
189 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
193 FGAIManager::attach(FGAIBase *model)
195 const char* typeString = model->getTypeString();
196 SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
200 // find free index in the property tree, if we have
201 // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
202 for (i = 0; i < 10000; i++) {
203 p = root->getNode(typeString, i, false);
205 if (!p || !p->getBoolValue("valid", false))
208 if (p->getIntValue("id",-1)==model->getID()) {
209 p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
213 p = root->getNode(typeString, i, true);
214 model->setManager(this, p);
215 ai_list.push_back(model);
217 model->init(model->getType()==FGAIBase::otAircraft
218 || model->getType()==FGAIBase::otMultiplayer
219 || model->getType()==FGAIBase::otStatic);
221 p->setBoolValue("valid", true);
225 FGAIManager::getNumAiObjects(void) const
227 return ai_list.size();
231 FGAIManager::fetchUserState( void ) {
233 user_latitude = user_latitude_node->getDoubleValue();
234 user_longitude = user_longitude_node->getDoubleValue();
235 user_altitude = user_altitude_node->getDoubleValue();
236 user_heading = user_heading_node->getDoubleValue();
237 user_pitch = user_pitch_node->getDoubleValue();
238 user_yaw = user_yaw_node->getDoubleValue();
239 user_speed = user_speed_node->getDoubleValue() * 0.592484;
240 user_roll = user_roll_node->getDoubleValue();
241 wind_from_east = wind_from_east_node->getDoubleValue();
242 wind_from_north = wind_from_north_node->getDoubleValue();
243 user_altitude_agl = user_altitude_agl_node->getDoubleValue();
247 // only keep the results from the nearest thermal
249 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
252 if ( thermal->_getRange() < range_nearest ) {
253 range_nearest = thermal->_getRange();
254 strength = thermal->getStrength();
262 FGAIManager::processScenario( const string &filename ) {
264 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
269 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
274 for (int i = 0; i < scenarios->nChildren(); i++) {
275 SGPropertyNode* scEntry = scenarios->getChild(i);
277 if (strcmp(scEntry->getName(), "entry"))
279 const std::string& type = scEntry->getStringValue("type", "aircraft");
281 if (type == "tanker") { // refueling scenarios
282 FGAITanker* tanker = new FGAITanker;
283 tanker->readFromScenario(scEntry);
286 } else if (type == "wingman") {
287 FGAIWingman* wingman = new FGAIWingman;
288 wingman->readFromScenario(scEntry);
291 } else if (type == "aircraft") {
292 FGAIAircraft* aircraft = new FGAIAircraft;
293 aircraft->readFromScenario(scEntry);
296 } else if (type == "ship") {
297 FGAIShip* ship = new FGAIShip;
298 ship->readFromScenario(scEntry);
301 } else if (type == "carrier") {
302 FGAICarrier* carrier = new FGAICarrier;
303 carrier->readFromScenario(scEntry);
306 } else if (type == "groundvehicle") {
307 FGAIGroundVehicle* groundvehicle = new FGAIGroundVehicle;
308 groundvehicle->readFromScenario(scEntry);
309 attach(groundvehicle);
311 } else if (type == "escort") {
312 FGAIEscort* escort = new FGAIEscort;
313 escort->readFromScenario(scEntry);
316 } else if (type == "thunderstorm") {
317 FGAIStorm* storm = new FGAIStorm;
318 storm->readFromScenario(scEntry);
321 } else if (type == "thermal") {
322 FGAIThermal* thermal = new FGAIThermal;
323 thermal->readFromScenario(scEntry);
326 } else if (type == "ballistic") {
327 FGAIBallistic* ballistic = new FGAIBallistic;
328 ballistic->readFromScenario(scEntry);
331 } else if (type == "static") {
332 FGAIStatic* aistatic = new FGAIStatic;
333 aistatic->readFromScenario(scEntry);
342 FGAIManager::loadScenarioFile(const std::string& filename)
344 SGPath path(globals->get_fg_root());
345 path.append("AI/" + filename + ".xml");
347 SGPropertyNode_ptr root = new SGPropertyNode;
348 readProperties(path.str(), root);
350 } catch (const sg_exception &t) {
351 SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
352 << path.str() << "': " << t.getFormattedMessage());
358 FGAIManager::getStartPosition(const string& id, const string& pid,
359 SGGeod& geodPos, double& hdng, SGVec3d& uvw)
362 SGPropertyNode* root = fgGetNode("sim/ai", true);
363 if (!root->getNode("enabled", true)->getBoolValue())
366 for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
367 SGPropertyNode *aiEntry = root->getChild( i );
368 if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
369 const string& filename = aiEntry->getStringValue();
370 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
372 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
374 for (int i = 0; i < scenarios->nChildren(); i++) {
375 SGPropertyNode* scEntry = scenarios->getChild(i);
376 const std::string& type = scEntry->getStringValue("type");
377 const std::string& pnumber = scEntry->getStringValue("pennant-number");
378 const std::string& name = scEntry->getStringValue("name");
379 if (type == "carrier" && (pnumber == id || name == id)) {
380 SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
381 carrier->readFromScenario(scEntry);
383 if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
397 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
399 // we specify tgt extent (ft) according to the AIObject type
400 double tgt_ht[] = {0, 50, 100, 250, 0, 100, 0, 0, 50, 50, 20, 100, 50};
401 double tgt_length[] = {0, 100, 200, 750, 0, 50, 0, 0, 200, 100, 40, 200, 100};
402 ai_list_iterator ai_list_itr = ai_list.begin();
403 ai_list_iterator end = ai_list.end();
405 SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
406 SGVec3d cartPos(SGVec3d::fromGeod(pos));
408 while (ai_list_itr != end) {
409 double tgt_alt = (*ai_list_itr)->_getAltitude();
410 int type = (*ai_list_itr)->getType();
411 tgt_ht[type] += fuse_range;
413 if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
414 || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
415 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
416 // << fabs(tgt_alt - alt)
424 int id = (*ai_list_itr)->getID();
426 double range = calcRange(cartPos, (*ai_list_itr));
428 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: AI list size "
430 // << " type " << type
432 // << " range " << range
433 // //<< " bearing " << bearing
434 // << " alt " << tgt_alt
437 tgt_length[type] += fuse_range;
439 if (range < tgt_length[type]){
440 SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
443 << " range " << range
444 << " alt " << tgt_alt
446 return (*ai_list_itr).get();
454 FGAIManager::calcRange(const SGVec3d& aCartPos, FGAIBase* aObject) const
456 double distM = dist(aCartPos, aObject->getCartPos());
457 return distM * SG_METER_TO_FEET;