2 * Navit, a modular navigation system.
3 * Copyright (C) 2005-2008 Navit Team
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * version 2 as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the
16 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
21 #define _FILE_OFFSET_BITS 64
22 #define _LARGEFILE_SOURCE
23 #define _LARGEFILE64_SOURCE
39 #ifdef HAVE_POSTGRESQL
43 #define BUFFER_SIZE 1280
45 #define GENERATE_INDEX
48 #define debug_tile(x) 0
50 #define debug_tile(x) (!strcmp(x,"bcdbd") || !strcmp(x,"bcdbd") || !strcmp(x,"bcdbda") || !strcmp(x,"bcdbdb") || !strcmp(x,"bcdbdba") || !strcmp(x,"bcdbdbb") || !strcmp(x,"bcdbdbba") || !strcmp(x,"bcdbdbaa") || !strcmp(x,"bcdbdbacaa") || !strcmp(x,"bcdbdbacab") || !strcmp(x,"bcdbdbacaba") || !strcmp(x,"bcdbdbacabaa") || !strcmp(x,"bcdbdbacabab") || !strcmp(x,"bcdbdbacababb") || !strcmp(x,"bcdbdbacababba") || !strcmp(x,"bcdbdbacababbb") || !strcmp(x,"bcdbdbacababbd") || !strcmp(x,"bcdbdbacababaa") || !strcmp(x,"bcdbdbacababab") || !strcmp(x,"bcdbdbacababac") || !strcmp(x,"bcdbdbacababad") || !strcmp(x,"bcdbdbacabaaa") || !strcmp(x,"bcdbdbacabaaba") || !strcmp(x,"bcdbdbacabaabb") || !strcmp(x,"bcdbdbacabaabc") || !strcmp(x,"bcdbdbacabaabd") || !strcmp(x,"bcdbdbacabaaaa") || !strcmp(x,"bcdbdbacabaaab") || !strcmp(x,"bcdbdbacabaaac") || !strcmp(x,"bcdbdbacabaaad") || 0)
53 #define IS_TOWN(item) ((item).type >= type_town_label && (item).type <= type_town_label_1e7)
54 #define IS_STREET(item) ((item).type >= type_street_nopass && (item).type <= type_ferry)
56 static GHashTable *dedupe_ways_hash;
58 static int attr_debug_level=1;
59 static int nodeid,wayid;
60 static int report,phase;
61 static int ignore_unkown = 0, coverage=0;
63 static char *attrmap={
65 "n amenity=hospital poi_hospital\n"
66 "n amenity=atm poi_bank\n"
67 "n amenity=bank poi_bank\n"
68 "n amenity=pub poi_bar\n"
69 "n amenity=cafe poi_cafe\n"
70 "n amenity=bus_station poi_bus_station\n"
71 "n amenity=parking poi_car_parking\n"
72 "n amenity=cinema poi_cinema\n"
73 "n amenity=fire_station poi_firebrigade\n"
74 "n amenity=fuel poi_fuel\n"
75 "n amenity=courthouse poi_justice\n"
76 "n amenity=library poi_library\n"
77 "n amenity=pharmacy poi_pharmacy\n"
78 "n amenity=place_of_worship,religion=christian poi_church\n"
79 "n amenity=police poi_police\n"
80 "n amenity=post_office poi_post\n"
81 "n amenity=post_box poi_post\n"
82 "n amenity=public_building poi_public_office\n"
83 "n amenity=restaurant poi_restaurant\n"
84 "n amenity=fast_food poi_fastfood\n"
85 "n amenity=toilets poi_restroom\n"
86 "n amenity=school poi_school\n"
87 "n amenity=university poi_school\n"
88 "n amenity=college poi_school\n"
89 "n amenity=telephone poi_telephone\n"
90 "n amenity=theatre poi_theater\n"
91 "n amenity=townhall poi_townhall\n"
92 "n highway=bus_stop poi_bus_stop\n"
93 "n highway=mini_roundabout mini_roundabout\n"
94 "n highway=motorway_junction highway_exit\n"
95 "n highway=traffic_signals traffic_signals\n"
96 "n highway=turning_circle turning_circle\n"
97 "n leisure=slipway poi_boat_ramp\n"
98 "n leisure=fishing poi_fish\n"
99 "n sport=golf poi_golf\n"
100 "n leisure=golf_course poi_golf\n"
101 "n leisure=marina poi_marine\n"
102 "n leisure=sports_centre poi_sport\n"
103 "n leisure=stadium poi_stadium\n"
104 "n shop=supermarket poi_shopping\n"
105 "n shop=convenience poi_shop_grocery\n"
106 "n tourism=attraction poi_attraction\n"
107 "n tourism=camp_site poi_camp_rv\n"
108 "n tourism=caravan_site poi_camp_rv\n"
109 "n tourism=hotel poi_hotel\n"
110 "n tourism=motel poi_hotel\n"
111 "n tourism=guest_house poi_hotel\n"
112 "n tourism=hostel poi_hotel\n"
113 "n tourism=information poi_information\n"
114 "n tourism=museum poi_museum_history\n"
115 "n tourism=picnic_site poi_picnic\n"
116 "n tourism=theme_park poi_resort\n"
117 "n tourism=zoo poi_zoo\n"
118 "n amenity=grave_yard poi_cemetery\n"
119 "n landuse=cemetery poi_cemetery\n"
120 "n military=airfield poi_military\n"
121 "n military=bunker poi_military\n"
122 "n military=barracks poi_military\n"
123 "n military=range poi_military\n"
124 "n military=danger_area poi_danger_area\n"
125 "n sport=swimming poi_swimming\n"
126 "n sport=skiing poi_skiing\n"
127 "n aeroway=aerodrome poi_airport\n"
128 "n aeroway=airport poi_airport\n"
129 "n aeroway=terminal poi_airport\n"
130 "n aeroway=helipad poi_heliport\n"
131 "n man_made=tower poi_tower\n"
132 "n natural=bay poi_bay\n"
133 "n natural=peak poi_peak\n"
134 "n place=suburb district_label\n"
135 "n place=city town_label_2e5\n"
136 "n place=town town_label_2e4\n"
137 "n place=village town_label_2e3\n"
138 "n place=hamlet town_label_2e2\n"
139 "n place=locality town_label_2e0\n"
140 "n railway=halt poi_rail_halt\n"
141 "n railway=level_crossing poi_level_crossing\n"
142 "n railway=station poi_rail_station\n"
143 "n railway=tram_stop poi_rail_tram_stop\n"
144 "w *=* street_unkn\n"
145 "w amenity=place_of_worship poly_building\n"
146 "w building=* poly_building\n"
147 "w aeroway=aerodrome poly_airport\n"
148 "w aeroway=apron poly_apron\n"
149 "w aeroway=runway aeroway_runway\n"
150 "w aeroway=taxiway aeroway_taxiway\n"
151 "w aeroway=terminal poly_terminal\n"
152 "w highway=bridleway bridleway\n"
153 "w highway=cycleway cycleway\n"
154 "w highway=cyclepath cycleway\n"
155 "w highway=footway footway\n"
156 "w highway=steps steps\n"
157 "w highway=unsurfaced track_gravelled\n"
158 "w highway=track track_gravelled\n"
159 "w highway=track,tracktype=grade1 track_paved\n"
160 "w highway=track,surface=paved track_paved\n"
161 "w highway=track,tracktype=grade2 track_gravelled\n"
162 "w highway=track,surface=gravel track_gravelled\n"
163 "w highway=track,tracktype=grade3 track_unpaved\n"
164 "w highway=track,surface=unpaved track_unpaved\n"
165 "w highway=track,tracktype=grade4 track_ground\n"
166 "w highway=track,surface=ground track_ground\n"
167 "w highway=track,tracktype=grade5 track_grass\n"
168 "w highway=track,surface=grass track_grass\n"
169 "w highway=service street_service\n"
170 "w highway=construction street_construction\n"
171 "w highway=pedestrian street_pedestrian\n"
172 "w highway=pedestrian,area=1 poly_pedestrian\n"
173 "w highway=plaza poly_plaza\n"
174 "w landuse=plaza poly_plaza\n"
175 "w highway=residential street_1_city\n"
176 "w highway=living_street living_street\n"
177 "w highway=unclassified street_1_city\n"
178 "w highway=road street_1_city\n"
179 "w highway=minor street_1_land\n"
180 "w highway=tertiary street_2_city\n"
181 "w highway=tertiary_link ramp\n"
182 "w highway=secondary street_3_city\n"
183 "w highway=secondary_link ramp\n"
184 "w highway=primary street_4_city\n"
185 "w highway=primary_link ramp\n"
186 "w highway=trunk street_4_city\n"
187 "w highway=trunk_link ramp\n"
188 "w highway=motorway highway_city\n"
189 "w highway=motorway_link ramp\n"
190 "w historic=town gate poly_building\n"
191 "w cycleway=track cycleway\n"
192 "w amenity=parking poly_car_parking\n"
193 "w landuse=allotments poly_allotments\n"
194 "w landuse=cemetery poly_cemetery\n"
195 "w amenity=grave_yard poly_cemetery\n"
196 "w landuse=forest poly_wood\n"
197 "w landuse=industrial poly_industry\n"
198 "w landuse=residential poly_town\n"
199 "w landuse=residential,area=1 poly_town\n"
200 "w amenity=college poly_college\n"
201 "w amenity=university poly_university\n"
202 "w tourism=camp_site poly_camp_site\n"
203 "w tourism=caravan_site poly_caravan_site\n"
204 "w tourism=picnic_site poly_picnic_site\n"
205 "w tourism=theme_park poly_theme_park\n"
206 "w tourism=attraction poly_attraction\n"
207 "w tourism=zoo poly_zoo\n"
208 "w tourism=artwork poly_artwork\n"
209 "w historic=archaeological_site poly_archaeological_site\n"
210 "w historic=ruins poly_ruins\n"
211 "w historic=battlefield poly_battlefield\n"
212 "w landuse=quarry poly_quarry\n"
213 "w landuse=landfill poly_landfill\n"
214 "w landuse=retail poly_retail\n"
215 "w landuse=commercial poly_commercial\n"
216 "w landuse=brownfield poly_brownfield\n"
217 "w landuse=greenfield poly_greenfield\n"
218 "w landuse=construction poly_construction\n"
219 "w landuse=railway poly_railway\n"
220 "w natural=glacier poly_glacier\n"
221 "w natural=scree poly_scree\n"
222 "w natural=scrub poly_scrub\n"
223 "w natural=fell poly_fell\n"
224 "w natural=heath poly_heath\n"
225 "w natural=marsh poly_marsh\n"
226 "w natural=mud poly_mud\n"
227 "w natural=beach poly_beach\n"
228 "w natural=land poly_land\n"
229 "w landuse=basin poly_basin\n"
230 "w landuse=reservoir poly_reservoir\n"
231 "w landuse=farm poly_farm\n"
232 "w landuse=vineyard poly_farm\n"
233 "w leisure=park poly_park\n"
234 "w landuse=village_green poly_village_green\n"
235 "w landuse=recreation_ground poly_recreation_ground\n"
236 "w natural=wood poly_wood\n"
237 "w natural=water poly_water\n"
238 "w natural=coastline water_line\n"
239 "w place=suburb poly_town\n"
240 "w place=town poly_town\n"
241 "w landuse=military poly_military\n"
242 "w military=airfield poly_airfield\n"
243 "w military=barracks poly_barracks\n"
244 "w military=danger_area poly_danger_area\n"
245 "w military=range poly_range\n"
246 "w military=naval_base poly_naval_base\n"
247 "w power=line powerline\n"
248 "w railway=rail rail\n"
249 "w railway=narrow_gauge rail_narrow_gauge\n"
250 "w railway=light_rail rail_light\n"
251 "w railway=subway rail_subway\n"
252 "w railway=tram rail_tram\n"
253 "w railway=monorail rail_mono\n"
254 "w railway=preserved rail_preserved\n"
255 "w railway=disused rail_disused\n"
256 "w railway=abandoned rail_abandoned\n"
257 "w aerialway=cable_car lift_cable_car\n"
258 "w aerialway=chair_lift lift_chair\n"
259 "w aerialway=drag_lift lift_drag\n"
260 "w leisure=golf_course poly_golf_course\n"
261 "w sport=* poly_sport\n"
262 "w leisure=sports_centre poly_sport\n"
263 "w leisure=stadium poly_sports_stadium\n"
264 "w leisure=track poly_sports_track\n"
265 "w leisure=pitch poly_sports_pitch\n"
266 "w leisure=water_park poly_water_park\n"
267 "w leisure=marina poly_marina\n"
268 "w leisure=fishing poly_fishing\n"
269 "w leisure=garden poly_garden\n"
270 "w leisure=common poly_common\n"
271 "w leisure=playground poly_playground\n"
272 "w leisure=nature_reserve poly_nature_reserve\n"
273 "w waterway=canal water_canal\n"
274 "w waterway=river water_river\n"
275 "w waterway=stream water_stream\n"
276 "w waterway=drain water_drain\n"
277 "w waterway=riverbank poly_water\n"
278 "w boundary=administrative border_country\n"
279 "w boundary=civil border_civil\n"
280 "w boundary=political border_political\n"
281 "w boundary=national_park border_national_park\n"
282 "w route=ferry ferry\n"
283 "w highway=bus_guideway bus_guideway\n"
289 } coord_buffer[65536];
291 #define IS_REF(c) ((c).x >= (1 << 30))
292 #define REF(c) ((c).y)
293 #define SET_REF(c,ref) do { (c).x = 1 << 30; (c).y = ref ; } while(0)
299 static void bbox_extend(struct coord *c, struct rect *r);
301 #ifdef GENERATE_INDEX
303 static GHashTable *aux_tile_hash;
304 GList *aux_tile_list;
306 struct country_table {
313 } country_table[] = {
314 { 40,"Austria,Österreich,AUT"},
316 {276,"Germany,Deutschland,Bundesrepublik Deutschland"},
317 {528,"Nederland,The Netherlands,Niederlande,NL"},
321 static GHashTable *country_table_hash;
324 struct attr_mapping {
326 int attr_present_idx_count;
327 int attr_present_idx[0];
330 static struct attr_mapping **attr_mapping_node;
331 static int attr_mapping_node_count;
332 static struct attr_mapping **attr_mapping_way;
333 static int attr_mapping_way_count;
335 static char *attr_present;
336 static int attr_present_count;
337 static GHashTable *attr_hash;
340 static GHashTable *strings_hash = NULL;
343 static char* string_hash_lookup( const char* key )
345 char* key_ptr = NULL;
347 if ( strings_hash == NULL ) {
348 strings_hash = g_hash_table_new(g_str_hash, g_str_equal);
351 if ( ( key_ptr = g_hash_table_lookup(strings_hash, key )) == NULL ) {
352 key_ptr = g_strdup( key );
353 g_hash_table_insert(strings_hash, key_ptr, (gpointer)key_ptr );
360 build_attrmap_line(char *line)
362 char *t=NULL,*kvl=NULL,*i=NULL,*p,*kv;
363 struct attr_mapping ***attr_mapping_curr,*attr_mapping=g_malloc0(sizeof(struct attr_mapping));
364 int idx,attr_mapping_count=0,*attr_mapping_curr_count;
381 attr_mapping_curr=&attr_mapping_way;
382 attr_mapping_curr_count=&attr_mapping_way_count;
386 attr_mapping_curr=&attr_mapping_node;
387 attr_mapping_curr_count=&attr_mapping_node_count;
389 attr_mapping->type=item_from_name(i);
390 while ((kv=strtok(kvl, ","))) {
392 if (!(idx=(int)g_hash_table_lookup(attr_hash, kv))) {
393 idx=attr_present_count++;
394 g_hash_table_insert(attr_hash, kv, (gpointer) idx);
396 attr_mapping=g_realloc(attr_mapping, sizeof(struct attr_mapping)+(attr_mapping_count+1)*sizeof(int));
397 attr_mapping->attr_present_idx[attr_mapping_count++]=idx;
398 attr_mapping->attr_present_idx_count=attr_mapping_count;
400 *attr_mapping_curr=g_realloc(*attr_mapping_curr, sizeof(**attr_mapping_curr)*(*attr_mapping_curr_count+1));
401 (*attr_mapping_curr)[(*attr_mapping_curr_count)++]=attr_mapping;
405 build_attrmap(char *map)
408 attr_hash=g_hash_table_new(g_str_hash, g_str_equal);
409 attr_present_count=1;
415 build_attrmap_line(map);
418 attr_present=g_malloc0(sizeof(*attr_present)*attr_present_count);
421 #ifdef GENERATE_INDEX
423 build_countrytable(void)
426 char *names,*str,*tok;
427 country_table_hash=g_hash_table_new(g_str_hash, g_str_equal);
428 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
429 names=g_strdup(country_table[i].names);
431 while ((tok=strtok(str, ","))) {
433 g_hash_table_insert(country_table_hash, tok, (gpointer)&country_table[i]);
441 static int processed_nodes, processed_nodes_out, processed_ways, processed_relations, processed_tiles;
442 static int in_way, in_node, in_relation;
448 signal(SIGALRM, sig_alrm);
451 fprintf(stderr,"PROGRESS%d: Processed %d nodes (%d out) %d ways %d relations %d tiles\n", phase, processed_nodes, processed_nodes_out, processed_ways, processed_relations, processed_tiles);
465 struct attr_bin label_attr = {
468 char label_attr_buffer[BUFFER_SIZE];
470 struct attr_bin town_name_attr = {
474 struct attr_bin street_name_attr = {
478 struct attr_bin street_name_systematic_attr = {
479 0, attr_street_name_systematic
481 char street_name_systematic_attr_buffer[BUFFER_SIZE];
483 struct attr_bin debug_attr = {
486 char debug_attr_buffer[BUFFER_SIZE];
488 struct attr_bin flags_attr = {
491 int flags_attr_value;
493 char is_in_buffer[BUFFER_SIZE];
496 static void write_zipmember(FILE *out, FILE *dir_out, char *name, int filelen, char *data, int data_size, int compression_level);
499 pad_text_attr(struct attr_bin *a, char *buffer)
502 if (buffer && buffer[0]) {
512 xml_get_attribute(char *xml, char *attribute, char *buffer, int buffer_size)
514 int len=strlen(attribute);
515 char *pos,*i,s,attr[len+2];
516 strcpy(attr, attribute);
517 strcpy(attr+len, "=");
518 pos=strstr(xml, attr);
528 if (i - pos > buffer_size) {
529 fprintf(stderr,"Buffer overflow %d vs %d\n", i-pos, buffer_size);
532 strncpy(buffer, pos, i-pos);
537 static int node_is_tagged;
540 add_tag(char *k, char *v)
542 GHashTable *value_hash;
545 char buffer[BUFFER_SIZE*2+2];
546 if (! strcmp(k,"ele"))
548 if (! strcmp(k,"time"))
550 if (! strcmp(k,"created_by"))
552 if (! strncmp(k,"tiger:",6) || !strcmp(k,"AND_nodes"))
554 if (! strcmp(k,"converted_by") || ! strcmp(k,"source"))
556 if (! strncmp(k,"osmarender:",11) || !strncmp(k,"svg:",4))
558 if (! strcmp(k,"layer"))
560 if (! strcasecmp(v,"true") || ! strcasecmp(v,"yes"))
562 if (! strcmp(k,"oneway")) {
563 if (!strcmp(v,"1")) {
564 flags_attr_value=AF_ONEWAY;
567 if (! strcmp(v,"-1")) {
568 flags_attr_value=AF_ONEWAYREV;
576 if (! strcmp(k,"junction")) {
577 if (! strcmp(v,"roundabout")) {
578 flags_attr_value=AF_ONEWAY;
582 if (! strcmp(k,"maxspeed")) {
585 if (! strcmp(k,"bicycle")) {
588 if (! strcmp(k,"foot")) {
591 if (! strcmp(k,"note"))
593 if (! strcmp(k,"name")) {
594 strcpy(label_attr_buffer, v);
595 pad_text_attr(&label_attr, label_attr_buffer);
598 if (! strcmp(k,"ref")) {
600 strcpy(street_name_systematic_attr_buffer, v);
601 pad_text_attr(&street_name_systematic_attr, street_name_systematic_attr_buffer);
605 if (! strcmp(k,"is_in")) {
606 strcpy(is_in_buffer, v);
609 if (! strcmp(k,"lanes")) {
612 if (attr_debug_level >= level) {
613 int bytes_left = sizeof( debug_attr_buffer ) - strlen(debug_attr_buffer) - 1;
614 if ( bytes_left > 0 )
616 snprintf(debug_attr_buffer+strlen(debug_attr_buffer), bytes_left, " %s=%s", k, v);
617 debug_attr_buffer[ sizeof( debug_attr_buffer ) - 1 ] = '\0';
626 strcpy(buffer,"*=*");
627 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
630 sprintf(buffer,"%s=*", k);
631 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
634 sprintf(buffer,"*=%s", v);
635 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
638 sprintf(buffer,"%s=%s", k, v);
639 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
655 decode_entities(char *buffer)
660 while ((pos=strchr(pos, '&'))) {
662 for (i = 0 ; i < sizeof(entities)/sizeof(struct entity); i++) {
663 len=strlen(entities[i].entity);
664 if (!strncmp(pos, entities[i].entity, len)) {
666 memmove(pos+1, pos+len, strlen(pos+len)+1);
678 char k_buffer[BUFFER_SIZE];
679 char v_buffer[BUFFER_SIZE];
680 if (!xml_get_attribute(p, "k", k_buffer, BUFFER_SIZE))
682 if (!xml_get_attribute(p, "v", v_buffer, BUFFER_SIZE))
684 decode_entities(v_buffer);
685 add_tag(k_buffer, v_buffer);
697 static struct tile_head {
705 struct tile_head *next;
721 static struct buffer node_buffer = {
726 static char** th_get_subtile( const struct tile_head* th, int idx )
728 char* subtile_ptr = NULL;
729 subtile_ptr = (char*)th + sizeof( struct tile_head ) + idx * sizeof( char *);
730 return (char**)subtile_ptr;
734 extend_buffer(struct buffer *b)
736 b->malloced+=b->malloced_step;
737 b->base=realloc(b->base, b->malloced);
738 if (b->base == NULL) {
739 fprintf(stderr,"realloc of %d bytes failed\n",b->malloced);
746 GHashTable *node_hash;
749 node_buffer_to_hash(void)
751 int i,count=node_buffer.size/sizeof(struct node_item);
752 struct node_item *ni=(struct node_item *)node_buffer.base;
753 for (i = 0 ; i < count ; i++)
754 g_hash_table_insert(node_hash, (gpointer)(ni[i].id), (gpointer)i);
757 static struct node_item *ni;
760 add_node(int id, double lat, double lon)
762 if (node_buffer.size + sizeof(struct node_item) > node_buffer.malloced)
763 extend_buffer(&node_buffer);
766 item.type=type_point_unkn;
768 town_name_attr.len=0;
770 is_in_buffer[0]='\0';
771 sprintf(debug_attr_buffer,"nodeid=%d", nodeid);
772 ni=(struct node_item *)(node_buffer.base+node_buffer.size);
778 ni->c.x=lon*6371000.0*M_PI/180;
779 ni->c.y=log(tan(M_PI_4+lat*M_PI/360))*6371000.0;
780 node_buffer.size+=sizeof(struct node_item);
782 if (ni->id > nodeid_last) {
785 fprintf(stderr,"INFO: Nodes out of sequence (new %d vs old %d), adding hash\n", ni->id, nodeid_last);
786 node_hash=g_hash_table_new(NULL, NULL);
787 node_buffer_to_hash();
790 if (!g_hash_table_lookup(node_hash, (gpointer)(ni->id)))
791 g_hash_table_insert(node_hash, (gpointer)(ni->id), (gpointer)(ni-(struct node_item *)node_buffer.base));
793 node_buffer.size-=sizeof(struct node_item);
802 char id_buffer[BUFFER_SIZE];
803 char lat_buffer[BUFFER_SIZE];
804 char lon_buffer[BUFFER_SIZE];
805 if (!xml_get_attribute(p, "id", id_buffer, BUFFER_SIZE))
807 if (!xml_get_attribute(p, "lat", lat_buffer, BUFFER_SIZE))
809 if (!xml_get_attribute(p, "lon", lon_buffer, BUFFER_SIZE))
811 add_node(atoi(id_buffer), atof(lat_buffer), atof(lon_buffer));
816 static struct node_item *
817 node_item_get(int id)
819 struct node_item *ni=(struct node_item *)(node_buffer.base);
820 int count=node_buffer.size/sizeof(struct node_item);
821 int interval=count/4;
825 i=(int)(g_hash_table_lookup(node_hash, (gpointer)id));
828 while (ni[p].id != id) {
830 fprintf(stderr,"p=%d count=%d interval=%d id=%d ni[p].id=%d\n", p, count, interval, id, ni[p].id);
865 struct node_item *ni=node_item_get(id);
867 fprintf(stderr,"WARNING: node id %d not found\n", id);
879 item.type=type_street_unkn;
881 street_name_attr.len=0;
882 street_name_systematic_attr.len=0;
885 sprintf(debug_attr_buffer,"wayid=%d", wayid);
891 char id_buffer[BUFFER_SIZE];
892 if (!xml_get_attribute(p, "id", id_buffer, BUFFER_SIZE))
894 add_way(atoi(id_buffer));
899 parse_relation(char *p)
901 debug_attr_buffer[0]='\0';
906 write_attr(FILE *out, struct attr_bin *attr, void *buffer)
909 fwrite(attr, sizeof(*attr), 1, out);
910 fwrite(buffer, (attr->len-1)*4, 1, out);
915 attr_longest_match(struct attr_mapping **mapping, int mapping_count, enum item_type *types, int types_count)
917 int i,j,longest=0,ret=0,sum,val;
918 struct attr_mapping *curr;
919 for (i = 0 ; i < mapping_count ; i++) {
922 for (j = 0 ; j < curr->attr_present_idx_count ; j++) {
923 val=attr_present[curr->attr_present_idx[j]];
935 if (sum > 0 && sum == longest && ret < types_count)
936 types[ret++]=curr->type;
938 memset(attr_present, 0, sizeof(*attr_present)*attr_present_count);
946 enum item_type types[5];
950 if (dedupe_ways_hash) {
951 if (g_hash_table_lookup(dedupe_ways_hash, (gpointer)wayid))
953 g_hash_table_insert(dedupe_ways_hash, (gpointer)wayid, (gpointer)1);
955 count=attr_longest_match(attr_mapping_way, attr_mapping_way_count, types, sizeof(types)/sizeof(enum item_type));
956 pad_text_attr(&debug_attr, debug_attr_buffer);
958 alen+=label_attr.len+1;
959 if (street_name_systematic_attr.len)
960 alen+=street_name_systematic_attr.len+1;
962 alen+=debug_attr.len+1;
964 alen+=flags_attr.len+1;
968 item.type=type_street_unkn;
969 if (coverage && IS_STREET(item))
970 item.type=type_coverage;
971 item.clen=coord_count*2;
972 item.len=item.clen+2+alen;
973 fwrite(&item, sizeof(item), 1, out);
974 fwrite(coord_buffer, coord_count*sizeof(struct coord), 1, out);
975 if (IS_STREET(item)) {
976 street_name_attr.len=label_attr.len;
977 write_attr(out, &street_name_attr, label_attr_buffer);
979 write_attr(out, &label_attr, label_attr_buffer);
980 write_attr(out, &street_name_systematic_attr, street_name_systematic_attr_buffer);
981 write_attr(out, &debug_attr, debug_attr_buffer);
982 write_attr(out, &flags_attr, &flags_attr_value);
988 int alen=0,conflict=0,count;
989 enum item_type types[5];
990 struct country_table *result=NULL, *lookup;
991 if (!out || ! node_is_tagged || ! nodeid)
993 count=attr_longest_match(attr_mapping_node, attr_mapping_node_count, types, sizeof(types)/sizeof(enum item_type));
994 pad_text_attr(&debug_attr, debug_attr_buffer);
996 alen+=label_attr.len+1;
998 alen+=debug_attr.len+1;
1002 item.type=type_point_unkn;
1004 item.len=item.clen+2+alen;
1005 fwrite(&item, sizeof(item), 1, out);
1006 fwrite(&ni->c, 1*sizeof(struct coord), 1, out);
1007 if (IS_TOWN(item)) {
1008 town_name_attr.len=label_attr.len;
1009 write_attr(out, &town_name_attr, label_attr_buffer);
1011 write_attr(out, &label_attr, label_attr_buffer);
1012 write_attr(out, &debug_attr, debug_attr_buffer);
1013 #ifdef GENERATE_INDEX
1014 if (IS_TOWN(item) && town_name_attr.len) {
1015 char *tok,*buf=is_in_buffer;
1016 while ((tok=strtok(buf, ","))) {
1019 lookup=g_hash_table_lookup(country_table_hash,tok);
1021 if (result && result->countryid != lookup->countryid) {
1022 fprintf(stderr,"conflict for %s %s country %d vs %d\n", label_attr_buffer, debug_attr_buffer, lookup->countryid, result->countryid);
1029 if (result && !conflict) {
1030 if (!result->file) {
1031 char *name=g_strdup_printf("country_%d.bin.unsorted", result->countryid);
1032 result->file=fopen(name,"w");
1037 item.len=item.clen+2+label_attr.len+1;
1038 fwrite(&item, sizeof(item), 1, result->file);
1039 fwrite(&ni->c, 1*sizeof(struct coord), 1, result->file);
1040 write_attr(result->file, &town_name_attr, label_attr_buffer);
1042 result->size+=(item.clen+3+label_attr.len+1)*4;
1048 processed_nodes_out++;
1052 sort_countries_compare(const void *p1, const void *p2)
1054 struct item_bin *ib1=*((struct item_bin **)p1),*ib2=*((struct item_bin **)p2);
1055 struct attr_bin *attr1,*attr2;
1057 assert(ib1->clen==2);
1058 assert(ib2->clen==2);
1059 attr1=(struct attr_bin *)((int *)(ib1+1)+ib1->clen);
1060 attr2=(struct attr_bin *)((int *)(ib2+1)+ib1->clen);
1061 assert(attr1->type == attr_town_name);
1062 assert(attr2->type == attr_town_name);
1063 s1=(char *)(attr1+1);
1064 s2=(char *)(attr2+1);
1065 return strcmp(s1, s2);
1067 fprintf(stderr,"sort_countries_compare p1=%p p2=%p %s %s\n",p1,p2,s1,s2);
1072 #ifdef GENERATE_INDEX
1074 sort_countries(void)
1077 struct country_table *co;
1079 struct item_bin *ib;
1081 char *p,*buffer,**idx,*name;
1082 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
1083 co=&country_table[i];
1089 buffer=malloc(co->size);
1090 assert(buffer != NULL);
1091 idx=malloc(co->count*sizeof(void *));
1092 assert(idx != NULL);
1093 name=g_strdup_printf("country_%d.bin.unsorted", co->countryid);
1096 fread(buffer, co->size, 1, f);
1101 for (j = 0 ; j < co->count ; j++) {
1103 p+=(*((int *)p)+1)*4;
1105 qsort(idx, co->count, sizeof(void *), sort_countries_compare);
1106 name=g_strdup_printf("country_%d.bin", co->countryid);
1108 for (j = 0 ; j < co->count ; j++) {
1109 ib=(struct item_bin *)(idx[j]);
1110 c=(struct coord *)(ib+1);
1111 fwrite(ib, (ib->len+1)*4, 1, f);
1113 bbox_extend(c, &co->r);
1125 add_nd(char *p, int ref)
1128 struct node_item *ni;
1129 ni=node_item_get(ref);
1132 coord_buffer[coord_count++]=ni->c;
1134 SET_REF(coord_buffer[coord_count], ref);
1140 if (len > 0 && p[len-1]=='\n')
1142 fprintf(stderr,"WARNING: way %d: node %d not found (%s)\n",wayid,ref,p);
1144 if (coord_count > 65536) {
1145 fprintf(stderr,"ERROR: Overflow\n");
1153 char ref_buffer[BUFFER_SIZE];
1154 if (!xml_get_attribute(p, "ref", ref_buffer, BUFFER_SIZE))
1156 add_nd(p, atoi(ref_buffer));
1162 save_buffer(char *filename, struct buffer *b)
1165 f=fopen(filename,"wb+");
1166 fwrite(b->base, b->size, 1, f);
1171 load_buffer(char *filename, struct buffer *b)
1177 f=fopen(filename,"rb");
1178 fseek(f, 0, SEEK_END);
1179 b->size=b->malloced=ftell(f);
1180 fprintf(stderr,"reading %d bytes from %s\n", b->size, filename);
1181 fseek(f, 0, SEEK_SET);
1182 b->base=malloc(b->size);
1183 assert(b->base != NULL);
1184 fread(b->base, b->size, 1, f);
1189 phase1(FILE *in, FILE *out_ways, FILE *out_nodes)
1195 while (fgets(buffer, size, in)) {
1196 p=strchr(buffer,'<');
1198 fprintf(stderr,"WARNING: wrong line %s\n", buffer);
1201 if (!strncmp(p, "<?xml ",6)) {
1202 } else if (!strncmp(p, "<osm ",5)) {
1203 } else if (!strncmp(p, "<bound ",7)) {
1204 } else if (!strncmp(p, "<node ",6)) {
1206 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1209 } else if (!strncmp(p, "<tag ",5)) {
1211 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1212 } else if (!strncmp(p, "<way ",5)) {
1215 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1217 } else if (!strncmp(p, "<nd ",4)) {
1219 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1220 } else if (!strncmp(p, "<relation ",10)) {
1222 if (!parse_relation(p))
1223 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1224 processed_relations++;
1225 } else if (!strncmp(p, "<member ",8)) {
1226 } else if (!strncmp(p, "</node>",7)) {
1228 end_node(out_nodes);
1229 } else if (!strncmp(p, "</way>",6)) {
1232 } else if (!strncmp(p, "</relation>",11)) {
1234 } else if (!strncmp(p, "</osm>",6)) {
1236 fprintf(stderr,"WARNING: unknown tag in %s\n", buffer);
1244 #ifdef HAVE_POSTGRESQL
1246 phase1_db(char *dbstr, FILE *out_ways, FILE *out_nodes)
1249 PGresult *res,*node,*way,*tag;
1250 int count,tagged,i,j,k;
1251 long min, max, id, tag_id, node_id;
1255 conn=PQconnectdb(dbstr);
1257 fprintf(stderr,"Failed to connect to database with '%s'\n",dbstr);
1260 res=PQexec(conn, "begin");
1262 fprintf(stderr, "Cannot begin transaction: %s\n", PQerrorMessage(conn));
1266 res=PQexec(conn, "set transaction isolation level serializable");
1268 fprintf(stderr, "Cannot set isolation level: %s\n", PQerrorMessage(conn));
1272 res=PQexec(conn, "declare node cursor for select id,x(coordinate),y(coordinate) from node order by id");
1274 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1278 res=PQexec(conn, "declare way cursor for select id from way order by id");
1280 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1284 res=PQexec(conn, "declare relation cursor for select id from relation order by id");
1286 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1291 node=PQexec(conn, "fetch 100000 from node");
1293 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1297 count=PQntuples(node);
1300 min=atol(PQgetvalue(node, 0, 0));
1301 max=atol(PQgetvalue(node, count-1, 0));
1302 sprintf(query,"select node_id,name,value from node_tag where node_id >= %ld and node_id <= %ld order by node_id", min, max);
1303 tag=PQexec(conn, query);
1305 fprintf(stderr, "Cannot query node_tag: %s\n", PQerrorMessage(conn));
1309 for (i = 0 ; i < count ; i++) {
1310 id=atol(PQgetvalue(node, i, 0));
1311 add_node(id, atof(PQgetvalue(node, i, 1)), atof(PQgetvalue(node, i, 2)));
1315 while (j < PQntuples(tag)) {
1316 tag_id=atol(PQgetvalue(tag, j, 0));
1318 add_tag(PQgetvalue(tag, j, 1), PQgetvalue(tag, j, 2));
1328 end_node(out_nodes);
1335 way=PQexec(conn, "fetch 100000 from way");
1337 fprintf(stderr, "Cannot setup cursor for ways: %s\n", PQerrorMessage(conn));
1341 count=PQntuples(way);
1344 min=atol(PQgetvalue(way, 0, 0));
1345 max=atol(PQgetvalue(way, count-1, 0));
1346 sprintf(query,"select way_id,node_id from way_node where way_id >= %ld and way_id <= %ld order by way_id,sequence_id", min, max);
1347 node=PQexec(conn, query);
1349 fprintf(stderr, "Cannot query way_node: %s\n", PQerrorMessage(conn));
1352 sprintf(query,"select way_id,name,value from way_tag where way_id >= %ld and way_id <= %ld", min, max);
1353 tag=PQexec(conn, query);
1355 fprintf(stderr, "Cannot query way_tag: %s\n", PQerrorMessage(conn));
1360 for (i = 0 ; i < count ; i++) {
1361 id=atol(PQgetvalue(way, i, 0));
1366 while (k < PQntuples(node)) {
1367 node_id=atol(PQgetvalue(node, k, 0));
1368 if (node_id == id) {
1369 add_nd("",atol(PQgetvalue(node, k, 1)));
1378 while (j < PQntuples(tag)) {
1379 tag_id=atol(PQgetvalue(tag, j, 0));
1381 add_tag(PQgetvalue(tag, j, 1), PQgetvalue(tag, j, 2));
1399 res=PQexec(conn, "commit");
1401 fprintf(stderr, "Cannot commit transaction: %s\n", PQerrorMessage(conn));
1411 static char buffer[150000];
1415 static struct item_bin *
1418 struct item_bin *ib=(struct item_bin *) buffer;
1420 r=fread(ib, sizeof(*ib), 1, in);
1424 assert((ib->len+1) < sizeof(buffer));
1425 s=(ib->len+1)*4-sizeof(*ib);
1426 r=fread(ib+1, s, 1, in);
1434 bbox_extend(struct coord *c, struct rect *r)
1447 bbox(struct coord *c, int count, struct rect *r)
1460 contains_bbox(int xl, int yl, int xh, int yh, struct rect *r)
1462 if (r->h.x < xl || r->h.x > xh) {
1465 if (r->l.x > xh || r->l.x < xl) {
1468 if (r->h.y < yl || r->h.y > yh) {
1471 if (r->l.y > yh || r->l.y < yl) {
1477 struct rect world_bbox = {
1478 { -20000000, -20000000},
1479 { 20000000, 20000000},
1483 tile(struct rect *r, char *ret, int max)
1492 for (i = 0 ; i < max ; i++) {
1499 if ( contains_bbox(x0,y0,x2,y2,r)) {
1503 } else if (contains_bbox(x2,y0,x4,y2,r)) {
1507 } else if (contains_bbox(x0,y2,x2,y4,r)) {
1511 } else if (contains_bbox(x2,y2,x4,y4,r)) {
1521 tile_bbox(char *tile, struct rect *r)
1526 c.x=(r->l.x+r->h.x)/2;
1527 c.y=(r->l.y+r->h.y)/2;
1550 GHashTable *tile_hash;
1551 GHashTable *tile_hash2;
1554 tile_extend(char *tile, struct item_bin *ib, GList **tiles_list)
1556 struct tile_head *th=NULL;
1557 if (debug_tile(tile))
1558 fprintf(stderr,"Tile:Writing %d bytes to '%s' (%p,%p)\n", (ib->len+1)*4, tile, g_hash_table_lookup(tile_hash, tile), tile_hash2 ? g_hash_table_lookup(tile_hash2, tile) : NULL);
1560 th=g_hash_table_lookup(tile_hash2, tile);
1562 th=g_hash_table_lookup(tile_hash, tile);
1564 th=malloc(sizeof(struct tile_head)+ sizeof( char* ) );
1566 // strcpy(th->subtiles, tile);
1569 th->total_size_used=0;
1572 th->name=string_hash_lookup(tile);
1573 *th_get_subtile( th, 0 ) = th->name;
1576 g_hash_table_insert(tile_hash2, string_hash_lookup( th->name ), th);
1578 *tiles_list=g_list_append(*tiles_list, string_hash_lookup( th->name ) );
1580 if (debug_tile(tile))
1581 fprintf(stderr,"new '%s'\n", tile);
1583 th->total_size+=ib->len*4+4;
1584 if (debug_tile(tile))
1585 fprintf(stderr,"New total size of %s(%p):%d\n", th->name, th, th->total_size);
1586 g_hash_table_insert(tile_hash, string_hash_lookup( th->name ), th);
1590 tile_data_size(char *tile)
1592 struct tile_head *th;
1593 th=g_hash_table_lookup(tile_hash, tile);
1596 return th->total_size;
1600 merge_tile(char *base, char *sub)
1602 struct tile_head *thb, *ths;
1603 thb=g_hash_table_lookup(tile_hash, base);
1604 ths=g_hash_table_lookup(tile_hash, sub);
1607 if (debug_tile(base) || debug_tile(sub))
1608 fprintf(stderr,"merging '%s'(%p) (%d) with '%s'(%p) (%d)\n", base, thb, thb ? thb->total_size : 0, sub, ths, ths->total_size);
1611 g_hash_table_remove(tile_hash, sub);
1612 thb->name=string_hash_lookup(base);
1613 g_hash_table_insert(tile_hash, string_hash_lookup( thb->name ), thb);
1616 thb=realloc(thb, sizeof(struct tile_head)+( ths->num_subtiles+thb->num_subtiles ) * sizeof( char*) );
1617 assert(thb != NULL);
1618 memcpy( th_get_subtile( thb, thb->num_subtiles ), th_get_subtile( ths, 0 ), ths->num_subtiles * sizeof( char*) );
1619 thb->num_subtiles+=ths->num_subtiles;
1620 thb->total_size+=ths->total_size;
1621 g_hash_table_insert(tile_hash, string_hash_lookup( thb->name ), thb);
1622 g_hash_table_remove(tile_hash, sub);
1630 get_tiles_list_func(char *key, struct tile_head *th, GList **list)
1632 *list=g_list_prepend(*list, key);
1636 get_tiles_list(void)
1639 g_hash_table_foreach(tile_hash, (GHFunc)get_tiles_list_func, &ret);
1645 write_tile(char *key, struct tile_head *th, gpointer dummy)
1649 fprintf(stderr,"DEBUG: Writing %s\n", key);
1650 strcpy(buffer,"tiles/");
1653 strcat(buffer,".bin");
1655 f=fopen(buffer, "wb+");
1657 fwrite(th->data, th->size, 1, f);
1665 write_item(char *tile, struct item_bin *ib)
1667 struct tile_head *th;
1670 th=g_hash_table_lookup(tile_hash2, tile);
1672 th=g_hash_table_lookup(tile_hash, tile);
1674 if (th->process != 0 && th->process != 1) {
1675 fprintf(stderr,"error with tile '%s' of length %d\n", tile, strlen(tile));
1680 if (debug_tile(tile))
1681 fprintf(stderr,"Data:Writing %d bytes to '%s' (%p,%p)\n", (ib->len+1)*4, tile, g_hash_table_lookup(tile_hash, tile), tile_hash2 ? g_hash_table_lookup(tile_hash2, tile) : NULL);
1683 if (th->total_size_used+size > th->total_size) {
1684 fprintf(stderr,"Overflow in tile %s (used %d max %d item %d)\n", tile, th->total_size_used, th->total_size, size);
1688 memcpy(th->zip_data+th->total_size_used, ib, size);
1689 th->total_size_used+=size;
1691 fprintf(stderr,"no tile hash found for %s\n", tile);
1698 write_item_part(FILE *out, struct item_bin *orig, int first, int last)
1700 struct item_bin new;
1701 struct coord *c=(struct coord *)(orig+1);
1702 char *attr=(char *)(c+orig->clen/2);
1703 int attr_len=orig->len-orig->clen-2;
1705 new.type=orig->type;
1706 new.clen=(last-first+1)*2;
1707 new.len=new.clen+attr_len+2;
1709 fprintf(stderr,"first %d last %d type 0x%x len %d clen %d attr_len %d\n", first, last, new.type, new.len, new.clen, attr_len);
1711 fwrite(&new, sizeof(new), 1, out);
1712 fwrite(c+first, new.clen*4, 1, out);
1713 fwrite(attr, attr_len*4, 1, out);
1717 phase2(FILE *in, FILE *out)
1720 int i,ccount,last,ndref;
1721 struct item_bin *ib;
1722 struct node_item *ni;
1724 processed_nodes=processed_nodes_out=processed_ways=processed_relations=processed_tiles=0;
1726 while ((ib=read_item(in))) {
1728 fprintf(stderr,"type 0x%x len %d clen %d\n", ib->type, ib->len, ib->clen);
1731 c=(struct coord *)(ib+1);
1733 for (i = 0 ; i < ccount ; i++) {
1736 ni=node_item_get(ndref);
1738 fprintf(stderr,"ni=%p\n", ni);
1741 if (ni->ref_way > 1 && i != 0 && i != ccount-1 && IS_STREET(*ib)) {
1742 write_item_part(out, ib, last, i);
1747 write_item_part(out, ib, last, ccount-1);
1755 phase34_process_file(int phase, FILE *in)
1757 struct item_bin *ib;
1762 while ((ib=read_item(in))) {
1763 if (ib->type < 0x80000000)
1767 bbox((struct coord *)(ib+1), ib->clen/2, &r);
1770 if (ib->type == type_street_n_lanes || ib->type == type_highway_city || ib->type == type_highway_land || ib->type == type_ramp)
1772 if (ib->type == type_street_3_city || ib->type == type_street_4_city || ib->type == type_street_3_land || ib->type == type_street_4_land)
1775 tile(&r, buffer, max);
1777 fprintf(stderr,"%s\n", buffer);
1780 tile_extend(buffer, ib, NULL);
1782 write_item(buffer, ib);
1787 struct item_bin item;
1789 struct attr_bin attr_order_limit;
1792 struct attr_bin attr_zipfile_ref;
1797 index_submap_add(int phase, struct tile_head *th, GList **tiles_list)
1799 struct index_item ii;
1800 int len=strlen(th->name);
1801 char index_tile[len+1];
1803 ii.min=(len > 4) ? len-4 : 0;
1805 strcpy(index_tile, th->name);
1811 tile_bbox(th->name, &ii.r);
1813 ii.item.len=sizeof(ii)/4-1;
1814 ii.item.type=type_submap;
1817 ii.attr_order_limit.len=2;
1818 ii.attr_order_limit.type=attr_order_limit;
1820 ii.attr_zipfile_ref.len=2;
1821 ii.attr_zipfile_ref.type=attr_zipfile_ref;
1822 ii.zipfile_ref=th->zipnum;
1825 tile_extend(index_tile, (struct item_bin *)&ii, tiles_list);
1827 write_item(index_tile, (struct item_bin *)&ii);
1829 unsigned int *c=(unsigned int *)ⅈ
1831 for (i = 0 ; i < sizeof(ii)/4 ; i++) {
1832 fprintf(stderr,"%08x ", c[i]);
1834 fprintf(stderr,"\n");
1839 add_tile_hash(struct tile_head *th)
1841 int idx,len,maxnamelen=0;
1845 g_hash_table_insert(tile_hash2, string_hash_lookup( th->name ), th);
1847 for( idx = 0; idx < th->num_subtiles; idx++ ) {
1849 data = th_get_subtile( th, idx );
1851 if (debug_tile(data) || debug_tile(th->name)) {
1852 fprintf(stderr,"Parent for '%s' is '%s'\n", *data, th->name);
1855 g_hash_table_insert(tile_hash2, *data, th);
1857 len = strlen( *data );
1859 if (len > maxnamelen) {
1868 create_tile_hash(void)
1870 struct tile_head *th;
1871 int len,maxnamelen=0;
1873 tile_hash2=g_hash_table_new(g_str_hash, g_str_equal);
1876 len=add_tile_hash(th);
1877 if (len > maxnamelen)
1885 create_tile_hash_list(GList *list)
1888 struct tile_head *th;
1890 tile_hash2=g_hash_table_new(g_str_hash, g_str_equal);
1892 fprintf(stderr,"list=%p\n", list);
1893 next=g_list_first(list);
1895 th=g_hash_table_lookup(tile_hash, next->data);
1897 fprintf(stderr,"No tile found for '%s'\n", (char *)(next->data));
1900 next=g_list_next(next);
1905 destroy_tile_hash(void)
1907 g_hash_table_destroy(tile_hash2);
1913 static void write_countrydir(int phase, int maxnamelen);
1916 write_tilesdir(int phase, int maxlen, FILE *out)
1919 GList *tiles_list,*next;
1921 struct tile_head *th,**last=NULL;
1924 tiles_list=get_tiles_list();
1926 create_tile_hash_list(tiles_list);
1927 next=g_list_first(tiles_list);
1928 last=&tile_head_root;
1931 if (strlen(next->data) > maxlen)
1932 maxlen=strlen(next->data);
1933 next=g_list_next(next);
1939 fprintf(stderr,"PROGRESS: collecting tiles with len=%d\n", len);
1941 #ifdef GENERATE_INDEX
1943 write_countrydir(phase, maxlen);
1945 next=g_list_first(tiles_list);
1947 if (strlen(next->data) == len) {
1948 th=g_hash_table_lookup(tile_hash, next->data);
1954 fprintf(out,"%s:%d",(char *)next->data,th->total_size);
1956 for ( idx = 0; idx< th->num_subtiles; idx++ ){
1957 data= th_get_subtile( th, idx );
1958 fprintf(out,":%s", *data);
1964 index_submap_add(phase, th, &tiles_list);
1968 next=g_list_next(next);
1977 struct tile_head *th;
1978 char basetile[1024];
1980 GList *tiles_list_sorted,*last;
1981 int i,i_min,len,size_all,size[5],size_min,work_done;
1985 tiles_list_sorted=get_tiles_list();
1986 fprintf(stderr,"PROGRESS: sorting %d tiles\n", g_list_length(tiles_list_sorted));
1987 tiles_list_sorted=g_list_sort(tiles_list_sorted, (GCompareFunc)strcmp);
1988 fprintf(stderr,"PROGRESS: sorting %d tiles done\n", g_list_length(tiles_list_sorted));
1989 last=g_list_last(tiles_list_sorted);
1992 th=g_hash_table_lookup(tile_hash, last->data);
1993 zip_size+=th->total_size;
1994 last=g_list_previous(last);
1996 fprintf(stderr,"DEBUG: size=%Ld\n", zip_size);
1997 last=g_list_last(tiles_list_sorted);
2001 len=strlen(last->data);
2003 strcpy(basetile,last->data);
2004 basetile[len-1]='\0';
2005 strcpy(subtile,last->data);
2006 for (i = 0 ; i < 4 ; i++) {
2007 subtile[len-1]='a'+i;
2008 size[i]=tile_data_size(subtile);
2010 size[4]=tile_data_size(basetile);
2011 size_all=size[0]+size[1]+size[2]+size[3]+size[4];
2012 if (size_all < 65536 && size_all > 0 && size_all != size[4]) {
2013 for (i = 0 ; i < 4 ; i++) {
2014 subtile[len-1]='a'+i;
2015 work_done+=merge_tile(basetile, subtile);
2021 for (i = 0 ; i < 4 ; i++) {
2022 if (size[i] && size[i] < size_min) {
2029 if (size[4]+size_min >= 65536)
2031 subtile[len-1]='a'+i_min;
2032 work_done+=merge_tile(basetile, subtile);
2033 size[4]+=size[i_min];
2038 last=g_list_previous(last);
2040 g_list_free(tiles_list_sorted);
2041 fprintf(stderr,"PROGRESS: merged %d tiles\n", work_done);
2042 } while (work_done);
2045 struct country_index_item {
2046 struct item_bin item;
2047 struct attr_bin attr_country_id;
2049 struct attr_bin attr_zipfile_ref;
2054 index_country_add(int phase, int country_id, int zipnum)
2056 struct country_index_item ii;
2057 char *index_tile="";
2059 ii.item.len=sizeof(ii)/4-1;
2060 ii.item.type=type_countryindex;
2063 ii.attr_country_id.len=2;
2064 ii.attr_country_id.type=attr_country_id;
2065 ii.country_id=country_id;
2067 ii.attr_zipfile_ref.len=2;
2068 ii.attr_zipfile_ref.type=attr_zipfile_ref;
2069 ii.zipfile_ref=zipnum;
2072 tile_extend(index_tile, (struct item_bin *)&ii, NULL);
2074 write_item(index_tile, (struct item_bin *)&ii);
2077 #ifdef GENERATE_INDEX
2085 add_aux_tile(int phase, char *name, char *filename, int size)
2087 struct aux_tile *at;
2089 at=g_new0(struct aux_tile, 1);
2090 at->name=g_strdup(name);
2091 at->filename=g_strdup(filename);
2093 aux_tile_list=g_list_append(aux_tile_list, at);
2099 write_aux_tiles(FILE *out, FILE *dir_out, int compression_level, int namelen)
2101 GList *l=aux_tile_list;
2102 struct aux_tile *at;
2109 buffer=malloc(at->size);
2110 assert(buffer != NULL);
2111 f=fopen(at->filename,"r");
2113 fread(buffer, at->size, 1, f);
2115 write_zipmember(out, dir_out, at->name, namelen, buffer, at->size, compression_level);
2123 write_countrydir(int phase, int maxnamelen)
2128 char searchtile[32];
2130 struct country_table *co;
2131 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
2132 co=&country_table[i];
2135 tile(&co->r, tilename, max);
2136 sprintf(searchtile,"%ss%d", tilename, 0);
2137 sprintf(filename,"country_%d.bin", co->countryid);
2138 zipnum=add_aux_tile(phase, searchtile, filename, co->size);
2139 index_country_add(phase,co->countryid,zipnum);
2145 remove_countryfiles(void)
2149 struct country_table *co;
2151 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
2152 co=&country_table[i];
2154 sprintf(filename,"country_%d.bin", co->countryid);
2162 phase34(int phase, int maxnamelen, FILE *ways_in, FILE *nodes_in, FILE *tilesdir_out)
2165 processed_nodes=processed_nodes_out=processed_ways=processed_relations=processed_tiles=0;
2169 tile_hash=g_hash_table_new(g_str_hash, g_str_equal);
2171 phase34_process_file(phase, ways_in);
2173 phase34_process_file(phase, nodes_in);
2174 fprintf(stderr,"read %d bytes\n", bytes_read);
2179 write_tilesdir(phase, maxnamelen, tilesdir_out);
2186 phase3(FILE *ways_in, FILE *nodes_in, FILE *tilesdir_out)
2188 return phase34(3, 0, ways_in, nodes_in, tilesdir_out);
2191 static long long zipoffset;
2192 static int zipdir_size;
2195 compress2_int(Byte *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level)
2200 stream.next_in = (Bytef*)source;
2201 stream.avail_in = (uInt)sourceLen;
2202 stream.next_out = dest;
2203 stream.avail_out = (uInt)*destLen;
2204 if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
2206 stream.zalloc = (alloc_func)0;
2207 stream.zfree = (free_func)0;
2208 stream.opaque = (voidpf)0;
2210 err = deflateInit2(&stream, level, Z_DEFLATED, -15, 9, Z_DEFAULT_STRATEGY);
2211 if (err != Z_OK) return err;
2213 err = deflate(&stream, Z_FINISH);
2214 if (err != Z_STREAM_END) {
2215 deflateEnd(&stream);
2216 return err == Z_OK ? Z_BUF_ERROR : err;
2218 *destLen = stream.total_out;
2220 err = deflateEnd(&stream);
2225 write_zipmember(FILE *out, FILE *dir_out, char *name, int filelen, char *data, int data_size, int compression_level)
2227 struct zip_lfh lfh = {
2240 struct zip_cd cd = {
2261 char filename[filelen+1];
2262 int error,crc,len,comp_size=data_size;
2263 uLongf destlen=data_size+data_size/500+12;
2264 char compbuffer[destlen];
2266 crc=crc32(0, NULL, 0);
2267 crc=crc32(crc, (unsigned char *)data, data_size);
2268 if (compression_level) {
2269 error=compress2_int((Byte *)compbuffer, &destlen, (Bytef *)data, data_size, compression_level);
2270 if (error == Z_OK) {
2271 if (destlen < data_size) {
2276 fprintf(stderr,"compress2 returned %d\n", error);
2280 lfh.zipsize=comp_size;
2281 lfh.zipuncmp=data_size;
2282 lfh.zipmthd=compression_level ? 8:0;
2284 cd.zipcsiz=comp_size;
2285 cd.zipcunc=data_size;
2286 cd.zipcmthd=compression_level ? 8:0;
2287 strcpy(filename, name);
2288 len=strlen(filename);
2289 while (len < filelen) {
2290 filename[len++]='_';
2292 filename[filelen]='\0';
2293 fwrite(&lfh, sizeof(lfh), 1, out);
2294 fwrite(filename, filelen, 1, out);
2295 fwrite(data, comp_size, 1, out);
2296 zipoffset+=sizeof(lfh)+filelen+comp_size;
2297 fwrite(&cd, sizeof(cd), 1, dir_out);
2298 fwrite(filename, filelen, 1, dir_out);
2299 zipdir_size+=sizeof(cd)+filelen;
2303 process_slice(FILE *ways_in, FILE *nodes_in, int size, int maxnamelen, FILE *out, FILE *dir_out, int compression_level)
2305 struct tile_head *th;
2306 char *slice_data,*zip_data;
2309 slice_data=malloc(size);
2310 assert(slice_data != NULL);
2311 zip_data=slice_data;
2315 th->zip_data=zip_data;
2316 zip_data+=th->total_size;
2321 fseek(ways_in, 0, SEEK_SET);
2323 fseek(nodes_in, 0, SEEK_SET);
2324 phase34(4, maxnamelen, ways_in, nodes_in, NULL);
2329 #ifdef GENERATE_INDEX
2330 if (! strlen(th->name))
2331 zipfiles+=write_aux_tiles(out, dir_out, compression_level, maxnamelen);
2333 if (th->total_size != th->total_size_used) {
2334 fprintf(stderr,"Size error '%s': %d vs %d\n", th->name, th->total_size, th->total_size_used);
2337 if (strlen(th->name))
2338 write_zipmember(out, dir_out, th->name, maxnamelen, th->zip_data, th->total_size, compression_level);
2340 write_zipmember(out, dir_out, "index", sizeof("index")-1, th->zip_data, th->total_size, compression_level);
2353 cat(FILE *in, FILE *out)
2357 while ((size=fread(buffer, 1, 4096, in)))
2358 fwrite(buffer, 1, size, out);
2362 phase4(FILE *ways_in, FILE *nodes_in, FILE *out, FILE *dir_out, int compression_level)
2364 int slice_size=1024*1024*1024;
2365 int maxnamelen,size,slices;
2367 struct tile_head *th,*th2;
2368 struct zip_eoc eoc = {
2379 maxnamelen=create_tile_hash();
2384 fprintf(stderr, "Maximum slice size %d\n", slice_size);
2386 if (size + th->total_size > slice_size) {
2387 fprintf(stderr,"Slice %d is of size %d\n", slices, size);
2391 size+=th->total_size;
2395 fprintf(stderr,"Slice %d is of size %d\n", slices, size);
2406 while (th && size+th->total_size < slice_size) {
2407 size+=th->total_size;
2411 zipfiles+=process_slice(ways_in, nodes_in, size, maxnamelen, out, dir_out, compression_level);
2414 fseek(dir_out, 0, SEEK_SET);
2416 eoc.zipenum=zipfiles;
2417 eoc.zipecenn=zipfiles;
2418 eoc.zipecsz=zipdir_size;
2419 eoc.zipeofst=zipoffset;
2420 fwrite(&eoc, sizeof(eoc), 1, out);
2430 fprintf(f,"osm2navit - parse osm textfile and converts to NavIt binfile format\n\n");
2431 fprintf(f,"Usage :\n");
2432 fprintf(f,"bzcat planet.osm.bz2 | osm2navit mymap.bin\n");
2433 fprintf(f,"Available switches:\n");
2434 fprintf(f,"-h (--help) : this screen\n");
2435 fprintf(f,"-N (--nodes-only) : process only nodes\n");
2436 fprintf(f,"-W (--ways-only) : process only ways\n");
2437 fprintf(f,"-a (--attr-debug-level) : control which data is included in the debug attribute\n");
2438 fprintf(f,"-c (--dump-coordinates) : dump coordinates after phase 1\n");
2439 #ifdef HAVE_POSTGRESQL
2440 fprintf(f,"-d (--db) : get osm data out of a postgresql database with osm simple scheme and given connect string\n");
2442 fprintf(f,"-e (--end) : end at specified phase\n");
2443 fprintf(f,"-k (--keep-tmpfiles) : do not delete tmp files after processing. useful to reuse them\n\n");
2444 fprintf(f,"-o (--coverage) : map every street to item overage\n");
2445 fprintf(f,"-s (--start) : start at specified phase\n");
2446 fprintf(f,"-i (--input-file) : specify the input file name (OSM), overrules default stdin\n");
2447 fprintf(f,"-w (--dedupe-ways) : ensure no duplicate ways or nodes. useful when using several input files\n");
2448 fprintf(f,"-z (--compression-level) : set the compression level\n");
2452 int main(int argc, char **argv)
2454 FILE *ways=NULL,*ways_split=NULL,*nodes=NULL,*tilesdir,*zipdir,*res;
2455 char *map=g_strdup(attrmap);
2456 int c,start=1,end=4,dump_coordinates=0;
2457 int keep_tmpfiles=0;
2458 int process_nodes=1, process_ways=1;
2459 int compression_level=9;
2460 char *result,*dbstr=NULL;
2461 FILE* input_file = stdin;
2466 int this_option_optind = optind ? optind : 1;
2468 int option_index = 0;
2469 static struct option long_options[] = {
2470 {"attr-debug-level", 1, 0, 'a'},
2471 {"compression-level", 1, 0, 'z'},
2472 {"coverage", 0, 0, 'o'},
2473 #ifdef HAVE_POSTGRESQL
2476 {"dedupe-ways", 0, 0, 'w'},
2478 {"help", 0, 0, 'h'},
2479 {"keep-tmpfiles", 0, 0, 'k'},
2480 {"nodes-only", 0, 0, 'N'},
2481 {"start", 1, 0, 's'},
2482 {"input-file", 1, 0, 'i'},
2483 {"ignore-unknown", 0, 0, 'n'},
2484 {"ways-only", 0, 0, 'W'},
2487 c = getopt_long (argc, argv, "Nni:Wa:c"
2488 #ifdef HAVE_POSTGRESQL
2491 "e:hks:w", long_options, &option_index);
2502 attr_debug_level=atoi(optarg);
2507 #ifdef HAVE_POSTGRESQL
2519 fprintf(stderr,"I will IGNORE unknown types\n");
2523 fprintf(stderr,"I will KEEP tmp files\n");
2533 dedupe_ways_hash=g_hash_table_new(NULL, NULL);
2536 input_file = fopen( optarg, "r" );
2537 if ( input_file == NULL )
2539 fprintf( stderr, "\nInput file (%s) not found\n", optarg );
2544 compression_level=atoi(optarg);
2550 fprintf(stderr,"c=%d\n", c);
2554 if (optind != argc-1)
2556 result=argv[optind];
2558 #ifdef GENERATE_INDEX
2559 build_countrytable();
2565 ways=fopen("ways.tmp","wb+");
2567 nodes=fopen("nodes.tmp","wb+");
2569 fprintf(stderr,"PROGRESS: Phase 1: collecting data\n");
2570 #ifdef HAVE_POSTGRESQL
2572 phase1_db(dbstr,ways,nodes);
2575 phase1(input_file,ways,nodes);
2580 #ifdef GENERATE_INDEX
2581 fprintf(stderr,"PROGRESS: Phase 1: sorting countries\n");
2585 if (end == 1 || dump_coordinates)
2586 save_buffer("coords.tmp",&node_buffer);
2590 load_buffer("coords.tmp",&node_buffer);
2593 ways=fopen("ways.tmp","rb");
2594 ways_split=fopen("ways_split.tmp","wb+");
2596 fprintf(stderr,"PROGRESS: Phase 2: finding intersections\n");
2597 phase2(ways,ways_split);
2603 fprintf(stderr,"PROGRESS: Skipping Phase 2\n");
2605 free(node_buffer.base);
2606 node_buffer.base=NULL;
2607 node_buffer.malloced=0;
2613 fprintf(stderr,"PROGRESS: Phase 3: generating tiles\n");
2615 ways_split=fopen("ways_split.tmp","rb");
2617 nodes=fopen("nodes.tmp","rb");
2618 tilesdir=fopen("tilesdir.tmp","wb+");
2619 phase3(ways_split,nodes,tilesdir);
2630 fprintf(stderr,"PROGRESS: Phase 4: assembling map\n");
2632 ways_split=fopen("ways_split.tmp","rb");
2634 nodes=fopen("nodes.tmp","rb");
2635 res=fopen(result,"wb+");
2636 zipdir=fopen("zipdir.tmp","wb+");
2637 phase4(ways_split,nodes,res,zipdir,compression_level);
2644 if(!keep_tmpfiles) {
2645 remove("nodes.tmp");
2646 remove("ways_split.tmp");
2647 remove("tilesdir.tmp");
2648 remove("zipdir.tmp");
2649 #ifdef GENERATE_INDEX
2650 remove_countryfiles();