]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIManager.cxx
Break upwards dependency on Traffic in the AI code
[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/sg_inlines.h>
24 #include <simgear/math/sg_geodesy.hxx>
25 #include <simgear/props/props_io.hxx>
26 #include <simgear/structure/exception.hxx>
27 #include <boost/mem_fn.hpp>
28 #include <boost/foreach.hpp>
29
30 #include <Main/globals.hxx>
31 #include <Airports/simple.hxx>
32
33 #include "AIManager.hxx"
34 #include "AIAircraft.hxx"
35 #include "AIShip.hxx"
36 #include "AIBallistic.hxx"
37 #include "AIStorm.hxx"
38 #include "AIThermal.hxx"
39 #include "AICarrier.hxx"
40 #include "AIStatic.hxx"
41 #include "AIMultiplayer.hxx"
42 #include "AITanker.hxx"
43 #include "AIWingman.hxx"
44 #include "AIGroundVehicle.hxx"
45 #include "AIEscort.hxx"
46
47 FGAIManager::FGAIManager() :
48     cb_ai_bare(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
49                fgGetNode("/sim/rendering/static-lod/ai-bare", true))),
50     cb_ai_detailed(SGPropertyChangeCallback<FGAIManager>(this,&FGAIManager::updateLOD,
51                    fgGetNode("/sim/rendering/static-lod/ai-detailed", true)))
52 {
53
54 }
55
56 FGAIManager::~FGAIManager()
57 {
58     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::unbind));
59 }
60
61 void
62 FGAIManager::init() {
63     root = fgGetNode("sim/ai", true);
64
65     enabled = root->getNode("enabled", true);
66
67     thermal_lift_node = fgGetNode("/environment/thermal-lift-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_altitude_agl_node  = fgGetNode("/position/altitude-agl-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
86     if (!root->getBoolValue("scenarios-enabled", true))
87         return;
88
89     // scenarios enabled, AI subsystem required
90     if (!enabled->getBoolValue())
91         enabled->setBoolValue(true);
92
93     // process all scenarios
94     map<string, bool> scenarios;
95     for (int i = 0 ; i < root->nChildren() ; i++) {
96         SGPropertyNode *n = root->getChild(i);
97         if (strcmp(n->getName(), "scenario"))
98             continue;
99
100         string name = n->getStringValue();
101         if (name.empty())
102             continue;
103
104         if (scenarios.find(name) != scenarios.end()) {
105             SG_LOG(SG_AI, SG_DEBUG, "won't load scenario '" << name << "' twice");
106             continue;
107         }
108
109         SG_LOG(SG_AI, SG_ALERT, "loading scenario '" << name << '\'');
110         processScenario(name);
111         scenarios[name] = true;
112     }
113 }
114
115 void
116 FGAIManager::reinit()
117 {
118     update(0.0);
119     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::reinit));
120 }
121
122 void
123 FGAIManager::bind() {
124     root = globals->get_props()->getNode("ai/models", true);
125     root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
126         &FGAIManager::getNumAiObjects));
127 }
128
129 void
130 FGAIManager::unbind() {
131     root->untie("count");
132 }
133
134 void FGAIManager::removeDeadItem(FGAIBase* base)
135 {
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
149 void
150 FGAIManager::update(double dt) {
151     // initialize these for finding nearest thermals
152     range_nearest = 10000.0;
153     strength = 0.0;
154
155     if (!enabled->getBoolValue())
156         return;
157
158     fetchUserState();
159
160     // partition the list into dead followed by alive
161     ai_list_iterator firstAlive =
162       std::stable_partition(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::getDie));
163     
164     // clean up each item and finally remove from the container
165     for (ai_list_iterator it=ai_list.begin(); it != firstAlive; ++it) {
166         removeDeadItem(*it);
167     }
168   
169     ai_list.erase(ai_list.begin(), firstAlive);
170   
171     // every remaining item is alive
172     BOOST_FOREACH(FGAIBase* base, ai_list) {
173         if (base->isa(FGAIBase::otThermal)) {
174             processThermal(dt, (FGAIThermal*)base);
175         } else {
176             base->update(dt);
177         }
178     } // of live AI objects iteration
179
180     thermal_lift_node->setDoubleValue( strength );  // for thermals
181 }
182
183 /** update LOD settings of all AI/MP models */
184 void
185 FGAIManager::updateLOD(SGPropertyNode* node)
186 {
187     SG_UNUSED(node);
188     std::for_each(ai_list.begin(), ai_list.end(), boost::mem_fn(&FGAIBase::updateLOD));
189 }
190
191 void
192 FGAIManager::attach(FGAIBase *model)
193 {
194     const char* typeString = model->getTypeString();
195     SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
196     SGPropertyNode* p;
197     int i;
198
199     // find free index in the property tree, if we have
200     // more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
201     for (i = 0; i < 10000; i++) {
202         p = root->getNode(typeString, i, false);
203
204         if (!p || !p->getBoolValue("valid", false))
205             break;
206
207         if (p->getIntValue("id",-1)==model->getID()) {
208             p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
209         }
210     }
211
212     p = root->getNode(typeString, i, true);
213     model->setManager(this, p);
214     ai_list.push_back(model);
215
216     model->init(model->getType()==FGAIBase::otAircraft
217         || model->getType()==FGAIBase::otMultiplayer
218         || model->getType()==FGAIBase::otStatic);
219     model->bind();
220     p->setBoolValue("valid", true);
221 }
222
223 int
224 FGAIManager::getNumAiObjects(void) const
225 {
226     return ai_list.size();
227 }
228
229 void
230 FGAIManager::fetchUserState( void ) {
231
232     user_latitude  = user_latitude_node->getDoubleValue();
233     user_longitude = user_longitude_node->getDoubleValue();
234     user_altitude  = user_altitude_node->getDoubleValue();
235     user_heading   = user_heading_node->getDoubleValue();
236     user_pitch     = user_pitch_node->getDoubleValue();
237     user_yaw       = user_yaw_node->getDoubleValue();
238     user_speed     = user_speed_node->getDoubleValue() * 0.592484;
239     user_roll      = user_roll_node->getDoubleValue();
240     wind_from_east = wind_from_east_node->getDoubleValue();
241     wind_from_north   = wind_from_north_node->getDoubleValue();
242     user_altitude_agl = user_altitude_agl_node->getDoubleValue();
243
244 }
245
246 // only keep the results from the nearest thermal
247 void
248 FGAIManager::processThermal( double dt, FGAIThermal* thermal ) {
249     thermal->update(dt);
250
251     if ( thermal->_getRange() < range_nearest ) {
252         range_nearest = thermal->_getRange();
253         strength = thermal->getStrength();
254     }
255
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 == "groundvehicle") {
306             FGAIGroundVehicle* groundvehicle = new FGAIGroundVehicle;
307             groundvehicle->readFromScenario(scEntry);
308             attach(groundvehicle);
309
310         } else if (type == "escort") {
311             FGAIEscort* escort = new FGAIEscort;
312             escort->readFromScenario(scEntry);
313             attach(escort);
314
315         } else if (type == "thunderstorm") {
316             FGAIStorm* storm = new FGAIStorm;
317             storm->readFromScenario(scEntry);
318             attach(storm);
319
320         } else if (type == "thermal") {
321             FGAIThermal* thermal = new FGAIThermal;
322             thermal->readFromScenario(scEntry);
323             attach(thermal);
324
325         } else if (type == "ballistic") {
326             FGAIBallistic* ballistic = new FGAIBallistic;
327             ballistic->readFromScenario(scEntry);
328             attach(ballistic);
329
330         } else if (type == "static") {
331             FGAIStatic* aistatic = new FGAIStatic;
332             aistatic->readFromScenario(scEntry);
333             attach(aistatic);
334         }
335
336     }
337
338 }
339
340 SGPropertyNode_ptr
341 FGAIManager::loadScenarioFile(const std::string& filename)
342 {
343     SGPath path(globals->get_fg_root());
344     path.append("AI/" + filename + ".xml");
345     try {
346         SGPropertyNode_ptr root = new SGPropertyNode;
347         readProperties(path.str(), root);
348         return root;
349     } catch (const sg_exception &t) {
350         SG_LOG(SG_AI, SG_ALERT, "Failed to load scenario '"
351             << path.str() << "': " << t.getFormattedMessage());
352         return 0;
353     }
354 }
355
356 bool
357 FGAIManager::getStartPosition(const string& id, const string& pid,
358                               SGGeod& geodPos, double& hdng, SGVec3d& uvw)
359 {
360     bool found = false;
361     SGPropertyNode* root = fgGetNode("sim/ai", true);
362     if (!root->getNode("enabled", true)->getBoolValue())
363         return found;
364
365     for (int i = 0 ; (!found) && i < root->nChildren() ; i++) {
366         SGPropertyNode *aiEntry = root->getChild( i );
367         if ( !strcmp( aiEntry->getName(), "scenario" ) ) {
368             string filename = aiEntry->getStringValue();
369             SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
370             if (scenarioTop) {
371                 SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
372                 if (scenarios) {
373                     for (int i = 0; i < scenarios->nChildren(); i++) {
374                         SGPropertyNode* scEntry = scenarios->getChild(i);
375                         std::string type = scEntry->getStringValue("type");
376                         std::string pnumber = scEntry->getStringValue("pennant-number");
377                         std::string name = scEntry->getStringValue("name");
378                         if (type == "carrier" && (pnumber == id || name == id)) {
379                             SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
380                             carrier->readFromScenario(scEntry);
381
382                             if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
383                                 found = true;
384                                 break;
385                             }
386                         }
387                     }
388                 }
389             }
390         }
391     }
392     return found;
393 }
394
395 const FGAIBase *
396 FGAIManager::calcCollision(double alt, double lat, double lon, double fuse_range)
397 {
398     // we specify tgt extent (ft) according to the AIObject type
399     double tgt_ht[]     = {0,  50, 100, 250, 0, 100, 0, 0,  50,  50, 20, 100,  50};
400     double tgt_length[] = {0, 100, 200, 750, 0,  50, 0, 0, 200, 100, 40, 200, 100};
401     ai_list_iterator ai_list_itr = ai_list.begin();
402     ai_list_iterator end = ai_list.end();
403
404     SGGeod pos(SGGeod::fromDegFt(lon, lat, alt));
405     SGVec3d cartPos(SGVec3d::fromGeod(pos));
406     
407     while (ai_list_itr != end) {
408         double tgt_alt = (*ai_list_itr)->_getAltitude();
409         int type       = (*ai_list_itr)->getType();
410         tgt_ht[type] += fuse_range;
411
412         if (fabs(tgt_alt - alt) > tgt_ht[type] || type == FGAIBase::otBallistic
413             || type == FGAIBase::otStorm || type == FGAIBase::otThermal ) {
414                 //SG_LOG(SG_AI, SG_DEBUG, "AIManager: skipping "
415                 //    << fabs(tgt_alt - alt)
416                 //    << " "
417                 //    << type
418                 //    );
419                 ++ai_list_itr;
420                 continue;
421         }
422
423         int id         = (*ai_list_itr)->getID();
424
425         double range = calcRange(cartPos, (*ai_list_itr));
426
427         //SG_LOG(SG_AI, SG_DEBUG, "AIManager:  AI list size "
428         //    << ai_list.size()
429         //    << " type " << type
430         //    << " ID " << id
431         //    << " range " << range
432         //    //<< " bearing " << bearing
433         //    << " alt " << tgt_alt
434         //    );
435
436         tgt_length[type] += fuse_range;
437
438         if (range < tgt_length[type]){
439             SG_LOG(SG_AI, SG_DEBUG, "AIManager: HIT! "
440                 << " type " << type
441                 << " ID " << id
442                 << " range " << range
443                 << " alt " << tgt_alt
444                 );
445             return (*ai_list_itr).get();
446         }
447         ++ai_list_itr;
448     }
449     return 0;
450 }
451
452 double
453 FGAIManager::calcRange(const SGVec3d& aCartPos, FGAIBase* aObject) const
454 {
455     double distM = dist(aCartPos, aObject->getCartPos());
456     return distM * SG_METER_TO_FEET;
457 }
458
459 //end AIManager.cxx