]> git.mxchange.org Git - flightgear.git/blob - utils/TerraSync/terrasync.cxx
91017fb341b195e40e6f452b5c5e4f8ee538f241
[flightgear.git] / utils / TerraSync / terrasync.cxx
1 // terrasync.cxx -- "JIT" scenery fetcher
2 //
3 // Written by Curtis Olson, started November 2002.
4 //
5 // Copyright (C) 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
6 // Copyright (C) 2008  Alexander R. Perry <alex.perry@ieee.org>
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #ifdef HAVE_WINDOWS_H
29 #include <windows.h>
30 #endif
31
32 #ifdef __MINGW32__
33 #include <time.h>
34 #include <unistd.h>
35 #elif defined(_MSC_VER)
36 #include <io.h>
37 #endif
38
39 #include <stdlib.h>             // atoi() atof() abs() system()
40 #include <signal.h>             // signal()
41
42 #include <simgear/compiler.h>
43
44 #include <iostream>
45 #include <fstream>
46 #include <string>
47 #include <deque>
48 #include <map>
49
50 #include <plib/netSocket.h>
51 #include <plib/ul.h>
52
53 #include <simgear/bucket/newbucket.hxx>
54 #include <simgear/misc/sg_path.hxx>
55
56 #ifdef HAVE_SVN_CLIENT_H
57 #  ifdef HAVE_LIBSVN_CLIENT_1
58 #    include <svn_auth.h>
59 #    include <svn_client.h>
60 #    include <svn_cmdline.h>
61 #    include <svn_pools.h>
62 #  else
63 #    undef HAVE_SVN_CLIENT_H
64 #  endif
65 #endif
66
67 using namespace std;
68
69 const char* source_base = NULL;
70 const char* svn_base =
71   "http://terrascenery.googlecode.com/svn/trunk/data/Scenery";
72 const char* rsync_base = "scenery.flightgear.org::Scenery";
73 const char* dest_base = "terrasyncdir";
74 const char* rsync_cmd = 
75     "rsync --verbose --archive --delete --perms --owner --group";
76
77 #ifdef HAVE_SVN_CLIENT_H
78 bool use_svn = true;
79 #else
80 bool use_svn = false;
81 const char* svn_cmd = "svn checkout";
82 #endif
83
84 // display usage
85 static void usage( const string& prog ) {
86     cout << 
87 "Usage:  terrasync [options]\n"
88 "Options:  \n"
89 " -d <dest>       destination directory [required]\n"
90 " -R              transport using pipe to rsync\n"
91 " -S              transport using built-in svn\n"
92 " -p <port>       listen on UDP port [default: 5501]\n"
93 " -s <source>     source base [default: '']\n"
94 " -pid <pidfile>  write PID to file\n"
95 " -v              be more verbose\n"
96 ;
97
98 #ifdef HAVE_SVN_CLIENT_H
99     cout << "    (defaults to the built in subversion)" << endl;
100 #else
101     cout << "    (defaults to rsync, using external commands)" << endl;
102 #endif
103
104   cout << "\nExample:\n"
105 "pid=$(cat $pidfile 2>/dev/null)\n"
106 "if test -n \"$pid\" && kill -0 $pid ; then\n"
107 "    echo \"terrasync already running: $pid\"\n"
108 "else\n"
109 "    nice /games/sport/fgs/utils/TerraSync/terrasync         \\\n"
110 "      -v -pid $pidfile -S -p 5500 -d /games/orig/terrasync &\n"
111 "fi" << endl;
112
113 }
114
115 deque<string> waitingTiles;
116 typedef map<string,time_t> CompletedTiles;
117 CompletedTiles completedTiles;
118 netSocket theSocket;
119
120 #ifdef HAVE_SVN_CLIENT_H
121
122 // Things we need for doing subversion checkout - often
123 apr_pool_t *mysvn_pool = NULL;
124 svn_client_ctx_t *mysvn_ctx = NULL;
125 svn_opt_revision_t *mysvn_rev = NULL;
126 svn_opt_revision_t *mysvn_rev_peg = NULL;
127
128 static const svn_version_checklist_t mysvn_checklist[] = {
129     { "svn_subr",   svn_subr_version },
130     { "svn_client", svn_client_version },
131     { "svn_wc",     svn_wc_version },
132     { "svn_ra",     svn_ra_version },
133     { "svn_delta",  svn_delta_version },
134     { "svn_diff",   svn_diff_version },
135     { NULL, NULL }
136 };
137
138 // Configure our subversion session
139 int mysvn_setup(void) {
140     // Are we already prepared?
141     if (mysvn_pool) return EXIT_SUCCESS;
142     // No, so initialize svn internals generally
143 #ifdef _MSC_VER
144     // there is a segfault when providing an error stream.
145     //  Apparently, calling setvbuf with a nul buffer is
146     //  not supported under msvc 7.1 ( code inside svn_cmdline_init )
147     if (svn_cmdline_init("terrasync", 0) != EXIT_SUCCESS)
148         return EXIT_FAILURE;
149 #else
150     if (svn_cmdline_init("terrasync", stderr) != EXIT_SUCCESS)
151         return EXIT_FAILURE;
152 #endif
153     apr_pool_t *pool;
154     apr_pool_create(&pool, NULL);
155     svn_error_t *err = NULL;
156     SVN_VERSION_DEFINE(mysvn_version);
157     err = svn_ver_check_list(&mysvn_version, mysvn_checklist);
158     if (err)
159         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
160     err = svn_ra_initialize(pool);
161     if (err)
162         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
163     char *config_dir = NULL;
164     err = svn_config_ensure(config_dir, pool);
165     if (err)
166         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
167     err = svn_client_create_context(&mysvn_ctx, pool);
168     if (err)
169         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
170     err = svn_config_get_config(&(mysvn_ctx->config),
171         config_dir, pool);
172     if (err)
173         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
174     svn_config_t *cfg;
175     cfg = ( svn_config_t*) apr_hash_get(
176         mysvn_ctx->config,
177         SVN_CONFIG_CATEGORY_CONFIG,
178         APR_HASH_KEY_STRING);
179     if (err)
180         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
181     svn_auth_baton_t *ab;
182     err = svn_cmdline_setup_auth_baton(&ab,
183         TRUE, NULL, NULL, config_dir, TRUE, cfg,
184         mysvn_ctx->cancel_func, mysvn_ctx->cancel_baton, pool);
185     if (err)
186         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
187     mysvn_ctx->auth_baton = ab;
188     mysvn_ctx->conflict_func = NULL;
189     mysvn_ctx->conflict_baton = NULL;
190     // Now our magic revisions
191     mysvn_rev = (svn_opt_revision_t*) apr_palloc(pool, 
192         sizeof(svn_opt_revision_t));
193     if (!mysvn_rev)
194         return EXIT_FAILURE;
195     mysvn_rev_peg = (svn_opt_revision_t*) apr_palloc(pool, 
196         sizeof(svn_opt_revision_t));
197     if (!mysvn_rev_peg)
198         return EXIT_FAILURE;
199     mysvn_rev->kind = svn_opt_revision_head;
200     mysvn_rev_peg->kind = svn_opt_revision_unspecified;
201     // Success if we got this far
202     mysvn_pool = pool;
203     return EXIT_SUCCESS;
204 }
205
206 #endif
207
208 // sync one directory tree
209 void sync_tree(const char* dir) {
210     int rc;
211     char command[512];
212     SGPath path( dest_base );
213
214     path.append( dir );
215     rc = path.create_dir( 0755 );
216     if (rc) {
217         cout << "Return code = " << rc << endl;
218         exit(1);
219     }
220
221     if (use_svn) {
222 #ifdef HAVE_SVN_CLIENT_H
223         cout << dir << " ... ";
224         cout.flush();
225         char dest_base_dir[512];
226         snprintf( command, 512,
227             "%s/%s", source_base, dir);
228         snprintf( dest_base_dir, 512,
229             "%s/%s", dest_base, dir);
230         svn_error_t *err = NULL;
231         if (mysvn_setup() != EXIT_SUCCESS)
232             exit(1);
233         apr_pool_t *subpool = svn_pool_create(mysvn_pool);
234         err = svn_client_checkout3(NULL,
235             command,
236             dest_base_dir,
237             mysvn_rev_peg,
238             mysvn_rev,
239             svn_depth_infinity,
240             0,
241             0,
242             mysvn_ctx,
243             subpool);
244         if (err) {
245             // Report errors from the checkout attempt
246             cout << "failed: " << endl
247                  << err->message << endl;
248             svn_error_clear(err);
249             return;
250         } else {
251             cout << "done" << endl;
252         }
253         svn_pool_destroy(subpool);
254         return;
255 #else
256
257         snprintf( command, 512,
258             "%s %s/%s %s/%s", svn_cmd,
259             source_base, dir,
260             dest_base, dir );
261 #endif
262     } else {
263         snprintf( command, 512,
264             "%s %s/%s/ %s/%s/", rsync_cmd,
265             source_base, dir,
266             dest_base, dir );
267     }
268     cout << command << endl;
269     rc = system( command );
270     if (rc) {
271         cout << "Return code = " << rc << endl;
272         if (rc == 5120) exit(1);
273     }
274 }
275
276 #ifdef _MSC_VER
277 typedef void (__cdecl * sighandler_t)(int);
278 #endif
279
280 bool terminating = false;
281 sighandler_t prior_signal_handlers[32];
282 int termination_triggering_signals[] = {
283 #ifndef _MSC_VER
284     SIGHUP, SIGINT, SIGQUIT, SIGKILL,
285 #else
286     SIGINT, SIGILL, SIGFPE, SIGSEGV, SIGTERM, SIGBREAK, SIGABRT,
287 #endif
288     0};  // zero terminated
289
290 void terminate_request_handler(int param) {
291     char msg[] = "\nReceived signal XX, intend to exit soon.\n"
292          "repeat the signal to force immediate termination.\n";
293     msg[17] = '0' + param / 10;
294     msg[18] = '0' + param % 10;
295     write(1, msg, sizeof(msg) - 1);
296     terminating = true;
297     signal(param, prior_signal_handlers[param]);
298     theSocket.close();
299 }
300
301
302 const int nowhere = -9999;
303
304
305 // parse message
306 static void parse_message( const string &msg, int *lat, int *lon ) {
307     double dlat, dlon;
308     string text = msg;
309
310     // find GGA string and advance to start of lat
311     string::size_type pos = text.find( "$GPGGA" );
312     if ( pos == string::npos )
313     {
314         *lat = nowhere;
315         *lon = nowhere;
316         return;
317     }
318     string tmp = text.substr( pos + 7 );
319     pos = tmp.find( "," );
320     tmp = tmp.substr( pos + 1 );
321     // cout << "-> " << tmp << endl;
322
323     // find lat then advance to start of hemisphere
324     pos = tmp.find( "," );
325     string lats = tmp.substr( 0, pos );
326     dlat = atof( lats.c_str() ) / 100.0;
327     tmp = tmp.substr( pos + 1 );
328
329     // find N/S hemisphere and advance to start of lon
330     if ( tmp.substr( 0, 1 ) == "S" ) {
331         dlat = -dlat;
332     }
333     pos = tmp.find( "," );
334     tmp = tmp.substr( pos + 1 );
335
336     // find lon
337     pos = tmp.find( "," );
338     string lons = tmp.substr( 0, pos );
339     dlon = atof( lons.c_str() ) / 100.0;
340     tmp = tmp.substr( pos + 1 );
341
342     // find E/W hemisphere and advance to start of lon
343     if ( tmp.substr( 0, 1 ) == "W" ) {
344         dlon = -dlon;
345     }
346
347     if ( dlat < 0 ) {
348         *lat = (int)dlat - 1;
349     } else {
350         *lat = (int)dlat;
351     }
352
353     if ( dlon < 0 ) {
354         *lon = (int)dlon - 1;
355     } else {
356         *lon = (int)dlon;
357     }
358
359     if ((dlon == 0) && (dlat == 0)) {
360       *lon = nowhere;
361       *lat = nowhere;
362     }
363 }
364
365
366 // sync area
367 static void sync_area( int lat, int lon ) {
368     if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
369         return;
370     char NS, EW;
371     int baselat, baselon;
372
373     if ( lat < 0 ) {
374         int base = (int)(lat / 10);
375         if ( lat == base * 10 ) {
376             baselat = base * 10;
377         } else {
378             baselat = (base - 1) * 10;
379         }
380         NS = 's';
381     } else {
382         baselat = (int)(lat / 10) * 10;
383         NS = 'n';
384     }
385     if ( lon < 0 ) {
386         int base = (int)(lon / 10);
387         if ( lon == base * 10 ) {
388             baselon = base * 10;
389         } else {
390             baselon = (base - 1) * 10;
391         }
392         EW = 'w';
393     } else {
394         baselon = (int)(lon / 10) * 10;
395         EW = 'e';
396     }
397
398     const char* terrainobjects[3] = { "Terrain", "Objects", 0 };
399     
400     for (const char** tree = &terrainobjects[0]; *tree; tree++) {
401         char dir[512];
402         snprintf( dir, 512, "%s/%c%03d%c%02d/%c%03d%c%02d",
403                 *tree,
404                 EW, abs(baselon), NS, abs(baselat),
405                 EW, abs(lon), NS, abs(lat) );
406         waitingTiles.push_back( dir );
407     }
408 }
409
410
411 // sync areas
412 static void sync_areas( int lat, int lon, int lat_dir, int lon_dir ) {
413     // do current 1x1 degree area first
414     sync_area( lat, lon );
415
416     if ( lat_dir == 0 && lon_dir == 0 ) {
417         // now do surrounding 8 1x1 degree areas.
418         for ( int i = lat - 1; i <= lat + 1; ++i ) {
419             for ( int j = lon - 1; j <= lon + 1; ++j ) {
420                 if ( i != lat || j != lon ) {
421                     sync_area( i, j );
422                 }
423             }
424         }
425     } else {
426         if ( lat_dir != 0 ) {
427             sync_area( lat + lat_dir, lon );
428             sync_area( lat + lat_dir, lon - 1 );
429             sync_area( lat + lat_dir, lon + 1 );
430         }
431         if ( lon_dir != 0 ) {
432             sync_area( lat, lon + lon_dir );
433             sync_area( lat - 1, lon + lon_dir );
434             sync_area( lat + 1, lon + lon_dir );
435         }
436     }
437 }
438
439 void getWaitingTile() {
440     while ( !waitingTiles.empty() ) {
441         CompletedTiles::iterator ii =
442             completedTiles.find( waitingTiles.front() );
443         time_t now = time(0);
444         if ( ii == completedTiles.end() || ii->second + 600 < now ) {
445             sync_tree(waitingTiles.front().c_str());
446             completedTiles[ waitingTiles.front() ] = now;
447             waitingTiles.pop_front();
448             break;
449         }
450         waitingTiles.pop_front();
451     }
452 }
453
454 int main( int argc, char **argv ) {
455     int port = 5501;
456     char host[256] = "localhost";
457     bool testing = false;
458     bool do_checkout(true);
459     int verbose(0);
460     const char* pidfn = "";
461
462     // parse arguments
463     int i = 1;
464     while ( i < argc ) {
465         if ( (string)argv[i] == "-p" ) {
466             ++i;
467             port = atoi( argv[i] );
468         } else if ( string(argv[i]).find("-pid") == 0 ) {
469             ++i;
470             pidfn = argv[i];
471             cout << "pidfn: " << pidfn << endl;
472         } else if ( (string)argv[i] == "-s" ) {
473             ++i;
474             source_base = argv[i];
475         } else if ( (string)argv[i] == "-d" ) {
476             ++i;
477             dest_base = argv[i];
478         } else if ( (string)argv[i] == "-R" ) {
479             use_svn = false;
480         } else if ( (string)argv[i] == "-S" ) {
481             use_svn = true;
482         } else if ( (string)argv[i] == "-v" ) {
483             verbose++;
484         } else if ( (string)argv[i] == "-T" ) {
485             testing = true;
486         } else if ( (string)argv[i] == "-h" ) {
487             usage( argv[0] );
488             exit(0);
489         } else {
490             cerr << "Unrecognized verbiage '" << argv[i] << "'" << endl;
491             usage( argv[0] );
492             exit(-1);        
493         }
494         ++i;
495     }
496
497     if (*pidfn) {
498       ofstream pidstream;
499       pidstream.open(pidfn);
500       if (!pidstream.good()) {
501         cerr << "Cannot open pid file '" << pidfn << "': ";
502         perror(0);
503         exit(2);
504       }
505       pidstream << getpid() << endl;
506       pidstream.close();
507     }
508
509     // Use the appropriate default for the "-s" flag
510     if (source_base == NULL) {
511         if (use_svn)
512             source_base = svn_base;
513         else
514             source_base = rsync_base;
515     }
516     
517     // Must call this before any other net stuff
518     netInit( &argc,argv );
519
520     if ( ! theSocket.open( false ) ) {  // open a UDP socket
521         printf("error opening socket\n");
522         return -1;
523     }
524
525     if ( theSocket.bind( host, port ) == -1 ) {
526         printf("error binding to port %d\n", port);
527         return -1;
528     }
529
530     char msg[256];
531     int maxlen = 256;
532     int len;
533     int lat, lon;
534     int last_lat = nowhere;
535     int last_lon = nowhere;
536     bool recv_msg = false;
537
538     char synced_other;
539     if (do_checkout) {
540         for ( synced_other = 'K'; synced_other <= 'Z'; synced_other++ ) {
541             char dir[512];
542             snprintf( dir, 512, "Airports/%c", synced_other );
543             waitingTiles.push_back( dir );
544         }
545         for ( synced_other = 'A'; synced_other <= 'J'; synced_other++ ) {
546             char dir[512];
547             snprintf( dir, 512, "Airports/%c", synced_other );
548             waitingTiles.push_back( dir );
549         }
550         if ( use_svn ) {
551             waitingTiles.push_back( "Models" );
552         }
553     }
554
555
556     for (int* sigp=termination_triggering_signals; *sigp; sigp++) {
557         prior_signal_handlers[*sigp] =
558             signal(*sigp, *terminate_request_handler);
559         if (verbose) cout << "Intercepted signal " << *sigp << endl;
560     }
561
562     while ( !terminating ) {
563         // main loop
564         recv_msg = false;
565         if ( testing ) {
566             // No FGFS communications
567             lat = 37;
568             lon = -123;
569             recv_msg = (lat != last_lat) || (lon != last_lon);
570         } else {
571             if (verbose && waitingTiles.empty()) {
572                 cout << "Idle; waiting for FlightGear position\n";
573             }
574             theSocket.setBlocking(waitingTiles.empty());
575             len = theSocket.recv(msg, maxlen, 0);
576             if (len >= 0) {
577                 msg[len] = '\0';
578                 recv_msg = true;
579                 if (verbose) cout << "recv length: " << len << endl;
580                 parse_message( msg, &lat, &lon );
581             }
582         }
583
584         if ( recv_msg ) {
585              // Ignore messages where the location does not change
586              if ( lat != last_lat || lon != last_lon ) {
587                 cout << "pos in msg = " << lat << "," << lon << endl;
588                 deque<string> oldRequests;
589                 oldRequests.swap( waitingTiles );
590                 int lat_dir, lon_dir, dist;
591                 if ( last_lat == nowhere || last_lon == nowhere ) {
592                     lat_dir = lon_dir = 0;
593                 } else {
594                     dist = lat - last_lat;
595                     if ( dist != 0 ) {
596                         lat_dir = dist / abs(dist);
597                     } else {
598                         lat_dir = 0;
599                     }
600                     dist = lon - last_lon;
601                     if ( dist != 0 ) {
602                         lon_dir = dist / abs(dist);
603                     } else {
604                         lon_dir = 0;
605                     }
606                 }
607                 cout << "lat = " << lat << " lon = " << lon << endl;
608                 cout << "lat_dir = " << lat_dir << "  "
609                      << "lon_dir = " << lon_dir << endl;
610                 sync_areas( lat, lon, lat_dir, lon_dir );
611                 while ( !oldRequests.empty() ) {
612                     waitingTiles.push_back( oldRequests.front() );
613                     oldRequests.pop_front();
614                 }
615                 last_lat = lat;
616                 last_lon = lon;
617             }
618         }
619
620         // No messages inbound, so process some pending work
621         else if ( !waitingTiles.empty() ) {
622             getWaitingTile();
623         }
624
625         else if ( testing ) {
626             terminating = true;
627         } else
628
629         ulSleep( 1 );
630     } // while !terminating
631         
632     return 0;
633 }