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 <simgear/structure/commands.hxx>
30 #include <boost/mem_fn.hpp>
31 #include <boost/foreach.hpp>
33 #include <Main/globals.hxx>
34 #include <Airports/airport.hxx>
36 #include "AIManager.hxx"
37 #include "AIAircraft.hxx"
39 #include "AIBallistic.hxx"
40 #include "AIStorm.hxx"
41 #include "AIThermal.hxx"
42 #include "AICarrier.hxx"
43 #include "AIStatic.hxx"
44 #include "AIMultiplayer.hxx"
45 #include "AITanker.hxx"
46 #include "AIWingman.hxx"
47 #include "AIGroundVehicle.hxx"
48 #include "AIEscort.hxx"
50 class FGAIManager::Scenario
53 Scenario(FGAIManager* man, SGPropertyNode* scenarios) :
56 BOOST_FOREACH(SGPropertyNode* scEntry, scenarios->getChildren("entry")) {
57 FGAIBasePtr ai = man->addObject(scEntry);
59 _objects.push_back(ai);
61 } // of scenario entry iteration
66 BOOST_FOREACH(FGAIBasePtr ai, _objects) {
71 FGAIManager* _manager;
72 std::vector<FGAIBasePtr> _objects;
75 ///////////////////////////////////////////////////////////////////////////////
77 FGAIManager::FGAIManager() :
78 cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
79 fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
80 cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
81 fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
86 FGAIManager::~FGAIManager()
88 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
93 root = fgGetNode("sim/ai", true);
95 enabled = root->getNode("enabled", true);
97 thermal_lift_node = fgGetNode("/environment/thermal-lift-fps", true);
98 wind_from_east_node = fgGetNode("/environment/wind-from-east-fps",true);
99 wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
101 user_altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
102 user_yaw_node = fgGetNode("/orientation/side-slip-deg", true);
103 user_speed_node = fgGetNode("/velocities/uBody-fps", true);
105 globals->get_commands()->addCommand("load-scenario", this, &FGAIManager::loadScenarioCommand);
106 globals->get_commands()->addCommand("unload-scenario", this, &FGAIManager::unloadScenarioCommand);
110 FGAIManager::postinit() {
111 // postinit, so that it can access the Nasal subsystem
113 if (!root->getBoolValue("scenarios-enabled", true))
116 // scenarios enabled, AI subsystem required
117 if (!enabled->getBoolValue())
118 enabled->setBoolValue(true);
120 // process all scenarios
121 BOOST_FOREACH(SGPropertyNode* n, root->getChildren("scenario")) {
122 const string& name = n->getStringValue();
126 if (_scenarios.find(name) != _scenarios.end()) {
127 SG_LOG(SG_AI, SG_WARN, "won't load scenario '" << name << "' twice");
131 SG_LOG(SG_AI, SG_INFO, "loading scenario '" << name << '\'');
137 FGAIManager::reinit()
140 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
144 FGAIManager::bind() {
145 root = globals->get_props()->getNode("ai/models", true);
146 root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
147 &FGAIManager::getNumAiObjects));
151 FGAIManager::unbind() {
152 root->untie("count");
155 void FGAIManager::removeDeadItem(FGAIBase* base)
157 SGPropertyNode *props = base->_getProps();
159 props->setBoolValue("valid", false);
162 // for backward compatibility reset properties, so that aircraft,
163 // which don't know the <valid> property, keep working
164 // TODO: remove after a while
165 props->setIntValue("id", -1);
166 props->setBoolValue("radar/in-range", false);
167 props->setIntValue("refuel/tanker", false);
171 FGAIManager::update(double dt) {
172 // initialize these for finding nearest thermals
173 range_nearest = 10000.0;
176 if (!enabled->getBoolValue())
181 // partition the list into dead followed by alive
182 ai_list_iterator firstAlive =
183 std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
185 // clean up each item and finally remove from the container
186 for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
190 ai_list.erase(ai_list.begin(), firstAlive);
192 // every remaining item is alive
193 BOOST_FOREACH(FGAIBase* base, ai_list) {
194 if (base->isa(FGAIBase::otThermal)) {
195 processThermal(dt, (FGAIThermal*)base);
199 } // of live AI objects iteration
201 thermal_lift_node->setDoubleValue( strength ); // for thermals
204 /** update LOD settings of all AI/MP models */
206 FGAIManager::updateLOD(SGPropertyNode* node)
209 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
213 FGAIManager::attach(FGAIBase *model)
215 const char* typeString = model->getTypeString();
216 SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
220 // find free index in the property tree, if we have
221 // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
222 for (i = 0; i < 10000; i++) {
223 p = root->getNode(typeString, i, false);
225 if (!p || !p->getBoolValue("valid", false))
228 if (p->getIntValue("id",-1)==model->getID()) {
229 p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
233 p = root->getNode(typeString, i, true);
234 model->setManager(this, p);
235 ai_list.push_back(model);
237 model->init(model->getType()==FGAIBase::otAircraft
238 || model->getType()==FGAIBase::otMultiplayer
239 || model->getType()==FGAIBase::otStatic);
241 p->setBoolValue("valid", true);
245 FGAIManager::getNumAiObjects(void) const
247 return ai_list.size();
251 FGAIManager::fetchUserState( void ) {
253 user_yaw = user_yaw_node->getDoubleValue();
254 globals->get_aircraft_orientation(user_heading, user_pitch, user_roll);
256 user_speed = user_speed_node->getDoubleValue() * 0.592484;
257 wind_from_east = wind_from_east_node->getDoubleValue();
258 wind_from_north = wind_from_north_node->getDoubleValue();
259 user_altitude_agl = user_altitude_agl_node->getDoubleValue();
263 // only keep the results from the nearest thermal
265 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
268 if ( thermal->_getRange() < range_nearest ) {
269 range_nearest = thermal->_getRange();
270 strength = thermal->getStrength();
275 bool FGAIManager::loadScenarioCommand(const SGPropertyNode* args)
277 std::string name = args->getStringValue("name");
278 return loadScenario(name);
281 bool FGAIManager::unloadScenarioCommand(const SGPropertyNode* args)
283 std::string name = args->getStringValue("name");
284 unloadScenario(name);
288 bool FGAIManager::addObjectCommand(const SGPropertyNode* definition)
290 addObject(definition);
294 FGAIBasePtr FGAIManager::addObject(const SGPropertyNode* definition)
296 const std::string& type = definition->getStringValue("type", "aircraft");
299 if (type == "tanker") { // refueling scenarios
301 } else if (type == "wingman") {
302 ai = new FGAIWingman;
303 } else if (type == "aircraft") {
304 ai = new FGAIAircraft;
305 } else if (type == "ship") {
307 } else if (type == "carrier") {
308 ai = new FGAICarrier;
309 } else if (type == "groundvehicle") {
310 ai = new FGAIGroundVehicle;
311 } else if (type == "escort") {
313 } else if (type == "thunderstorm") {
315 } else if (type == "thermal") {
316 ai = new FGAIThermal;
317 } else if (type == "ballistic") {
318 ai = new FGAIBallistic;
319 } else if (type == "static") {
323 ai->readFromScenario(const_cast<SGPropertyNode*>(definition));
328 bool FGAIManager::removeObject(const SGPropertyNode* args)
330 int id = args->getIntValue("id");
331 BOOST_FOREACH(FGAIBase* ai, get_ai_list()) {
332 if (ai->getID() == id) {
342 FGAIManager::loadScenario( const string &filename )
344 SGPropertyNode_ptr file = loadScenarioFile(filename);
349 SGPropertyNode_ptr scNode = file->getChild("scenario");
354 _scenarios[filename] = new Scenario(this, scNode);
360 FGAIManager::unloadScenario( const string &filename)
362 ScenarioDict::iterator it = _scenarios.find(filename);
363 if (it == _scenarios.end()) {
364 SG_LOG(SG_AI, SG_WARN, "unload scenario: not found:" << filename);
369 _scenarios.erase(it);
373 FGAIManager::loadScenarioFile(const std::string& filename)
375 SGPath path(globals->get_fg_root());
376 path.append("AI/" + filename + ".xml");
378 SGPropertyNode_ptr root = new SGPropertyNode;
379 readProperties(path.str(), root);
381 } catch (const sg_exception &t) {
382 SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
383 << path.str() << "': " << t.getFormattedMessage());
389 FGAIManager::getStartPosition(const string& id, const string& pid,
390 SGGeod& geodPos, double& hdng, SGVec3d& uvw)
393 SGPropertyNode* root = fgGetNode("sim/ai", true);
394 if (!root->getNode("enabled", true)->getBoolValue())
397 for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
398 SGPropertyNode *aiEntry = root->getChild( i );
399 if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
400 const string& filename = aiEntry->getStringValue();
401 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
403 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
405 for (int i = 0; i < scenarios->nChildren(); i++) {
406 SGPropertyNode* scEntry = scenarios->getChild(i);
407 const std::string& type = scEntry->getStringValue("type");
408 const std::string& pnumber = scEntry->getStringValue("pennant-number");
409 const std::string& name = scEntry->getStringValue("name");
410 if (type == "carrier" && (pnumber == id || name == id)) {
411 SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
412 carrier->readFromScenario(scEntry);
414 if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
428 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
430 // we specify tgt extent (ft) according to the AIObject type
431 double tgt_ht[] = {0, 50, 100, 250, 0, 100, 0, 0, 50, 50, 20, 100, 50};
432 double tgt_length[] = {0, 100, 200, 750, 0, 50, 0, 0, 200, 100, 40, 200, 100};
433 ai_list_iterator ai_list_itr = ai_list.begin();
434 ai_list_iterator end = ai_list.end();
436 SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
437 SGVec3d cartPos(SGVec3d::fromGeod(pos));
439 while (ai_list_itr != end) {
440 double tgt_alt = (*ai_list_itr)->_getAltitude();
441 int type = (*ai_list_itr)->getType();
442 tgt_ht[type] += fuse_range;
444 if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
445 || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
446 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
447 // << fabs(tgt_alt - alt)
455 int id = (*ai_list_itr)->getID();
457 double range = calcRangeFt(cartPos, (*ai_list_itr));
459 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: AI list size "
461 // << " type " << type
463 // << " range " << range
464 // //<< " bearing " << bearing
465 // << " alt " << tgt_alt
468 tgt_length[type] += fuse_range;
470 if (range < tgt_length[type]){
471 SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
474 << " range " << range
475 << " alt " << tgt_alt
477 return (*ai_list_itr).get();
485 FGAIManager::calcRangeFt(const SGVec3d& aCartPos, FGAIBase* aObject) const
487 double distM = dist(aCartPos, aObject->getCartPos());
488 return distM * SG_METER_TO_FEET;