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