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.
23 #include <simgear/sg_inlines.h>
24 #include <simgear/math/sg_geodesy.hxx>
25 #include <simgear/props/props_io.hxx>
26 #include <simgear/structure/exception.hxx>
27 #include <boost/mem_fn.hpp>
28 #include <boost/foreach.hpp>
30 #include <Main/globals.hxx>
31 #include <Airports/simple.hxx>
33 #include "AIManager.hxx"
34 #include "AIAircraft.hxx"
36 #include "AIBallistic.hxx"
37 #include "AIStorm.hxx"
38 #include "AIThermal.hxx"
39 #include "AICarrier.hxx"
40 #include "AIStatic.hxx"
41 #include "AIMultiplayer.hxx"
42 #include "AITanker.hxx"
43 #include "AIWingman.hxx"
44 #include "AIGroundVehicle.hxx"
45 #include "AIEscort.hxx"
47 FGAIManager::FGAIManager() :
48 cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
49 fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
50 cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
51 fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
56 FGAIManager::~FGAIManager()
58 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
63 root = fgGetNode("sim/ai", true);
65 enabled = root->getNode("enabled", true);
67 thermal_lift_node = fgGetNode("/environment/thermal-lift-fps", true);
68 wind_from_east_node = fgGetNode("/environment/wind-from-east-fps",true);
69 wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
71 user_latitude_node = fgGetNode("/position/latitude-deg", true);
72 user_longitude_node = fgGetNode("/position/longitude-deg", true);
73 user_altitude_node = fgGetNode("/position/altitude-ft", true);
74 user_altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
75 user_heading_node = fgGetNode("/orientation/heading-deg", true);
76 user_pitch_node = fgGetNode("/orientation/pitch-deg", true);
77 user_yaw_node = fgGetNode("/orientation/side-slip-deg", true);
78 user_roll_node = fgGetNode("/orientation/roll-deg", true);
79 user_speed_node = fgGetNode("/velocities/uBody-fps", true);
83 FGAIManager::postinit() {
84 // postinit, so that it can access the Nasal subsystem
86 if (!root->getBoolValue("scenarios-enabled", true))
89 // scenarios enabled, AI subsystem required
90 if (!enabled->getBoolValue())
91 enabled->setBoolValue(true);
93 // process all scenarios
94 std::map<string, bool> scenarios;
95 for (int i = 0 ; i < root->nChildren() ; i++) {
96 SGPropertyNode *n = root->getChild(i);
97 if (strcmp(n->getName(), "scenario"))
100 string name = n->getStringValue();
104 if (scenarios.find(name) != scenarios.end()) {
105 SG_LOG(SG_AI, SG_DEBUG, "won't load scenario '" << name << "' twice");
109 SG_LOG(SG_AI, SG_ALERT, "loading scenario '" << name << '\'');
110 processScenario(name);
111 scenarios[name] = true;
116 FGAIManager::reinit()
119 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
123 FGAIManager::bind() {
124 root = globals->get_props()->getNode("ai/models", true);
125 root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
126 &FGAIManager::getNumAiObjects));
130 FGAIManager::unbind() {
131 root->untie("count");
134 void FGAIManager::removeDeadItem(FGAIBase* base)
136 SGPropertyNode *props = base->_getProps();
138 props->setBoolValue("valid", false);
141 // for backward compatibility reset properties, so that aircraft,
142 // which don't know the <valid> property, keep working
143 // TODO: remove after a while
144 props->setIntValue("id", -1);
145 props->setBoolValue("radar/in-range", false);
146 props->setIntValue("refuel/tanker", false);
150 FGAIManager::update(double dt) {
151 // initialize these for finding nearest thermals
152 range_nearest = 10000.0;
155 if (!enabled->getBoolValue())
160 // partition the list into dead followed by alive
161 ai_list_iterator firstAlive =
162 std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
164 // clean up each item and finally remove from the container
165 for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
169 ai_list.erase(ai_list.begin(), firstAlive);
171 // every remaining item is alive
172 BOOST_FOREACH(FGAIBase* base, ai_list) {
173 if (base->isa(FGAIBase::otThermal)) {
174 processThermal(dt, (FGAIThermal*)base);
178 } // of live AI objects iteration
180 thermal_lift_node->setDoubleValue( strength ); // for thermals
183 /** update LOD settings of all AI/MP models */
185 FGAIManager::updateLOD(SGPropertyNode* node)
188 std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
192 FGAIManager::attach(FGAIBase *model)
194 const char* typeString = model->getTypeString();
195 SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
199 // find free index in the property tree, if we have
200 // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
201 for (i = 0; i < 10000; i++) {
202 p = root->getNode(typeString, i, false);
204 if (!p || !p->getBoolValue("valid", false))
207 if (p->getIntValue("id",-1)==model->getID()) {
208 p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
212 p = root->getNode(typeString, i, true);
213 model->setManager(this, p);
214 ai_list.push_back(model);
216 model->init(model->getType()==FGAIBase::otAircraft
217 || model->getType()==FGAIBase::otMultiplayer
218 || model->getType()==FGAIBase::otStatic);
220 p->setBoolValue("valid", true);
224 FGAIManager::getNumAiObjects(void) const
226 return ai_list.size();
230 FGAIManager::fetchUserState( void ) {
232 user_latitude = user_latitude_node->getDoubleValue();
233 user_longitude = user_longitude_node->getDoubleValue();
234 user_altitude = user_altitude_node->getDoubleValue();
235 user_heading = user_heading_node->getDoubleValue();
236 user_pitch = user_pitch_node->getDoubleValue();
237 user_yaw = user_yaw_node->getDoubleValue();
238 user_speed = user_speed_node->getDoubleValue() * 0.592484;
239 user_roll = user_roll_node->getDoubleValue();
240 wind_from_east = wind_from_east_node->getDoubleValue();
241 wind_from_north = wind_from_north_node->getDoubleValue();
242 user_altitude_agl = user_altitude_agl_node->getDoubleValue();
246 // only keep the results from the nearest thermal
248 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
251 if ( thermal->_getRange() < range_nearest ) {
252 range_nearest = thermal->_getRange();
253 strength = thermal->getStrength();
261 FGAIManager::processScenario( const string &filename ) {
263 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
268 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
273 for (int i = 0; i < scenarios->nChildren(); i++) {
274 SGPropertyNode* scEntry = scenarios->getChild(i);
276 if (strcmp(scEntry->getName(), "entry"))
278 std::string type = scEntry->getStringValue("type", "aircraft");
280 if (type == "tanker") { // refueling scenarios
281 FGAITanker* tanker = new FGAITanker;
282 tanker->readFromScenario(scEntry);
285 } else if (type == "wingman") {
286 FGAIWingman* wingman = new FGAIWingman;
287 wingman->readFromScenario(scEntry);
290 } else if (type == "aircraft") {
291 FGAIAircraft* aircraft = new FGAIAircraft;
292 aircraft->readFromScenario(scEntry);
295 } else if (type == "ship") {
296 FGAIShip* ship = new FGAIShip;
297 ship->readFromScenario(scEntry);
300 } else if (type == "carrier") {
301 FGAICarrier* carrier = new FGAICarrier;
302 carrier->readFromScenario(scEntry);
305 } else if (type == "groundvehicle") {
306 FGAIGroundVehicle* groundvehicle = new FGAIGroundVehicle;
307 groundvehicle->readFromScenario(scEntry);
308 attach(groundvehicle);
310 } else if (type == "escort") {
311 FGAIEscort* escort = new FGAIEscort;
312 escort->readFromScenario(scEntry);
315 } else if (type == "thunderstorm") {
316 FGAIStorm* storm = new FGAIStorm;
317 storm->readFromScenario(scEntry);
320 } else if (type == "thermal") {
321 FGAIThermal* thermal = new FGAIThermal;
322 thermal->readFromScenario(scEntry);
325 } else if (type == "ballistic") {
326 FGAIBallistic* ballistic = new FGAIBallistic;
327 ballistic->readFromScenario(scEntry);
330 } else if (type == "static") {
331 FGAIStatic* aistatic = new FGAIStatic;
332 aistatic->readFromScenario(scEntry);
341 FGAIManager::loadScenarioFile(const std::string& filename)
343 SGPath path(globals->get_fg_root());
344 path.append("AI/" + filename + ".xml");
346 SGPropertyNode_ptr root = new SGPropertyNode;
347 readProperties(path.str(), root);
349 } catch (const sg_exception &t) {
350 SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
351 << path.str() << "': " << t.getFormattedMessage());
357 FGAIManager::getStartPosition(const string& id, const string& pid,
358 SGGeod& geodPos, double& hdng, SGVec3d& uvw)
361 SGPropertyNode* root = fgGetNode("sim/ai", true);
362 if (!root->getNode("enabled", true)->getBoolValue())
365 for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
366 SGPropertyNode *aiEntry = root->getChild( i );
367 if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
368 string filename = aiEntry->getStringValue();
369 SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
371 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
373 for (int i = 0; i < scenarios->nChildren(); i++) {
374 SGPropertyNode* scEntry = scenarios->getChild(i);
375 std::string type = scEntry->getStringValue("type");
376 std::string pnumber = scEntry->getStringValue("pennant-number");
377 std::string name = scEntry->getStringValue("name");
378 if (type == "carrier" && (pnumber == id || name == id)) {
379 SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
380 carrier->readFromScenario(scEntry);
382 if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
396 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
398 // we specify tgt extent (ft) according to the AIObject type
399 double tgt_ht[] = {0, 50, 100, 250, 0, 100, 0, 0, 50, 50, 20, 100, 50};
400 double tgt_length[] = {0, 100, 200, 750, 0, 50, 0, 0, 200, 100, 40, 200, 100};
401 ai_list_iterator ai_list_itr = ai_list.begin();
402 ai_list_iterator end = ai_list.end();
404 SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
405 SGVec3d cartPos(SGVec3d::fromGeod(pos));
407 while (ai_list_itr != end) {
408 double tgt_alt = (*ai_list_itr)->_getAltitude();
409 int type = (*ai_list_itr)->getType();
410 tgt_ht[type] += fuse_range;
412 if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
413 || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
414 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
415 // << fabs(tgt_alt - alt)
423 int id = (*ai_list_itr)->getID();
425 double range = calcRange(cartPos, (*ai_list_itr));
427 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: AI list size "
429 // << " type " << type
431 // << " range " << range
432 // //<< " bearing " << bearing
433 // << " alt " << tgt_alt
436 tgt_length[type] += fuse_range;
438 if (range < tgt_length[type]){
439 SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
442 << " range " << range
443 << " alt " << tgt_alt
445 return (*ai_list_itr).get();
453 FGAIManager::calcRange(const SGVec3d& aCartPos, FGAIBase* aObject) const
455 double distM = dist(aCartPos, aObject->getCartPos());
456 return distM * SG_METER_TO_FEET;