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