]> git.mxchange.org Git - flightgear.git/blob - utils/TerraSync/terrasync.cxx
* add support for self-contained tags like <test/>
[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
33 #include <stdlib.h>             // atoi() atof() abs() system()
34
35 #include <simgear/compiler.h>
36
37 #include <iostream>
38 #include <string>
39 #include <deque>
40 #include <map>
41
42 #include <plib/netSocket.h>
43 #include <plib/ul.h>
44
45 #include <simgear/bucket/newbucket.hxx>
46 #include <simgear/misc/sg_path.hxx>
47
48 #ifdef HAVE_SVN_CLIENT_H
49 #  ifdef HAVE_LIBSVN_CLIENT_1
50 #    include <svn_auth.h>
51 #    include <svn_client.h>
52 #    include <svn_cmdline.h>
53 #    include <svn_pools.h>
54 #  else
55 #    undef HAVE_SVN_CLIENT_H
56 #  endif
57 #endif
58
59 using std::string;
60 using std::cout;
61 using std::endl;
62
63 const char* source_base = NULL;
64 const char* svn_base =
65   "http://terrascenery.googlecode.com/svn/trunk/data/Scenery";
66 const char* rsync_base = "scenery.flightgear.org::Scenery";
67 const char* dest_base = "terrasyncdir";
68 const char* rsync_cmd = 
69     "rsync --verbose --archive --delete --perms --owner --group";
70
71 #ifdef HAVE_SVN_CLIENT_H
72 bool use_svn = true;
73 #else
74 bool use_svn = false;
75 const char* svn_cmd = "svn checkout";
76 #endif
77
78 // display usage
79 static void usage( const string& prog ) {
80     cout << "Usage: " << endl
81          << prog << " -p <port> "
82          << "-R [ -s <rsync_source> ] -d <dest>" << endl
83          << prog << " -p <port> "
84          << "-S [ -s <svn_source> ] -d <dest>" << endl;
85 #ifdef HAVE_SVN_CLIENT_H
86     cout << "    (defaults to the built in subversion)" << endl;
87 #else
88     cout << "    (defaults to rsync, using external commands)" << endl;
89 #endif
90 }
91
92 std::deque<std::string> waitingTiles;
93 typedef std::map<std::string,time_t> CompletedTiles;
94 CompletedTiles completedTiles;
95
96 #ifdef HAVE_SVN_CLIENT_H
97
98 // Things we need for doing subversion checkout - often
99 apr_pool_t *mysvn_pool = NULL;
100 svn_client_ctx_t *mysvn_ctx = NULL;
101 svn_opt_revision_t *mysvn_rev = NULL;
102
103 static const svn_version_checklist_t mysvn_checklist[] = {
104     { "svn_subr",   svn_subr_version },
105     { "svn_client", svn_client_version },
106     { "svn_wc",     svn_wc_version },
107     { "svn_ra",     svn_ra_version },
108     { "svn_delta",  svn_delta_version },
109     { "svn_diff",   svn_diff_version },
110     { NULL, NULL }
111 };
112
113 // Configure our subversion session
114 int mysvn_setup(void) {
115     // Are we already prepared?
116     if (mysvn_pool) return EXIT_SUCCESS;
117     // No, so initialize svn internals generally
118 #ifdef _MSC_VER
119     // there is a segfault when providing an error stream.
120     //  Apparently, calling setvbuf with a nul buffer is
121     //  not supported under msvc 7.1 ( code inside svn_cmdline_init )
122     if (svn_cmdline_init("terrasync", 0) != EXIT_SUCCESS)
123         return EXIT_FAILURE;
124 #else
125     if (svn_cmdline_init("terrasync", stderr) != EXIT_SUCCESS)
126         return EXIT_FAILURE;
127 #endif
128     apr_pool_t *pool;
129     apr_pool_create(&pool, NULL);
130     svn_error_t *err = NULL;
131     SVN_VERSION_DEFINE(mysvn_version);
132     err = svn_ver_check_list(&mysvn_version, mysvn_checklist);
133     if (err)
134         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
135     err = svn_ra_initialize(pool);
136     if (err)
137         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
138     char *config_dir = NULL;
139     err = svn_config_ensure(config_dir, pool);
140     if (err)
141         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
142     err = svn_client_create_context(&mysvn_ctx, pool);
143     if (err)
144         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
145     err = svn_config_get_config(&(mysvn_ctx->config),
146         config_dir, pool);
147     if (err)
148         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
149     svn_config_t *cfg;
150     cfg = ( svn_config_t*) apr_hash_get(
151         mysvn_ctx->config,
152         SVN_CONFIG_CATEGORY_CONFIG,
153         APR_HASH_KEY_STRING);
154     if (err)
155         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
156     svn_auth_baton_t *ab;
157     err = svn_cmdline_setup_auth_baton(&ab,
158         TRUE, NULL, NULL, config_dir, TRUE, cfg,
159         mysvn_ctx->cancel_func, mysvn_ctx->cancel_baton, pool);
160     if (err)
161         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
162     mysvn_ctx->auth_baton = ab;
163     mysvn_ctx->conflict_func = NULL;
164     mysvn_ctx->conflict_baton = NULL;
165     mysvn_rev = (svn_opt_revision_t*) apr_palloc(pool, 
166         sizeof(svn_opt_revision_t));
167     if (!mysvn_rev)
168         return EXIT_FAILURE;
169     mysvn_rev->kind = svn_opt_revision_head;
170     // Success if we got this far
171     mysvn_pool = pool;
172     return EXIT_SUCCESS;
173 }
174
175 #endif
176
177 // sync one directory tree
178 void sync_tree(const char* dir) {
179     int rc;
180     char command[512];
181     SGPath path( dest_base );
182
183     path.append( dir );
184     rc = path.create_dir( 0755 );
185     if (rc) {
186         cout << "Return code = " << rc << endl;
187         exit(1);
188     }
189
190     if (use_svn) {
191 #ifdef HAVE_SVN_CLIENT_H
192         cout << dir << " ... ";
193         cout.flush();
194         char dest_base_dir[512];
195         snprintf( command, 512,
196             "%s/%s", source_base, dir);
197         snprintf( dest_base_dir, 512,
198             "%s/%s", dest_base, dir);
199         svn_error_t *err = NULL;
200         if (mysvn_setup() != EXIT_SUCCESS)
201             exit(1);
202         apr_pool_t *subpool = svn_pool_create(mysvn_pool);
203         err = svn_client_checkout(NULL,
204             command,
205             dest_base_dir,
206             mysvn_rev,
207             1,
208             mysvn_ctx,
209             subpool);
210         if (err) {
211             // Report errors from the checkout attempt
212             cout << "failed: " << endl
213                  << err->message << endl;
214             svn_error_clear(err);
215             return;
216         } else {
217             cout << "done" << endl;
218         }
219         svn_pool_destroy(subpool);
220         return;
221 #else
222
223         snprintf( command, 512,
224             "%s %s/%s %s/%s", svn_cmd,
225             source_base, dir,
226             dest_base, dir );
227 #endif
228     } else {
229         snprintf( command, 512,
230             "%s %s/%s/ %s/%s/", rsync_cmd,
231             source_base, dir,
232             dest_base, dir );
233     }
234     cout << command << endl;
235     rc = system( command );
236     if (rc) {
237         cout << "Return code = " << rc << endl;
238         if (rc == 5120) exit(1);
239     }
240 }
241
242
243 const int nowhere = -9999;
244
245 // parse message
246 static void parse_message( const string &msg, int *lat, int *lon ) {
247     double dlat, dlon;
248     string text = msg;
249
250     // find GGA string and advance to start of lat
251     string::size_type pos = text.find( "$GPGGA" );
252     if ( pos == string::npos )
253     {
254         *lat = -9999.0;
255         *lon = -9999.0;
256         return;
257     }
258     string tmp = text.substr( pos + 7 );
259     pos = tmp.find( "," );
260     tmp = tmp.substr( pos + 1 );
261     // cout << "-> " << tmp << endl;
262
263     // find lat then advance to start of hemisphere
264     pos = tmp.find( "," );
265     string lats = tmp.substr( 0, pos );
266     dlat = atof( lats.c_str() ) / 100.0;
267     tmp = tmp.substr( pos + 1 );
268
269     // find N/S hemisphere and advance to start of lon
270     if ( tmp.substr( 0, 1 ) == "S" ) {
271         dlat = -dlat;
272     }
273     pos = tmp.find( "," );
274     tmp = tmp.substr( pos + 1 );
275
276     // find lon
277     pos = tmp.find( "," );
278     string lons = tmp.substr( 0, pos );
279     dlon = atof( lons.c_str() ) / 100.0;
280     tmp = tmp.substr( pos + 1 );
281
282     // find E/W hemisphere and advance to start of lon
283     if ( tmp.substr( 0, 1 ) == "W" ) {
284         dlon = -dlon;
285     }
286
287     if ( dlat < 0 ) {
288         *lat = (int)dlat - 1;
289     } else {
290         *lat = (int)dlat;
291     }
292
293     if ( dlon < 0 ) {
294         *lon = (int)dlon - 1;
295     } else {
296         *lon = (int)dlon;
297     }
298
299     if ((dlon == 0) && (dlat == 0)) {
300       *lon = nowhere;
301       *lat = nowhere;
302     }
303 }
304
305
306 // sync area
307 static void sync_area( int lat, int lon ) {
308     if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
309         return;
310     char NS, EW;
311     int baselat, baselon;
312
313     if ( lat < 0 ) {
314         int base = (int)(lat / 10);
315         if ( lat == base * 10 ) {
316             baselat = base * 10;
317         } else {
318             baselat = (base - 1) * 10;
319         }
320         NS = 's';
321     } else {
322         baselat = (int)(lat / 10) * 10;
323         NS = 'n';
324     }
325     if ( lon < 0 ) {
326         int base = (int)(lon / 10);
327         if ( lon == base * 10 ) {
328             baselon = base * 10;
329         } else {
330             baselon = (base - 1) * 10;
331         }
332         EW = 'w';
333     } else {
334         baselon = (int)(lon / 10) * 10;
335         EW = 'e';
336     }
337
338     const char* terrainobjects[3] = { "Terrain", "Objects", 0 };
339     
340     for (const char** tree = &terrainobjects[0]; *tree; tree++) {
341         char dir[512];
342         snprintf( dir, 512, "%s/%c%03d%c%02d/%c%03d%c%02d",
343                 *tree,
344                 EW, abs(baselon), NS, abs(baselat),
345                 EW, abs(lon), NS, abs(lat) );
346         waitingTiles.push_back( dir );
347     }
348 }
349
350
351 // sync areas
352 static void sync_areas( int lat, int lon, int lat_dir, int lon_dir ) {
353     // do current 1x1 degree area first
354     sync_area( lat, lon );
355
356     if ( lat_dir == 0 && lon_dir == 0 ) {
357         // now do surrounding 8 1x1 degree areas.
358         for ( int i = lat - 1; i <= lat + 1; ++i ) {
359             for ( int j = lon - 1; j <= lon + 1; ++j ) {
360                 if ( i != lat || j != lon ) {
361                     sync_area( i, j );
362                 }
363             }
364         }
365     } else {
366         if ( lat_dir != 0 ) {
367             sync_area( lat + lat_dir, lon );
368             sync_area( lat + lat_dir, lon - 1 );
369             sync_area( lat + lat_dir, lon + 1 );
370         }
371         if ( lon_dir != 0 ) {
372             sync_area( lat, lon + lon_dir );
373             sync_area( lat - 1, lon + lon_dir );
374             sync_area( lat + 1, lon + lon_dir );
375         }
376     }
377 }
378
379 void getWaitingTile() {
380     while ( !waitingTiles.empty() ) {
381         CompletedTiles::iterator ii = completedTiles.find( waitingTiles.front() );
382         time_t now = time(0);
383         if ( ii == completedTiles.end() || ii->second + 600 < now ) {
384             sync_tree(waitingTiles.front().c_str());
385             completedTiles[ waitingTiles.front() ] = now;
386             waitingTiles.pop_front();
387             break;
388         }
389         waitingTiles.pop_front();
390     }
391 }
392
393 int main( int argc, char **argv ) {
394     int port = 5501;
395     char host[256] = "";        // accept messages from anyone
396     bool testing = false;
397
398     // parse arguments
399     int i = 1;
400     while ( i < argc ) {
401         if ( (string)argv[i] == "-p" ) {
402             ++i;
403             port = atoi( argv[i] );
404         } else if ( (string)argv[i] == "-s" ) {
405             ++i;
406             source_base = argv[i];
407         } else if ( (string)argv[i] == "-d" ) {
408             ++i;
409             dest_base = argv[i];
410         } else if ( (string)argv[i] == "-R" ) {
411             use_svn = false;
412         } else if ( (string)argv[i] == "-S" ) {
413             use_svn = true;
414         } else if ( (string)argv[i] == "-T" ) {
415             testing = true;
416         } else {
417             usage( argv[0] );
418             exit(-1);        
419         }
420         ++i;
421     }
422
423     // Use the appropriate default for the "-s" flag
424     if (source_base == NULL) {
425         if (use_svn)
426             source_base = svn_base;
427         else
428             source_base = rsync_base;
429     }
430     
431     // We just want one grid square, no FGFS communications
432     if (testing) {
433           sync_areas( 37, -123, 0, 0 );
434           exit(0);
435     }
436
437     // Must call this before any other net stuff
438     netInit( &argc,argv );
439
440     netSocket s;
441
442     if ( ! s.open( false ) ) {  // open a UDP socket
443         printf("error opening socket\n");
444         return -1;
445     }
446
447     s.setBlocking( false );
448
449     if ( s.bind( host, port ) == -1 ) {
450         printf("error binding to port %d\n", port);
451         return -1;
452     }
453
454     char msg[256];
455     int maxlen = 256;
456     int len;
457     int lat, lon;
458     int last_lat = nowhere;
459     int last_lon = nowhere;
460     bool recv_msg = false;
461     char synced_other = 'K';
462
463     while ( true ) {
464         recv_msg = false;
465         while ( (len = s.recv(msg, maxlen, 0)) >= 0 ) {
466             msg[len] = '\0';
467             recv_msg = true;
468
469             parse_message( msg, &lat, &lon );
470         }
471
472         if ( recv_msg ) {
473             if ( lat != last_lat || lon != last_lon ) {
474                 cout << "pos in msg = " << lat << "," << lon << endl;
475                 std::deque<std::string> oldRequests;
476                 oldRequests.swap( waitingTiles );
477                 int lat_dir, lon_dir, dist;
478                 if ( last_lat == nowhere || last_lon == nowhere ) {
479                     lat_dir = lon_dir = 0;
480                 } else {
481                     dist = lat - last_lat;
482                     if ( dist != 0 ) {
483                         lat_dir = dist / abs(dist);
484                     } else {
485                         lat_dir = 0;
486                     }
487                     dist = lon - last_lon;
488                     if ( dist != 0 ) {
489                         lon_dir = dist / abs(dist);
490                     } else {
491                         lon_dir = 0;
492                     }
493                 }
494                 cout << "lat = " << lat << " lon = " << lon << endl;
495                 cout << "lat_dir = " << lat_dir << "  "
496                      << "lon_dir = " << lon_dir << endl;
497                 sync_areas( lat, lon, lat_dir, lon_dir );
498                 while ( !oldRequests.empty() ) {
499                     waitingTiles.push_back( oldRequests.front() );
500                     oldRequests.pop_front();
501                 }
502             } else if ( !waitingTiles.empty() ) {
503                 getWaitingTile();
504             } else {
505                 if ( last_lat == nowhere || last_lon == nowhere ) {
506                     cout << "Waiting for FGFS to finish startup" << endl;
507                 }
508                 char c;
509                 while ( !isdigit( c = synced_other++ ) && !isupper( c ) );
510
511                 char dir[512];
512                 snprintf( dir, 512, "Airports/%c", c );
513                 waitingTiles.push_back( dir );
514             }
515
516             last_lat = lat;
517             last_lon = lon;
518         } else if ( !waitingTiles.empty() ) {
519             getWaitingTile();
520         } 
521
522         ulSleep( 1 );
523     } // while true
524         
525     return 0;
526 }