]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIManager.cxx
Interim windows build fix
[flightgear.git] / src / AIModel / AIManager.cxx
1 // AIManager.cxx  Based on David Luff's AIMgr:
2 // - a global management type for AI objects
3 //
4 // Written by David Culp, started October 2003.
5 // - davidculp2@comcast.net 
6 //
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.
11 //
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.
16 //
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.
20
21 #include <cstring>
22 #include <algorithm>
23
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>
29 #include <simgear/structure/SGBinding.hxx>
30
31 #include <boost/mem_fn.hpp>
32 #include <boost/foreach.hpp>
33
34 #include <Main/globals.hxx>
35 #include <Main/fg_props.hxx>
36 #include <Airports/airport.hxx>
37 #include <Scripting/NasalSys.hxx>
38
39 #include "AIManager.hxx"
40 #include "AIAircraft.hxx"
41 #include "AIShip.hxx"
42 #include "AIBallistic.hxx"
43 #include "AIStorm.hxx"
44 #include "AIThermal.hxx"
45 #include "AICarrier.hxx"
46 #include "AIStatic.hxx"
47 #include "AIMultiplayer.hxx"
48 #include "AITanker.hxx"
49 #include "AIWingman.hxx"
50 #include "AIGroundVehicle.hxx"
51 #include "AIEscort.hxx"
52
53 class FGAIManager::Scenario
54 {
55 public:
56     Scenario(FGAIManager* man, const std::string& nm, SGPropertyNode* scenarios) :
57         _internalName(nm)
58     {
59         BOOST_FOREACH(SGPropertyNode* scEntry, scenarios->getChildren("entry")) {
60             FGAIBasePtr ai = man->addObject(scEntry);
61             if (ai) {
62                 _objects.push_back(ai);
63             }
64         } // of scenario entry iteration
65         
66         SGPropertyNode* nasalScripts = scenarios->getChild("nasal");
67         if (!nasalScripts) {
68             return;
69         }
70         
71         _unloadScript = nasalScripts->getStringValue("unload");
72         std::string loadScript = nasalScripts->getStringValue("load");
73         if (!loadScript.empty()) {
74             FGNasalSys* nasalSys = (FGNasalSys*) globals->get_subsystem("nasal");
75             std::string moduleName = "scenario_" + _internalName;
76             nasalSys->createModule(moduleName.c_str(), moduleName.c_str(),
77                                    loadScript.c_str(), loadScript.size(),
78                                    0);
79         }
80     }
81     
82     ~Scenario()
83     {
84         BOOST_FOREACH(FGAIBasePtr ai, _objects) {
85             ai->setDie(true);
86         }
87         
88         FGNasalSys* nasalSys = (FGNasalSys*) globals->get_subsystem("nasal");
89         if (!nasalSys)
90             return;
91         
92         std::string moduleName = "scenario_" + _internalName;
93         if (!_unloadScript.empty()) {
94             nasalSys->createModule(moduleName.c_str(), moduleName.c_str(),
95                                    _unloadScript.c_str(), _unloadScript.size(),
96                                    0);
97         }
98         
99         nasalSys->deleteModule(moduleName.c_str());
100     }
101 private:
102     std::vector<FGAIBasePtr> _objects;
103     std::string _internalName;
104     std::string _unloadScript;
105 };
106
107 ///////////////////////////////////////////////////////////////////////////////
108
109 FGAIManager::FGAIManager() :
110     cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
111                fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
112     cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
113                    fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
114 {
115
116 }
117
118 FGAIManager::~FGAIManager()
119 {
120     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
121 }
122
123 void
124 FGAIManager::init() {
125     root = fgGetNode("sim/ai", true);
126
127     enabled = root->getNode("enabled", true);
128
129     thermal_lift_node = fgGetNode("/environment/thermal-lift-fps", true);
130     wind_from_east_node  = fgGetNode("/environment/wind-from-east-fps",true);
131     wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
132
133     user_altitude_agl_node  = fgGetNode("/position/altitude-agl-ft", true);
134     user_speed_node     = fgGetNode("/velocities/uBody-fps", true);
135     
136     globals->get_commands()->addCommand("load-scenario", this, &FGAIManager::loadScenarioCommand);
137     globals->get_commands()->addCommand("unload-scenario", this, &FGAIManager::unloadScenarioCommand);
138     _environmentVisiblity = fgGetNode("/environment/visibility-m");
139 }
140
141 void
142 FGAIManager::postinit()
143 {
144     // postinit, so that it can access the Nasal subsystem
145
146     // scenarios enabled, AI subsystem required
147     if (!enabled->getBoolValue())
148         enabled->setBoolValue(true);
149
150     // process all scenarios
151     BOOST_FOREACH(SGPropertyNode* n, root->getChildren("scenario")) {
152         const string& name = n->getStringValue();
153         if (name.empty())
154             continue;
155
156         if (_scenarios.find(name) != _scenarios.end()) {
157             SG_LOG(SG_AI, SG_WARN, "won't load scenario '" << name << "' twice");
158             continue;
159         }
160
161         SG_LOG(SG_AI, SG_INFO, "loading scenario '" << name << '\'');
162         loadScenario(name);
163     }
164 }
165
166 void
167 FGAIManager::reinit()
168 {
169     // shutdown scenarios
170     unloadAllScenarios();
171     
172     update(0.0);
173     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
174     
175     // (re-)load scenarios
176     postinit();
177 }
178
179 void
180 FGAIManager::shutdown()
181 {
182     unloadAllScenarios();
183     
184     BOOST_FOREACH(FGAIBase* ai, ai_list) {
185         ai->unbind();
186     }
187     
188     ai_list.clear();
189     _environmentVisiblity.clear();
190     
191     globals->get_commands()->removeCommand("load-scenario");
192     globals->get_commands()->removeCommand("unload-scenario");
193 }
194
195 void
196 FGAIManager::bind() {
197     root = globals->get_props()->getNode("ai/models", true);
198     root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
199         &FGAIManager::getNumAiObjects));
200 }
201
202 void
203 FGAIManager::unbind() {
204     root->untie("count");
205 }
206
207 void FGAIManager::removeDeadItem(FGAIBase* base)
208 {
209     SGPropertyNode *props = base->_getProps();
210     
211     props->setBoolValue("valid", false);
212     base->unbind();
213     
214     // for backward compatibility reset properties, so that aircraft,
215     // which don't know the <valid> property, keep working
216     // TODO: remove after a while
217     props->setIntValue("id", -1);
218     props->setBoolValue("radar/in-range", false);
219     props->setIntValue("refuel/tanker", false);
220 }
221
222 void
223 FGAIManager::update(double dt) {
224     // initialize these for finding nearest thermals
225     range_nearest = 10000.0;
226     strength = 0.0;
227
228     if (!enabled->getBoolValue())
229         return;
230
231     fetchUserState();
232
233     // partition the list into dead followed by alive
234     ai_list_iterator firstAlive =
235       std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
236     
237     // clean up each item and finally remove from the container
238     for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
239         removeDeadItem(*it);
240     }
241   
242     ai_list.erase(ai_list.begin(), firstAlive);
243   
244     // every remaining item is alive. update them in turn, but guard for
245     // exceptions, so a single misbehaving AI object doesn't bring down the
246     // entire subsystem.
247     BOOST_FOREACH(FGAIBase* base, ai_list) {
248         try {
249             if (base->isa(FGAIBase::otThermal)) {
250                 processThermal(dt, (FGAIThermal*)base);
251             } else {
252                 base->update(dt);
253             }
254         } catch (sg_exception& e) {
255             SG_LOG(SG_AI, SG_WARN, "caught exception updating AI model:" << base->_getName()<< ", which will be killed."
256                    "\n\tError:" << e.getFormattedMessage());
257             base->setDie(true);
258         }
259     } // of live AI objects iteration
260
261     thermal_lift_node->setDoubleValue( strength );  // for thermals
262 }
263
264 /** update LOD settings of all AI/MP models */
265 void
266 FGAIManager::updateLOD(SGPropertyNode* node)
267 {
268     SG_UNUSED(node);
269     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
270 }
271
272 void
273 FGAIManager::attach(FGAIBase *model)
274 {
275     const char* typeString = model->getTypeString();
276     SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
277     SGPropertyNode* p;
278     int i;
279
280     // find free index in the property tree, if we have
281     // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
282     for (i = 0; i < 10000; i++) {
283         p = root->getNode(typeString, i, false);
284
285         if (!p || !p->getBoolValue("valid", false))
286             break;
287
288         if (p->getIntValue("id",-1)==model->getID()) {
289             p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
290         }
291     }
292
293     p = root->getNode(typeString, i, true);
294     model->setManager(this, p);
295     ai_list.push_back(model);
296
297     model->init(model->getType()==FGAIBase::otAircraft
298         || model->getType()==FGAIBase::otMultiplayer
299         || model->getType()==FGAIBase::otStatic);
300     model->bind();
301     p->setBoolValue("valid", true);
302 }
303
304 bool FGAIManager::isVisible(const SGGeod& pos) const
305 {
306   double visibility_meters = _environmentVisiblity->getDoubleValue();
307   return ( dist(globals->get_view_position_cart(), SGVec3d::fromGeod(pos)) ) <= visibility_meters;
308 }
309
310 int
311 FGAIManager::getNumAiObjects() const
312 {
313     return ai_list.size();
314 }
315
316 void
317 FGAIManager::fetchUserState( void ) {
318
319     globals->get_aircraft_orientation(user_heading, user_pitch, user_roll);
320     user_speed     = user_speed_node->getDoubleValue() * 0.592484;
321     wind_from_east = wind_from_east_node->getDoubleValue();
322     wind_from_north   = wind_from_north_node->getDoubleValue();
323     user_altitude_agl = user_altitude_agl_node->getDoubleValue();
324
325 }
326
327 // only keep the results from the nearest thermal
328 void
329 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
330     thermal->update(dt);
331
332     if ( thermal->_getRange() < range_nearest ) {
333         range_nearest = thermal->_getRange();
334         strength = thermal->getStrength();
335     }
336
337 }
338
339 bool FGAIManager::loadScenarioCommand(const SGPropertyNode* args)
340 {
341     std::string name = args->getStringValue("name");
342     if (args->hasChild("load-property")) {
343         // slightly ugly, to simplify life in the dialogs, make load allow
344         // loading or unloading based on a bool property.
345         bool loadIt = fgGetBool(args->getStringValue("load-property"));
346         if (!loadIt) {
347             // user actually wants to unload, fine.
348             return unloadScenario(name);
349         }
350     }
351     
352     if (_scenarios.find(name) != _scenarios.end()) {
353         SG_LOG(SG_AI, SG_WARN, "scenario '" << name << "' already loaded");
354         return false;
355     }
356     
357     bool ok = loadScenario(name);
358     if (ok) {
359         // create /sim/ai node for consistency
360         int index = 0;
361         for (; root->hasChild("scenario", index); ++index) {}
362         
363         SGPropertyNode* scenarioNode = root->getChild("scenario", index, true);
364         scenarioNode->setStringValue(name);
365     }
366     
367     return ok;
368 }
369
370 bool FGAIManager::unloadScenarioCommand(const SGPropertyNode* args)
371 {
372     std::string name = args->getStringValue("name");
373     return unloadScenario(name);
374 }
375
376 bool FGAIManager::addObjectCommand(const SGPropertyNode* definition)
377 {
378     addObject(definition);
379     return true;
380 }
381
382 FGAIBasePtr FGAIManager::addObject(const SGPropertyNode* definition)
383 {
384     const std::string& type = definition->getStringValue("type", "aircraft");
385     
386     FGAIBase* ai = NULL;
387     if (type == "tanker") { // refueling scenarios
388         ai = new FGAITanker; 
389     } else if (type == "wingman") {
390         ai = new FGAIWingman;
391     } else if (type == "aircraft") {
392         ai = new FGAIAircraft;
393     } else if (type == "ship") {
394         ai = new FGAIShip;
395     } else if (type == "carrier") {
396         ai = new FGAICarrier;
397     } else if (type == "groundvehicle") {
398         ai = new FGAIGroundVehicle;
399     } else if (type == "escort") {
400         ai = new FGAIEscort;
401     } else if (type == "thunderstorm") {
402         ai = new FGAIStorm;
403     } else if (type == "thermal") {
404         ai = new FGAIThermal;
405     } else if (type == "ballistic") {
406         ai = new FGAIBallistic;
407     } else if (type == "static") {
408         ai = new FGAIStatic;
409     }
410
411     ai->readFromScenario(const_cast<SGPropertyNode*>(definition));
412         if((ai->isValid())){
413                 attach(ai);
414         SG_LOG(SG_AI, SG_DEBUG, "attached scenario " << ai->_getName());
415         }
416         else{
417                 ai->setDie(true);
418                 SG_LOG(SG_AI, SG_ALERT, "killed invalid scenario "  << ai->_getName());
419         }
420     return ai;
421 }
422
423 bool FGAIManager::removeObject(const SGPropertyNode* args)
424 {
425     int id = args->getIntValue("id");
426     BOOST_FOREACH(FGAIBase* ai, get_ai_list()) {
427         if (ai->getID() == id) {
428             ai->setDie(true);
429             break;
430         }
431     }
432     
433     return false;
434 }
435
436 FGAIBasePtr FGAIManager::getObjectFromProperty(const SGPropertyNode* aProp) const
437 {
438     BOOST_FOREACH(FGAIBase* ai, get_ai_list()) {
439         if (ai->_getProps() == aProp) {
440             return ai;
441         }
442     } // of AI objects iteration
443     
444     return NULL;
445 }
446
447 bool
448 FGAIManager::loadScenario( const string &filename )
449 {
450     SGPropertyNode_ptr file = loadScenarioFile(filename);
451     if (!file) {
452         return false;
453     }
454     
455     SGPropertyNode_ptr scNode = file->getChild("scenario");
456     if (!scNode) {
457         return false;
458     }
459     
460     _scenarios[filename] = new Scenario(this, filename, scNode);
461     return true;
462 }
463
464
465 bool
466 FGAIManager::unloadScenario( const string &filename)
467 {
468     ScenarioDict::iterator it = _scenarios.find(filename);
469     if (it == _scenarios.end()) {
470         SG_LOG(SG_AI, SG_WARN, "unload scenario: not found:" << filename);
471         return false;
472     }
473     
474 // remove /sim/ai node
475     unsigned int index = 0;
476     for (SGPropertyNode* n = NULL; (n = root->getChild("scenario", index)) != NULL; ++index) {
477         if (n->getStringValue() == filename) {
478             root->removeChild("scenario", index);
479             break;
480         }
481     }
482     
483     delete it->second;
484     _scenarios.erase(it);
485     return true;
486 }
487
488 void
489 FGAIManager::unloadAllScenarios()
490 {
491     ScenarioDict::iterator it = _scenarios.begin();
492     for (; it != _scenarios.end(); ++it) {
493         delete it->second;
494     } // of scenarios iteration
495     
496     
497     // remove /sim/ai node
498     root->removeChildren("scenario");
499     _scenarios.clear();
500 }
501
502
503 SGPropertyNode_ptr
504 FGAIManager::loadScenarioFile(const std::string& filename)
505 {
506     SGPath path(globals->get_fg_root());
507     path.append("AI/" + filename + ".xml");
508     try {
509         SGPropertyNode_ptr root = new SGPropertyNode;
510         readProperties(path.str(), root);
511         return root;
512     } catch (const sg_exception &t) {
513         SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
514             << path.str() << "': " << t.getFormattedMessage());
515     }
516     return 0;
517 }
518
519 bool
520 FGAIManager::getStartPosition(const string& id, const string& pid,
521                               SGGeod& geodPos, double& hdng, SGVec3d& uvw)
522 {
523     bool found = false;
524     SGPropertyNode* root = fgGetNode("sim/ai", true);
525     if (!root->getNode("enabled", true)->getBoolValue())
526         return found;
527
528     for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
529         SGPropertyNode *aiEntry = root->getChild( i );
530         if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
531             const string& filename = aiEntry->getStringValue();
532             SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
533             if (scenarioTop) {
534                 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
535                 if (scenarios) {
536                     for (int i = 0; i < scenarios->nChildren(); i++) {
537                         SGPropertyNode* scEntry = scenarios->getChild(i);
538                         const std::string& type = scEntry->getStringValue("type");
539                         const std::string& pnumber = scEntry->getStringValue("pennant-number");
540                         const std::string& name = scEntry->getStringValue("name");
541                         if (type == "carrier" && (pnumber == id || name == id)) {
542                             SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
543                             carrier->readFromScenario(scEntry);
544
545                             if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
546                                 found = true;
547                                 break;
548                             }
549                         }
550                     }
551                 }
552             }
553         }
554     }
555     return found;
556 }
557
558 const FGAIBase *
559 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
560 {
561     // we specify tgt extent (ft) according to the AIObject type
562     double tgt_ht[]     = {0,  50, 100, 250, 0, 100, 0, 0,  50,  50, 20, 100,  50};
563     double tgt_length[] = {0, 100, 200, 750, 0,  50, 0, 0, 200, 100, 40, 200, 100};
564     ai_list_iterator ai_list_itr = ai_list.begin();
565     ai_list_iterator end = ai_list.end();
566
567     SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
568     SGVec3d cartPos(SGVec3d::fromGeod(pos));
569     
570     while (ai_list_itr != end) {
571         double tgt_alt = (*ai_list_itr)->_getAltitude();
572         int type       = (*ai_list_itr)->getType();
573         tgt_ht[type] += fuse_range;
574
575         if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
576             || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
577                 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
578                 //    << fabs(tgt_alt - alt)
579                 //    << " "
580                 //    << type
581                 //    );
582                 ++ai_list_itr;
583                 continue;
584         }
585
586         int id         = (*ai_list_itr)->getID();
587
588         double range = calcRangeFt(cartPos, (*ai_list_itr));
589
590         //SG_LOG(SG_AI, SG_DEBUG, "AIManager:  AI list size "
591         //    << ai_list.size()
592         //    << " type " << type
593         //    << " ID " << id
594         //    << " range " << range
595         //    //<< " bearing " << bearing
596         //    << " alt " << tgt_alt
597         //    );
598
599         tgt_length[type] += fuse_range;
600
601         if (range < tgt_length[type]){
602             SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
603                 << " type " << type
604                 << " ID " << id
605                 << " range " << range
606                 << " alt " << tgt_alt
607                 );
608             return (*ai_list_itr).get();
609         }
610         ++ai_list_itr;
611     }
612     return 0;
613 }
614
615 double
616 FGAIManager::calcRangeFt(const SGVec3d& aCartPos, FGAIBase* aObject) const
617 {
618     double distM = dist(aCartPos, aObject->getCartPos());
619     return distM * SG_METER_TO_FEET;
620 }
621
622 //end AIManager.cxx