]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIManager.cxx
027d59b50a68843bbd406b366f1b7ed4da7905b3
[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
36 FGAIManager::FGAIManager() {
37   _dt = 0.0;
38   mNumAiModels = 0;
39   for (unsigned i = 0; i < FGAIBase::MAX_OBJECTS; ++i)
40     mNumAiTypeModels[i] = 0;
41 }
42
43 FGAIManager::~FGAIManager() {
44   ai_list_iterator ai_list_itr = ai_list.begin();
45   while(ai_list_itr != ai_list.end()) {
46       (*ai_list_itr)->unbind();
47       ++ai_list_itr;
48   }
49 }
50
51
52 void FGAIManager::init() {
53   root = fgGetNode("sim/ai", true);
54
55   enabled = root->getNode("enabled", true)->getBoolValue();
56   if (!enabled)
57       return;
58
59   wind_from_down_node = fgGetNode("/environment/wind-from-down-fps", true);
60   wind_from_east_node  = fgGetNode("/environment/wind-from-east-fps",true);
61   wind_from_north_node = fgGetNode("/environment/wind-from-north-fps",true);
62
63   user_latitude_node  = fgGetNode("/position/latitude-deg", true);
64   user_longitude_node = fgGetNode("/position/longitude-deg", true);
65   user_altitude_node  = fgGetNode("/position/altitude-ft", true);
66   user_heading_node   = fgGetNode("/orientation/heading-deg", true);
67   user_pitch_node     = fgGetNode("/orientation/pitch-deg", true);
68   user_yaw_node       = fgGetNode("/orientation/side-slip-deg", true);
69   user_speed_node     = fgGetNode("/velocities/uBody-fps", true);
70
71
72   /// Move that into the constructor
73   for(int i = 0 ; i < root->nChildren() ; i++) {
74     SGPropertyNode *aiEntry = root->getChild( i );
75     if( !strcmp( aiEntry->getName(), "scenario" ) ) {
76       scenario_filename = aiEntry->getStringValue();
77       if (!scenario_filename.empty())
78         processScenario( scenario_filename );
79     }
80   }
81 }
82
83
84 void FGAIManager::reinit() {
85    update(0.0);
86    ai_list_iterator ai_list_itr = ai_list.begin();
87
88    while(ai_list_itr != ai_list.end()) {
89       (*ai_list_itr)->reinit();
90       ++ai_list_itr;
91    }
92 }
93
94
95 void FGAIManager::bind() {
96    root = globals->get_props()->getNode("ai/models", true);
97    root->tie("count", SGRawValueMethods<FGAIManager, int>(*this,
98              &FGAIManager::getNumAiObjects));
99 }
100
101
102 void FGAIManager::unbind() {
103     root->untie("count");
104 }
105
106
107 void FGAIManager::update(double dt) {
108   // initialize these for finding nearest thermals
109   range_nearest = 10000.0;
110   strength = 0.0;
111   if (!enabled)
112     return;
113
114   FGTrafficManager *tmgr = (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
115   _dt = dt;
116
117   ai_list_iterator ai_list_itr = ai_list.begin();
118   while(ai_list_itr != ai_list.end()) {
119     if ((*ai_list_itr)->getDie()) {      
120       tmgr->release((*ai_list_itr)->getID());
121       --mNumAiModels;
122       --(mNumAiTypeModels[(*ai_list_itr)->getType()]);
123       (*ai_list_itr)->unbind();
124       ai_list_itr = ai_list.erase(ai_list_itr);
125     } else {
126       fetchUserState();
127       if ((*ai_list_itr)->isa(FGAIBase::otThermal)) {
128         FGAIBase *base = *ai_list_itr;
129         processThermal((FGAIThermal*)base); 
130       } else { 
131         (*ai_list_itr)->update(_dt);
132       }
133       ++ai_list_itr;
134     }
135   }
136   wind_from_down_node->setDoubleValue( strength ); // for thermals
137 }
138
139 void
140 FGAIManager::attach(SGSharedPtr<FGAIBase> model)
141 {
142   unsigned idx = mNumAiTypeModels[model->getType()];
143   const char* typeString = model->getTypeString();
144   SGPropertyNode* root = globals->get_props()->getNode("ai/models", true);
145   SGPropertyNode* p;
146   int i;
147   for (i=0;i<10000;i++) //find free index in the property tree, if we have
148       //more than 10000 mp-aircrafts in the property tree we should optimize the mp-server
149   {
150     p = root->getNode(typeString, i, false);
151     if (!p) break;
152     if (p->getIntValue("id",-1)==model->getID())
153     {
154         p->setStringValue("callsign","***invalid node***"); //debug only, should never set!
155                                               
156     }
157   }
158   p = root->getNode(typeString, i, true);
159   model->setManager(this, p);
160   ai_list.push_back(model);
161   ++mNumAiModels;
162   ++(mNumAiTypeModels[model->getType()]);
163   model->init(model->getType()==FGAIBase::otAircraft
164       || model->getType()==FGAIBase::otMultiplayer
165       || model->getType()==FGAIBase::otStatic);
166   model->bind();
167 }
168
169
170 void FGAIManager::destroyObject( int ID ) {
171   ai_list_iterator ai_list_itr = ai_list.begin();
172   while(ai_list_itr != ai_list.end()) {
173     if ((*ai_list_itr)->getID() == ID) {
174       --mNumAiModels;
175       --(mNumAiTypeModels[(*ai_list_itr)->getType()]);
176       (*ai_list_itr)->unbind();
177       ai_list_itr = ai_list.erase(ai_list_itr);
178     } else
179       ++ai_list_itr;
180   }
181 }
182
183 int
184 FGAIManager::getNumAiObjects(void) const
185 {
186   return mNumAiModels;
187 }
188
189 void FGAIManager::fetchUserState( void ) {
190      user_latitude  = user_latitude_node->getDoubleValue();
191      user_longitude = user_longitude_node->getDoubleValue();
192      user_altitude  = user_altitude_node->getDoubleValue();
193      user_heading   = user_heading_node->getDoubleValue();
194      user_pitch     = user_pitch_node->getDoubleValue();
195      user_yaw       = user_yaw_node->getDoubleValue();
196      user_speed     = user_speed_node->getDoubleValue() * 0.592484;
197      wind_from_east = wind_from_east_node->getDoubleValue();
198      wind_from_north = wind_from_north_node->getDoubleValue();
199 }
200
201
202 // only keep the results from the nearest thermal
203 void FGAIManager::processThermal( FGAIThermal* thermal ) {
204   thermal->update(_dt);
205   if ( thermal->_getRange() < range_nearest ) {
206      range_nearest = thermal->_getRange();
207      strength = thermal->getStrength();
208   }
209 }
210
211
212 void FGAIManager::processScenario( const string &filename ) {
213
214   SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
215   if (!scenarioTop)
216     return;
217   SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
218   if (!scenarios)
219     return;
220
221   for (int i = 0; i < scenarios->nChildren(); i++) { 
222     SGPropertyNode* scEntry = scenarios->getChild(i);
223     std::string type = scEntry->getStringValue("type", "aircraft");
224
225     if (type == "aircraft") {
226       FGAIAircraft* aircraft = new FGAIAircraft;
227       aircraft->readFromScenario(scEntry);
228       attach(aircraft);
229
230     } else if (type == "ship") {
231       FGAIShip* ship = new FGAIShip;
232       ship->readFromScenario(scEntry);
233       attach(ship);
234       
235     } else if (type == "carrier") {
236       FGAICarrier* carrier = new FGAICarrier;
237       carrier->readFromScenario(scEntry);
238       attach(carrier);
239       
240     } else if (type == "thunderstorm") {
241       FGAIStorm* storm = new FGAIStorm;
242       storm->readFromScenario(scEntry);
243       attach(storm);
244       
245     } else if (type == "thermal") {
246       FGAIThermal* thermal = new FGAIThermal;
247       thermal->readFromScenario(scEntry);
248       attach(thermal);
249       
250     } else if (type == "ballistic") {
251       FGAIBallistic* ballistic = new FGAIBallistic;
252       ballistic->readFromScenario(scEntry);
253       attach(ballistic);
254       
255     } else if (type == "static") {
256       FGAIStatic* aistatic = new FGAIStatic;
257       aistatic->readFromScenario(scEntry);
258       attach(aistatic);
259       
260     }
261   }
262 }
263
264 SGPropertyNode_ptr
265 FGAIManager::loadScenarioFile(const std::string& filename)
266 {
267   SGPath path(globals->get_fg_root());
268   path.append("AI/" + filename + ".xml");
269   try {
270     SGPropertyNode_ptr root = new SGPropertyNode;
271     readProperties(path.str(), root);
272     return root;
273   } catch (const sg_exception &e) {
274     SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path specified for AI "
275            "scenario: \"" << path.str() << "\"");
276     return 0;
277   }
278 }
279
280 bool FGAIManager::getStartPosition(const string& id, const string& pid,
281                                    SGGeod& geodPos, double& hdng, SGVec3d& uvw)
282 {
283   bool found = false;
284   SGPropertyNode* root = fgGetNode("sim/ai", true);
285   if (!root->getNode("enabled", true)->getBoolValue())
286       return found;
287
288   for(int i = 0 ; (!found) && i < root->nChildren() ; i++) {
289     SGPropertyNode *aiEntry = root->getChild( i );
290     if( !strcmp( aiEntry->getName(), "scenario" ) ) {
291       string filename = aiEntry->getStringValue();
292       SGPropertyNode_ptr scenarioTop = loadScenarioFile(filename);
293       if (scenarioTop) {
294         SGPropertyNode* scenarios = scenarioTop->getChild("scenario");
295         if (scenarios) {
296           for (int i = 0; i < scenarios->nChildren(); i++) { 
297             SGPropertyNode* scEntry = scenarios->getChild(i);
298             std::string type = scEntry->getStringValue("type");
299             std::string pnumber = scEntry->getStringValue("pennant-number");
300             std::string name = scEntry->getStringValue("name");
301             if (type == "carrier" && (pnumber == id || name == id)) {
302               SGSharedPtr<FGAICarrier> carrier = new FGAICarrier;
303               carrier->readFromScenario(scEntry);
304               
305               if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) {
306                 found = true;
307                 break;
308               }
309             }
310           }
311         }
312       }
313     }
314   }
315   return found;
316 }
317
318 //end AIManager.cxx