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