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