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