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