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