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)
54 static GHashTable *dedupe_ways_hash;
56 static int attr_debug_level=1;
57 static int nodeid,wayid;
58 static int report,phase;
59 static int ignore_unkown = 0, coverage=0;
61 static char *attrmap={
63 "n amenity=hospital poi_hospital\n"
64 "n amenity=atm poi_bank\n"
65 "n amenity=bank poi_bank\n"
66 "n amenity=pub poi_bar\n"
67 "n amenity=cafe poi_cafe\n"
68 "n amenity=bus_station poi_bus_station\n"
69 "n amenity=parking poi_car_parking\n"
70 "n amenity=cinema poi_cinema\n"
71 "n amenity=fire_station poi_firebrigade\n"
72 "n amenity=fuel poi_fuel\n"
73 "n amenity=courthouse poi_justice\n"
74 "n amenity=library poi_library\n"
75 "n amenity=pharmacy poi_pharmacy\n"
76 "n amenity=place_of_worship,religion=christian poi_church\n"
77 "n amenity=police poi_police\n"
78 "n amenity=post_office poi_post\n"
79 "n amenity=post_box poi_post\n"
80 "n amenity=public_building poi_public_office\n"
81 "n amenity=restaurant poi_restaurant\n"
82 "n amenity=fast_food poi_fastfood\n"
83 "n amenity=toilets poi_restroom\n"
84 "n amenity=school poi_school\n"
85 "n amenity=university poi_school\n"
86 "n amenity=college poi_school\n"
87 "n amenity=telephone poi_telephone\n"
88 "n amenity=theatre poi_theater\n"
89 "n amenity=townhall poi_townhall\n"
90 "n highway=bus_stop poi_bus_stop\n"
91 "n highway=mini_roundabout mini_roundabout\n"
92 "n highway=motorway_junction highway_exit\n"
93 "n highway=traffic_signals traffic_signals\n"
94 "n highway=turning_circle turning_circle\n"
95 "n leisure=slipway poi_boat_ramp\n"
96 "n leisure=fishing poi_fish\n"
97 "n sport=golf poi_golf\n"
98 "n leisure=golf_course poi_golf\n"
99 "n leisure=marina poi_marine\n"
100 "n leisure=sports_centre poi_sport\n"
101 "n leisure=stadium poi_stadium\n"
102 "n shop=supermarket poi_shopping\n"
103 "n shop=convenience poi_shop_grocery\n"
104 "n tourism=attraction poi_attraction\n"
105 "n tourism=camp_site poi_camp_rv\n"
106 "n tourism=caravan_site poi_camp_rv\n"
107 "n tourism=hotel poi_hotel\n"
108 "n tourism=motel poi_hotel\n"
109 "n tourism=guest_house poi_hotel\n"
110 "n tourism=hostel poi_hotel\n"
111 "n tourism=information poi_information\n"
112 "n tourism=museum poi_museum_history\n"
113 "n tourism=picnic_site poi_picnic\n"
114 "n tourism=theme_park poi_resort\n"
115 "n tourism=zoo poi_zoo\n"
116 "n amenity=grave_yard poi_cemetery\n"
117 "n landuse=cemetery poi_cemetery\n"
118 "n military=airfield poi_military\n"
119 "n military=bunker poi_military\n"
120 "n military=barracks poi_military\n"
121 "n military=range poi_military\n"
122 "n military=danger_area poi_danger_area\n"
123 "n sport=swimming poi_swimming\n"
124 "n sport=skiing poi_skiing\n"
125 "n aeroway=aerodrome poi_airport\n"
126 "n aeroway=airport poi_airport\n"
127 "n aeroway=terminal poi_airport\n"
128 "n aeroway=helipad poi_heliport\n"
129 "n man_made=tower poi_tower\n"
130 "n natural=bay poi_bay\n"
131 "n natural=peak poi_peak\n"
132 "n place=suburb district_label\n"
133 "n place=city town_label_2e5\n"
134 "n place=town town_label_2e4\n"
135 "n place=village town_label_2e3\n"
136 "n place=hamlet town_label_2e2\n"
137 "n place=locality town_label_2e0\n"
138 "n railway=halt poi_rail_halt\n"
139 "n railway=level_crossing poi_level_crossing\n"
140 "n railway=station poi_rail_station\n"
141 "n railway=tram_stop poi_rail_tram_stop\n"
142 "w *=* street_unkn\n"
143 "w amenity=place_of_worship poly_building\n"
144 "w building=* poly_building\n"
145 "w aeroway=aerodrome poly_airport\n"
146 "w aeroway=apron poly_apron\n"
147 "w aeroway=runway aeroway_runway\n"
148 "w aeroway=taxiway aeroway_taxiway\n"
149 "w aeroway=terminal poly_terminal\n"
150 "w highway=bridleway bridleway\n"
151 "w highway=path,horse=designated bridleway\n"
152 "w highway=cycleway cycleway\n"
153 "w highway=cyclepath cycleway\n"
154 "w highway=path,bicycle=designated cycleway\n"
155 "w highway=footway footway\n"
156 "w piste:type=nordic piste_nordic\n"
157 "w route=ski piste_nordic\n"
158 "w piste:type=downhill,piste:difficulty=novice piste_downhill_novice\n"
159 "w piste:type=downhill,piste:difficulty=easy piste_downhill_easy\n"
160 "w piste:type=downhill,piste:difficulty=intermediate piste_downhill_intermediate\n"
161 "w piste:type=downhill,piste:difficulty=advanced piste_downhill_advanced\n"
162 "w piste:type=downhill,piste:difficulty=expert piste_downhill_expert\n"
163 "w piste:type=downhill,piste:difficulty=freeride piste_downhill_freeride\n"
164 "w highway=path,foot=designated footway\n"
165 "w highway=steps steps\n"
166 "w highway=path path\n"
167 "w highway=unsurfaced track_gravelled\n"
168 "w highway=track track_gravelled\n"
169 "w highway=track,tracktype=grade1 track_paved\n"
170 "w highway=track,surface=paved track_paved\n"
171 "w highway=track,tracktype=grade2 track_gravelled\n"
172 "w highway=track,surface=gravel track_gravelled\n"
173 "w highway=track,tracktype=grade3 track_unpaved\n"
174 "w highway=track,surface=unpaved track_unpaved\n"
175 "w highway=track,tracktype=grade4 track_ground\n"
176 "w highway=track,surface=ground track_ground\n"
177 "w highway=track,tracktype=grade5 track_grass\n"
178 "w highway=track,surface=grass track_grass\n"
179 "w highway=parking_lane street_parking_lane\n"
180 "w highway=service street_service\n"
181 "w highway=service,area=1 poly_service\n"
182 "w highway=construction street_construction\n"
183 "w highway=pedestrian street_pedestrian\n"
184 "w highway=pedestrian,area=1 poly_pedestrian\n"
185 "w highway=plaza poly_plaza\n"
186 "w landuse=plaza poly_plaza\n"
187 "w highway=residential street_1_city\n"
188 "w highway=residential,area=1 poly_street_1\n"
189 "w highway=living_street living_street\n"
190 "w highway=unclassified street_1_city\n"
191 "w highway=unclassified,area=1 poly_street_1\n"
192 "w highway=road street_1_city\n"
193 "w highway=minor street_1_land\n"
194 "w highway=tertiary street_2_city\n"
195 "w highway=tertiary,area=1 poly_street_2\n"
196 "w highway=tertiary_link ramp\n"
197 "w highway=secondary street_3_city\n"
198 "w highway=secondary,area=1 poly_street_3\n"
199 "w highway=secondary_link ramp\n"
200 "w highway=primary street_4_city\n"
201 "w highway=primary_link ramp\n"
202 "w highway=trunk street_4_city\n"
203 "w highway=trunk_link ramp\n"
204 "w highway=motorway highway_city\n"
205 "w highway=motorway_link ramp\n"
206 "w historic=town gate poly_building\n"
207 "w cycleway=track cycleway\n"
208 "w amenity=parking poly_car_parking\n"
209 "w landuse=allotments poly_allotments\n"
210 "w landuse=cemetery poly_cemetery\n"
211 "w amenity=grave_yard poly_cemetery\n"
212 "w landuse=forest poly_wood\n"
213 "w landuse=industrial poly_industry\n"
214 "w landuse=residential poly_town\n"
215 "w landuse=residential,area=1 poly_town\n"
216 "w landuse=farmyard poly_town\n"
217 "w amenity=college poly_college\n"
218 "w amenity=university poly_university\n"
219 "w tourism=camp_site poly_camp_site\n"
220 "w tourism=caravan_site poly_caravan_site\n"
221 "w tourism=picnic_site poly_picnic_site\n"
222 "w tourism=theme_park poly_theme_park\n"
223 "w tourism=attraction poly_attraction\n"
224 "w tourism=zoo poly_zoo\n"
225 "w tourism=artwork poly_artwork\n"
226 "w historic=archaeological_site poly_archaeological_site\n"
227 "w historic=ruins poly_ruins\n"
228 "w historic=battlefield poly_battlefield\n"
229 "w landuse=quarry poly_quarry\n"
230 "w landuse=landfill poly_landfill\n"
231 "w landuse=retail poly_retail\n"
232 "w landuse=commercial poly_commercial\n"
233 "w landuse=brownfield poly_brownfield\n"
234 "w landuse=greenfield poly_greenfield\n"
235 "w landuse=construction poly_construction\n"
236 "w landuse=railway poly_railway\n"
237 "w natural=glacier poly_glacier\n"
238 "w natural=scree poly_scree\n"
239 "w natural=scrub poly_scrub\n"
240 "w natural=fell poly_fell\n"
241 "w natural=heath poly_heath\n"
242 "w natural=marsh poly_marsh\n"
243 "w natural=mud poly_mud\n"
244 "w natural=beach poly_beach\n"
245 "w natural=land poly_land\n"
246 "w landuse=basin poly_basin\n"
247 "w landuse=reservoir poly_reservoir\n"
248 "w landuse=farm poly_farm\n"
249 "w landuse=farmland poly_farm\n"
250 "w landuse=vineyard poly_farm\n"
251 "w leisure=park poly_park\n"
252 "w landuse=village_green poly_village_green\n"
253 "w landuse=recreation_ground poly_recreation_ground\n"
254 "w natural=wood poly_wood\n"
255 "w natural=water poly_water\n"
256 "w natural=coastline water_line\n"
257 "w place=suburb poly_town\n"
258 "w place=town poly_town\n"
259 "w landuse=military poly_military\n"
260 "w military=airfield poly_airfield\n"
261 "w military=barracks poly_barracks\n"
262 "w military=danger_area poly_danger_area\n"
263 "w military=range poly_range\n"
264 "w military=naval_base poly_naval_base\n"
265 "w power=line powerline\n"
266 "w railway=rail rail\n"
267 "w railway=narrow_gauge rail_narrow_gauge\n"
268 "w railway=light_rail rail_light\n"
269 "w railway=subway rail_subway\n"
270 "w railway=tram rail_tram\n"
271 "w railway=monorail rail_mono\n"
272 "w railway=preserved rail_preserved\n"
273 "w railway=disused rail_disused\n"
274 "w railway=abandoned rail_abandoned\n"
275 "w aerialway=cable_car lift_cable_car\n"
276 "w aerialway=chair_lift lift_chair\n"
277 "w aerialway=drag_lift lift_drag\n"
278 "w leisure=golf_course poly_golf_course\n"
279 "w sport=* poly_sport\n"
280 "w leisure=sports_centre poly_sport\n"
281 "w leisure=stadium poly_sports_stadium\n"
282 "w leisure=track poly_sports_track\n"
283 "w leisure=pitch poly_sports_pitch\n"
284 "w leisure=water_park poly_water_park\n"
285 "w leisure=marina poly_marina\n"
286 "w leisure=fishing poly_fishing\n"
287 "w leisure=garden poly_garden\n"
288 "w leisure=common poly_common\n"
289 "w leisure=playground poly_playground\n"
290 "w leisure=nature_reserve poly_nature_reserve\n"
291 "w waterway=canal water_canal\n"
292 "w waterway=river water_river\n"
293 "w waterway=stream water_stream\n"
294 "w waterway=drain water_drain\n"
295 "w waterway=riverbank poly_water\n"
296 "w boundary=administrative border_country\n"
297 "w boundary=civil border_civil\n"
298 "w boundary=political border_political\n"
299 "w boundary=national_park border_national_park\n"
300 "w route=ferry ferry\n"
301 "w highway=bus_guideway bus_guideway\n"
307 } coord_buffer[65536];
309 #define IS_REF(c) ((c).x >= (1 << 30))
310 #define REF(c) ((c).y)
311 #define SET_REF(c,ref) do { (c).x = 1 << 30; (c).y = ref ; } while(0)
317 static void bbox_extend(struct coord *c, struct rect *r);
319 #ifdef GENERATE_INDEX
321 static GHashTable *aux_tile_hash;
322 GList *aux_tile_list;
324 struct country_table {
331 } country_table[] = {
332 { 40,"Austria,Österreich,AUT"},
334 {276,"Germany,Deutschland,Bundesrepublik Deutschland"},
335 {528,"Nederland,The Netherlands,Niederlande,NL"},
340 static GHashTable *country_table_hash;
343 struct attr_mapping {
345 int attr_present_idx_count;
346 int attr_present_idx[0];
349 static struct attr_mapping **attr_mapping_node;
350 static int attr_mapping_node_count;
351 static struct attr_mapping **attr_mapping_way;
352 static int attr_mapping_way_count;
354 static char *attr_present;
355 static int attr_present_count;
356 static GHashTable *attr_hash;
359 static GHashTable *strings_hash = NULL;
362 static char* string_hash_lookup( const char* key )
364 char* key_ptr = NULL;
366 if ( strings_hash == NULL ) {
367 strings_hash = g_hash_table_new(g_str_hash, g_str_equal);
370 if ( ( key_ptr = g_hash_table_lookup(strings_hash, key )) == NULL ) {
371 key_ptr = g_strdup( key );
372 g_hash_table_insert(strings_hash, key_ptr, (gpointer)key_ptr );
379 build_attrmap_line(char *line)
381 char *t=NULL,*kvl=NULL,*i=NULL,*p,*kv;
382 struct attr_mapping ***attr_mapping_curr,*attr_mapping=g_malloc0(sizeof(struct attr_mapping));
383 int idx,attr_mapping_count=0,*attr_mapping_curr_count;
400 attr_mapping_curr=&attr_mapping_way;
401 attr_mapping_curr_count=&attr_mapping_way_count;
405 attr_mapping_curr=&attr_mapping_node;
406 attr_mapping_curr_count=&attr_mapping_node_count;
408 attr_mapping->type=item_from_name(i);
409 while ((kv=strtok(kvl, ","))) {
411 if (!(idx=(int)g_hash_table_lookup(attr_hash, kv))) {
412 idx=attr_present_count++;
413 g_hash_table_insert(attr_hash, kv, (gpointer) idx);
415 attr_mapping=g_realloc(attr_mapping, sizeof(struct attr_mapping)+(attr_mapping_count+1)*sizeof(int));
416 attr_mapping->attr_present_idx[attr_mapping_count++]=idx;
417 attr_mapping->attr_present_idx_count=attr_mapping_count;
419 *attr_mapping_curr=g_realloc(*attr_mapping_curr, sizeof(**attr_mapping_curr)*(*attr_mapping_curr_count+1));
420 (*attr_mapping_curr)[(*attr_mapping_curr_count)++]=attr_mapping;
424 build_attrmap(char *map)
427 attr_hash=g_hash_table_new(g_str_hash, g_str_equal);
428 attr_present_count=1;
434 build_attrmap_line(map);
437 attr_present=g_malloc0(sizeof(*attr_present)*attr_present_count);
440 #ifdef GENERATE_INDEX
442 build_countrytable(void)
445 char *names,*str,*tok;
446 country_table_hash=g_hash_table_new(g_str_hash, g_str_equal);
447 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
448 names=g_strdup(country_table[i].names);
450 while ((tok=strtok(str, ","))) {
452 g_hash_table_insert(country_table_hash, tok, (gpointer)&country_table[i]);
460 static int processed_nodes, processed_nodes_out, processed_ways, processed_relations, processed_tiles;
461 static int in_way, in_node, in_relation;
467 signal(SIGALRM, sig_alrm);
470 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);
484 struct attr_bin label_attr = {
487 char label_attr_buffer[BUFFER_SIZE];
489 struct attr_bin town_name_attr = {
493 struct attr_bin street_name_attr = {
497 struct attr_bin street_name_systematic_attr = {
498 0, attr_street_name_systematic
500 char street_name_systematic_attr_buffer[BUFFER_SIZE];
502 struct attr_bin debug_attr = {
505 char debug_attr_buffer[BUFFER_SIZE];
507 struct attr_bin flags_attr = {
510 int flags_attr_value;
512 char is_in_buffer[BUFFER_SIZE];
515 static void write_zipmember(FILE *out, FILE *dir_out, char *name, int filelen, char *data, int data_size, int compression_level);
518 pad_text_attr(struct attr_bin *a, char *buffer)
521 if (buffer && buffer[0]) {
531 xml_get_attribute(char *xml, char *attribute, char *buffer, int buffer_size)
533 int len=strlen(attribute);
534 char *pos,*i,s,attr[len+2];
535 strcpy(attr, attribute);
536 strcpy(attr+len, "=");
537 pos=strstr(xml, attr);
547 if (i - pos > buffer_size) {
548 fprintf(stderr,"Buffer overflow %d vs %d\n", i-pos, buffer_size);
551 strncpy(buffer, pos, i-pos);
556 static int node_is_tagged;
559 add_tag(char *k, char *v)
561 GHashTable *value_hash;
564 char buffer[BUFFER_SIZE*2+2];
565 if (! strcmp(k,"ele"))
567 if (! strcmp(k,"time"))
569 if (! strcmp(k,"created_by"))
571 if (! strncmp(k,"tiger:",6) || !strcmp(k,"AND_nodes"))
573 if (! strcmp(k,"converted_by") || ! strcmp(k,"source"))
575 if (! strncmp(k,"osmarender:",11) || !strncmp(k,"svg:",4))
577 if (! strcmp(k,"layer"))
579 if (! strcasecmp(v,"true") || ! strcasecmp(v,"yes"))
581 if (! strcmp(k,"oneway")) {
582 if (!strcmp(v,"1")) {
583 flags_attr_value=AF_ONEWAY;
586 if (! strcmp(v,"-1")) {
587 flags_attr_value=AF_ONEWAYREV;
595 if (! strcmp(k,"junction")) {
596 if (! strcmp(v,"roundabout")) {
597 flags_attr_value=AF_ONEWAY;
601 if (! strcmp(k,"maxspeed")) {
604 if (! strcmp(k,"bicycle")) {
607 if (! strcmp(k,"foot")) {
610 if (! strcmp(k,"note"))
612 if (! strcmp(k,"name")) {
613 strcpy(label_attr_buffer, v);
614 pad_text_attr(&label_attr, label_attr_buffer);
617 if (! strcmp(k,"ref")) {
619 strcpy(street_name_systematic_attr_buffer, v);
620 pad_text_attr(&street_name_systematic_attr, street_name_systematic_attr_buffer);
624 if (! strcmp(k,"is_in")) {
625 strcpy(is_in_buffer, v);
628 if (! strcmp(k,"gnis:ST_alpha")) {
629 /* assume a gnis tag means it is part of the USA:
630 http://en.wikipedia.org/wiki/Geographic_Names_Information_System
631 many US towns do not have is_in tags
633 strcpy(is_in_buffer, "USA");
636 if (! strcmp(k,"lanes")) {
639 if (attr_debug_level >= level) {
640 int bytes_left = sizeof( debug_attr_buffer ) - strlen(debug_attr_buffer) - 1;
641 if ( bytes_left > 0 )
643 snprintf(debug_attr_buffer+strlen(debug_attr_buffer), bytes_left, " %s=%s", k, v);
644 debug_attr_buffer[ sizeof( debug_attr_buffer ) - 1 ] = '\0';
653 strcpy(buffer,"*=*");
654 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
657 sprintf(buffer,"%s=*", k);
658 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
661 sprintf(buffer,"*=%s", v);
662 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
665 sprintf(buffer,"%s=%s", k, v);
666 if ((idx=(int)g_hash_table_lookup(attr_hash, buffer)))
682 decode_entities(char *buffer)
687 while ((pos=strchr(pos, '&'))) {
689 for (i = 0 ; i < sizeof(entities)/sizeof(struct entity); i++) {
690 len=strlen(entities[i].entity);
691 if (!strncmp(pos, entities[i].entity, len)) {
693 memmove(pos+1, pos+len, strlen(pos+len)+1);
705 char k_buffer[BUFFER_SIZE];
706 char v_buffer[BUFFER_SIZE];
707 if (!xml_get_attribute(p, "k", k_buffer, BUFFER_SIZE))
709 if (!xml_get_attribute(p, "v", v_buffer, BUFFER_SIZE))
711 decode_entities(v_buffer);
712 add_tag(k_buffer, v_buffer);
724 static struct tile_head {
732 struct tile_head *next;
748 static struct buffer node_buffer = {
753 static char** th_get_subtile( const struct tile_head* th, int idx )
755 char* subtile_ptr = NULL;
756 subtile_ptr = (char*)th + sizeof( struct tile_head ) + idx * sizeof( char *);
757 return (char**)subtile_ptr;
761 extend_buffer(struct buffer *b)
763 b->malloced+=b->malloced_step;
764 b->base=realloc(b->base, b->malloced);
765 if (b->base == NULL) {
766 fprintf(stderr,"realloc of %d bytes failed\n",b->malloced);
773 GHashTable *node_hash;
776 node_buffer_to_hash(void)
778 int i,count=node_buffer.size/sizeof(struct node_item);
779 struct node_item *ni=(struct node_item *)node_buffer.base;
780 for (i = 0 ; i < count ; i++)
781 g_hash_table_insert(node_hash, (gpointer)(ni[i].id), (gpointer)i);
784 static struct node_item *ni;
787 add_node(int id, double lat, double lon)
789 if (node_buffer.size + sizeof(struct node_item) > node_buffer.malloced)
790 extend_buffer(&node_buffer);
793 item.type=type_point_unkn;
795 town_name_attr.len=0;
797 is_in_buffer[0]='\0';
798 sprintf(debug_attr_buffer,"nodeid=%d", nodeid);
799 ni=(struct node_item *)(node_buffer.base+node_buffer.size);
805 ni->c.x=lon*6371000.0*M_PI/180;
806 ni->c.y=log(tan(M_PI_4+lat*M_PI/360))*6371000.0;
807 node_buffer.size+=sizeof(struct node_item);
809 if (ni->id > nodeid_last) {
812 fprintf(stderr,"INFO: Nodes out of sequence (new %d vs old %d), adding hash\n", ni->id, nodeid_last);
813 node_hash=g_hash_table_new(NULL, NULL);
814 node_buffer_to_hash();
817 if (!g_hash_table_lookup(node_hash, (gpointer)(ni->id)))
818 g_hash_table_insert(node_hash, (gpointer)(ni->id), (gpointer)(ni-(struct node_item *)node_buffer.base));
820 node_buffer.size-=sizeof(struct node_item);
829 char id_buffer[BUFFER_SIZE];
830 char lat_buffer[BUFFER_SIZE];
831 char lon_buffer[BUFFER_SIZE];
832 if (!xml_get_attribute(p, "id", id_buffer, BUFFER_SIZE))
834 if (!xml_get_attribute(p, "lat", lat_buffer, BUFFER_SIZE))
836 if (!xml_get_attribute(p, "lon", lon_buffer, BUFFER_SIZE))
838 add_node(atoi(id_buffer), atof(lat_buffer), atof(lon_buffer));
843 static struct node_item *
844 node_item_get(int id)
846 struct node_item *ni=(struct node_item *)(node_buffer.base);
847 int count=node_buffer.size/sizeof(struct node_item);
848 int interval=count/4;
852 i=(int)(g_hash_table_lookup(node_hash, (gpointer)id));
855 while (ni[p].id != id) {
857 fprintf(stderr,"p=%d count=%d interval=%d id=%d ni[p].id=%d\n", p, count, interval, id, ni[p].id);
892 struct node_item *ni=node_item_get(id);
894 fprintf(stderr,"WARNING: node id %d not found\n", id);
906 item.type=type_street_unkn;
908 street_name_attr.len=0;
909 street_name_systematic_attr.len=0;
912 sprintf(debug_attr_buffer,"wayid=%d", wayid);
918 char id_buffer[BUFFER_SIZE];
919 if (!xml_get_attribute(p, "id", id_buffer, BUFFER_SIZE))
921 add_way(atoi(id_buffer));
926 parse_relation(char *p)
928 debug_attr_buffer[0]='\0';
933 write_attr(FILE *out, struct attr_bin *attr, void *buffer)
936 fwrite(attr, sizeof(*attr), 1, out);
937 fwrite(buffer, (attr->len-1)*4, 1, out);
942 attr_longest_match(struct attr_mapping **mapping, int mapping_count, enum item_type *types, int types_count)
944 int i,j,longest=0,ret=0,sum,val;
945 struct attr_mapping *curr;
946 for (i = 0 ; i < mapping_count ; i++) {
949 for (j = 0 ; j < curr->attr_present_idx_count ; j++) {
950 val=attr_present[curr->attr_present_idx[j]];
962 if (sum > 0 && sum == longest && ret < types_count)
963 types[ret++]=curr->type;
965 memset(attr_present, 0, sizeof(*attr_present)*attr_present_count);
973 enum item_type types[5];
977 if (dedupe_ways_hash) {
978 if (g_hash_table_lookup(dedupe_ways_hash, (gpointer)wayid))
980 g_hash_table_insert(dedupe_ways_hash, (gpointer)wayid, (gpointer)1);
982 count=attr_longest_match(attr_mapping_way, attr_mapping_way_count, types, sizeof(types)/sizeof(enum item_type));
983 pad_text_attr(&debug_attr, debug_attr_buffer);
985 alen+=label_attr.len+1;
986 if (street_name_systematic_attr.len)
987 alen+=street_name_systematic_attr.len+1;
989 alen+=debug_attr.len+1;
991 alen+=flags_attr.len+1;
995 item.type=type_street_unkn;
996 if (coverage && item_is_street(item))
997 item.type=type_coverage;
998 item.clen=coord_count*2;
999 item.len=item.clen+2+alen;
1000 fwrite(&item, sizeof(item), 1, out);
1001 fwrite(coord_buffer, coord_count*sizeof(struct coord), 1, out);
1002 if (item_is_street(item)) {
1003 street_name_attr.len=label_attr.len;
1004 write_attr(out, &street_name_attr, label_attr_buffer);
1006 write_attr(out, &label_attr, label_attr_buffer);
1007 write_attr(out, &street_name_systematic_attr, street_name_systematic_attr_buffer);
1008 write_attr(out, &debug_attr, debug_attr_buffer);
1009 write_attr(out, &flags_attr, &flags_attr_value);
1015 int alen=0,conflict=0,count;
1016 enum item_type types[5];
1017 struct country_table *result=NULL, *lookup;
1018 if (!out || ! node_is_tagged || ! nodeid)
1020 count=attr_longest_match(attr_mapping_node, attr_mapping_node_count, types, sizeof(types)/sizeof(enum item_type));
1021 pad_text_attr(&debug_attr, debug_attr_buffer);
1023 alen+=label_attr.len+1;
1025 alen+=debug_attr.len+1;
1029 item.type=type_point_unkn;
1031 item.len=item.clen+2+alen;
1032 fwrite(&item, sizeof(item), 1, out);
1033 fwrite(&ni->c, 1*sizeof(struct coord), 1, out);
1034 if (item_is_town(item)) {
1035 town_name_attr.len=label_attr.len;
1036 write_attr(out, &town_name_attr, label_attr_buffer);
1038 write_attr(out, &label_attr, label_attr_buffer);
1039 write_attr(out, &debug_attr, debug_attr_buffer);
1040 #ifdef GENERATE_INDEX
1041 if (item_is_town(item) && town_name_attr.len) {
1042 char *tok,*buf=is_in_buffer;
1043 while ((tok=strtok(buf, ","))) {
1046 lookup=g_hash_table_lookup(country_table_hash,tok);
1048 if (result && result->countryid != lookup->countryid) {
1049 fprintf(stderr,"conflict for %s %s country %d vs %d\n", label_attr_buffer, debug_attr_buffer, lookup->countryid, result->countryid);
1056 if (result && !conflict) {
1057 if (!result->file) {
1058 char *name=g_strdup_printf("country_%d.bin.unsorted", result->countryid);
1059 result->file=fopen(name,"w");
1064 item.len=item.clen+2+label_attr.len+1;
1065 fwrite(&item, sizeof(item), 1, result->file);
1066 fwrite(&ni->c, 1*sizeof(struct coord), 1, result->file);
1067 write_attr(result->file, &town_name_attr, label_attr_buffer);
1069 result->size+=(item.clen+3+label_attr.len+1)*4;
1075 processed_nodes_out++;
1079 sort_countries_compare(const void *p1, const void *p2)
1081 struct item_bin *ib1=*((struct item_bin **)p1),*ib2=*((struct item_bin **)p2);
1082 struct attr_bin *attr1,*attr2;
1084 assert(ib1->clen==2);
1085 assert(ib2->clen==2);
1086 attr1=(struct attr_bin *)((int *)(ib1+1)+ib1->clen);
1087 attr2=(struct attr_bin *)((int *)(ib2+1)+ib1->clen);
1088 assert(attr1->type == attr_town_name);
1089 assert(attr2->type == attr_town_name);
1090 s1=(char *)(attr1+1);
1091 s2=(char *)(attr2+1);
1092 return strcmp(s1, s2);
1094 fprintf(stderr,"sort_countries_compare p1=%p p2=%p %s %s\n",p1,p2,s1,s2);
1099 #ifdef GENERATE_INDEX
1101 sort_countries(void)
1104 struct country_table *co;
1106 struct item_bin *ib;
1108 char *p,*buffer,**idx,*name;
1109 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
1110 co=&country_table[i];
1116 buffer=malloc(co->size);
1117 assert(buffer != NULL);
1118 idx=malloc(co->count*sizeof(void *));
1119 assert(idx != NULL);
1120 name=g_strdup_printf("country_%d.bin.unsorted", co->countryid);
1123 fread(buffer, co->size, 1, f);
1128 for (j = 0 ; j < co->count ; j++) {
1130 p+=(*((int *)p)+1)*4;
1132 qsort(idx, co->count, sizeof(void *), sort_countries_compare);
1133 name=g_strdup_printf("country_%d.bin", co->countryid);
1135 for (j = 0 ; j < co->count ; j++) {
1136 ib=(struct item_bin *)(idx[j]);
1137 c=(struct coord *)(ib+1);
1138 fwrite(ib, (ib->len+1)*4, 1, f);
1140 bbox_extend(c, &co->r);
1152 add_nd(char *p, int ref)
1155 struct node_item *ni;
1156 ni=node_item_get(ref);
1159 coord_buffer[coord_count++]=ni->c;
1161 SET_REF(coord_buffer[coord_count], ref);
1167 if (len > 0 && p[len-1]=='\n')
1169 fprintf(stderr,"WARNING: way %d: node %d not found (%s)\n",wayid,ref,p);
1171 if (coord_count > 65536) {
1172 fprintf(stderr,"ERROR: Overflow\n");
1180 char ref_buffer[BUFFER_SIZE];
1181 if (!xml_get_attribute(p, "ref", ref_buffer, BUFFER_SIZE))
1183 add_nd(p, atoi(ref_buffer));
1189 save_buffer(char *filename, struct buffer *b)
1192 f=fopen(filename,"wb+");
1193 fwrite(b->base, b->size, 1, f);
1198 load_buffer(char *filename, struct buffer *b)
1204 f=fopen(filename,"rb");
1205 fseek(f, 0, SEEK_END);
1206 b->size=b->malloced=ftell(f);
1207 fprintf(stderr,"reading %d bytes from %s\n", b->size, filename);
1208 fseek(f, 0, SEEK_SET);
1209 b->base=malloc(b->size);
1210 assert(b->base != NULL);
1211 fread(b->base, b->size, 1, f);
1216 phase1(FILE *in, FILE *out_ways, FILE *out_nodes)
1222 while (fgets(buffer, size, in)) {
1223 p=strchr(buffer,'<');
1225 fprintf(stderr,"WARNING: wrong line %s\n", buffer);
1228 if (!strncmp(p, "<?xml ",6)) {
1229 } else if (!strncmp(p, "<osm ",5)) {
1230 } else if (!strncmp(p, "<bound ",7)) {
1231 } else if (!strncmp(p, "<node ",6)) {
1233 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1236 } else if (!strncmp(p, "<tag ",5)) {
1238 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1239 } else if (!strncmp(p, "<way ",5)) {
1242 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1244 } else if (!strncmp(p, "<nd ",4)) {
1246 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1247 } else if (!strncmp(p, "<relation ",10)) {
1249 if (!parse_relation(p))
1250 fprintf(stderr,"WARNING: failed to parse %s\n", buffer);
1251 processed_relations++;
1252 } else if (!strncmp(p, "<member ",8)) {
1253 } else if (!strncmp(p, "</node>",7)) {
1255 end_node(out_nodes);
1256 } else if (!strncmp(p, "</way>",6)) {
1259 } else if (!strncmp(p, "</relation>",11)) {
1261 } else if (!strncmp(p, "</osm>",6)) {
1263 fprintf(stderr,"WARNING: unknown tag in %s\n", buffer);
1271 #ifdef HAVE_POSTGRESQL
1273 phase1_db(char *dbstr, FILE *out_ways, FILE *out_nodes)
1276 PGresult *res,*node,*way,*tag;
1277 int count,tagged,i,j,k;
1278 long min, max, id, tag_id, node_id;
1282 conn=PQconnectdb(dbstr);
1284 fprintf(stderr,"Failed to connect to database with '%s'\n",dbstr);
1287 res=PQexec(conn, "begin");
1289 fprintf(stderr, "Cannot begin transaction: %s\n", PQerrorMessage(conn));
1293 res=PQexec(conn, "set transaction isolation level serializable");
1295 fprintf(stderr, "Cannot set isolation level: %s\n", PQerrorMessage(conn));
1299 res=PQexec(conn, "declare node cursor for select id,x(coordinate),y(coordinate) from node order by id");
1301 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1305 res=PQexec(conn, "declare way cursor for select id from way order by id");
1307 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1311 res=PQexec(conn, "declare relation cursor for select id from relation order by id");
1313 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1318 node=PQexec(conn, "fetch 100000 from node");
1320 fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
1324 count=PQntuples(node);
1327 min=atol(PQgetvalue(node, 0, 0));
1328 max=atol(PQgetvalue(node, count-1, 0));
1329 sprintf(query,"select node_id,name,value from node_tag where node_id >= %ld and node_id <= %ld order by node_id", min, max);
1330 tag=PQexec(conn, query);
1332 fprintf(stderr, "Cannot query node_tag: %s\n", PQerrorMessage(conn));
1336 for (i = 0 ; i < count ; i++) {
1337 id=atol(PQgetvalue(node, i, 0));
1338 add_node(id, atof(PQgetvalue(node, i, 1)), atof(PQgetvalue(node, i, 2)));
1342 while (j < PQntuples(tag)) {
1343 tag_id=atol(PQgetvalue(tag, j, 0));
1345 add_tag(PQgetvalue(tag, j, 1), PQgetvalue(tag, j, 2));
1355 end_node(out_nodes);
1362 way=PQexec(conn, "fetch 100000 from way");
1364 fprintf(stderr, "Cannot setup cursor for ways: %s\n", PQerrorMessage(conn));
1368 count=PQntuples(way);
1371 min=atol(PQgetvalue(way, 0, 0));
1372 max=atol(PQgetvalue(way, count-1, 0));
1373 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);
1374 node=PQexec(conn, query);
1376 fprintf(stderr, "Cannot query way_node: %s\n", PQerrorMessage(conn));
1379 sprintf(query,"select way_id,name,value from way_tag where way_id >= %ld and way_id <= %ld order by way_id", min, max);
1380 tag=PQexec(conn, query);
1382 fprintf(stderr, "Cannot query way_tag: %s\n", PQerrorMessage(conn));
1387 for (i = 0 ; i < count ; i++) {
1388 id=atol(PQgetvalue(way, i, 0));
1393 while (k < PQntuples(node)) {
1394 node_id=atol(PQgetvalue(node, k, 0));
1395 if (node_id == id) {
1396 add_nd("",atol(PQgetvalue(node, k, 1)));
1405 while (j < PQntuples(tag)) {
1406 tag_id=atol(PQgetvalue(tag, j, 0));
1408 add_tag(PQgetvalue(tag, j, 1), PQgetvalue(tag, j, 2));
1426 res=PQexec(conn, "commit");
1428 fprintf(stderr, "Cannot commit transaction: %s\n", PQerrorMessage(conn));
1438 static char buffer[150000];
1442 static struct item_bin *
1445 struct item_bin *ib=(struct item_bin *) buffer;
1447 r=fread(ib, sizeof(*ib), 1, in);
1451 assert((ib->len+1) < sizeof(buffer));
1452 s=(ib->len+1)*4-sizeof(*ib);
1453 r=fread(ib+1, s, 1, in);
1461 bbox_extend(struct coord *c, struct rect *r)
1474 bbox(struct coord *c, int count, struct rect *r)
1487 contains_bbox(int xl, int yl, int xh, int yh, struct rect *r)
1489 if (r->h.x < xl || r->h.x > xh) {
1492 if (r->l.x > xh || r->l.x < xl) {
1495 if (r->h.y < yl || r->h.y > yh) {
1498 if (r->l.y > yh || r->l.y < yl) {
1504 struct rect world_bbox = {
1505 { -20000000, -20000000},
1506 { 20000000, 20000000},
1510 tile(struct rect *r, char *ret, int max)
1519 for (i = 0 ; i < max ; i++) {
1526 if ( contains_bbox(x0,y0,x2,y2,r)) {
1530 } else if (contains_bbox(x2,y0,x4,y2,r)) {
1534 } else if (contains_bbox(x0,y2,x2,y4,r)) {
1538 } else if (contains_bbox(x2,y2,x4,y4,r)) {
1548 tile_bbox(char *tile, struct rect *r)
1553 c.x=(r->l.x+r->h.x)/2;
1554 c.y=(r->l.y+r->h.y)/2;
1577 GHashTable *tile_hash;
1578 GHashTable *tile_hash2;
1581 tile_extend(char *tile, struct item_bin *ib, GList **tiles_list)
1583 struct tile_head *th=NULL;
1584 if (debug_tile(tile))
1585 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);
1587 th=g_hash_table_lookup(tile_hash2, tile);
1589 th=g_hash_table_lookup(tile_hash, tile);
1591 th=malloc(sizeof(struct tile_head)+ sizeof( char* ) );
1593 // strcpy(th->subtiles, tile);
1596 th->total_size_used=0;
1599 th->name=string_hash_lookup(tile);
1600 *th_get_subtile( th, 0 ) = th->name;
1603 g_hash_table_insert(tile_hash2, string_hash_lookup( th->name ), th);
1605 *tiles_list=g_list_append(*tiles_list, string_hash_lookup( th->name ) );
1607 if (debug_tile(tile))
1608 fprintf(stderr,"new '%s'\n", tile);
1610 th->total_size+=ib->len*4+4;
1611 if (debug_tile(tile))
1612 fprintf(stderr,"New total size of %s(%p):%d\n", th->name, th, th->total_size);
1613 g_hash_table_insert(tile_hash, string_hash_lookup( th->name ), th);
1617 tile_data_size(char *tile)
1619 struct tile_head *th;
1620 th=g_hash_table_lookup(tile_hash, tile);
1623 return th->total_size;
1627 merge_tile(char *base, char *sub)
1629 struct tile_head *thb, *ths;
1630 thb=g_hash_table_lookup(tile_hash, base);
1631 ths=g_hash_table_lookup(tile_hash, sub);
1634 if (debug_tile(base) || debug_tile(sub))
1635 fprintf(stderr,"merging '%s'(%p) (%d) with '%s'(%p) (%d)\n", base, thb, thb ? thb->total_size : 0, sub, ths, ths->total_size);
1638 g_hash_table_remove(tile_hash, sub);
1639 thb->name=string_hash_lookup(base);
1640 g_hash_table_insert(tile_hash, string_hash_lookup( thb->name ), thb);
1643 thb=realloc(thb, sizeof(struct tile_head)+( ths->num_subtiles+thb->num_subtiles ) * sizeof( char*) );
1644 assert(thb != NULL);
1645 memcpy( th_get_subtile( thb, thb->num_subtiles ), th_get_subtile( ths, 0 ), ths->num_subtiles * sizeof( char*) );
1646 thb->num_subtiles+=ths->num_subtiles;
1647 thb->total_size+=ths->total_size;
1648 g_hash_table_insert(tile_hash, string_hash_lookup( thb->name ), thb);
1649 g_hash_table_remove(tile_hash, sub);
1657 get_tiles_list_func(char *key, struct tile_head *th, GList **list)
1659 *list=g_list_prepend(*list, key);
1663 get_tiles_list(void)
1666 g_hash_table_foreach(tile_hash, (GHFunc)get_tiles_list_func, &ret);
1672 write_tile(char *key, struct tile_head *th, gpointer dummy)
1676 fprintf(stderr,"DEBUG: Writing %s\n", key);
1677 strcpy(buffer,"tiles/");
1680 strcat(buffer,".bin");
1682 f=fopen(buffer, "wb+");
1684 fwrite(th->data, th->size, 1, f);
1692 write_item(char *tile, struct item_bin *ib)
1694 struct tile_head *th;
1697 th=g_hash_table_lookup(tile_hash2, tile);
1699 th=g_hash_table_lookup(tile_hash, tile);
1701 if (th->process != 0 && th->process != 1) {
1702 fprintf(stderr,"error with tile '%s' of length %d\n", tile, strlen(tile));
1707 if (debug_tile(tile))
1708 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);
1710 if (th->total_size_used+size > th->total_size) {
1711 fprintf(stderr,"Overflow in tile %s (used %d max %d item %d)\n", tile, th->total_size_used, th->total_size, size);
1715 memcpy(th->zip_data+th->total_size_used, ib, size);
1716 th->total_size_used+=size;
1718 fprintf(stderr,"no tile hash found for %s\n", tile);
1725 write_item_part(FILE *out, struct item_bin *orig, int first, int last)
1727 struct item_bin new;
1728 struct coord *c=(struct coord *)(orig+1);
1729 char *attr=(char *)(c+orig->clen/2);
1730 int attr_len=orig->len-orig->clen-2;
1732 new.type=orig->type;
1733 new.clen=(last-first+1)*2;
1734 new.len=new.clen+attr_len+2;
1736 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);
1738 fwrite(&new, sizeof(new), 1, out);
1739 fwrite(c+first, new.clen*4, 1, out);
1740 fwrite(attr, attr_len*4, 1, out);
1744 phase2(FILE *in, FILE *out)
1747 int i,ccount,last,ndref;
1748 struct item_bin *ib;
1749 struct node_item *ni;
1751 processed_nodes=processed_nodes_out=processed_ways=processed_relations=processed_tiles=0;
1753 while ((ib=read_item(in))) {
1755 fprintf(stderr,"type 0x%x len %d clen %d\n", ib->type, ib->len, ib->clen);
1758 c=(struct coord *)(ib+1);
1760 for (i = 0 ; i < ccount ; i++) {
1763 ni=node_item_get(ndref);
1765 fprintf(stderr,"ni=%p\n", ni);
1768 if (ni->ref_way > 1 && i != 0 && i != ccount-1 && item_is_street(*ib)) {
1769 write_item_part(out, ib, last, i);
1774 write_item_part(out, ib, last, ccount-1);
1782 phase34_process_file(int phase, FILE *in)
1784 struct item_bin *ib;
1789 while ((ib=read_item(in))) {
1790 if (ib->type < 0x80000000)
1794 bbox((struct coord *)(ib+1), ib->clen/2, &r);
1797 if (ib->type == type_street_n_lanes || ib->type == type_highway_city || ib->type == type_highway_land || ib->type == type_ramp)
1799 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)
1802 tile(&r, buffer, max);
1804 fprintf(stderr,"%s\n", buffer);
1807 tile_extend(buffer, ib, NULL);
1809 write_item(buffer, ib);
1814 struct item_bin item;
1816 struct attr_bin attr_order;
1819 struct attr_bin attr_zipfile_ref;
1824 index_submap_add(int phase, struct tile_head *th, GList **tiles_list)
1826 struct index_item ii;
1827 int len=strlen(th->name);
1828 char index_tile[len+1];
1830 ii.min=(len > 4) ? len-4 : 0;
1832 strcpy(index_tile, th->name);
1838 tile_bbox(th->name, &ii.r);
1840 ii.item.len=sizeof(ii)/4-1;
1841 ii.item.type=type_submap;
1844 ii.attr_order.len=2;
1845 ii.attr_order.type=attr_order;
1847 ii.attr_zipfile_ref.len=2;
1848 ii.attr_zipfile_ref.type=attr_zipfile_ref;
1849 ii.zipfile_ref=th->zipnum;
1852 tile_extend(index_tile, (struct item_bin *)&ii, tiles_list);
1854 write_item(index_tile, (struct item_bin *)&ii);
1856 unsigned int *c=(unsigned int *)ⅈ
1858 for (i = 0 ; i < sizeof(ii)/4 ; i++) {
1859 fprintf(stderr,"%08x ", c[i]);
1861 fprintf(stderr,"\n");
1866 add_tile_hash(struct tile_head *th)
1868 int idx,len,maxnamelen=0;
1872 g_hash_table_insert(tile_hash2, string_hash_lookup( th->name ), th);
1874 for( idx = 0; idx < th->num_subtiles; idx++ ) {
1876 data = th_get_subtile( th, idx );
1878 if (debug_tile(data) || debug_tile(th->name)) {
1879 fprintf(stderr,"Parent for '%s' is '%s'\n", *data, th->name);
1882 g_hash_table_insert(tile_hash2, *data, th);
1884 len = strlen( *data );
1886 if (len > maxnamelen) {
1895 create_tile_hash(void)
1897 struct tile_head *th;
1898 int len,maxnamelen=0;
1900 tile_hash2=g_hash_table_new(g_str_hash, g_str_equal);
1903 len=add_tile_hash(th);
1904 if (len > maxnamelen)
1912 create_tile_hash_list(GList *list)
1915 struct tile_head *th;
1917 tile_hash2=g_hash_table_new(g_str_hash, g_str_equal);
1919 fprintf(stderr,"list=%p\n", list);
1920 next=g_list_first(list);
1922 th=g_hash_table_lookup(tile_hash, next->data);
1924 fprintf(stderr,"No tile found for '%s'\n", (char *)(next->data));
1927 next=g_list_next(next);
1932 destroy_tile_hash(void)
1934 g_hash_table_destroy(tile_hash2);
1940 static void write_countrydir(int phase, int maxnamelen);
1943 write_tilesdir(int phase, int maxlen, FILE *out)
1946 GList *tiles_list,*next;
1948 struct tile_head *th,**last=NULL;
1951 tiles_list=get_tiles_list();
1953 create_tile_hash_list(tiles_list);
1954 next=g_list_first(tiles_list);
1955 last=&tile_head_root;
1958 if (strlen(next->data) > maxlen)
1959 maxlen=strlen(next->data);
1960 next=g_list_next(next);
1966 fprintf(stderr,"PROGRESS: collecting tiles with len=%d\n", len);
1968 #ifdef GENERATE_INDEX
1970 write_countrydir(phase, maxlen);
1972 next=g_list_first(tiles_list);
1974 if (strlen(next->data) == len) {
1975 th=g_hash_table_lookup(tile_hash, next->data);
1981 fprintf(out,"%s:%d",(char *)next->data,th->total_size);
1983 for ( idx = 0; idx< th->num_subtiles; idx++ ){
1984 data= th_get_subtile( th, idx );
1985 fprintf(out,":%s", *data);
1991 index_submap_add(phase, th, &tiles_list);
1995 next=g_list_next(next);
2004 struct tile_head *th;
2005 char basetile[1024];
2007 GList *tiles_list_sorted,*last;
2008 int i,i_min,len,size_all,size[5],size_min,work_done;
2012 tiles_list_sorted=get_tiles_list();
2013 fprintf(stderr,"PROGRESS: sorting %d tiles\n", g_list_length(tiles_list_sorted));
2014 tiles_list_sorted=g_list_sort(tiles_list_sorted, (GCompareFunc)strcmp);
2015 fprintf(stderr,"PROGRESS: sorting %d tiles done\n", g_list_length(tiles_list_sorted));
2016 last=g_list_last(tiles_list_sorted);
2019 th=g_hash_table_lookup(tile_hash, last->data);
2020 zip_size+=th->total_size;
2021 last=g_list_previous(last);
2023 fprintf(stderr,"DEBUG: size=%Ld\n", zip_size);
2024 last=g_list_last(tiles_list_sorted);
2028 len=strlen(last->data);
2030 strcpy(basetile,last->data);
2031 basetile[len-1]='\0';
2032 strcpy(subtile,last->data);
2033 for (i = 0 ; i < 4 ; i++) {
2034 subtile[len-1]='a'+i;
2035 size[i]=tile_data_size(subtile);
2037 size[4]=tile_data_size(basetile);
2038 size_all=size[0]+size[1]+size[2]+size[3]+size[4];
2039 if (size_all < 65536 && size_all > 0 && size_all != size[4]) {
2040 for (i = 0 ; i < 4 ; i++) {
2041 subtile[len-1]='a'+i;
2042 work_done+=merge_tile(basetile, subtile);
2048 for (i = 0 ; i < 4 ; i++) {
2049 if (size[i] && size[i] < size_min) {
2056 if (size[4]+size_min >= 65536)
2058 subtile[len-1]='a'+i_min;
2059 work_done+=merge_tile(basetile, subtile);
2060 size[4]+=size[i_min];
2065 last=g_list_previous(last);
2067 g_list_free(tiles_list_sorted);
2068 fprintf(stderr,"PROGRESS: merged %d tiles\n", work_done);
2069 } while (work_done);
2072 struct country_index_item {
2073 struct item_bin item;
2074 struct attr_bin attr_country_id;
2076 struct attr_bin attr_zipfile_ref;
2081 index_country_add(int phase, int country_id, int zipnum)
2083 struct country_index_item ii;
2084 char *index_tile="";
2086 ii.item.len=sizeof(ii)/4-1;
2087 ii.item.type=type_countryindex;
2090 ii.attr_country_id.len=2;
2091 ii.attr_country_id.type=attr_country_id;
2092 ii.country_id=country_id;
2094 ii.attr_zipfile_ref.len=2;
2095 ii.attr_zipfile_ref.type=attr_zipfile_ref;
2096 ii.zipfile_ref=zipnum;
2099 tile_extend(index_tile, (struct item_bin *)&ii, NULL);
2101 write_item(index_tile, (struct item_bin *)&ii);
2104 #ifdef GENERATE_INDEX
2112 add_aux_tile(int phase, char *name, char *filename, int size)
2114 struct aux_tile *at;
2116 at=g_new0(struct aux_tile, 1);
2117 at->name=g_strdup(name);
2118 at->filename=g_strdup(filename);
2120 aux_tile_list=g_list_append(aux_tile_list, at);
2126 write_aux_tiles(FILE *out, FILE *dir_out, int compression_level, int namelen)
2128 GList *l=aux_tile_list;
2129 struct aux_tile *at;
2136 buffer=malloc(at->size);
2137 assert(buffer != NULL);
2138 f=fopen(at->filename,"r");
2140 fread(buffer, at->size, 1, f);
2142 write_zipmember(out, dir_out, at->name, namelen, buffer, at->size, compression_level);
2150 write_countrydir(int phase, int maxnamelen)
2155 char searchtile[32];
2157 struct country_table *co;
2158 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
2159 co=&country_table[i];
2162 tile(&co->r, tilename, max);
2163 sprintf(searchtile,"%ss%d", tilename, 0);
2164 sprintf(filename,"country_%d.bin", co->countryid);
2165 zipnum=add_aux_tile(phase, searchtile, filename, co->size);
2166 index_country_add(phase,co->countryid,zipnum);
2172 remove_countryfiles(void)
2176 struct country_table *co;
2178 for (i = 0 ; i < sizeof(country_table)/sizeof(struct country_table) ; i++) {
2179 co=&country_table[i];
2181 sprintf(filename,"country_%d.bin", co->countryid);
2189 phase34(int phase, int maxnamelen, FILE *ways_in, FILE *nodes_in, FILE *tilesdir_out)
2192 processed_nodes=processed_nodes_out=processed_ways=processed_relations=processed_tiles=0;
2196 tile_hash=g_hash_table_new(g_str_hash, g_str_equal);
2198 phase34_process_file(phase, ways_in);
2200 phase34_process_file(phase, nodes_in);
2201 fprintf(stderr,"read %d bytes\n", bytes_read);
2206 write_tilesdir(phase, maxnamelen, tilesdir_out);
2213 dump_coord(struct coord *c)
2215 printf("0x%x 0x%x",c->x, c->y);
2221 struct item_bin *ib;
2229 while ((ib=read_item(in))) {
2230 c=(struct coord *)(ib+1);
2231 if (ib->type < type_line) {
2235 attr_start=(int *)(ib+1)+ib->clen;
2236 attr_end=(int *)ib+ib->len+1;
2237 printf("type=%s", item_to_name(ib->type));
2238 while (attr_start < attr_end) {
2239 a=(struct attr_bin *)(attr_start);
2240 attr_start+=a->len+1;
2242 attr_data_set(&attr, (a+1));
2243 str=attr_to_text(&attr, NULL, 1);
2244 printf(" %s=\"%s\"", attr_to_name(a->type), str);
2247 printf(" debug=\"length=%d\"", ib->len);
2249 if (ib->type >= type_line) {
2250 for (i = 0 ; i < ib->clen/2 ; i++) {
2260 phase3(FILE *ways_in, FILE *nodes_in, FILE *tilesdir_out)
2262 return phase34(3, 0, ways_in, nodes_in, tilesdir_out);
2265 static long long zipoffset;
2266 static int zipdir_size;
2269 compress2_int(Byte *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level)
2274 stream.next_in = (Bytef*)source;
2275 stream.avail_in = (uInt)sourceLen;
2276 stream.next_out = dest;
2277 stream.avail_out = (uInt)*destLen;
2278 if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
2280 stream.zalloc = (alloc_func)0;
2281 stream.zfree = (free_func)0;
2282 stream.opaque = (voidpf)0;
2284 err = deflateInit2(&stream, level, Z_DEFLATED, -15, 9, Z_DEFAULT_STRATEGY);
2285 if (err != Z_OK) return err;
2287 err = deflate(&stream, Z_FINISH);
2288 if (err != Z_STREAM_END) {
2289 deflateEnd(&stream);
2290 return err == Z_OK ? Z_BUF_ERROR : err;
2292 *destLen = stream.total_out;
2294 err = deflateEnd(&stream);
2299 write_zipmember(FILE *out, FILE *dir_out, char *name, int filelen, char *data, int data_size, int compression_level)
2301 struct zip_lfh lfh = {
2314 struct zip_cd cd = {
2335 char filename[filelen+1];
2336 int error,crc,len,comp_size=data_size;
2337 uLongf destlen=data_size+data_size/500+12;
2338 char compbuffer[destlen];
2340 crc=crc32(0, NULL, 0);
2341 crc=crc32(crc, (unsigned char *)data, data_size);
2342 if (compression_level) {
2343 error=compress2_int((Byte *)compbuffer, &destlen, (Bytef *)data, data_size, compression_level);
2344 if (error == Z_OK) {
2345 if (destlen < data_size) {
2350 fprintf(stderr,"compress2 returned %d\n", error);
2354 lfh.zipsize=comp_size;
2355 lfh.zipuncmp=data_size;
2356 lfh.zipmthd=compression_level ? 8:0;
2358 cd.zipcsiz=comp_size;
2359 cd.zipcunc=data_size;
2360 cd.zipcmthd=compression_level ? 8:0;
2361 strcpy(filename, name);
2362 len=strlen(filename);
2363 while (len < filelen) {
2364 filename[len++]='_';
2366 filename[filelen]='\0';
2367 fwrite(&lfh, sizeof(lfh), 1, out);
2368 fwrite(filename, filelen, 1, out);
2369 fwrite(data, comp_size, 1, out);
2370 zipoffset+=sizeof(lfh)+filelen+comp_size;
2371 fwrite(&cd, sizeof(cd), 1, dir_out);
2372 fwrite(filename, filelen, 1, dir_out);
2373 zipdir_size+=sizeof(cd)+filelen;
2377 process_slice(FILE *ways_in, FILE *nodes_in, int size, int maxnamelen, FILE *out, FILE *dir_out, int compression_level)
2379 struct tile_head *th;
2380 char *slice_data,*zip_data;
2383 slice_data=malloc(size);
2384 assert(slice_data != NULL);
2385 zip_data=slice_data;
2389 th->zip_data=zip_data;
2390 zip_data+=th->total_size;
2395 fseek(ways_in, 0, SEEK_SET);
2397 fseek(nodes_in, 0, SEEK_SET);
2398 phase34(4, maxnamelen, ways_in, nodes_in, NULL);
2403 #ifdef GENERATE_INDEX
2404 if (! strlen(th->name))
2405 zipfiles+=write_aux_tiles(out, dir_out, compression_level, maxnamelen);
2407 if (th->total_size != th->total_size_used) {
2408 fprintf(stderr,"Size error '%s': %d vs %d\n", th->name, th->total_size, th->total_size_used);
2411 if (strlen(th->name))
2412 write_zipmember(out, dir_out, th->name, maxnamelen, th->zip_data, th->total_size, compression_level);
2414 write_zipmember(out, dir_out, "index", sizeof("index")-1, th->zip_data, th->total_size, compression_level);
2427 cat(FILE *in, FILE *out)
2431 while ((size=fread(buffer, 1, 4096, in)))
2432 fwrite(buffer, 1, size, out);
2436 phase4(FILE *ways_in, FILE *nodes_in, FILE *out, FILE *dir_out, int compression_level)
2438 int slice_size=1024*1024*1024;
2439 int maxnamelen,size,slices;
2441 struct tile_head *th,*th2;
2442 struct zip_eoc eoc = {
2453 maxnamelen=create_tile_hash();
2458 fprintf(stderr, "Maximum slice size %d\n", slice_size);
2460 if (size + th->total_size > slice_size) {
2461 fprintf(stderr,"Slice %d is of size %d\n", slices, size);
2465 size+=th->total_size;
2469 fprintf(stderr,"Slice %d is of size %d\n", slices, size);
2480 while (th && size+th->total_size < slice_size) {
2481 size+=th->total_size;
2485 zipfiles+=process_slice(ways_in, nodes_in, size, maxnamelen, out, dir_out, compression_level);
2488 fseek(dir_out, 0, SEEK_SET);
2490 eoc.zipenum=zipfiles;
2491 eoc.zipecenn=zipfiles;
2492 eoc.zipecsz=zipdir_size;
2493 eoc.zipeofst=zipoffset;
2494 fwrite(&eoc, sizeof(eoc), 1, out);
2504 fprintf(f,"osm2navit - parse osm textfile and converts to NavIt binfile format\n\n");
2505 fprintf(f,"Usage :\n");
2506 fprintf(f,"bzcat planet.osm.bz2 | osm2navit mymap.bin\n");
2507 fprintf(f,"Available switches:\n");
2508 fprintf(f,"-h (--help) : this screen\n");
2509 fprintf(f,"-N (--nodes-only) : process only nodes\n");
2510 fprintf(f,"-W (--ways-only) : process only ways\n");
2511 fprintf(f,"-a (--attr-debug-level) : control which data is included in the debug attribute\n");
2512 fprintf(f,"-c (--dump-coordinates) : dump coordinates after phase 1\n");
2513 #ifdef HAVE_POSTGRESQL
2514 fprintf(f,"-d (--db) : get osm data out of a postgresql database with osm simple scheme and given connect string\n");
2516 fprintf(f,"-e (--end) : end at specified phase\n");
2517 fprintf(f,"-k (--keep-tmpfiles) : do not delete tmp files after processing. useful to reuse them\n\n");
2518 fprintf(f,"-o (--coverage) : map every street to item overage\n");
2519 fprintf(f,"-s (--start) : start at specified phase\n");
2520 fprintf(f,"-i (--input-file) : specify the input file name (OSM), overrules default stdin\n");
2521 fprintf(f,"-w (--dedupe-ways) : ensure no duplicate ways or nodes. useful when using several input files\n");
2522 fprintf(f,"-z (--compression-level) : set the compression level\n");
2527 process_binfile(FILE *in, FILE *out)
2529 struct item_bin *ib;
2530 while ((ib=read_item(in))) {
2531 fwrite(ib, (ib->len+1)*4, 1, out);
2535 int main(int argc, char **argv)
2537 FILE *ways=NULL,*ways_split=NULL,*nodes=NULL,*tilesdir,*zipdir,*res;
2538 char *map=g_strdup(attrmap);
2539 int i,c,start=1,end=4,dump_coordinates=0;
2540 int keep_tmpfiles=0;
2541 int process_nodes=1, process_ways=1;
2542 int compression_level=9;
2545 char *result,*dbstr=NULL;
2546 FILE* input_file = stdin;
2547 struct plugins *plugins=NULL;
2548 struct attr **attrs;
2552 int this_option_optind = optind ? optind : 1;
2554 int option_index = 0;
2555 static struct option long_options[] = {
2556 {"attr-debug-level", 1, 0, 'a'},
2557 {"binfile", 0, 0, 'b'},
2558 {"compression-level", 1, 0, 'z'},
2559 {"coverage", 0, 0, 'o'},
2560 #ifdef HAVE_POSTGRESQL
2563 {"dedupe-ways", 0, 0, 'w'},
2564 {"dump", 0, 0, 'D'},
2566 {"help", 0, 0, 'h'},
2567 {"keep-tmpfiles", 0, 0, 'k'},
2568 {"nodes-only", 0, 0, 'N'},
2570 {"plugin", 1, 0, 'p'},
2571 {"start", 1, 0, 's'},
2572 {"input-file", 1, 0, 'i'},
2573 {"ignore-unknown", 0, 0, 'n'},
2574 {"ways-only", 0, 0, 'W'},
2577 c = getopt_long (argc, argv, "DNWa:bc"
2578 #ifdef HAVE_POSTGRESQL
2581 "e:hi:knm:ps:w", long_options, &option_index);
2595 attr_debug_level=atoi(optarg);
2603 #ifdef HAVE_POSTGRESQL
2615 attrs=(struct attr*[]){
2616 &(struct attr){attr_type,{"textfile"}},
2617 &(struct attr){attr_data,{"bookmark.txt"}},
2620 fprintf(stderr,"optarg=%s\n", optarg);
2623 fprintf(stderr,"I will IGNORE unknown types\n");
2627 fprintf(stderr,"I will KEEP tmp files\n");
2635 plugins=plugins_new();
2636 attrs=(struct attr*[]){&(struct attr){attr_path,{optarg}},NULL};
2637 plugins_add_path(plugins, attrs);
2643 dedupe_ways_hash=g_hash_table_new(NULL, NULL);
2646 input_file = fopen( optarg, "r" );
2647 if ( input_file == NULL )
2649 fprintf( stderr, "\nInput file (%s) not found\n", optarg );
2654 compression_level=atoi(optarg);
2660 fprintf(stderr,"c=%d\n", c);
2664 if (optind != argc-(output == 1 ? 0:1))
2667 plugins_init(plugins);
2668 result=argv[optind];
2670 #ifdef GENERATE_INDEX
2671 build_countrytable();
2678 ways=fopen("ways.tmp","wb+");
2680 nodes=fopen("nodes.tmp","wb+");
2682 fprintf(stderr,"PROGRESS: Phase 1: collecting data\n");
2683 #ifdef HAVE_POSTGRESQL
2685 phase1_db(dbstr,ways,nodes);
2688 phase1(input_file,ways,nodes);
2693 #ifdef GENERATE_INDEX
2694 fprintf(stderr,"PROGRESS: Phase 1: sorting countries\n");
2698 if (end == 1 || dump_coordinates)
2699 save_buffer("coords.tmp",&node_buffer);
2703 load_buffer("coords.tmp",&node_buffer);
2706 ways=fopen("ways.tmp","rb");
2707 ways_split=fopen("ways_split.tmp","wb+");
2709 fprintf(stderr,"PROGRESS: Phase 2: finding intersections\n");
2710 phase2(ways,ways_split);
2716 fprintf(stderr,"PROGRESS: Skipping Phase 2\n");
2718 free(node_buffer.base);
2719 node_buffer.base=NULL;
2720 node_buffer.malloced=0;
2725 ways_split=fopen("ways_split.tmp","wb+");
2726 process_binfile(stdin, ways_split);
2730 fprintf(stderr,"PROGRESS: Phase 3: dumping\n");
2731 if (process_nodes) {
2732 nodes=fopen("nodes.tmp","rb");
2739 ways_split=fopen("ways_split.tmp","rb");
2749 fprintf(stderr,"PROGRESS: Phase 3: generating tiles\n");
2751 ways_split=fopen("ways_split.tmp","rb");
2753 nodes=fopen("nodes.tmp","rb");
2754 tilesdir=fopen("tilesdir.tmp","wb+");
2755 phase3(ways_split,nodes,tilesdir);
2766 fprintf(stderr,"PROGRESS: Phase 4: assembling map\n");
2768 ways_split=fopen("ways_split.tmp","rb");
2770 nodes=fopen("nodes.tmp","rb");
2771 res=fopen(result,"wb+");
2772 zipdir=fopen("zipdir.tmp","wb+");
2773 phase4(ways_split,nodes,res,zipdir,compression_level);
2780 if(!keep_tmpfiles) {
2781 remove("nodes.tmp");
2782 remove("ways_split.tmp");
2783 remove("tilesdir.tmp");
2784 remove("zipdir.tmp");
2785 #ifdef GENERATE_INDEX
2786 remove_countryfiles();