]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIManager.cxx
AIManager cleanups, no functionality change.
[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
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>
29
30 #include <Main/globals.hxx>
31
32 #include <Airports/simple.hxx>
33 #include <Traffic/TrafficMgr.hxx>
34
35 #include "AIManager.hxx"
36 #include "AIAircraft.hxx"
37 #include "AIShip.hxx"
38 #include "AIBallistic.hxx"
39 #include "AIStorm.hxx"
40 #include "AIThermal.hxx"
41 #include "AICarrier.hxx"
42 #include "AIStatic.hxx"
43 #include "AIMultiplayer.hxx"
44 #include "AITanker.hxx"
45 #include "AIWingman.hxx"
46 #include "AIGroundVehicle.hxx"
47 #include "AIEscort.hxx"
48
49 FGAIManager::FGAIManager() :
50     cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
51                fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
52     cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
53                    fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
54 {
55
56 }
57
58 FGAIManager::~FGAIManager()
59 {
60     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
61 }
62
63 void
64 FGAIManager::init() {
65     root = fgGetNode("sim/ai", true);
66
67     enabled = root->getNode("enabled", true);
68
69     thermal_lift_node = fgGetNode("/environment/thermal-lift-fps", true);
70     wind_from_east_node  = fgGetNode("/environment/wind-from-east-fps",true);
71     wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
72
73     user_latitude_node  = fgGetNode("/position/latitude-deg", true);
74     user_longitude_node = fgGetNode("/position/longitude-deg", true);
75     user_altitude_node  = fgGetNode("/position/altitude-ft", true);
76     user_altitude_agl_node  = fgGetNode("/position/altitude-agl-ft", true);
77     user_heading_node   = fgGetNode("/orientation/heading-deg", true);
78     user_pitch_node     = fgGetNode("/orientation/pitch-deg", true);
79     user_yaw_node       = fgGetNode("/orientation/side-slip-deg", true);
80     user_roll_node      = fgGetNode("/orientation/roll-deg", true);
81     user_speed_node     = fgGetNode("/velocities/uBody-fps", true);
82 }
83
84 void
85 FGAIManager::postinit() {
86     // postinit, so that it can access the Nasal subsystem
87
88     if (!root->getBoolValue("scenarios-enabled", true))
89         return;
90
91     // scenarios enabled, AI subsystem required
92     if (!enabled->getBoolValue())
93         enabled->setBoolValue(true);
94
95     // process all scenarios
96     map<string, bool> scenarios;
97     for (int i = 0 ; i < root->nChildren() ; i++) {
98         SGPropertyNode *n = root->getChild(i);
99         if (strcmp(n->getName(), "scenario"))
100             continue;
101
102         string name = n->getStringValue();
103         if (name.empty())
104             continue;
105
106         if (scenarios.find(name) != scenarios.end()) {
107             SG_LOG(SG_AI, SG_DEBUG, "won't load scenario '" << name << "' twice");
108             continue;
109         }
110
111         SG_LOG(SG_AI, SG_ALERT, "loading scenario '" << name << '\'');
112         processScenario(name);
113         scenarios[name] = true;
114     }
115 }
116
117 void
118 FGAIManager::reinit()
119 {
120     update(0.0);
121     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
122 }
123
124 void
125 FGAIManager::bind() {
126     root = globals->get_props()->getNode("ai/models", true);
127     root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
128         &FGAIManager::getNumAiObjects));
129 }
130
131 void
132 FGAIManager::unbind() {
133     root->untie("count");
134 }
135
136 void FGAIManager::removeDeadItem(FGAIBase* base)
137 {
138     FGTrafficManager *tmgr = (FGTrafficManager*) globals->get_subsystem("traffic-manager");
139     if (tmgr) {
140         tmgr->release(base->getID());
141     }
142     
143     SGPropertyNode *props = base->_getProps();
144     
145     props->setBoolValue("valid", false);
146     base->unbind();
147     
148     // for backward compatibility reset properties, so that aircraft,
149     // which don't know the <valid> property, keep working
150     // TODO: remove after a while
151     props->setIntValue("id", -1);
152     props->setBoolValue("radar/in-range", false);
153     props->setIntValue("refuel/tanker", false);
154 }
155
156 void
157 FGAIManager::update(double dt) {
158     // initialize these for finding nearest thermals
159     range_nearest = 10000.0;
160     strength = 0.0;
161
162     if (!enabled->getBoolValue())
163         return;
164
165     fetchUserState();
166
167     // partition the list into dead followed by alive
168     ai_list_iterator firstAlive =
169       std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
170     
171     // clean up each item and finally remove from the container
172     for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
173         removeDeadItem(*it);
174     }
175   
176     ai_list.erase(ai_list.begin(), firstAlive);
177   
178     // every remaining item is alive
179     BOOST_FOREACH(FGAIBase* base, ai_list) {
180         if (base->isa(FGAIBase::otThermal)) {
181             processThermal(dt, (FGAIThermal*)base);
182         } else {
183             base->update(dt);
184         }
185     } // of live AI objects iteration
186
187     thermal_lift_node->setDoubleValue( strength );  // for thermals
188 }
189
190 /** update LOD settings of all AI/MP models */
191 void
192 FGAIManager::updateLOD(SGPropertyNode* node)
193 {
194     SG_UNUSED(node);
195     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
196 }
197
198 void
199 FGAIManager::attach(FGAIBase *model)
200 {
201     const char* typeString = model->getTypeString();
202     SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
203     SGPropertyNode* p;
204     int i;
205
206     // find free index in the property tree, if we have
207     // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
208     for (i = 0; i < 10000; i++) {
209         p = root->getNode(typeString, i, false);
210
211         if (!p || !p->getBoolValue("valid", false))
212             break;
213
214         if (p->getIntValue("id",-1)==model->getID()) {
215             p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
216         }
217     }
218
219     p = root->getNode(typeString, i, true);
220     model->setManager(this, p);
221     ai_list.push_back(model);
222
223     model->init(model->getType()==FGAIBase::otAircraft
224         || model->getType()==FGAIBase::otMultiplayer
225         || model->getType()==FGAIBase::otStatic);
226     model->bind();
227     p->setBoolValue("valid", true);
228 }
229
230 void
231 FGAIManager::destroyObject( int ID ) {
232     ai_list_iterator ai_list_itr = ai_list.begin();
233
234     while(ai_list_itr != ai_list.end()) {
235
236         if ((*ai_list_itr)->getID() == ID) {
237             (*ai_list_itr)->unbind();
238             ai_list_itr = ai_list.erase(ai_list_itr);
239         } else
240             ++ai_list_itr;
241     }
242
243 }
244
245 int
246 FGAIManager::getNumAiObjects(void) const
247 {
248     return ai_list.size();
249 }
250
251 void
252 FGAIManager::fetchUserState( void ) {
253
254     user_latitude  = user_latitude_node->getDoubleValue();
255     user_longitude = user_longitude_node->getDoubleValue();
256     user_altitude  = user_altitude_node->getDoubleValue();
257     user_heading   = user_heading_node->getDoubleValue();
258     user_pitch     = user_pitch_node->getDoubleValue();
259     user_yaw       = user_yaw_node->getDoubleValue();
260     user_speed     = user_speed_node->getDoubleValue() * 0.592484;
261     user_roll      = user_roll_node->getDoubleValue();
262     wind_from_east = wind_from_east_node->getDoubleValue();
263     wind_from_north   = wind_from_north_node->getDoubleValue();
264     user_altitude_agl = user_altitude_agl_node->getDoubleValue();
265
266 }
267
268 // only keep the results from the nearest thermal
269 void
270 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
271     thermal->update(dt);
272
273     if ( thermal->_getRange() < range_nearest ) {
274         range_nearest = thermal->_getRange();
275         strength = thermal->getStrength();
276     }
277
278 }
279
280
281
282 void
283 FGAIManager::processScenario( const string &filename ) {
284
285     SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
286
287     if (!scenarioTop)
288         return;
289
290     SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
291
292     if (!scenarios)
293         return;
294
295     for (int i = 0; i < scenarios->nChildren(); i++) {
296         SGPropertyNode* scEntry = scenarios->getChild(i);
297
298         if (strcmp(scEntry->getName(), "entry"))
299             continue;
300         std::string type = scEntry->getStringValue("type", "aircraft");
301
302         if (type == "tanker") { // refueling scenarios
303             FGAITanker* tanker = new FGAITanker;
304             tanker->readFromScenario(scEntry);
305             attach(tanker);
306
307         } else if (type == "wingman") {
308             FGAIWingman* wingman = new FGAIWingman;
309             wingman->readFromScenario(scEntry);
310             attach(wingman);
311
312         } else if (type == "aircraft") {
313             FGAIAircraft* aircraft = new FGAIAircraft;
314             aircraft->readFromScenario(scEntry);
315             attach(aircraft);
316
317         } else if (type == "ship") {
318             FGAIShip* ship = new FGAIShip;
319             ship->readFromScenario(scEntry);
320             attach(ship);
321
322         } else if (type == "carrier") {
323             FGAICarrier* carrier = new FGAICarrier;
324             carrier->readFromScenario(scEntry);
325             attach(carrier);
326
327         } else if (type == "groundvehicle") {
328             FGAIGroundVehicle* groundvehicle = new FGAIGroundVehicle;
329             groundvehicle->readFromScenario(scEntry);
330             attach(groundvehicle);
331
332         } else if (type == "escort") {
333             FGAIEscort* escort = new FGAIEscort;
334             escort->readFromScenario(scEntry);
335             attach(escort);
336
337         } else if (type == "thunderstorm") {
338             FGAIStorm* storm = new FGAIStorm;
339             storm->readFromScenario(scEntry);
340             attach(storm);
341
342         } else if (type == "thermal") {
343             FGAIThermal* thermal = new FGAIThermal;
344             thermal->readFromScenario(scEntry);
345             attach(thermal);
346
347         } else if (type == "ballistic") {
348             FGAIBallistic* ballistic = new FGAIBallistic;
349             ballistic->readFromScenario(scEntry);
350             attach(ballistic);
351
352         } else if (type == "static") {
353             FGAIStatic* aistatic = new FGAIStatic;
354             aistatic->readFromScenario(scEntry);
355             attach(aistatic);
356         }
357
358     }
359
360 }
361
362 SGPropertyNode_ptr
363 FGAIManager::loadScenarioFile(const std::string& filename)
364 {
365     SGPath path(globals->get_fg_root());
366     path.append("AI/" + filename + ".xml");
367     try {
368         SGPropertyNode_ptr root = new SGPropertyNode;
369         readProperties(path.str(), root);
370         return root;
371     } catch (const sg_exception &t) {
372         SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
373             << path.str() << "': " << t.getFormattedMessage());
374         return 0;
375     }
376 }
377
378 bool
379 FGAIManager::getStartPosition(const string& id, const string& pid,
380                               SGGeod& geodPos, double& hdng, SGVec3d& uvw)
381 {
382     bool found = false;
383     SGPropertyNode* root = fgGetNode("sim/ai", true);
384     if (!root->getNode("enabled", true)->getBoolValue())
385         return found;
386
387     for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
388         SGPropertyNode *aiEntry = root->getChild( i );
389         if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
390             string filename = aiEntry->getStringValue();
391             SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
392             if (scenarioTop) {
393                 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
394                 if (scenarios) {
395                     for (int i = 0; i < scenarios->nChildren(); i++) {
396                         SGPropertyNode* scEntry = scenarios->getChild(i);
397                         std::string type = scEntry->getStringValue("type");
398                         std::string pnumber = scEntry->getStringValue("pennant-number");
399                         std::string name = scEntry->getStringValue("name");
400                         if (type == "carrier" && (pnumber == id || name == id)) {
401                             SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
402                             carrier->readFromScenario(scEntry);
403
404                             if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
405                                 found = true;
406                                 break;
407                             }
408                         }
409                     }
410                 }
411             }
412         }
413     }
414     return found;
415 }
416
417 const FGAIBase *
418 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
419 {
420     // we specify tgt extent (ft) according to the AIObject type
421     double tgt_ht[]     = {0,  50, 100, 250, 0, 100, 0, 0,  50,  50, 20, 100,  50};
422     double tgt_length[] = {0, 100, 200, 750, 0,  50, 0, 0, 200, 100, 40, 200, 100};
423     ai_list_iterator ai_list_itr = ai_list.begin();
424     ai_list_iterator end = ai_list.end();
425
426     SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
427     SGVec3d cartPos(SGVec3d::fromGeod(pos));
428     
429     while (ai_list_itr != end) {
430         double tgt_alt = (*ai_list_itr)->_getAltitude();
431         int type       = (*ai_list_itr)->getType();
432         tgt_ht[type] += fuse_range;
433
434         if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
435             || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
436                 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
437                 //    << fabs(tgt_alt - alt)
438                 //    << " "
439                 //    << type
440                 //    );
441                 ++ai_list_itr;
442                 continue;
443         }
444
445         int id         = (*ai_list_itr)->getID();
446
447         double range = calcRange(cartPos, (*ai_list_itr));
448
449         //SG_LOG(SG_AI, SG_DEBUG, "AIManager:  AI list size "
450         //    << ai_list.size()
451         //    << " type " << type
452         //    << " ID " << id
453         //    << " range " << range
454         //    //<< " bearing " << bearing
455         //    << " alt " << tgt_alt
456         //    );
457
458         tgt_length[type] += fuse_range;
459
460         if (range < tgt_length[type]){
461             SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
462                 << " type " << type
463                 << " ID " << id
464                 << " range " << range
465                 << " alt " << tgt_alt
466                 );
467             return (*ai_list_itr).get();
468         }
469         ++ai_list_itr;
470     }
471     return 0;
472 }
473
474 double
475 FGAIManager::calcRange(const SGVec3d& aCartPos, FGAIBase* aObject) const
476 {
477     double distM = dist(aCartPos, aObject->getCartPos());
478     return distM * SG_METER_TO_FEET;
479 }
480
481 //end AIManager.cxx