]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIManager.cxx
Make units of a function explicit.
[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
30 #include <boost/mem_fn.hpp>
31 #include <boost/foreach.hpp>
32
33 #include <Main/globals.hxx>
34 #include <Airports/airport.hxx>
35
36 #include "AIManager.hxx"
37 #include "AIAircraft.hxx"
38 #include "AIShip.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"
49
50 class FGAIManager::Scenario
51 {
52 public:
53     Scenario(FGAIManager* man, SGPropertyNode* scenarios) :
54         _manager(man)
55     {
56         BOOST_FOREACH(SGPropertyNode* scEntry, scenarios->getChildren("entry")) {
57             FGAIBasePtr ai = man->addObject(scEntry);
58             if (ai) {
59                 _objects.push_back(ai);
60             }
61         } // of scenario entry iteration
62     }
63     
64     ~Scenario()
65     {
66         BOOST_FOREACH(FGAIBasePtr ai, _objects) {
67             ai->setDie(true);
68         }
69     }
70 private:
71     FGAIManager* _manager;
72     std::vector<FGAIBasePtr> _objects;
73 };
74
75 ///////////////////////////////////////////////////////////////////////////////
76
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)))
82 {
83
84 }
85
86 FGAIManager::~FGAIManager()
87 {
88     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
89 }
90
91 void
92 FGAIManager::init() {
93     root = fgGetNode("sim/ai", true);
94
95     enabled = root->getNode("enabled", true);
96
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);
100
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);
104     
105     globals->get_commands()->addCommand("load-scenario", this, &FGAIManager::loadScenarioCommand);
106     globals->get_commands()->addCommand("unload-scenario", this, &FGAIManager::unloadScenarioCommand);
107 }
108
109 void
110 FGAIManager::postinit() {
111     // postinit, so that it can access the Nasal subsystem
112
113     if (!root->getBoolValue("scenarios-enabled", true))
114         return;
115
116     // scenarios enabled, AI subsystem required
117     if (!enabled->getBoolValue())
118         enabled->setBoolValue(true);
119
120     // process all scenarios
121     BOOST_FOREACH(SGPropertyNode* n, root->getChildren("scenario")) {
122         const string& name = n->getStringValue();
123         if (name.empty())
124             continue;
125
126         if (_scenarios.find(name) != _scenarios.end()) {
127             SG_LOG(SG_AI, SG_WARN, "won't load scenario '" << name << "' twice");
128             continue;
129         }
130
131         SG_LOG(SG_AI, SG_INFO, "loading scenario '" << name << '\'');
132         loadScenario(name);
133     }
134 }
135
136 void
137 FGAIManager::reinit()
138 {
139     update(0.0);
140     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
141 }
142
143 void
144 FGAIManager::bind() {
145     root = globals->get_props()->getNode("ai/models", true);
146     root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
147         &FGAIManager::getNumAiObjects));
148 }
149
150 void
151 FGAIManager::unbind() {
152     root->untie("count");
153 }
154
155 void FGAIManager::removeDeadItem(FGAIBase* base)
156 {
157     SGPropertyNode *props = base->_getProps();
158     
159     props->setBoolValue("valid", false);
160     base->unbind();
161     
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);
168 }
169
170 void
171 FGAIManager::update(double dt) {
172     // initialize these for finding nearest thermals
173     range_nearest = 10000.0;
174     strength = 0.0;
175
176     if (!enabled->getBoolValue())
177         return;
178
179     fetchUserState();
180
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));
184     
185     // clean up each item and finally remove from the container
186     for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
187         removeDeadItem(*it);
188     }
189   
190     ai_list.erase(ai_list.begin(), firstAlive);
191   
192     // every remaining item is alive
193     BOOST_FOREACH(FGAIBase* base, ai_list) {
194         if (base->isa(FGAIBase::otThermal)) {
195             processThermal(dt, (FGAIThermal*)base);
196         } else {
197             base->update(dt);
198         }
199     } // of live AI objects iteration
200
201     thermal_lift_node->setDoubleValue( strength );  // for thermals
202 }
203
204 /** update LOD settings of all AI/MP models */
205 void
206 FGAIManager::updateLOD(SGPropertyNode* node)
207 {
208     SG_UNUSED(node);
209     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
210 }
211
212 void
213 FGAIManager::attach(FGAIBase *model)
214 {
215     const char* typeString = model->getTypeString();
216     SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
217     SGPropertyNode* p;
218     int i;
219
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);
224
225         if (!p || !p->getBoolValue("valid", false))
226             break;
227
228         if (p->getIntValue("id",-1)==model->getID()) {
229             p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
230         }
231     }
232
233     p = root->getNode(typeString, i, true);
234     model->setManager(this, p);
235     ai_list.push_back(model);
236
237     model->init(model->getType()==FGAIBase::otAircraft
238         || model->getType()==FGAIBase::otMultiplayer
239         || model->getType()==FGAIBase::otStatic);
240     model->bind();
241     p->setBoolValue("valid", true);
242 }
243
244 int
245 FGAIManager::getNumAiObjects(void) const
246 {
247     return ai_list.size();
248 }
249
250 void
251 FGAIManager::fetchUserState( void ) {
252
253     user_yaw       = user_yaw_node->getDoubleValue();
254     globals->get_aircraft_orientation(user_heading, user_pitch, user_roll);
255
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();
260
261 }
262
263 // only keep the results from the nearest thermal
264 void
265 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
266     thermal->update(dt);
267
268     if ( thermal->_getRange() < range_nearest ) {
269         range_nearest = thermal->_getRange();
270         strength = thermal->getStrength();
271     }
272
273 }
274
275 bool FGAIManager::loadScenarioCommand(const SGPropertyNode* args)
276 {
277     std::string name = args->getStringValue("name");
278     return loadScenario(name);
279 }
280
281 bool FGAIManager::unloadScenarioCommand(const SGPropertyNode* args)
282 {
283     std::string name = args->getStringValue("name");
284     unloadScenario(name);
285     return true;
286 }
287
288 bool FGAIManager::addObjectCommand(const SGPropertyNode* definition)
289 {
290     addObject(definition);
291     return true;
292 }
293
294 FGAIBasePtr FGAIManager::addObject(const SGPropertyNode* definition)
295 {
296     const std::string& type = definition->getStringValue("type", "aircraft");
297     
298     FGAIBase* ai = NULL;
299     if (type == "tanker") { // refueling scenarios
300         ai = new FGAITanker; 
301     } else if (type == "wingman") {
302         ai = new FGAIWingman;
303     } else if (type == "aircraft") {
304         ai = new FGAIAircraft;
305     } else if (type == "ship") {
306         ai = new FGAIShip;
307     } else if (type == "carrier") {
308         ai = new FGAICarrier;
309     } else if (type == "groundvehicle") {
310         ai = new FGAIGroundVehicle;
311     } else if (type == "escort") {
312         ai = new FGAIEscort;
313     } else if (type == "thunderstorm") {
314         ai = new FGAIStorm;
315     } else if (type == "thermal") {
316         ai = new FGAIThermal;
317     } else if (type == "ballistic") {
318         ai = new FGAIBallistic;
319     } else if (type == "static") {
320         ai = new FGAIStatic;
321     }
322
323     ai->readFromScenario(const_cast<SGPropertyNode*>(definition));
324     attach(ai);
325     return ai;
326 }
327
328 bool FGAIManager::removeObject(const SGPropertyNode* args)
329 {
330     int id = args->getIntValue("id");
331     BOOST_FOREACH(FGAIBase* ai, get_ai_list()) {
332         if (ai->getID() == id) {
333             ai->setDie(true);
334             break;
335         }
336     }
337     
338     return false;
339 }
340
341 bool
342 FGAIManager::loadScenario( const string &filename )
343 {
344     SGPropertyNode_ptr file = loadScenarioFile(filename);
345     if (!file) {
346         return false;
347     }
348     
349     SGPropertyNode_ptr scNode = file->getChild("scenario");
350     if (!scNode) {
351         return false;
352     }
353     
354     _scenarios[filename] = new Scenario(this, scNode);
355     return true;
356 }
357
358
359 void
360 FGAIManager::unloadScenario( const string &filename)
361 {
362     ScenarioDict::iterator it = _scenarios.find(filename);
363     if (it == _scenarios.end()) {
364         SG_LOG(SG_AI, SG_WARN, "unload scenario: not found:" << filename);
365         return;
366     }
367     
368     delete it->second;
369     _scenarios.erase(it);
370 }
371
372 SGPropertyNode_ptr
373 FGAIManager::loadScenarioFile(const std::string& filename)
374 {
375     SGPath path(globals->get_fg_root());
376     path.append("AI/" + filename + ".xml");
377     try {
378         SGPropertyNode_ptr root = new SGPropertyNode;
379         readProperties(path.str(), root);
380         return root;
381     } catch (const sg_exception &t) {
382         SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
383             << path.str() << "': " << t.getFormattedMessage());
384     }
385     return 0;
386 }
387
388 bool
389 FGAIManager::getStartPosition(const string& id, const string& pid,
390                               SGGeod& geodPos, double& hdng, SGVec3d& uvw)
391 {
392     bool found = false;
393     SGPropertyNode* root = fgGetNode("sim/ai", true);
394     if (!root->getNode("enabled", true)->getBoolValue())
395         return found;
396
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);
402             if (scenarioTop) {
403                 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
404                 if (scenarios) {
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);
413
414                             if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
415                                 found = true;
416                                 break;
417                             }
418                         }
419                     }
420                 }
421             }
422         }
423     }
424     return found;
425 }
426
427 const FGAIBase *
428 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
429 {
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();
435
436     SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
437     SGVec3d cartPos(SGVec3d::fromGeod(pos));
438     
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;
443
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)
448                 //    << " "
449                 //    << type
450                 //    );
451                 ++ai_list_itr;
452                 continue;
453         }
454
455         int id         = (*ai_list_itr)->getID();
456
457         double range = calcRangeFt(cartPos, (*ai_list_itr));
458
459         //SG_LOG(SG_AI, SG_DEBUG, "AIManager:  AI list size "
460         //    << ai_list.size()
461         //    << " type " << type
462         //    << " ID " << id
463         //    << " range " << range
464         //    //<< " bearing " << bearing
465         //    << " alt " << tgt_alt
466         //    );
467
468         tgt_length[type] += fuse_range;
469
470         if (range < tgt_length[type]){
471             SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
472                 << " type " << type
473                 << " ID " << id
474                 << " range " << range
475                 << " alt " << tgt_alt
476                 );
477             return (*ai_list_itr).get();
478         }
479         ++ai_list_itr;
480     }
481     return 0;
482 }
483
484 double
485 FGAIManager::calcRangeFt(const SGVec3d& aCartPos, FGAIBase* aObject) const
486 {
487     double distM = dist(aCartPos, aObject->getCartPos());
488     return distM * SG_METER_TO_FEET;
489 }
490
491 //end AIManager.cxx