1 //
2 // Written and (c) Torsten Dreyer - Torsten(at)t3r_dot_de
3 //
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License as
6 // published by the Free Software Foundation; either version 2 of the
7 // License, or (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but
10 // WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 //
18
19 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
22
23 #ifdef HAVE_WINDOWS_H
24 # include <windows.h>
25 # include <direct.h>
26 #else
27 # include <unistd.h>
28 #endif
29
30 #ifdef __APPLE__
31 # include <CoreFoundation/CoreFoundation.h>
32 #endif
33
34 #include <iostream>
35
36 #if defined (SG_MAC)
37 #include <OpenGL/gl.h>
38 #include <GLUT/glut.h>
39 #elif defined (_GLES2)
40 #include <GLES2/gl2.h>
41 #else
42 #include <GL/glew.h> // Must be included before <GL/gl.h>
43 #include <GL/gl.h>
44 #include <GL/glut.h>
45 #endif
46
47 #include "FGGLApplication.hxx"
48 #include "FGPanelApplication.hxx"
49
50 #include <simgear/math/SGMisc.hxx>
51 #include <simgear/misc/sg_path.hxx>
52 #include <simgear/props/props_io.hxx>
53 #include <simgear/structure/exception.hxx>
54 #include <simgear/misc/ResourceManager.hxx>
55
56 #include "panel_io.hxx"
57 #include "ApplicationProperties.hxx"
58
59 using namespace std;
60
61 inline static string
ParseArgs(int argc,char ** argv,const string & token)62 ParseArgs (int argc, char **argv, const string &token) {
63 for (int i = 0; i < argc; i++) {
64 const string arg (argv[i]);
65 if (arg.find (token) == 0) {
66 return arg.substr (token.length ());
67 }
68 }
69 return "";
70 }
71
72 // define default location of fgdata (use the same as for fgfs)
73 inline static SGPath
platformDefaultRoot()74 platformDefaultRoot () {
75 #if defined(__CYGWIN__)
76 return SGPath ("../data");
77 #elif defined(_WIN32)
78 return SGPath ("..\\data");
79 #elif defined(__APPLE__)
80 /*
81 The following code looks for the base package inside the application
82 bundle, in the standard Contents/Resources location.
83 */
84 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL (CFBundleGetMainBundle ());
85
86 // look for a 'data' subdir
87 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent (NULL, resourcesUrl, CFSTR ("data"), true);
88
89 // now convert down to a path, and the a c-string
90 CFStringRef path = CFURLCopyFileSystemPath (dataDir, kCFURLPOSIXPathStyle);
91 string root = CFStringGetCStringPtr (path, CFStringGetSystemEncoding ());
92
93 CFRelease (resourcesUrl);
94 CFRelease (dataDir);
95 CFRelease (path);
96
97 return SGPath (root);
98 #else
99 return SGPath (PKGLIBDIR);
100 #endif
101 }
102
103 #include "FGPNGTextureLoader.hxx"
104 #include "FGRGBTextureLoader.hxx"
105
106 static FGPNGTextureLoader pngTextureLoader;
107 static FGRGBTextureLoader rgbTextureLoader;
108
FGPanelApplication(int argc,char ** argv)109 FGPanelApplication::FGPanelApplication (int argc, char **argv) :
110 FGGLApplication ("FlightGear Panel", argc, argv) {
111 sglog().setLogLevels (SG_ALL, SG_WARN);
112 FGCroppedTexture::registerTextureLoader ("png", &pngTextureLoader);
113 FGCroppedTexture::registerTextureLoader ("rgb", &rgbTextureLoader);
114
115 ApplicationProperties::root = platformDefaultRoot ().local8BitStr ();
116
117 const string panelFilename (ParseArgs (argc, argv, "--panel="));
118 const string fgRoot (ParseArgs (argc, argv, "--fg-root="));
119
120 if (fgRoot.length () > 0) {
121 ApplicationProperties::root = fgRoot;
122 }
123 simgear::ResourceManager::instance ()->addBasePath (ApplicationProperties::root);
124
125 if (panelFilename.length () == 0 ) {
126 cerr << "Need a panel filename. Use --panel=path_to_filename" << endl;
127 throw exception ();
128 }
129
130 // see if we got a valid fgdata path
131 SGPath BaseCheck (ApplicationProperties::root);
132 BaseCheck.append ("version");
133 if (!BaseCheck.exists ()) {
134 cerr << "Missing base package. Use --fg-root=path_to_fgdata" << endl;
135 throw exception ();
136 }
137
138 try {
139 const SGPath tpath (ApplicationProperties::GetRootPath (panelFilename.c_str ()));
140 readProperties (tpath, ApplicationProperties::Properties);
141 }
142 catch (sg_io_exception & e) {
143 cerr << e.getFormattedMessage () << endl;
144 throw;
145 }
146
147 for (int i = 1; i < argc; i++) {
148 const string arg (argv[i]);
149 if (arg.find ("--prop:") == 0 ) {
150 const string s2 (arg.substr (7));
151 string::size_type p (s2.find ("="));
152 if (p != string::npos) {
153 const string propertyName (s2.substr (0, p));
154 const string propertyValue (s2.substr (p + 1));
155 ApplicationProperties::Properties->getNode (propertyName.c_str (), true )->setValue (propertyValue.c_str ());
156 }
157 }
158 }
159
160 const SGPropertyNode_ptr n (ApplicationProperties::Properties->getNode ("panel"));
161 if (n != NULL) {
162 panel = FGReadablePanel::read (n);
163 }
164 protocol = new FGPanelProtocol (ApplicationProperties::Properties->getNode ("communication", true));
165 protocol->init ();
166 }
167
~FGPanelApplication()168 FGPanelApplication::~FGPanelApplication () {
169 }
170
171 void
Run()172 FGPanelApplication::Run () {
173 #ifdef _GLES2
174 const int mode (0);
175 #else
176 const int mode (GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
177 #endif
178 int w (panel == NULL ? 0 : panel->getWidth ());
179 int h (panel == NULL ? 0 : panel->getHeight ());
180 if (w == 0 && h == 0) {
181 w = 1024;
182 h = 768;
183 } else if (w == 0) {
184 w = h / 0.75;
185 } else if (h == 0) {
186 h = w * 0.75;
187 }
188
189 const bool gameMode (ApplicationProperties::Properties->getNode ( "game-mode", true)->getBoolValue ());
190 FGGLApplication::Run (mode, gameMode, w, h);
191 }
192
193 void
Init()194 FGPanelApplication::Init () {
195 #ifndef _GLES2
196 glutSetCursor (GLUT_CURSOR_NONE);
197 #endif
198 if (panel != NULL) {
199 panel->init ();
200 }
201 }
202
203 void
Reshape(const int width,const int height)204 FGPanelApplication::Reshape (const int width, const int height) {
205 this->width = width;
206 this->height = height;
207 glViewport (0, 0, GLsizei (width), GLsizei (height));
208 }
209
210 void
Idle()211 FGPanelApplication::Idle () {
212 #ifndef _GLES2
213 const double d (glutGet (GLUT_ELAPSED_TIME));
214 #endif
215 const double dt (Sleep ());
216 if (dt == 0) {
217 return;
218 }
219 if (panel != NULL) {
220 panel->update (dt);
221 }
222 #ifndef _GLES2
223 glutSwapBuffers ();
224 #endif
225 if (protocol != NULL) {
226 protocol->update (dt);
227 }
228 #ifndef _GLES2
229 static double dsum = 0.0;
230 static unsigned cnt = 0;
231 dsum += glutGet (GLUT_ELAPSED_TIME) - d;
232 cnt++;
233 if (dsum > 1000.0) {
234 ApplicationProperties::Properties->getNode ("/sim/frame-rate", true)->setDoubleValue (cnt * 1000.0 / dsum);
235 dsum = 0.0;
236 cnt = 0;
237 }
238 #endif
239 }
240
241 void
Key(const unsigned char key,const int x,const int y)242 FGPanelApplication::Key (const unsigned char key, const int x, const int y) {
243 switch (key) {
244 case 0x1b:
245 exit(0);
246 break;
247 }
248 }
249
250 double
Sleep()251 FGPanelApplication::Sleep () {
252 SGTimeStamp current_time_stamp;
253 static SGTimeStamp last_time_stamp;
254
255 if (last_time_stamp.get_seconds () == 0) {
256 last_time_stamp.stamp ();
257 }
258 const double model_hz (60);
259 const double throttle_hz (ApplicationProperties::getDouble ("/sim/frame-rate-throttle-hz", 0.0));
260 if (throttle_hz > 0.0) {
261 // optionally throttle the frame rate (to get consistent frame
262 // rates or reduce cpu usage.
263
264 double frame_us (1.0e6 / throttle_hz);
265
266 // sleep based timing loop.
267 //
268 // Calling sleep, even usleep() on linux is less accurate than
269 // we like, but it does free up the cpu for other tasks during
270 // the sleep so it is desirable. Because of the way sleep()
271 // is implemented in consumer operating systems like windows
272 // and linux, you almost always sleep a little longer than the
273 // requested amount.
274 //
275 // To combat the problem of sleeping too long, we calculate the
276 // desired wait time and shorten it by 2000us (2ms) to avoid
277 // [hopefully] over-sleep'ing. The 2ms value was arrived at
278 // via experimentation. We follow this up at the end with a
279 // simple busy-wait loop to get the final pause timing exactly
280 // right.
281 //
282 // Assuming we don't oversleep by more than 2000us, this
283 // should be a reasonable compromise between sleep based
284 // waiting, and busy waiting.
285
286 // sleep() will always overshoot by a bit so undersleep by
287 // 2000us in the hopes of never oversleeping.
288 frame_us -= 2000.0;
289 if (frame_us < 0.0) {
290 frame_us = 0.0;
291 }
292 current_time_stamp.stamp ();
293
294 /* Convert to ms */
295 const double elapsed_us ((current_time_stamp - last_time_stamp).toUSecs ());
296 if (elapsed_us < frame_us) {
297 const double requested_us (frame_us - elapsed_us);
298 #ifdef _WIN32
299 ::Sleep (int (requested_us / 1000.0));
300 #else
301 usleep (useconds_t (requested_us));
302 #endif
303 }
304 // busy wait timing loop.
305 //
306 // This yields the most accurate timing. If the previous
307 // usleep() call is omitted this will peg the cpu
308 // (which is just fine if FG is the only app you care about.)
309 current_time_stamp.stamp ();
310 const SGTimeStamp next_time_stamp (last_time_stamp + SGTimeStamp::fromSec (1e-6*frame_us));
311 while (current_time_stamp < next_time_stamp) {
312 current_time_stamp.stamp ();
313 }
314
315 } else {
316 current_time_stamp.stamp ();
317 }
318
319 static double reminder = 0.0;
320 static long global_multi_loop = 0;
321 const double real_delta_time_sec ((double (current_time_stamp.toUSecs () - last_time_stamp.toUSecs ()) / 1000000.0) + reminder);
322 last_time_stamp = current_time_stamp;
323 //fprintf(stdout,"\r%4.1lf ", 1/real_delta_time_sec );
324 //fflush(stdout);
325
326 // round the real time down to a multiple of 1/model-hz.
327 // this way all systems are updated the _same_ amount of dt.
328 global_multi_loop = long (floor (real_delta_time_sec * model_hz));
329 global_multi_loop = SGMisc<long>::max (0, global_multi_loop);
330 reminder = real_delta_time_sec - double (global_multi_loop) / double (model_hz);
331 return double (global_multi_loop) / double (model_hz);
332 }
333