diff --git a/src/Makefile.am b/src/Makefile.am index b074e52fe..7019e5b38 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -226,6 +226,7 @@ nobase_dist_HEADERS = \ overpass_api/core/index_computations.h\ overpass_api/core/parsed_query.h\ overpass_api/core/settings.h\ + overpass_api/core/tag_list.h\ overpass_api/core/type_area.h\ overpass_api/core/type_node.h\ overpass_api/core/type_relation.h\ @@ -278,6 +279,7 @@ nobase_dist_HEADERS = \ overpass_api/osm-backend/way_updater.h\ overpass_api/output_formats/output_csv.h\ overpass_api/output_formats/output_custom.h\ + overpass_api/output_formats/fixed7.h\ overpass_api/output_formats/output_json.h\ overpass_api/output_formats/output_popup.h\ overpass_api/output_formats/output_xml.h\ diff --git a/src/expat/escape_json.cc b/src/expat/escape_json.cc index 27a183b71..948444202 100644 --- a/src/expat/escape_json.cc +++ b/src/expat/escape_json.cc @@ -16,31 +16,82 @@ * along with Overpass_API. If not, see . */ +#include #include #include "escape_json.h" -std::string escape_cstr(const std::string& s) +namespace { - std::string result; - result.reserve(s.length()*2); - for (std::string::size_type i(0); i < s.size(); ++i) + +struct Replacements +{ + Replacements() + { + for (int c = 0; c < 256; ++c) + replacement[c] = c < 32 ? "?" : 0; + replacement[(unsigned char)'\"'] = "\\\""; + replacement[(unsigned char)'\\'] = "\\\\"; + replacement[(unsigned char)'\n'] = "\\n"; + replacement[(unsigned char)'\t'] = "\\t"; + replacement[(unsigned char)'\r'] = "\\r"; + } + + // What each byte is written as, or 0 if it is written as it is. + const char* replacement[256]; +}; + + +const Replacements& replacements() +{ + static const Replacements result; + return result; +} + + +struct Stream_Sink +{ + std::ostream& out; + void append(const char* s, std::string::size_type n) { out.write(s, n); } + void append(const char* s) { out< +void write_escaped(const std::string& s, Sink& sink) +{ + const Replacements& table = replacements(); + const char* run = s.data(); + const char* end = s.data() + s.size(); + for (const char* pos = run; pos != end; ++pos) { - if (s[i] == '\"') - result += "\\\""; - else if (s[i] == '\\') - result += "\\\\"; - else if (s[i] == '\n') - result += "\\n"; - else if (s[i] == '\t') - result += "\\t"; - else if (s[i] == '\r') - result += "\\r"; - else if ((unsigned char)s[i] < 32) - result += '?'; - else - result += s[i]; + const char* replacement = table.replacement[(unsigned char)*pos]; + if (replacement) + { + sink.append(run, pos - run); + sink.append(replacement); + run = pos + 1; + } } + sink.append(run, end - run); +} + +} + + +std::string escape_cstr(const std::string& s) +{ + std::string result; + result.reserve(s.size()); + write_escaped(s, result); return result; } + + +std::ostream& operator<<(std::ostream& out, const Json_Escaped& e) +{ + Stream_Sink sink{out}; + write_escaped(e.s, sink); + return out; +} diff --git a/src/expat/escape_json.h b/src/expat/escape_json.h index 78c57b0d6..dfc1b0d18 100644 --- a/src/expat/escape_json.h +++ b/src/expat/escape_json.h @@ -19,10 +19,21 @@ #ifndef DE__OSM3S___EXPAT__ESCAPE_JSON_H #define DE__OSM3S___EXPAT__ESCAPE_JSON_H +#include #include std::string escape_cstr(const std::string& s); +// Writes escape_cstr(s) to a stream without building the escaped copy. s must outlive the expression. +struct Json_Escaped +{ + explicit Json_Escaped(const std::string& s_) : s(s_) {} + const std::string& s; +}; + +std::ostream& operator<<(std::ostream& out, const Json_Escaped& e); + + #endif diff --git a/src/expat/escape_xml.cc b/src/expat/escape_xml.cc index d80cf441b..77d2ac9ea 100644 --- a/src/expat/escape_xml.cc +++ b/src/expat/escape_xml.cc @@ -16,36 +16,84 @@ * along with Overpass_API. If not, see . */ +#include #include #include "escape_xml.h" -std::string escape_xml(const std::string& s) +namespace { - const char* digit = "0123456789abcdef"; - std::string result; - result.reserve(s.length()*2); - for (std::string::size_type i(0); i < s.size(); ++i) +struct Replacements +{ + Replacements() { - if (s[i] == '&') - result += "&"; - else if (s[i] == '\"') - result += """; - else if (s[i] == '<') - result += "<"; - else if (s[i] == '>') - result += ">"; - else if ((unsigned char)s[i] < 32) + for (int c = 0; c < 256; ++c) + replacement[c] = c < 32 ? "?" : 0; + replacement[(unsigned char)'&'] = "&"; + replacement[(unsigned char)'\"'] = """; + replacement[(unsigned char)'<'] = "<"; + replacement[(unsigned char)'>'] = ">"; + replacement[(unsigned char)'\t'] = " "; + replacement[(unsigned char)'\n'] = " "; + replacement[(unsigned char)'\r'] = " "; + } + + // What each byte is written as, or 0 if it is written as it is. + const char* replacement[256]; +}; + + +const Replacements& replacements() +{ + static const Replacements result; + return result; +} + + +struct Stream_Sink +{ + std::ostream& out; + void append(const char* s, std::string::size_type n) { out.write(s, n); } + void append(const char* s) { out< +void write_escaped(const std::string& s, Sink& sink) +{ + const Replacements& table = replacements(); + const char* run = s.data(); + const char* end = s.data() + s.size(); + for (const char* pos = run; pos != end; ++pos) + { + const char* replacement = table.replacement[(unsigned char)*pos]; + if (replacement) { - if ((s[i] == '\n') || (s[i] == '\t') || (s[i] == '\r')) - result += std::string("&#x") + digit[s[i] / 16] + digit[s[i] % 16] + ';'; - else - result += '?'; + sink.append(run, pos - run); + sink.append(replacement); + run = pos + 1; } - else - result += s[i]; } + sink.append(run, end - run); +} + +} + + +std::string escape_xml(const std::string& s) +{ + std::string result; + result.reserve(s.size()); + write_escaped(s, result); return result; } + + +std::ostream& operator<<(std::ostream& out, const Xml_Escaped& e) +{ + Stream_Sink sink{out}; + write_escaped(e.s, sink); + return out; +} diff --git a/src/expat/escape_xml.h b/src/expat/escape_xml.h index 36284682e..e6d2b5644 100644 --- a/src/expat/escape_xml.h +++ b/src/expat/escape_xml.h @@ -19,10 +19,21 @@ #ifndef DE__OSM3S___EXPAT__ESCAPE_XML_H #define DE__OSM3S___EXPAT__ESCAPE_XML_H +#include #include std::string escape_xml(const std::string& s); +// Writes escape_xml(s) to a stream without building the escaped copy. s must outlive the expression. +struct Xml_Escaped +{ + explicit Xml_Escaped(const std::string& s_) : s(s_) {} + const std::string& s; +}; + +std::ostream& operator<<(std::ostream& out, const Xml_Escaped& e); + + #endif diff --git a/src/overpass_api/core/tag_list.h b/src/overpass_api/core/tag_list.h new file mode 100644 index 000000000..102702f16 --- /dev/null +++ b/src/overpass_api/core/tag_list.h @@ -0,0 +1,47 @@ +/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. + * + * This file is part of Overpass_API. + * + * Overpass_API is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * Overpass_API is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Overpass_API. If not, see . + */ + +#ifndef DE__OSM3S___OVERPASS_API__CORE__TAG_LIST_H +#define DE__OSM3S___OVERPASS_API__CORE__TAG_LIST_H + +#include +#include +#include + + +// A tag that refers to a key and value stored elsewhere. +struct Tag_Ref +{ + Tag_Ref(const std::string& first_, const std::string& second_) : first(first_), second(second_) {} + const std::string& first; + const std::string& second; +}; + +typedef std::vector< Tag_Ref > Tag_List; + + +inline void make_tag_list(const std::vector< std::pair< std::string, std::string > >& tags, Tag_List& result) +{ + result.clear(); + result.reserve(tags.size()); + for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) + result.push_back(Tag_Ref(it->first, it->second)); +} + + +#endif diff --git a/src/overpass_api/core/type_node.h b/src/overpass_api/core/type_node.h index 3bda1e9a6..5b126d7d6 100644 --- a/src/overpass_api/core/type_node.h +++ b/src/overpass_api/core/type_node.h @@ -58,12 +58,33 @@ struct Node }; +// A node's id and position without Node's tag vector, so it takes 16 bytes instead of 40. +// The geometry stores keep many of these to look up the coordinates of way and relation members. +struct Node_Position +{ + typedef Node::Id_Type Id_Type; + + Id_Type id; + uint32 index; + uint32 ll_lower_; + + Node_Position(Id_Type id_, uint32 ll_upper_, uint32 ll_lower__) + : id(id_), index(ll_upper_), ll_lower_(ll_lower__) + {} +}; + + struct Node_Comparator_By_Id { bool operator() (const Node& a, const Node& b) { return (a.id.val() < b.id.val()); } + bool operator() (const Node_Position& a, const Node_Position& b) + { + return (a.id.val() < b.id.val()); + } + bool operator() (const Node* a, const Node* b) { return (a->id.val() < b->id.val()); diff --git a/src/overpass_api/core/type_tags.h b/src/overpass_api/core/type_tags.h index bc3cdf0f6..1ce0c59ce 100644 --- a/src/overpass_api/core/type_tags.h +++ b/src/overpass_api/core/type_tags.h @@ -239,6 +239,15 @@ struct Tag_Index_Local }; +// The cell part of a Tag_Index_Local entry's index, read from the raw entry under a block +// iterator: (it.index().index & 0x7fffff00) without decoding the key and value. +template< typename Iterator > +inline uint32 tag_coarse_index(const Iterator& it) +{ + return ((*((uint32*)it.index_raw() + 1))<<8) & 0x7fffff00; +} + + inline const std::string& void_tag_value() { static std::string void_value = " "; @@ -268,6 +277,22 @@ Ranges< Tag_Index_Local > formulate_range_query(const std::map< uint32, Value >& } +// The tag entries of only the given keys, which must be sorted, in the given coarse indices. +// key + '\0' sorts after every entry of key and before any longer key that starts with it. +template< class Value, class Key_Container > +Ranges< Tag_Index_Local > formulate_range_query( + const std::map< uint32, Value >& coarse_indices, const Key_Container& keys) +{ + Ranges< Tag_Index_Local > ranges; + for (typename std::map< uint32, Value >::const_iterator it = coarse_indices.begin(); it != coarse_indices.end(); ++it) + { + for (typename Key_Container::const_iterator kit = keys.begin(); kit != keys.end(); ++kit) + ranges.push_back({ it->first, kit->first, "" }, { it->first, kit->first + std::string(1, '\0'), "" }); + } + return ranges; +} + + template< class TIndex, class TObject > void generate_ids_by_coarse (std::map< uint32, std::vector< typename TObject::Id_Type > >& ids_by_coarse, @@ -290,9 +315,6 @@ void generate_ids_by_coarse std::sort(ids_by_coarse_.begin(), ids_by_coarse_.end()); ids_by_coarse_.erase(std::unique(ids_by_coarse_.begin(), ids_by_coarse_.end()), ids_by_coarse_.end()); } - for (typename std::map< uint32, std::vector< typename TObject::Id_Type > >::iterator - it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) - std::sort(it->second.begin(), it->second.end()); } @@ -319,9 +341,61 @@ void generate_ids_by_coarse std::sort(ids_by_coarse_.begin(), ids_by_coarse_.end()); ids_by_coarse_.erase(std::unique(ids_by_coarse_.begin(), ids_by_coarse_.end()), ids_by_coarse_.end()); } +} + + +// As generate_ids_by_coarse, but only for the elements with ids in [lower_id_bound, upper_id_bound), +// so that a chunk of output needs the ids of that chunk only. +template< class TIndex, class TObject > +void generate_ids_by_coarse + (std::map< uint32, std::vector< typename TObject::Id_Type > >& ids_by_coarse, + const std::map< TIndex, std::vector< TObject > >& items, + typename TObject::Id_Type lower_id_bound, typename TObject::Id_Type upper_id_bound) +{ + for (typename std::map< TIndex, std::vector< TObject > >::const_iterator + it(items.begin()); it != items.end(); ++it) + { + for (typename std::vector< TObject >::const_iterator it2(it->second.begin()); + it2 != it->second.end(); ++it2) + { + if (!(it2->id < lower_id_bound) && it2->id < upper_id_bound) + ids_by_coarse[it->first.val() & 0x7fffff00].push_back(it2->id); + } + } + + for (typename std::map< uint32, std::vector< typename TObject::Id_Type > >::iterator + it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) + { + std::sort(it->second.begin(), it->second.end()); + it->second.erase(std::unique(it->second.begin(), it->second.end()), it->second.end()); + } +} + + +template< class TIndex, class TObject > +void generate_ids_by_coarse + (std::map< uint32, std::vector< Attic< typename TObject::Id_Type > > >& ids_by_coarse, + const std::map< TIndex, std::vector< TObject > >& items, + typename TObject::Id_Type lower_id_bound, typename TObject::Id_Type upper_id_bound) +{ + for (typename std::map< TIndex, std::vector< TObject > >::const_iterator + it(items.begin()); it != items.end(); ++it) + { + for (typename std::vector< TObject >::const_iterator it2(it->second.begin()); + it2 != it->second.end(); ++it2) + { + if (!(it2->id < lower_id_bound) && it2->id < upper_id_bound) + ids_by_coarse[it->first.val() & 0x7fffff00].push_back + (Attic< typename TObject::Id_Type >(it2->id, it2->timestamp)); + } + } + for (typename std::map< uint32, std::vector< Attic< typename TObject::Id_Type > > >::iterator it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) + { std::sort(it->second.begin(), it->second.end()); + it->second.erase(std::unique(it->second.begin(), it->second.end()), it->second.end()); + } } diff --git a/src/overpass_api/data/abstract_processing.h b/src/overpass_api/data/abstract_processing.h index 143173665..396b83bcc 100644 --- a/src/overpass_api/data/abstract_processing.h +++ b/src/overpass_api/data/abstract_processing.h @@ -22,6 +22,9 @@ #include "../core/datatypes.h" #include "../statements/statement.h" #include "filenames.h" +#include +#include +#include //----------------------------------------------------------------------------- @@ -83,19 +86,61 @@ class Trivial_Predicate //----------------------------------------------------------------------------- +/* A one-bit-per-hash-slot filter over a set of ids. It answers "definitely + not in the set" with a single bit test, and "maybe in the set" otherwise. + It uses about 16 bits per id (at most 16 MiB), so a false "maybe" happens + for roughly 6% of absent ids while the cap is not reached. */ +class Id_Bit_Filter +{ +public: + template< typename Id_Type > + explicit Id_Bit_Filter(const std::vector< Id_Type >& ids) + { + unsigned log_bits = 6; + while (log_bits < 27 && (uint64(1) << log_bits) < uint64(ids.size())*16) + ++log_bits; + shift = 64 - log_bits; + bits.assign((uint64(1) << log_bits)/64, 0); + for (typename std::vector< Id_Type >::const_iterator it = ids.begin(); it != ids.end(); ++it) + { + uint64 h = slot(it->val()); + bits[h>>6] |= uint64(1) << (h & 63); + } + } + + bool maybe_contains(uint64 id) const + { + uint64 h = slot(id); + return (bits[h>>6] >> (h & 63)) & 1; + } + +private: + uint64 slot(uint64 id) const { return (id * 0x9E3779B97F4A7C15ull) >> shift; } + + std::vector< uint64 > bits; + unsigned shift; +}; + + template < class Object > class Id_Predicate { public: Id_Predicate(const std::vector< typename Object::Id_Type >& ids_) - : ids(ids_) {} - bool match(const Object& obj) const { return std::binary_search(ids.begin(), ids.end(), obj.id); } - bool match(const Handle< Object >& h) const { return std::binary_search(ids.begin(), ids.end(), h.id()); } - bool match(const Handle< Attic< Object > >& h) const { return std::binary_search(ids.begin(), ids.end(), h.id()); } + : ids(ids_), filter(std::make_shared< const Id_Bit_Filter >(ids_)) {} + bool match(const Object& obj) const { return contains(obj.id); } + bool match(const Handle< Object >& h) const { return contains(h.id()); } + bool match(const Handle< Attic< Object > >& h) const { return contains(h.id()); } bool possible() const { return !ids.empty(); } private: + // Most candidates are not in ids, so the filter rejects them before the + // binary search; the binary search keeps the answer exact. + bool contains(const typename Object::Id_Type& id) const + { return filter->maybe_contains(id.val()) && std::binary_search(ids.begin(), ids.end(), id); } + const std::vector< typename Object::Id_Type >& ids; + std::shared_ptr< const Id_Bit_Filter > filter; }; //----------------------------------------------------------------------------- diff --git a/src/overpass_api/data/bbox_filter.cc b/src/overpass_api/data/bbox_filter.cc index 4b75a5049..fea693fcc 100644 --- a/src/overpass_api/data/bbox_filter.cc +++ b/src/overpass_api/data/bbox_filter.cc @@ -45,8 +45,9 @@ void filter_by_bbox(const Bbox_Double& bbox, std::map< Index, std::vector< Coord for (typename std::map< Index, std::vector< Coord > >::iterator it = nodes.begin(); it != nodes.end(); ++it) { - std::vector< Coord > local_into; - for (typename std::vector< Coord >::const_iterator iit = it->second.begin(); + // Compact in place, keeping the order, and drop the slack left by growing the vector. + typename std::vector< Coord >::iterator out = it->second.begin(); + for (typename std::vector< Coord >::iterator iit = it->second.begin(); iit != it->second.end(); ++iit) { uint32 lat(::ilat(it->first.val(), iit->ll_lower)); @@ -54,9 +55,14 @@ void filter_by_bbox(const Bbox_Double& bbox, std::map< Index, std::vector< Coord if ((lat >= south) && (lat <= north) && (((lon >= west) && (lon <= east)) || ((east < west) && ((lon >= west) || (lon <= east))))) - local_into.push_back(*iit); + { + if (out != iit) + *out = *iit; + ++out; + } } - it->second.swap(local_into); + it->second.erase(out, it->second.end()); + it->second.shrink_to_fit(); } } @@ -198,13 +204,41 @@ void filter_relations_expensive(const Bbox_Filter& filter, } +// Whether the whole area of a way or relation index lies in the bbox. Every node of a way +// with that index is then in the bbox, so the way matches without loading its geometry. +bool contains_index_area(const Bbox_Double& bbox, Uint31_Index idx) +{ + if (bbox.west > bbox.east || bbox.east - bbox.west >= 180.) + return false; + + std::pair< Uint32_Index, Uint32_Index > bounds = calc_bbox_bounds(idx); + uint32 south_west = bounds.first.val(); + uint32 north_east = bounds.second.val() - 1; + return bbox.south <= ::lat(south_west, 0u) && ::lat(north_east, 0xffffffffu) <= bbox.north + && bbox.west <= ::lon(south_west, 0u) && ::lon(north_east, 0xffffffffu) <= bbox.east; +} + + void Bbox_Filter::filter(const Statement& query, Resource_Manager& rman, Set& into) const { if (!bbox.valid()) return; - //Process ways + //Process ways: only those whose index area isn't inside the bbox need their geometry + std::map< Uint31_Index, std::vector< Way_Skeleton > > ways_inside; + for (auto it = into.ways.begin(); it != into.ways.end(); ) + { + if (contains_index_area(bbox, it->first)) + { + ways_inside[it->first].swap(it->second); + it = into.ways.erase(it); + } + else + ++it; + } filter_ways_expensive(*this, Way_Geometry_Store(into.ways, query, rman), into.ways); + for (auto it = ways_inside.begin(); it != ways_inside.end(); ++it) + into.ways[it->first].swap(it->second); Request_Context context(&query, rman); { diff --git a/src/overpass_api/data/collect_items.h b/src/overpass_api/data/collect_items.h index 2964d7061..6ae979de9 100644 --- a/src/overpass_api/data/collect_items.h +++ b/src/overpass_api/data/collect_items.h @@ -35,6 +35,28 @@ inline uint64 timestamp_of(const Way_Skeleton& skel) { return NOW; } inline uint64 timestamp_of(const Relation_Skeleton& skel) { return NOW; } + +// Appends to std::map< Index, std::vector< Object > > entries, remembering the last slot: +// block iterators deliver runs of objects with the same index. +template< typename Index, typename Object > +struct Indexed_Appender +{ + Indexed_Appender(std::map< Index, std::vector< Object > >& target_) + : target(&target_), last(target_.end()) {} + + void push_back(const Index& idx, const Object& obj) + { + if (last == target->end() || !(last->first == idx)) + last = target->insert(target->end(), std::make_pair(idx, std::vector< Object >())); + last->second.push_back(obj); + } + +private: + std::map< Index, std::vector< Object > >* target; + typename std::map< Index, std::vector< Object > >::iterator last; +}; + + template < class Index, class Object, class Iterator, class Predicate > void reconstruct_items( Iterator& it, const Iterator& end, Index index, @@ -60,6 +82,12 @@ void reconstruct_items( class Statement; +// A chunk of collected elements also ends once its accounted size (as eval_map counts it) reaches +// this, so a query whose filters drop most candidates doesn't hold all of them at once when its +// [maxsize:] budget is large. 16 MiB accounted is 2M nodes or 128k ways. +const uint64 MAX_CHUNK_ACCOUNTED_SIZE = 16ull*1024*1024; + + class Health_Guard { public: @@ -248,6 +276,15 @@ void check_for_duplicated_objects( } +// The size eval_map counts for the entry of m at idx, or 0 if m has none. +template< typename Index, typename Object > +uint64 eval_entry(const std::map< Index, std::vector< Object > >& m, const Index& idx) +{ + auto it = m.find(idx); + return it == m.end() ? 0 : eval_index_size + it->second.size()*eval_object_size((const Object*)0); +} + + template < class Index, class Object, class Current_Iterator, class Attic_Iterator, class Predicate > bool collect_items_by_timestamp(Health_Guard&& health_guard, Current_Iterator current_begin, Current_Iterator current_end, @@ -257,6 +294,10 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, std::map< Index, std::vector< Attic< Object > > >& attic_result) { uint32 count = 0; + // The sizes eval_map would report for result and attic_result, kept up to date per index + // instead of recounted: recounting walks the whole maps. + uint64 result_size = eval_map(result); + uint64 attic_size = eval_map(attic_result); while (!(current_begin == current_end) || !(attic_begin == attic_end)) { std::vector< std::pair< typename Object::Id_Type, uint64 > > timestamp_by_id; @@ -265,8 +306,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, if (++count >= 128*1024) { count = 0; - health_guard.check(0, eval_map(result)); - health_guard.check(0, eval_map(attic_result)); + uint64 chunk_size = result_size + attic_size; + too_much_data = health_guard.check(0, chunk_size) || chunk_size >= MAX_CHUNK_ACCOUNTED_SIZE; } Index index = (attic_begin == attic_end || @@ -278,6 +319,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, return true; } + uint64 result_before = eval_entry(result, index); + uint64 attic_before = eval_entry(attic_result, index); reconstruct_items( current_begin, current_end, index, predicate, result[index], timestamp_by_id, timestamp, count); reconstruct_items( @@ -287,6 +330,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, filter_items_by_timestamp(timestamp_by_id, result[index]); filter_items_by_timestamp(timestamp_by_id, attic_result[index]); + result_size += eval_entry(result, index) - result_before; + attic_size += eval_entry(attic_result, index) - attic_before; //check_for_duplicated_objects< Object >(timestamp_by_id, rman); } @@ -303,6 +348,10 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, std::map< Index, std::vector< Attic< Relation_Skeleton > > >& attic_result) { uint32 count = 0; + // The sizes eval_map would report for result and attic_result, kept up to date per index + // instead of recounted: recounting walks the whole maps. + uint64 result_size = eval_map(result); + uint64 attic_size = eval_map(attic_result); while (!(current_begin == current_end) || !(attic_begin == attic_end)) { std::vector< std::pair< Relation_Skeleton::Id_Type, uint64 > > timestamp_by_id; @@ -311,8 +360,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, if (++count >= 128*1024) { count = 0; - health_guard.check(0, eval_map(result)); - health_guard.check(0, eval_map(attic_result)); + uint64 chunk_size = result_size + attic_size; + too_much_data = health_guard.check(0, chunk_size) || chunk_size >= MAX_CHUNK_ACCOUNTED_SIZE; } Index index = (attic_begin == attic_end || @@ -324,6 +373,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, return true; } + uint64 result_before = eval_entry(result, index); + uint64 attic_before = eval_entry(attic_result, index); reconstruct_items(health_guard, current_begin, current_end, attic_begin, attic_end, index, predicate, result[index], attic_result[index], timestamp_by_id, timestamp); @@ -331,6 +382,11 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, filter_items_by_timestamp(timestamp_by_id, result[index]); filter_items_by_timestamp(timestamp_by_id, attic_result[index]); + result_size += eval_entry(result, index) - result_before; + attic_size += eval_entry(attic_result, index) - attic_before; + // Count elements, not only indexes, so the size check above runs every 128K or so elements: + // a whole extract can have fewer way or relation indexes than that. + count += result[index].size() + attic_result[index].size(); //check_for_duplicated_objects< Relation_Skeleton >(timestamp_by_id, rman); } @@ -388,6 +444,10 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, std::map< Index, std::vector< Attic< Way_Skeleton > > >& attic_result) { uint32 count = 0; + // The sizes eval_map would report for result and attic_result, kept up to date per index + // instead of recounted: recounting walks the whole maps. + uint64 result_size = eval_map(result); + uint64 attic_size = eval_map(attic_result); while (!(current_begin == current_end) || !(attic_begin == attic_end)) { std::vector< std::pair< Way_Skeleton::Id_Type, uint64 > > timestamp_by_id; @@ -396,8 +456,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, if (++count >= 128*1024) { count = 0; - health_guard.check(0, eval_map(result)); - health_guard.check(0, eval_map(attic_result)); + uint64 chunk_size = result_size + attic_size; + too_much_data = health_guard.check(0, chunk_size) || chunk_size >= MAX_CHUNK_ACCOUNTED_SIZE; } Index index = (attic_begin == attic_end || @@ -409,6 +469,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, return true; } + uint64 result_before = eval_entry(result, index); + uint64 attic_before = eval_entry(attic_result, index); reconstruct_items(health_guard, current_begin, current_end, attic_begin, attic_end, index, predicate, result[index], attic_result[index], timestamp_by_id, timestamp); @@ -416,6 +478,11 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, filter_items_by_timestamp(timestamp_by_id, result[index]); filter_items_by_timestamp(timestamp_by_id, attic_result[index]); + result_size += eval_entry(result, index) - result_before; + attic_size += eval_entry(attic_result, index) - attic_before; + // Count elements, not only indexes, so the size check above runs every 128K or so elements: + // a whole extract can have fewer way or relation indexes than that. + count += result[index].size() + attic_result[index].size(); //check_for_duplicated_objects< Way_Skeleton >(timestamp_by_id, rman); } @@ -431,10 +498,11 @@ void collect_items_discrete(Transaction& transaction, { Block_Backend< Index, Object, typename Container::const_iterator > db (transaction.data_index(&file_properties)); + Indexed_Appender< Index, Object > append(result); for (auto it = db.discrete_begin(req.begin(), req.end()); !(it == db.discrete_end()); ++it) { if (predicate.match(it.handle())) - result[it.index()].push_back(it.object()); + append.push_back(it.index(), it.object()); } } @@ -450,10 +518,11 @@ void collect_items_discrete(Request_Context& context, context.data_index(current_skeleton_file_properties< Object >())); if (timestamp == NOW) { + Indexed_Appender< Index, Object > append(result); for (auto it = current_db.discrete_begin(req.begin(), req.end()); !(it == current_db.discrete_end()); ++it) { if (predicate.match(it.handle())) - result[it.index()].push_back(it.object()); + append.push_back(it.index(), it.object()); } } else @@ -491,10 +560,11 @@ Timeless< Index, Object > collect_items_range(Request_Context& context, (context.data_index(current_skeleton_file_properties< Object >())); if (context.get_desired_timestamp() == NOW) { + Indexed_Appender< Index, Object > append(result.current); for (auto it = current_db.range_begin(ranges); !(it == current_db.range_end()); ++it) { if (predicate.match(it.handle())) - result.current[it.index()].push_back(it.object()); + append.push_back(it.index(), it.object()); } } else @@ -524,6 +594,10 @@ bool collect_items_range(Request_Context& context, { uint32 count = 0; bool too_much_data = false; + // The size eval_map would report for result, kept up to date as objects are added, + // and the entry objects were last added to: objects arrive ordered by index. + uint64 result_size = eval_map(result); + typename std::map< Index, std::vector< Object > >::iterator last = result.end(); for (auto it = current_db.range_begin(shortened); !(it == current_db.range_end()); ++it) { @@ -535,11 +609,24 @@ bool collect_items_range(Request_Context& context, if (++count >= 256*1024) { count = 0; - too_much_data = context.get_health_guard().check(0, eval_map(result)); + too_much_data = context.get_health_guard().check(0, result_size) + || result_size >= MAX_CHUNK_ACCOUNTED_SIZE; cur_idx = it.index(); } if (predicate.match(it.handle())) - result[it.index()].push_back(it.object()); + { + if (last == result.end() || !(last->first == it.index())) + { + last = result.lower_bound(it.index()); + if (last == result.end() || it.index() < last->first) + { + last = result.insert(last, std::make_pair(it.index(), std::vector< Object >())); + result_size += eval_index_size; + } + } + last->second.push_back(it.object()); + result_size += eval_object_size((const Object*)0); + } } return false; @@ -565,6 +652,7 @@ void collect_items_flat(Request_Context& context, { uint32 count = 0; Block_Backend< Index, Object > db(context.data_index(&file_properties)); + Indexed_Appender< Index, Object > append(result); for (typename Block_Backend< Index, Object >::Flat_Iterator it(db.flat_begin()); !(it == db.flat_end()); ++it) { @@ -574,7 +662,7 @@ void collect_items_flat(Request_Context& context, context.get_health_guard().check(0, eval_map(result)); } if (predicate.match(it.handle())) - result[it.index()].push_back(it.object()); + append.push_back(it.index(), it.object()); } } @@ -591,6 +679,7 @@ void collect_items_flat( if (context.get_desired_timestamp() == NOW) { uint32 count = 0; + Indexed_Appender< Index, Object > append(result); for (auto it = current_db.flat_begin(); !(it == current_db.flat_end()); ++it) { if (++count >= 256*1024) @@ -599,7 +688,7 @@ void collect_items_flat( context.get_health_guard().check(0, eval_map(result)); } if (predicate.match(it.handle())) - result[it.index()].push_back(it.object()); + append.push_back(it.index(), it.object()); } } else diff --git a/src/overpass_api/data/collect_members.cc b/src/overpass_api/data/collect_members.cc index be67d2d7b..b6911e784 100644 --- a/src/overpass_api/data/collect_members.cc +++ b/src/overpass_api/data/collect_members.cc @@ -674,6 +674,26 @@ Timeless< Uint32_Index, Node_Skeleton > paired_items_range( } +Timeless< Uint32_Index, Node_Skeleton > relation_and_way_node_members( + Request_Context& context, + const std::map< Uint31_Index, std::vector< Relation_Skeleton > >& relations, + const std::map< Uint31_Index, std::vector< Attic< Relation_Skeleton > > >& attic_relations, + const std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways, + const std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > >& attic_ways) +{ + // Both id lists are sorted and free of duplicates. + std::vector< Node::Id_Type > rel_ids = relation_node_member_ids(relations, attic_relations); + std::vector< Node::Id_Type > way_ids = way_nd_ids(ways, attic_ways, 0); + context.get_health_guard().check(); + std::vector< Node::Id_Type > ids; + ids.reserve(rel_ids.size() + way_ids.size()); + std::set_union(rel_ids.begin(), rel_ids.end(), way_ids.begin(), way_ids.end(), std::back_inserter(ids)); + + return paired_items_range(context, ids, + relation_node_member_indices(relations, attic_relations).union_(way_nd_indices(ways, attic_ways))); +} + + Timeless< Uint32_Index, Node_Skeleton > relation_node_members (Request_Context& context, const std::map< Uint31_Index, std::vector< Relation_Skeleton > >& relations, @@ -837,26 +857,6 @@ bool add_way_to_area_blocks(const std::vector< Quad_Coord >& coords, } -std::vector< Quad_Coord > make_geometry(const Way_Skeleton& way, const std::vector< Node >& nodes) -{ - std::vector< Quad_Coord > result; - - for (std::vector< Node::Id_Type >::const_iterator it3(way.nds.begin()); - it3 != way.nds.end(); ++it3) - { - const Node* node = binary_search_for_id(nodes, *it3); - if (node == 0) - { - result.clear(); - return result; - } - result.push_back(Quad_Coord(node->index, node->ll_lower_)); - } - - return result; -} - - std::vector< Uint31_Index > segment_idxs(const std::vector< Quad_Coord >& geometry) { std::vector< uint32 > nd_idxs; @@ -942,12 +942,12 @@ void filter_ways_by_ranges(std::map< Uint31_Index, std::vector< Attic< Way_Skele void keep_matching_skeletons - (std::vector< Node >& result, + (std::vector< Node_Position >& result, const std::map< Uint32_Index, std::vector< Node_Skeleton > >& current, const std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >& attic, uint64 timestamp) { - std::map< Node_Skeleton::Id_Type, uint64 > timestamp_by_id; + Valid_Until_By_Id< Node_Skeleton::Id_Type > timestamp_by_id(timestamp); result.clear(); @@ -955,7 +955,7 @@ void keep_matching_skeletons it != current.end(); ++it) { for (std::vector< Node_Skeleton >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - timestamp_by_id[it2->id] = NOW; + timestamp_by_id.add_current(it2->id); } for (std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >::const_iterator it = attic.begin(); @@ -963,20 +963,18 @@ void keep_matching_skeletons { for (std::vector< Attic >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - { - uint64& stored_timestamp = timestamp_by_id[it2->id]; - if (it2->timestamp > timestamp && (stored_timestamp == 0 || stored_timestamp > it2->timestamp)) - stored_timestamp = it2->timestamp; - } + timestamp_by_id.add_attic(it2->id, it2->timestamp); } + timestamp_by_id.finish(); + result.reserve(timestamp_by_id.count_valid()); for (std::map< Uint32_Index, std::vector< Node_Skeleton > >::const_iterator it = current.begin(); it != current.end(); ++it) { for (std::vector< Node_Skeleton >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == NOW) - result.push_back(Node(it2->id, it->first.val(), it2->ll_lower)); + if (timestamp_by_id.get(it2->id) == NOW) + result.push_back(Node_Position(it2->id, it->first.val(), it2->ll_lower)); } } @@ -986,8 +984,8 @@ void keep_matching_skeletons for (std::vector< Attic >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == it2->timestamp) - result.push_back(Node(it2->id, it->first.val(), it2->ll_lower)); + if (timestamp_by_id.get(it2->id) == it2->timestamp) + result.push_back(Node_Position(it2->id, it->first.val(), it2->ll_lower)); } } @@ -1065,8 +1063,30 @@ void add_nw_member_objects(Request_Context& context, const Set& input_set, Set& { Ranges< Uint32_Index > ranges_32(ranges_32_ ? *ranges_32_ : Ranges< Uint32_Index >::global()); Ranges< Uint31_Index > ranges_31(ranges_31_ ? *ranges_31_ : Ranges< Uint31_Index >::global()); - Timeless< Uint32_Index, Node_Skeleton > rel_nodes - = relation_node_members(context, input_set.relations, input_set.attic_relations, ranges_32, {}, true); + + if (context.get_desired_timestamp() == NOW && !ranges_32_) + { + // Collect the relations' node members and the ways' nodes in one pass over the node blocks. + relation_way_members(context, input_set.relations, {}, ranges_31, {}, true) + .swap(into.ways, into.attic_ways); + std::map< Uint31_Index, std::vector< Way_Skeleton > > source_ways = input_set.ways; + sort_second(source_ways); + sort_second(into.ways); + indexed_set_union(source_ways, into.ways); + Timeless< Uint32_Index, Node_Skeleton > nodes = relation_and_way_node_members( + context, input_set.relations, input_set.attic_relations, source_ways, {}); + nodes.current.swap(into.nodes); + sort_second(into.nodes); + return; + } + + // For a date without a range restriction, the relations' node members are collected below, + // in the same pass over the node blocks as the ways' nodes. + bool one_pass = !ranges_32_; + Timeless< Uint32_Index, Node_Skeleton > rel_nodes; + if (!one_pass) + rel_nodes = relation_node_members( + context, input_set.relations, input_set.attic_relations, ranges_32, {}, true); if (context.get_desired_timestamp() == NOW) { @@ -1099,8 +1119,10 @@ void add_nw_member_objects(Request_Context& context, const Set& input_set, Set& indexed_set_union(all_ways.current, source_ways); indexed_set_union(all_ways.attic, source_attic_ways); - Timeless< Uint32_Index, Node_Skeleton > more_nodes - = way_members(context, all_ways.current, all_ways.attic, 0, Ranges< Uint32_Index >::global(), {}, true); + Timeless< Uint32_Index, Node_Skeleton > more_nodes = one_pass + ? relation_and_way_node_members( + context, input_set.relations, input_set.attic_relations, all_ways.current, all_ways.attic) + : way_members(context, all_ways.current, all_ways.attic, 0, Ranges< Uint32_Index >::global(), {}, true); more_nodes.sort(); sort_second(into.nodes); sort_second(into.attic_nodes); diff --git a/src/overpass_api/data/collect_members.h b/src/overpass_api/data/collect_members.h index 9abd3b8c0..ece30d9cc 100644 --- a/src/overpass_api/data/collect_members.h +++ b/src/overpass_api/data/collect_members.h @@ -25,6 +25,7 @@ #include "collect_items.h" #include "filenames.h" +#include #include #include #include @@ -123,7 +124,26 @@ bool add_way_to_area_blocks(const std::vector< Quad_Coord >& coords, uint32 id, std::map< Uint31_Index, std::vector< Area_Block > >& areas); -std::vector< Quad_Coord > make_geometry(const Way_Skeleton& way, const std::vector< Node >& nodes); +// nodes must be sorted by id. Node_Type is Node or Node_Position. +template< typename Node_Type > +std::vector< Quad_Coord > make_geometry(const Way_Skeleton& way, const std::vector< Node_Type >& nodes) +{ + std::vector< Quad_Coord > result; + + for (std::vector< Node::Id_Type >::const_iterator it3(way.nds.begin()); + it3 != way.nds.end(); ++it3) + { + const Node_Type* node = binary_search_for_id(nodes, *it3); + if (node == 0) + { + result.clear(); + return result; + } + result.push_back(Quad_Coord(node->index, node->ll_lower_)); + } + + return result; +} void filter_ways_by_ranges(std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways, @@ -176,7 +196,7 @@ class Collect_Items const Ranges< Index >& ranges_, const Statement& query_, Resource_Manager& rman_) : ids(&ids_), invert_ids(invert_ids_), ranges(ranges_), query(&query_), rman(&rman_), - min_idx(ranges_.empty() ? Index() : ranges_.begin().lower_bound()) {} + min_idx(ranges_.empty() ? Index() : ranges_.begin().lower_bound()), id_pred(ids_) {} bool get_chunk( std::map< Index, std::vector< Object > >& elements, @@ -189,6 +209,8 @@ class Collect_Items const Statement* query; Resource_Manager* rman; Index min_idx; + // Built once and reused for every chunk. + Id_Predicate< Object > id_pred; }; @@ -221,11 +243,44 @@ bool Collect_Items< Index, Object >::get_chunk( elements, attic_elements, Trivial_Predicate< Object >(), ranges, min_idx, *query, *rman); else return get_elements_by_id_from_db_generic( - elements, attic_elements, Not_Predicate< Object, Id_Predicate< Object > >(Id_Predicate< Object >(*ids)), + elements, attic_elements, Not_Predicate< Object, Id_Predicate< Object > >(id_pred), ranges, min_idx, *query, *rman); } return get_elements_by_id_from_db_generic( - elements, attic_elements, Id_Predicate< Object >(*ids), ranges, min_idx, *query, *rman); + elements, attic_elements, id_pred, ranges, min_idx, *query, *rman); +} + + +// Sorts entries by id and keeps only the last entry of each id, in the order they were added, +// like repeated assignments to a std::map. +template< typename Id_Type, typename Value > +void sort_keeping_last_per_id(std::vector< std::pair< Id_Type, Value > >& entries) +{ + std::stable_sort(entries.begin(), entries.end(), + [](const std::pair< Id_Type, Value >& a, const std::pair< Id_Type, Value >& b) + { return a.first < b.first; }); + typename std::vector< std::pair< Id_Type, Value > >::iterator kept = entries.begin(); + for (typename std::vector< std::pair< Id_Type, Value > >::iterator it = entries.begin(); + it != entries.end(); ++it) + { + if (it + 1 != entries.end() && (it + 1)->first == it->first) + continue; + *kept++ = *it; + } + entries.erase(kept, entries.end()); +} + + +// Returns the value stored for id in entries sorted by sort_keeping_last_per_id, or 0. +template< typename Id_Type, typename Value > +Value* find_timestamps(std::vector< std::pair< Id_Type, Value > >& entries, const Id_Type& id) +{ + typename std::vector< std::pair< Id_Type, Value > >::iterator it = std::lower_bound( + entries.begin(), entries.end(), id, + [](const std::pair< Id_Type, Value >& a, const Id_Type& b) { return a.first < b; }); + if (it != entries.end() && it->first == id) + return &it->second; + return 0; } @@ -294,105 +349,123 @@ void filter_attic_elements // Confirm elements that are backed by meta data // Update element's expiration timestamp if a meta exists that is older than the current // expiration date and younger than timestamp - std::map< Index, std::map< typename Skeleton::Id_Type, std::pair< uint64, uint64 > > > - timestamp_by_id_by_idx; - for (typename std::map< Index, std::vector< Skeleton > >::const_iterator it = current.begin(); - it != current.end(); ++it) - { - std::map< typename Skeleton::Id_Type, std::pair< uint64, uint64 > >& entry - = timestamp_by_id_by_idx[it->first]; - for (typename std::vector< Skeleton >::const_iterator it2 = it->second.begin(); - it2 != it->second.end(); ++it2) - entry[it2->id] = std::make_pair(0, NOW); - } - for (typename std::map< Index, std::vector< Attic< Skeleton > > >::const_iterator it = attic.begin(); - it != attic.end(); ++it) - { - std::map< typename Skeleton::Id_Type, std::pair< uint64, uint64 > >& entry - = timestamp_by_id_by_idx[it->first]; - for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = it->second.begin(); - it2 != it->second.end(); ++it2) - entry[it2->id] = std::make_pair(0, it2->timestamp); - } + // The meta files are read in index order, so this works one index at a time: only one + // index's timestamps are held at once. Per index, the entries are sorted by id with one + // entry per id. + typedef std::pair< typename Skeleton::Id_Type, std::pair< uint64, uint64 > > Timestamps_Entry; Block_Backend< Index, OSM_Element_Metadata_Skeleton< typename Skeleton::Id_Type >, typename std::vector< Index >::const_iterator > attic_meta_db(rman.get_transaction()->data_index (attic_meta_file_properties< Skeleton >())); - for (auto it = attic_meta_db.discrete_begin(idx_set.begin(), idx_set.end()); - !(it == attic_meta_db.discrete_end()); ++it) - { - auto tit = timestamp_by_id_by_idx[it.index()].find(it.object().ref); - if (tit != timestamp_by_id_by_idx[it.index()].end()) - { - if (timestamp < it.object().timestamp) - tit->second.second = std::min(tit->second.second, it.object().timestamp); - else - tit->second.first = std::max(tit->second.first, it.object().timestamp); - } - } + auto attic_meta_it = attic_meta_db.discrete_begin(idx_set.begin(), idx_set.end()); - // Same thing with current meta data Block_Backend< Index, OSM_Element_Metadata_Skeleton< typename Skeleton::Id_Type >, typename std::vector< Index >::const_iterator > meta_db(rman.get_transaction()->data_index (current_meta_file_properties< Skeleton >())); + auto meta_it = meta_db.discrete_begin(idx_set.begin(), idx_set.end()); - for (auto it = meta_db.discrete_begin(idx_set.begin(), idx_set.end()); - !(it == meta_db.discrete_end()); ++it) + std::vector< Timestamps_Entry > entry; + for (typename std::vector< Index >::const_iterator idx = idx_set.begin(); idx != idx_set.end(); ++idx) { - auto tit = timestamp_by_id_by_idx[it.index()].find(it.object().ref); - if (tit != timestamp_by_id_by_idx[it.index()].end()) + typename std::map< Index, std::vector< Skeleton > >::iterator cit = current.find(*idx); + typename std::map< Index, std::vector< Attic< Skeleton > > >::iterator ait = attic.find(*idx); + + entry.clear(); + if (cit != current.end()) { - if (timestamp < it.object().timestamp) - tit->second.second = std::min(tit->second.second, it.object().timestamp); - else - tit->second.first = std::max(tit->second.first, it.object().timestamp); + for (typename std::vector< Skeleton >::const_iterator it2 = cit->second.begin(); + it2 != cit->second.end(); ++it2) + entry.push_back(Timestamps_Entry(it2->id, std::make_pair(0, NOW))); } - } - - // Filter current: only keep elements that have already existed at timestamp - for (typename std::map< Index, std::vector< Skeleton > >::iterator it = current.begin(); - it != current.end(); ++it) - { - std::vector< Skeleton > result; - std::map< typename Skeleton::Id_Type, std::pair< uint64, uint64 > >& entry - = timestamp_by_id_by_idx[it->first]; + if (ait != attic.end()) + { + for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = ait->second.begin(); + it2 != ait->second.end(); ++it2) + entry.push_back(Timestamps_Entry(it2->id, std::make_pair(0, it2->timestamp))); + } + sort_keeping_last_per_id(entry); - for (typename std::vector< Skeleton >::const_iterator it2 = it->second.begin(); - it2 != it->second.end(); ++it2) + while (!(attic_meta_it == attic_meta_db.discrete_end()) && attic_meta_it.index() < *idx) + ++attic_meta_it; + for (; !(attic_meta_it == attic_meta_db.discrete_end()) && attic_meta_it.index() == *idx; + ++attic_meta_it) { - if (entry[it2->id].first > 0) + std::pair< uint64, uint64 >* tit = find_timestamps(entry, attic_meta_it.object().ref); + if (tit) { - if (entry[it2->id].second == NOW) - result.push_back(*it2); + if (timestamp < attic_meta_it.object().timestamp) + tit->second = std::min(tit->second, attic_meta_it.object().timestamp); else - attic[it->first].push_back(Attic< Skeleton >(*it2, entry[it2->id].second)); + tit->first = std::max(tit->first, attic_meta_it.object().timestamp); } } - result.swap(it->second); - } - - // Filter attic: only keep elements that have already existed at timestamp - for (typename std::map< Index, std::vector< Attic< Skeleton > > >::iterator it = attic.begin(); - it != attic.end(); ++it) - { - std::vector< Attic< Skeleton > > result; - std::map< typename Skeleton::Id_Type, std::pair< uint64, uint64 > >& entry - = timestamp_by_id_by_idx[it->first]; + // Same thing with current meta data + while (!(meta_it == meta_db.discrete_end()) && meta_it.index() < *idx) + ++meta_it; + for (; !(meta_it == meta_db.discrete_end()) && meta_it.index() == *idx; ++meta_it) + { + std::pair< uint64, uint64 >* tit = find_timestamps(entry, meta_it.object().ref); + if (tit) + { + if (timestamp < meta_it.object().timestamp) + tit->second = std::min(tit->second, meta_it.object().timestamp); + else + tit->first = std::max(tit->first, meta_it.object().timestamp); + } + } - for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = it->second.begin(); - it2 != it->second.end(); ++it2) + // Filter current: only keep elements that have already existed at timestamp + if (cit != current.end()) { - if (entry[it2->id].first > 0) + // Compact in place, keeping the order, and drop the slack left by growing the vector. + typename std::vector< Skeleton >::iterator out = cit->second.begin(); + for (typename std::vector< Skeleton >::iterator it2 = cit->second.begin(); + it2 != cit->second.end(); ++it2) { - result.push_back(*it2); - result.back().timestamp = entry[it2->id].second; + const std::pair< uint64, uint64 >* timestamps = find_timestamps(entry, it2->id); + if (timestamps && timestamps->first > 0) + { + if (timestamps->second == NOW) + { + if (out != it2) + *out = std::move(*it2); + ++out; + } + else + { + if (ait == attic.end()) + ait = attic.insert(std::make_pair(*idx, std::vector< Attic< Skeleton > >())).first; + ait->second.push_back(Attic< Skeleton >(*it2, timestamps->second)); + } + } } + cit->second.erase(out, cit->second.end()); + cit->second.shrink_to_fit(); } - result.swap(it->second); + // Filter attic: only keep elements that have already existed at timestamp + if (ait != attic.end()) + { + // Compact in place, as above. + typename std::vector< Attic< Skeleton > >::iterator out = ait->second.begin(); + for (typename std::vector< Attic< Skeleton > >::iterator it2 = ait->second.begin(); + it2 != ait->second.end(); ++it2) + { + const std::pair< uint64, uint64 >* timestamps = find_timestamps(entry, it2->id); + if (timestamps && timestamps->first > 0) + { + if (out != it2) + *out = std::move(*it2); + out->timestamp = timestamps->second; + ++out; + } + } + ait->second.erase(out, ait->second.end()); + ait->second.shrink_to_fit(); + } } } } @@ -506,6 +579,67 @@ inline std::vector< Way::Id_Type > relation_way_member_ids } +// For each id, the end of validity of the version valid at a past date: NOW for the current +// version, else the earliest attic timestamp after that date, else 0 (no valid version). +// This is what a std::map< Id_Type, uint64 > filled by the same rules held, in a sorted vector +// of 16-byte entries instead of a tree node of about 48 bytes per id. +template< typename Id_Type > +class Valid_Until_By_Id +{ +public: + Valid_Until_By_Id(uint64 timestamp_) : timestamp(timestamp_), valid_count(0) {} + + void add_current(const Id_Type& id) { entries.push_back(std::make_pair(id, NOW)); } + + // Versions that ended at or before the date can't be the valid one, so they aren't stored: + // an id without entries reads as 0, like an id whose entries are all 0. + void add_attic(const Id_Type& id, uint64 attic_timestamp) + { + if (attic_timestamp > timestamp) + entries.push_back(std::make_pair(id, attic_timestamp)); + } + + // Call once after adding all entries: keeps per id the smallest nonzero value, else 0. + void finish() + { + std::sort(entries.begin(), entries.end()); + typename std::vector< std::pair< Id_Type, uint64 > >::iterator kept = entries.begin(); + typename std::vector< std::pair< Id_Type, uint64 > >::iterator it = entries.begin(); + while (it != entries.end()) + { + typename std::vector< std::pair< Id_Type, uint64 > >::iterator run_end = it; + uint64 valid_until = 0; + while (run_end != entries.end() && run_end->first == it->first) + { + if (valid_until == 0) + valid_until = run_end->second; + ++run_end; + } + if (valid_until != 0) + ++valid_count; + *kept++ = std::make_pair(it->first, valid_until); + it = run_end; + } + entries.erase(kept, entries.end()); + } + + uint64 get(const Id_Type& id) const + { + typename std::vector< std::pair< Id_Type, uint64 > >::const_iterator it = std::lower_bound( + entries.begin(), entries.end(), std::make_pair(id, uint64(0))); + return (it != entries.end() && it->first == id) ? it->second : 0; + } + + // The number of ids that have a valid version, i.e. the number of skeletons kept. + std::size_t count_valid() const { return valid_count; } + +private: + uint64 timestamp; + std::size_t valid_count; + std::vector< std::pair< Id_Type, uint64 > > entries; +}; + + template< typename Index, typename Skeleton > void keep_matching_skeletons (std::map< Index, std::vector< Skeleton > >& current, @@ -518,30 +652,27 @@ void keep_matching_skeletons return; } - std::map< typename Skeleton::Id_Type, uint64 > timestamp_by_id; + Valid_Until_By_Id< typename Skeleton::Id_Type > timestamp_by_id(timestamp); for (auto it = current.begin(); it != current.end(); ++it) { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) - timestamp_by_id[it2->id] = NOW; + timestamp_by_id.add_current(it2->id); } for (auto it = attic.begin(); it != attic.end(); ++it) { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) - { - uint64& stored_timestamp = timestamp_by_id[it2->id]; - if (it2->timestamp > timestamp && (stored_timestamp == 0 || stored_timestamp > it2->timestamp)) - stored_timestamp = it2->timestamp; - } + timestamp_by_id.add_attic(it2->id, it2->timestamp); } + timestamp_by_id.finish(); for (auto it = current.begin(); it != current.end(); ++it) { std::vector< Skeleton > local_into; for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == NOW) + if (timestamp_by_id.get(it2->id) == NOW) local_into.push_back(*it2); } local_into.swap(it->second); @@ -552,7 +683,7 @@ void keep_matching_skeletons std::vector< Attic< Skeleton > > local_into; for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == it2->timestamp) + if (timestamp_by_id.get(it2->id) == it2->timestamp) local_into.push_back(*it2); } local_into.swap(it->second); @@ -567,32 +698,29 @@ void keep_matching_skeletons const std::map< Index, std::vector< Attic< Skeleton > > >& attic, uint64 timestamp) { - std::map< typename Skeleton::Id_Type, uint64 > timestamp_by_id; + Valid_Until_By_Id< typename Skeleton::Id_Type > timestamp_by_id(timestamp); result.clear(); for (auto it = current.begin(); it != current.end(); ++it) { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) - timestamp_by_id[it2->id] = NOW; + timestamp_by_id.add_current(it2->id); } for (auto it = attic.begin(); it != attic.end(); ++it) { for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - { - uint64& stored_timestamp = timestamp_by_id[it2->id]; - if (it2->timestamp > timestamp && (stored_timestamp == 0 || stored_timestamp > it2->timestamp)) - stored_timestamp = it2->timestamp; - } + timestamp_by_id.add_attic(it2->id, it2->timestamp); } + timestamp_by_id.finish(); for (auto it = current.begin(); it != current.end(); ++it) { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == NOW) + if (timestamp_by_id.get(it2->id) == NOW) result[it->first].push_back(Attic< Skeleton >(*it2, NOW)); } } @@ -601,15 +729,39 @@ void keep_matching_skeletons { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == it2->timestamp) + if (timestamp_by_id.get(it2->id) == it2->timestamp) result[it->first].push_back(Attic< Skeleton >(*it2, it2->timestamp)); } } } +// Appends the nodes of skels to result as Node_Positions and empties skels as it goes, +// so the two copies don't coexist in full. result is not sorted. +template< typename Skeleton > +void move_to_node_positions( + std::map< Uint32_Index, std::vector< Skeleton > >& skels, std::vector< Node_Position >& result) +{ + std::size_t count = 0; + for (typename std::map< Uint32_Index, std::vector< Skeleton > >::const_iterator it = skels.begin(); + it != skels.end(); ++it) + count += it->second.size(); + result.reserve(result.size() + count); + + for (typename std::map< Uint32_Index, std::vector< Skeleton > >::iterator it = skels.begin(); + it != skels.end(); ++it) + { + for (typename std::vector< Skeleton >::const_iterator iit = it->second.begin(); + iit != it->second.end(); ++iit) + result.push_back(Node_Position(iit->id, it->first.val(), iit->ll_lower)); + std::vector< Skeleton >().swap(it->second); + } + skels.clear(); +} + + void keep_matching_skeletons - (std::vector< Node >& result, + (std::vector< Node_Position >& result, const std::map< Uint32_Index, std::vector< Node_Skeleton > >& current, const std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >& attic, uint64 timestamp); @@ -744,6 +896,18 @@ Ranges< Uint31_Index > relation_way_member_indices Ranges< Uint32_Index > calc_node_children_ranges(const std::vector< uint32 >& way_rel_idxs); +/* The node members of the relations and the nodes of the ways, read in a single pass + over the node blocks. Equivalent to the union of relation_node_members(relations) and + way_members(ways) with global ranges, but blocks holding both kinds of node are read + and decompressed once instead of twice. */ +Timeless< Uint32_Index, Node_Skeleton > relation_and_way_node_members( + Request_Context& context, + const std::map< Uint31_Index, std::vector< Relation_Skeleton > >& relations, + const std::map< Uint31_Index, std::vector< Attic< Relation_Skeleton > > >& attic_relations, + const std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways, + const std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > >& attic_ways); + + Ranges< Uint32_Index > relation_node_member_indices( const std::map< Uint31_Index, std::vector< Relation_Skeleton > >& current_rels, const std::map< Uint31_Index, std::vector< Attic< Relation_Skeleton > > >& attic_rels); diff --git a/src/overpass_api/data/diff_set.h b/src/overpass_api/data/diff_set.h index 9301a7440..9ed07e465 100644 --- a/src/overpass_api/data/diff_set.h +++ b/src/overpass_api/data/diff_set.h @@ -43,7 +43,7 @@ struct Node_With_Context uint64 expiration_date_, OSM_Element_Metadata_Skeleton< Node_Skeleton::Id_Type > meta_ = OSM_Element_Metadata_Skeleton< Node_Skeleton::Id_Type >(), Tag_Container tags_ = Tag_Container()) - : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), tags(tags_) {} + : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), tags(std::move(tags_)) {} bool operator<(const Node_With_Context& e) const { @@ -65,11 +65,12 @@ struct Way_With_Context Tag_Container tags; std::vector< Quad_Coord > geometry; - Way_With_Context(Uint31_Index idx_, Way_Skeleton elem_, const std::vector< Quad_Coord >& geometry_, + Way_With_Context(Uint31_Index idx_, Way_Skeleton elem_, std::vector< Quad_Coord > geometry_, uint64 expiration_date_, OSM_Element_Metadata_Skeleton< Way_Skeleton::Id_Type > meta_ = OSM_Element_Metadata_Skeleton< Way_Skeleton::Id_Type >(), Tag_Container tags_ = Tag_Container()) - : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), tags(tags_), geometry(geometry_) {} + : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), + tags(std::move(tags_)), geometry(std::move(geometry_)) {} bool operator<(const Way_With_Context& e) const { @@ -92,11 +93,12 @@ struct Relation_With_Context std::vector< std::vector< Quad_Coord > > geometry; Relation_With_Context(Uint31_Index idx_, Relation_Skeleton elem_, - const std::vector< std::vector< Quad_Coord > >& geometry_, + std::vector< std::vector< Quad_Coord > > geometry_, uint64 expiration_date_, OSM_Element_Metadata_Skeleton< Relation_Skeleton::Id_Type > meta_ = OSM_Element_Metadata_Skeleton< Relation_Skeleton::Id_Type >(), Tag_Container tags_ = Tag_Container()) - : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), tags(tags_), geometry(geometry_) {} + : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), + tags(std::move(tags_)), geometry(std::move(geometry_)) {} bool operator<(const Relation_With_Context& e) const { diff --git a/src/overpass_api/data/filter_ids_by_tags.h b/src/overpass_api/data/filter_ids_by_tags.h index afa2b24cb..683d04f6c 100644 --- a/src/overpass_api/data/filter_ids_by_tags.h +++ b/src/overpass_api/data/filter_ids_by_tags.h @@ -64,7 +64,8 @@ void filter_ids_by_tags key_relevant = true; old_ids.clear(); old_ids.swap(new_ids); - sort(old_ids.begin(), old_ids.end()); + if (!std::is_sorted(old_ids.begin(), old_ids.end())) + sort(old_ids.begin(), old_ids.end()); } matched_by_key_regexes.clear(); @@ -216,8 +217,8 @@ struct Tag_Entry_Listener_Value_Regex : public Tag_Entry_Listener< Id_Type > std::vector< Id_Type > result; for (typename std::vector< Id_Type >::const_iterator it = new_ids.begin(); it != new_ids.end(); ++it) { - std::pair< uint64, uint64 >& timestamp_ref = timestamps[*it]; - if (0 < timestamp_ref.first && timestamp_ref.first <= timestamp_ref.second) + typename std::map< Id_Type, std::pair< uint64, uint64 > >::const_iterator found = timestamps.find(*it); + if (found != timestamps.end() && 0 < found->second.first && found->second.first <= found->second.second) result.push_back(*it); } std::sort(result.begin(), result.end()); @@ -364,10 +365,10 @@ void filter_ids_by_tags while (true) { bool current_finished = - (tag_it == items_db.range_end() || ((tag_it.index().index) & 0x7fffff00) != coarse_index); + (tag_it == items_db.range_end() || (tag_coarse_index(tag_it)) != coarse_index); bool attic_finished = (attic_tag_it == attic_items_db.range_end() - || ((attic_tag_it.index().index) & 0x7fffff00) != coarse_index); + || (tag_coarse_index(attic_tag_it)) != coarse_index); if (!attic_finished && (current_finished || attic_tag_it.index().key < tag_it.index().key)) { diff --git a/src/overpass_api/data/meta_collector.h b/src/overpass_api/data/meta_collector.h index 542fe79c5..6743d1d7b 100644 --- a/src/overpass_api/data/meta_collector.h +++ b/src/overpass_api/data/meta_collector.h @@ -19,6 +19,7 @@ #ifndef DE__OSM3S___OVERPASS_API__STATEMENTS__META_COLLECTOR_H #define DE__OSM3S___OVERPASS_API__STATEMENTS__META_COLLECTOR_H +#include #include #include #include @@ -67,9 +68,12 @@ struct Meta_Collector ::Range_Iterator* range_it; Index* current_index; Index* last_index; - std::set< OSM_Element_Metadata_Skeleton< Id_Type > > current_objects; + // Sorted by (ref, timestamp), without duplicates: a flat replacement for a std::set, + // which is filled once per index and then only searched. + std::vector< OSM_Element_Metadata_Skeleton< Id_Type > > current_objects; void update_current_objects(const Index&); + void sort_current_objects(); }; @@ -162,9 +166,10 @@ void Meta_Collector< Index, Id_Type >::reset() current_index = new Index(db_it->index()); while (!(*db_it == meta_db->discrete_end()) && (*current_index == db_it->index())) { - current_objects.insert(db_it->object()); + current_objects.push_back(db_it->object()); ++(*db_it); } + sort_current_objects(); } else { @@ -175,9 +180,10 @@ void Meta_Collector< Index, Id_Type >::reset() current_index = new Index(range_it->index()); while (!(*range_it == meta_db->range_end()) && (*current_index == range_it->index())) { - current_objects.insert(range_it->object()); + current_objects.push_back(range_it->object()); ++(*range_it); } + sort_current_objects(); } } @@ -197,9 +203,10 @@ void Meta_Collector< Index, Id_Type >::update_current_objects(const Index& index *current_index = db_it->index(); while (!(*db_it == meta_db->discrete_end()) && (*current_index == db_it->index())) { - current_objects.insert(db_it->object()); + current_objects.push_back(db_it->object()); ++(*db_it); } + sort_current_objects(); } else if (range_it) { @@ -209,13 +216,26 @@ void Meta_Collector< Index, Id_Type >::update_current_objects(const Index& index *current_index = range_it->index(); while (!(*range_it == meta_db->range_end()) && (*current_index == range_it->index())) { - current_objects.insert(range_it->object()); + current_objects.push_back(range_it->object()); ++(*range_it); } + sort_current_objects(); } } +template< typename Index, typename Id_Type > +void Meta_Collector< Index, Id_Type >::sort_current_objects() +{ + // Keep the first of equal elements, as std::set::insert did. + if (!std::is_sorted(current_objects.begin(), current_objects.end())) + std::stable_sort(current_objects.begin(), current_objects.end()); + current_objects.erase(std::unique(current_objects.begin(), current_objects.end(), + [](const OSM_Element_Metadata_Skeleton< Id_Type >& a, const OSM_Element_Metadata_Skeleton< Id_Type >& b) + { return !(a < b) && !(b < a); }), current_objects.end()); +} + + template< typename Index, typename Id_Type > const OSM_Element_Metadata_Skeleton< Id_Type >* Meta_Collector< Index, Id_Type >::get (const Index& index, Id_Type ref) @@ -228,8 +248,8 @@ const OSM_Element_Metadata_Skeleton< Id_Type >* Meta_Collector< Index, Id_Type > if (current_index && *current_index < index) update_current_objects(index); - typename std::set< OSM_Element_Metadata_Skeleton< Id_Type > >::iterator it - = current_objects.lower_bound(OSM_Element_Metadata_Skeleton< Id_Type >(ref)); + auto it = std::lower_bound(current_objects.begin(), current_objects.end(), + OSM_Element_Metadata_Skeleton< Id_Type >(ref)); if (it != current_objects.end() && it->ref == ref) return &*it; else @@ -249,8 +269,8 @@ const OSM_Element_Metadata_Skeleton< Id_Type >* Meta_Collector< Index, Id_Type > if (current_index && *current_index < index) update_current_objects(index); - typename std::set< OSM_Element_Metadata_Skeleton< Id_Type > >::iterator it - = current_objects.lower_bound(OSM_Element_Metadata_Skeleton< Id_Type >(ref, timestamp)); + auto it = std::lower_bound(current_objects.begin(), current_objects.end(), + OSM_Element_Metadata_Skeleton< Id_Type >(ref, timestamp)); if (it == current_objects.begin()) return 0; --it; diff --git a/src/overpass_api/data/regular_expression.h b/src/overpass_api/data/regular_expression.h index 31083c8cf..242770c67 100644 --- a/src/overpass_api/data/regular_expression.h +++ b/src/overpass_api/data/regular_expression.h @@ -25,6 +25,7 @@ #include #include +#include struct Regular_Expression_Error @@ -55,6 +56,14 @@ class Regular_Expression if (strategy == call_library) { + literal_mode = parse_literals(regex, literals); + if (literal_mode != no_literals && !case_sensitive) + { + for (std::vector< std::string >::iterator it = literals.begin(); it != literals.end(); ++it) + *it = ascii_lower(*it); + } + literal_case_sensitive = case_sensitive; + setlocale(LC_ALL, "C.UTF-8"); int case_flag = case_sensitive ? 0 : REG_ICASE; int error_no = regcomp(&preg, regex.c_str(), REG_EXTENDED|REG_NOSUB|case_flag); @@ -78,6 +87,8 @@ class Regular_Expression // if (is_cache_available && line == prev_line) // return prev_result; + if (literal_mode != no_literals && is_ascii(line)) + return matches_literals(line); bool result = (regexec(&preg, line.c_str(), 0, 0, 0) == 0); // is_cache_available = true; @@ -88,11 +99,97 @@ class Regular_Expression } private: + // Patterns that are only plain ASCII words separated by '|', either unanchored + // ("cafe|bar": the value contains one of them) or anchored as a whole ("^(cafe|bar)$" + // or "^cafe$": the value is one of them), are matched without the library for ASCII + // values. For those, the result is the same, also with REG_ICASE. Other values go to + // the library, so its handling of non-ASCII text is unchanged. + enum Literal_Mode { no_literals, contains_literal, equals_literal }; + + static bool is_literal_char(char c) + { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') + || c == ' ' || c == '_' || c == '-' || c == ':' || c == ';' || c == ',' || c == '\'' || c == '&' || c == '/'; + } + + static bool is_ascii(const std::string& s) + { + for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) + { + if ((unsigned char)*it >= 0x80 || *it == 0) + return false; + } + return true; + } + + static std::string ascii_lower(std::string s) + { + for (std::string::iterator it = s.begin(); it != s.end(); ++it) + { + if (*it >= 'A' && *it <= 'Z') + *it += 'a' - 'A'; + } + return s; + } + + static Literal_Mode parse_literals(const std::string& regex, std::vector< std::string >& literals) + { + std::string body = regex; + Literal_Mode mode = contains_literal; + if (body.size() >= 2 && body[0] == '^' && body[body.size()-1] == '$') + { + body = body.substr(1, body.size() - 2); + if (body.size() >= 2 && body[0] == '(' && body[body.size()-1] == ')') + body = body.substr(1, body.size() - 2); + else if (body.find('|') != std::string::npos) + // "^a|b$" means "^a" or "b$". + return no_literals; + mode = equals_literal; + } + std::string::size_type start = 0; + while (true) + { + std::string::size_type end = body.find('|', start); + std::string literal = body.substr(start, end == std::string::npos ? std::string::npos : end - start); + if (literal.empty()) + return no_literals; + for (std::string::const_iterator it = literal.begin(); it != literal.end(); ++it) + { + if (!is_literal_char(*it)) + return no_literals; + } + literals.push_back(literal); + if (end == std::string::npos) + return mode; + start = end + 1; + } + } + + bool matches_literals(const std::string& line) const + { + if (literal_case_sensitive) + return matches_literals_exactly(line); + return matches_literals_exactly(ascii_lower(line)); + } + + bool matches_literals_exactly(const std::string& value) const + { + for (std::vector< std::string >::const_iterator it = literals.begin(); it != literals.end(); ++it) + { + if (literal_mode == equals_literal ? value == *it : value.find(*it) != std::string::npos) + return true; + } + return false; + } + Regular_Expression(const Regular_Expression&); const Regular_Expression& operator=(const Regular_Expression&); regex_t preg; Strategy strategy; + Literal_Mode literal_mode = no_literals; + bool literal_case_sensitive = true; + std::vector< std::string > literals; // mutable bool cache_available; // mutable std::string prev_line; // mutable bool prev_result; diff --git a/src/overpass_api/data/relation_geometry_store.cc b/src/overpass_api/data/relation_geometry_store.cc index 94dbf4f6f..c0650b86e 100644 --- a/src/overpass_api/data/relation_geometry_store.cc +++ b/src/overpass_api/data/relation_geometry_store.cc @@ -48,13 +48,7 @@ Relation_Geometry_Store::Relation_Geometry_Store = relation_node_members(context, relations, {}, node_ranges, {}, true); // Order node ids by id. - for (std::map< Uint32_Index, std::vector< Node_Skeleton > >::iterator it = node_members.current.begin(); - it != node_members.current.end(); ++it) - { - for (std::vector< Node_Skeleton >::const_iterator iit = it->second.begin(); - iit != it->second.end(); ++iit) - nodes.push_back(Node(iit->id, it->first.val(), iit->ll_lower)); - } + move_to_node_positions(node_members.current, nodes); sort(nodes.begin(), nodes.end(), Node_Comparator_By_Id()); Ranges< Uint31_Index > way_ranges(south <= north @@ -99,20 +93,14 @@ Relation_Geometry_Store::Relation_Geometry_Store auto nodes_by_idx = relation_node_members(context, {}, relations, node_ranges, {}, true); // Order node ids by id. - for (std::map< Uint32_Index, std::vector< Node_Skeleton > >::iterator it = nodes_by_idx.current.begin(); - it != nodes_by_idx.current.end(); ++it) - { - for (std::vector< Node_Skeleton >::const_iterator iit = it->second.begin(); - iit != it->second.end(); ++iit) - nodes.push_back(Node(iit->id, it->first.val(), iit->ll_lower)); - } - for (std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >::iterator it = nodes_by_idx.attic.begin(); - it != nodes_by_idx.attic.end(); ++it) - { - for (std::vector< Attic< Node_Skeleton > >::const_iterator iit = it->second.begin(); - iit != it->second.end(); ++iit) - nodes.push_back(Node(iit->id, it->first.val(), iit->ll_lower)); - } + std::size_t count = 0; + for (auto it = nodes_by_idx.current.begin(); it != nodes_by_idx.current.end(); ++it) + count += it->second.size(); + for (auto it = nodes_by_idx.attic.begin(); it != nodes_by_idx.attic.end(); ++it) + count += it->second.size(); + nodes.reserve(count); + move_to_node_positions(nodes_by_idx.current, nodes); + move_to_node_positions(nodes_by_idx.attic, nodes); sort(nodes.begin(), nodes.end(), Node_Comparator_By_Id()); Ranges< Uint31_Index > way_ranges(south <= north @@ -161,7 +149,7 @@ std::vector< std::vector< Quad_Coord > > Relation_Geometry_Store::get_geometry { if (it->type == Relation_Entry::NODE) { - const Node* node = binary_search_for_id(nodes, it->ref); + const Node_Position* node = binary_search_for_id(nodes, it->ref); if (node == 0 || !matches_bbox(node->index, node->ll_lower_)) result.push_back(std::vector< Quad_Coord >(1, Quad_Coord(0u, 0u))); else diff --git a/src/overpass_api/data/relation_geometry_store.h b/src/overpass_api/data/relation_geometry_store.h index 4428e528b..81335ce95 100644 --- a/src/overpass_api/data/relation_geometry_store.h +++ b/src/overpass_api/data/relation_geometry_store.h @@ -43,7 +43,7 @@ class Relation_Geometry_Store std::vector< std::vector< Quad_Coord > > get_geometry(const Relation_Skeleton& relation) const; private: - std::vector< Node > nodes; + std::vector< Node_Position > nodes; std::vector< Way_Skeleton > ways; Way_Geometry_Store* way_geometry_store; diff --git a/src/overpass_api/data/set_comparison.cc b/src/overpass_api/data/set_comparison.cc index 3db91e234..b3d261fa3 100644 --- a/src/overpass_api/data/set_comparison.cc +++ b/src/overpass_api/data/set_comparison.cc @@ -998,7 +998,7 @@ bool Derived_Structure_Handle::operator<(const Derived_Structure_Handle& rhs) co } -void Set_Comparison::compute_deriveds(std::map< Uint31_Index, std::vector< Derived_Structure > > rhs_deriveds) +void Set_Comparison::compute_deriveds(const std::map< Uint31_Index, std::vector< Derived_Structure > >& rhs_deriveds) { std::vector< Derived_Structure_Handle > lhs_handles; for (std::map< Uint31_Index, std::vector< Derived_Structure > >::const_iterator diff --git a/src/overpass_api/data/set_comparison.h b/src/overpass_api/data/set_comparison.h index 6715b1fd2..e52527c4f 100644 --- a/src/overpass_api/data/set_comparison.h +++ b/src/overpass_api/data/set_comparison.h @@ -145,7 +145,7 @@ class Set_Comparison void clear_ways(Resource_Manager& rman, bool add_deletion_information = false); void clear_relations(Resource_Manager& rman, bool add_deletion_information = false); - void compute_deriveds(std::map< Uint31_Index, std::vector< Derived_Structure > > rhs_deriveds); + void compute_deriveds(const std::map< Uint31_Index, std::vector< Derived_Structure > >& rhs_deriveds); const Set& lhs_set() const { return lhs_set_; } uint64 lhs_timestamp() const { return lhs_timestamp_; } diff --git a/src/overpass_api/data/tag_store.h b/src/overpass_api/data/tag_store.h index d1f565233..a6a0bb0c3 100644 --- a/src/overpass_api/data/tag_store.h +++ b/src/overpass_api/data/tag_store.h @@ -20,16 +20,24 @@ #define DE__OSM3S___OVERPASS_API__DATA__TAG_STORE_H +#include "abstract_processing.h" #include "filenames.h" #include "../core/datatypes.h" #include "../../template_db/block_backend.h" #include "../../template_db/transaction.h" +#include "../core/tag_list.h" +#include +#include #include #include #include +template< typename Id_Type > +using Tag_Refs_By_Id = std::map< Id_Type, Tag_List >; + + template< typename Index, typename Object > class Tag_Store { @@ -45,9 +53,13 @@ class Tag_Store typename Object::Id_Type lower_id_bound, typename Object::Id_Type upper_id_bound); const std::vector< std::pair< std::string, std::string > >* get(const Index& index, const Object& elem); + const Tag_List* get_refs(const Index& index, const Object& elem); private: std::map< typename Object::Id_Type, std::vector< std::pair< std::string, std::string > > > tags_by_id; + std::deque< std::pair< std::string, std::string > > tag_pool; + Tag_Refs_By_Id< typename Object::Id_Type > refs_by_id; + Tag_List scratch; Transaction* transaction; bool use_index; Index stored_index; @@ -74,6 +86,15 @@ class Tag_Store< Uint31_Index, Derived_Structure > const std::vector< std::pair< std::string, std::string > >* get( const Uint31_Index& index, const Derived_Structure& elem) const { return &elem.tags; } + + const Tag_List* get_refs(const Uint31_Index& index, const Derived_Structure& elem) + { + make_tag_list(elem.tags, scratch); + return &scratch; + } + +private: + Tag_List scratch; }; @@ -90,10 +111,10 @@ void collect_attic_tags // Collect all id-matched tag information from the current tags while ((!(current_tag_it == current_items_db.range_end())) && - (((current_tag_it.index().index) & 0x7fffff00) < coarse_index)) + ((tag_coarse_index(current_tag_it)) < coarse_index)) ++current_tag_it; while ((!(current_tag_it == current_items_db.range_end())) && - (((current_tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(current_tag_it)) == coarse_index)) { typename std::vector< Attic< Id_Type > >::const_iterator it_id = std::lower_bound(id_vec.begin(), id_vec.end(), Attic< Id_Type >(current_tag_it.object(), 0ull)); @@ -108,10 +129,10 @@ void collect_attic_tags // Collect all id-matched tag information that is younger than the respective timestamp from the attic tags while ((!(attic_tag_it == attic_items_db.range_end())) && - (((attic_tag_it.index().index) & 0x7fffff00) < coarse_index)) + ((tag_coarse_index(attic_tag_it)) < coarse_index)) ++attic_tag_it; while ((!(attic_tag_it == attic_items_db.range_end())) && - (((attic_tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(attic_tag_it)) == coarse_index)) { typename std::vector< Attic< Id_Type > >::const_iterator it_id = std::lower_bound(id_vec.begin(), id_vec.end(), Attic< Id_Type >(attic_tag_it.object(), 0ull)); @@ -123,6 +144,10 @@ void collect_attic_tags ++attic_tag_it; } + // The entries of tags_by_id this call adds to. Only these can hold empty placeholder tags + // afterwards: tags_by_id accumulates over the calls for a chunk, and earlier calls removed theirs. + std::vector< std::vector< std::pair< std::string, std::string > >* > touched; + // Actually take for each object and key of the multiple versions only the oldest valid version for (typename std::map< Attic< Id_Type >, std::vector< std::pair< std::string, std::string > > > ::const_iterator @@ -135,6 +160,7 @@ void collect_attic_tags while (it_id != it_id_end) { std::vector< std::pair< std::string, std::string > >& obj_vec = tags_by_id[*it_id]; + touched.push_back(&obj_vec); std::vector< std::pair< std::string, std::string > >::const_iterator last_added_it = it->second.end(); for (std::vector< std::pair< std::string, std::string > >::const_iterator it_source = it->second.begin(); it_source != it->second.end(); ++it_source) @@ -167,17 +193,15 @@ void collect_attic_tags } // Remove empty tags. They are placeholders for tags added later than each timestamp in question. - for (typename std::map< Id_Type, std::vector< std::pair< std::string, std::string > > > - ::iterator - it_obj = tags_by_id.begin(); it_obj != tags_by_id.end(); ++it_obj) + for (auto obj_vec : touched) { for (typename std::vector< std::pair< std::string, std::string > >::size_type - i = 0; i < it_obj->second.size(); ) + i = 0; i < obj_vec->size(); ) { - if (it_obj->second[i].second == void_tag_value()) + if ((*obj_vec)[i].second == void_tag_value()) { - it_obj->second[i] = it_obj->second.back(); - it_obj->second.pop_back(); + (*obj_vec)[i] = obj_vec->back(); + obj_vec->pop_back(); } else ++i; @@ -219,6 +243,24 @@ void collect_attic_tags } +// Whether the sorted ids contain id. cursor is where the previous lookup ended: the tag entries of +// one tag come in ascending id order, so the search gallops forward from there, and starts over +// only when id isn't greater than the id before the cursor. +template< class Id_Type > +bool contains_from_cursor(const std::vector< Id_Type >& ids, + typename std::vector< Id_Type >::const_iterator& cursor, const Id_Type& id) +{ + if (cursor != ids.begin() && !(*(cursor - 1) < id)) + cursor = ids.begin(); + typename std::vector< Id_Type >::size_type remaining = ids.end() - cursor; + typename std::vector< Id_Type >::size_type bound = 1; + while (bound < remaining && cursor[bound] < id) + bound *= 2; + cursor = std::lower_bound(cursor + bound/2, cursor + std::min(bound, remaining), id); + return cursor != ids.end() && !(id < *cursor); +} + + template< class Id_Type > void collect_tags (std::map< Id_Type, std::vector< std::pair< std::string, std::string > > >& tags_by_id, @@ -226,13 +268,14 @@ void collect_tags typename Block_Backend< Tag_Index_Local, Id_Type >::Range_Iterator& tag_it, const std::vector< Id_Type >& ids, uint32 coarse_index) { + typename std::vector< Id_Type >::const_iterator cursor = ids.begin(); while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) < coarse_index)) + ((tag_coarse_index(tag_it)) < coarse_index)) ++tag_it; while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(tag_it)) == coarse_index)) { - if ((binary_search(ids.begin(), ids.end(), tag_it.object()))) + if (contains_from_cursor(ids, cursor, tag_it.object())) tags_by_id[tag_it.object()].push_back (std::make_pair(tag_it.index().key, tag_it.index().value)); ++tag_it; @@ -242,27 +285,54 @@ void collect_tags template< class Id_Type > void collect_tags_framed - (std::map< Id_Type, std::vector< std::pair< std::string, std::string > > >& tags_by_id, + (Tag_Refs_By_Id< Id_Type >& refs_by_id, + std::deque< std::pair< std::string, std::string > >& tag_pool, const Block_Backend< Tag_Index_Local, Id_Type >& items_db, typename Block_Backend< Tag_Index_Local, Id_Type >::Range_Iterator& tag_it, std::map< uint32, std::vector< Id_Type > >& ids_by_coarse, uint32 coarse_index, Id_Type lower_id_bound, Id_Type upper_id_bound) { + const std::vector< Id_Type >& ids = ids_by_coarse[coarse_index]; + typename std::vector< Id_Type >::const_iterator cursor = ids.begin(); + // Most of a cell's tag entries belong to other elements: reject those with one bit test. + Id_Bit_Filter id_filter(ids); while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) < coarse_index)) + ((tag_coarse_index(tag_it)) < coarse_index)) ++tag_it; + std::vector< const std::pair< std::string, std::string >* > key_values; + std::vector< std::pair< Id_Type, uint32 > > found; while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(tag_it)) == coarse_index)) { - if (!(tag_it.object() < lower_id_bound) && + if (id_filter.maybe_contains(tag_it.object().val()) && + !(tag_it.object() < lower_id_bound) && (tag_it.object() < upper_id_bound) && - (binary_search(ids_by_coarse[coarse_index].begin(), - ids_by_coarse[coarse_index].end(), tag_it.object()))) - tags_by_id[tag_it.object()].push_back - (std::make_pair(tag_it.index().key, tag_it.index().value)); + contains_from_cursor(ids, cursor, tag_it.object())) + { + const Tag_Index_Local& idx = tag_it.index(); + if (key_values.empty() || key_values.back()->second != idx.value || key_values.back()->first != idx.key) + { + tag_pool.push_back(std::make_pair(idx.key, idx.value)); + key_values.push_back(&tag_pool.back()); + } + found.push_back(std::make_pair(tag_it.object(), uint32(key_values.size() - 1))); + } ++tag_it; } + + std::stable_sort(found.begin(), found.end(), + [](const std::pair< Id_Type, uint32 >& a, const std::pair< Id_Type, uint32 >& b) { return a.first < b.first; }); + for (typename std::vector< std::pair< Id_Type, uint32 > >::const_iterator it = found.begin(); it != found.end(); ) + { + typename std::vector< std::pair< Id_Type, uint32 > >::const_iterator end = it; + while (end != found.end() && end->first == it->first) + ++end; + Tag_List& tags = refs_by_id[it->first]; + tags.reserve(tags.size() + (end - it)); + for (; it != end; ++it) + tags.push_back(Tag_Ref(key_values[it->second]->first, key_values[it->second]->second)); + } } @@ -275,6 +345,8 @@ Tag_Store< Index, Object >::Tag_Store(Transaction& transaction_) template< typename Index, typename Object > void Tag_Store< Index, Object >::prefetch_all(const std::map< Index, std::vector< Object > >& elems) { + refs_by_id.clear(); + tag_pool.clear(); use_index = true; generate_ids_by_coarse(ids_by_coarse, elems); ranges = formulate_range_query(ids_by_coarse); @@ -302,9 +374,12 @@ void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vect typename Object::Id_Type lower_id_bound, typename Object::Id_Type upper_id_bound) { tags_by_id.clear(); + refs_by_id.clear(); + tag_pool.clear(); - //generate std::set of relevant coarse indices - generate_ids_by_coarse(ids_by_coarse, elems); + // The coarse indices and ids of this chunk's elements only: no other tags are collected. + ids_by_coarse.clear(); + generate_ids_by_coarse(ids_by_coarse, elems, lower_id_bound, upper_id_bound); Block_Backend< Tag_Index_Local, typename Object::Id_Type > items_db (transaction->data_index(current_local_tags_file_properties< Object >())); @@ -313,7 +388,7 @@ void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vect auto tag_it = items_db.range_begin(ranges); for (typename std::map< uint32, std::vector< typename Object::Id_Type > >::const_iterator it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) - collect_tags_framed< typename Object::Id_Type >(tags_by_id, items_db, tag_it, ids_by_coarse, it->first, + collect_tags_framed< typename Object::Id_Type >(refs_by_id, tag_pool, items_db, tag_it, ids_by_coarse, it->first, lower_id_bound, upper_id_bound); } @@ -321,6 +396,8 @@ void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vect template< typename Index, typename Object > void Tag_Store< Index, Object >::prefetch_all(const std::map< Index, std::vector< Attic< Object > > >& attic_items) { + refs_by_id.clear(); + tag_pool.clear(); use_index = true; generate_ids_by_coarse(attic_ids_by_coarse, attic_items); ranges = formulate_range_query(attic_ids_by_coarse); @@ -353,8 +430,12 @@ template< typename Index, typename Object > void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vector< Attic< Object > > >& attic_items, typename Object::Id_Type lower_id_bound, typename Object::Id_Type upper_id_bound) { - //generate std::set of relevant coarse indices - generate_ids_by_coarse(attic_ids_by_coarse, attic_items); + // As for current elements: only this chunk's tags and ids are needed. + tags_by_id.clear(); + refs_by_id.clear(); + tag_pool.clear(); + attic_ids_by_coarse.clear(); + generate_ids_by_coarse(attic_ids_by_coarse, attic_items, lower_id_bound, upper_id_bound); Block_Backend< Tag_Index_Local, typename Object::Id_Type > current_tags_db (transaction->data_index(current_local_tags_file_properties< Object >())); @@ -413,8 +494,29 @@ const std::vector< std::pair< std::string, std::string > >* auto it = tags_by_id.find(elem.id); if (it != tags_by_id.end()) return &it->second; - else + auto rit = refs_by_id.find(elem.id); + if (rit == refs_by_id.end()) + return 0; + std::vector< std::pair< std::string, std::string > >& tags = tags_by_id[elem.id]; + for (Tag_List::const_iterator tit = rit->second.begin(); tit != rit->second.end(); ++tit) + tags.push_back(std::make_pair(tit->first, tit->second)); + return &tags; +} + + +template< typename Index, typename Object > +const Tag_List* Tag_Store< Index, Object >::get_refs(const Index& index, const Object& elem) +{ + if (!refs_by_id.empty()) + { + auto rit = refs_by_id.find(elem.id); + return rit == refs_by_id.end() ? 0 : &rit->second; + } + const std::vector< std::pair< std::string, std::string > >* tags = get(index, elem); + if (!tags) return 0; + make_tag_list(*tags, scratch); + return &scratch; } diff --git a/src/overpass_api/data/tags_global_reader.h b/src/overpass_api/data/tags_global_reader.h index 929fc930d..5e894704c 100644 --- a/src/overpass_api/data/tags_global_reader.h +++ b/src/overpass_api/data/tags_global_reader.h @@ -22,6 +22,7 @@ #include #include +#include #include @@ -30,6 +31,7 @@ #include "../core/settings.h" #include "../statements/statement.h" #include "../dispatch/resource_manager.h" +#include "abstract_processing.h" #include "filenames.h" #include "filter_by_tags.h" #include "regular_expression.h" @@ -64,7 +66,7 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kv( std::vector< std::pair< std::string, std::string > >::const_iterator kvit, uint64 timestamp, Block_Backend< Tag_Index_Global, Tag_Object_Global< Id_Type > >& tags_db, Block_Backend< Tag_Index_Global, Attic< Tag_Object_Global< Id_Type > > >& attic_tags_db, - std::vector< std::pair< Id_Type, Uint31_Index > >* relevant_ids = 0) + std::vector< std::pair< Id_Type, Uint31_Index > >* relevant_ids = 0, std::size_t limit = 0) { std::map< Id_Type, std::pair< uint64, Uint31_Index > > timestamp_per_id; Ranges< Tag_Index_Global > tag_req = get_kv_req(kvit->first, kvit->second); @@ -73,7 +75,11 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kv( { if (!relevant_ids || std::binary_search( relevant_ids->begin(), relevant_ids->end(), std::make_pair(it2.object().id, Uint31_Index(0u)))) + { timestamp_per_id[it2.object().id] = std::make_pair(NOW, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; + } } for (auto it2 = attic_tags_db.range_begin(tag_req); !(it2 == attic_tags_db.range_end()); ++it2) @@ -85,6 +91,8 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kv( std::pair< uint64, Uint31_Index >& ref = timestamp_per_id[it2.object().id]; if (ref.first == 0 || it2.object().timestamp < ref.first) ref = std::make_pair(it2.object().timestamp, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; } } @@ -112,21 +120,34 @@ template< class Id_Type > std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_k( std::vector< std::string >::const_iterator kit, uint64 timestamp, Block_Backend< Tag_Index_Global, Tag_Object_Global< Id_Type > >& tags_db, - Block_Backend< Tag_Index_Global, Attic< Tag_Object_Global< Id_Type > > >& attic_tags_db) + Block_Backend< Tag_Index_Global, Attic< Tag_Object_Global< Id_Type > > >& attic_tags_db, + std::vector< std::pair< Id_Type, Uint31_Index > >* relevant_ids = 0, std::size_t limit = 0) { std::map< Id_Type, std::pair< uint64, Uint31_Index > > timestamp_per_id; Ranges< Tag_Index_Global > ranges = get_k_req(*kit); for (auto it2 = tags_db.range_begin(ranges); !(it2 == tags_db.range_end()); ++it2) - timestamp_per_id[it2.object().id] = std::make_pair(NOW, it2.object().idx); + { + if (!relevant_ids || std::binary_search( + relevant_ids->begin(), relevant_ids->end(), std::make_pair(it2.object().id, Uint31_Index(0u)))) + { + timestamp_per_id[it2.object().id] = std::make_pair(NOW, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; + } + } for (auto it2 = attic_tags_db.range_begin(ranges); !(it2 == attic_tags_db.range_end()); ++it2) { - if (it2.object().timestamp > timestamp && it2.index().value != void_tag_value()) + if (it2.object().timestamp > timestamp && it2.index().value != void_tag_value() + && (!relevant_ids || std::binary_search( + relevant_ids->begin(), relevant_ids->end(), std::make_pair(it2.object().id, Uint31_Index(0u))))) { std::pair< uint64, Uint31_Index >& ref = timestamp_per_id[it2.object().id]; if (ref.first == 0 || it2.object().timestamp < ref.first) ref = std::make_pair(it2.object().timestamp, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; } } @@ -153,7 +174,7 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kregv( std::vector< std::pair< std::string, Regular_Expression* > >::const_iterator krit, uint64 timestamp, Block_Backend< Tag_Index_Global, Tag_Object_Global< Id_Type > >& tags_db, Block_Backend< Tag_Index_Global, Attic< Tag_Object_Global< Id_Type > > >& attic_tags_db, - std::vector< std::pair< Id_Type, Uint31_Index > >* relevant_ids = 0) + std::vector< std::pair< Id_Type, Uint31_Index > >* relevant_ids = 0, std::size_t limit = 0) { std::map< Id_Type, std::pair< uint64, Uint31_Index > > timestamp_per_id; Ranges< Tag_Index_Global > ranges = get_k_req(krit->first); @@ -163,7 +184,11 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kregv( if ((!relevant_ids || std::binary_search( relevant_ids->begin(), relevant_ids->end(), std::make_pair(it2.object().id, Uint31_Index(0u)))) && krit->second->matches(it2.index().value)) + { timestamp_per_id[it2.object().id] = std::make_pair(NOW, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; + } } for (auto it2 = attic_tags_db.range_begin(ranges); !(it2 == attic_tags_db.range_end()); ++it2) @@ -176,6 +201,8 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kregv( std::pair< uint64, Uint31_Index >& ref = timestamp_per_id[it2.object().id]; if (ref.first == 0 || it2.object().timestamp < ref.first) ref = std::make_pair(it2.object().timestamp, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; } } @@ -283,6 +310,42 @@ struct Trivial_Regex }; +// Tests tag index entries against a key and a value regex. The entries come sorted by key and value, +// so consecutive entries mostly repeat both: only evaluate the regexes when one of them changes. +template< typename Key_Regex, typename Val_Regex > +class Tag_Entry_Matcher +{ +public: + Tag_Entry_Matcher(const Key_Regex& key_regex, const Val_Regex& val_regex) + : key_regex_(key_regex), val_regex_(val_regex), valid_(false), matches_(false) {} + + template< typename Index > + bool matches(const Index& index) + { + // Without regexes (key=value lookups) there is nothing worth remembering. + if (std::is_same< Key_Regex, Trivial_Regex >::value && std::is_same< Val_Regex, Trivial_Regex >::value) + return index.value != void_tag_value(); + + if (!valid_ || index.value != value_ || index.key != key_) + { + key_ = index.key; + value_ = index.value; + matches_ = key_regex_.matches(key_) && value_ != void_tag_value() && val_regex_.matches(value_); + valid_ = true; + } + return matches_; + } + +private: + const Key_Regex& key_regex_; + const Val_Regex& val_regex_; + std::string key_; + std::string value_; + bool valid_; + bool matches_; +}; + + template< typename Id_Type, typename Iterator, typename Key_Regex, typename Val_Regex > void filter_id_list( std::vector< std::pair< Id_Type, Uint31_Index > >& new_ids, bool& filtered, @@ -291,11 +354,22 @@ void filter_id_list( { std::vector< std::pair< Id_Type, Uint31_Index > > old_ids; old_ids.swap(new_ids); + Tag_Entry_Matcher< Key_Regex, Val_Regex > matcher(key_regex, val_regex); + // Most entries of a later key belong to none of the candidates: reject those with one bit test. + std::vector< Id_Type > old_id_list; + if (filtered) + { + old_id_list.reserve(old_ids.size()); + for (auto it = old_ids.begin(); it != old_ids.end(); ++it) + old_id_list.push_back(it->first); + } + Id_Bit_Filter old_id_filter(old_id_list); for (Iterator it = begin; !(it == end); ++it) { - if (key_regex.matches(it.index().key) && it.index().value != void_tag_value() - && val_regex.matches(it.index().value) && (!filtered || + if (filtered && !old_id_filter.maybe_contains(it.object().id.val())) + continue; + if (matcher.matches(it.index()) && (!filtered || std::binary_search(old_ids.begin(), old_ids.end(), std::make_pair(it.object().id, Uint31_Index(0u))))) new_ids.push_back(std::make_pair(it.object().id, it.object().idx)); @@ -320,11 +394,11 @@ void filter_id_list( { std::vector< Id_Type > old_ids; old_ids.swap(new_ids); + Tag_Entry_Matcher< Key_Regex, Val_Regex > matcher(key_regex, val_regex); for (Iterator it = begin; !(it == end); ++it) { - if (key_regex.matches(it.index().key) && it.index().value != void_tag_value() - && val_regex.matches(it.index().value) && + if (matcher.matches(it.index()) && (!filtered || std::binary_search(old_ids.begin(), old_ids.end(), it.object()))) new_ids.push_back(it.object()); } @@ -361,7 +435,64 @@ void filter_id_list( class Statement; -template< typename Skeleton, typename Id_Type > +// Blocks a late tag check of these candidates reads: their cells' skeletons and local tags. +template< typename Skeleton, typename Id_Type, typename Index > +uint64 count_late_check_blocks(const std::vector< std::pair< Id_Type, Uint31_Index > >& ids, Resource_Manager& rman) +{ + std::vector< uint32 > cells; + cells.reserve(ids.size()); + for (auto it = ids.begin(); it != ids.end(); ++it) + cells.push_back(it->second.val() & 0x7fffff00); + std::sort(cells.begin(), cells.end()); + cells.erase(std::unique(cells.begin(), cells.end()), cells.end()); + + Ranges< Tag_Index_Local > tag_ranges; + Ranges< Index > skeleton_ranges; + for (auto it = cells.begin(); it != cells.end(); ++it) + { + tag_ranges.push_back({ *it, "", "" }, { *it + 0x100, "", "" }); + skeleton_ranges.push_back(Index(*it), Index(*it + 0x100)); + } + tag_ranges.sort(); + skeleton_ranges.sort(); + Block_Backend< Tag_Index_Local, Id_Type > local_tags_db + (rman.get_transaction()->data_index(current_local_tags_file_properties< Skeleton >())); + Block_Backend< Index, Skeleton > skeletons_db + (rman.get_transaction()->data_index(current_skeleton_file_properties< Skeleton >())); + return local_tags_db.count_blocks(tag_ranges) + skeletons_db.count_blocks(skeleton_ranges); +} + + +// The global tag index stores coarse indices (multiples of 0x100): keep ids whose cell overlaps ranges. +template< typename Id_Type, typename Index > +void keep_ids_inside(std::vector< std::pair< Id_Type, Uint31_Index > >& ids, const Ranges< Index >& ranges) +{ + std::vector< std::pair< Index, Index > > bounds; + for (auto it = ranges.begin(); it != ranges.end(); ++it) + bounds.push_back(std::make_pair(it.lower_bound(), it.upper_bound())); + std::sort(bounds.begin(), bounds.end()); + std::vector< std::pair< Index, Index > > merged; + for (auto it = bounds.begin(); it != bounds.end(); ++it) + { + if (!merged.empty() && !(merged.back().second < it->first)) + merged.back().second = std::max(merged.back().second, it->second); + else + merged.push_back(*it); + } + std::vector< std::pair< Id_Type, Uint31_Index > > kept; + for (auto it = ids.begin(); it != ids.end(); ++it) + { + Index idx(it->second.val()); + auto b = std::upper_bound(merged.begin(), merged.end(), idx, + [](const Index& x, const std::pair< Index, Index >& r) { return x < r.second; }); + if (b != merged.end() && b->first < Index(idx.val() + 0x100)) + kept.push_back(*it); + } + kept.swap(ids); +} + + +template< typename Skeleton, typename Id_Type, typename Index > std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( const std::vector< std::string >& keys, const std::vector< std::pair< std::string, std::string > >& key_values, @@ -369,8 +500,10 @@ std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( const std::vector< std::pair< Regular_Expression*, Regular_Expression* > >& regkey_regexes, const File_Properties& file_prop, const File_Properties& attic_file_prop, Resource_Manager& rman, const Statement& stmt, - uint64 timestamp, Query_Filter_Strategy check_keys_late, bool& result_valid) + uint64 timestamp, Query_Filter_Strategy check_keys_late, bool& result_valid, bool& check_rest_late, + const Ranges< Index >* spatial_ranges) { + check_rest_late = false; if (key_values.empty() && keys.empty() && key_regexes.empty() && regkey_regexes.empty()) return std::vector< std::pair< Id_Type, Uint31_Index > >(); @@ -381,11 +514,86 @@ std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( new Block_Backend< Tag_Index_Global, Attic< Tag_Object_Global< Id_Type > > > (rman.get_transaction()->data_index(&attic_file_prop))); - // Handle simple Key-Value pairs std::vector< std::pair< Id_Type, Uint31_Index > > new_ids; bool filtered = false; result_valid = false; + if (timestamp == NOW) + { + // Smallest lookups first; stop when checking the remaining tags late reads fewer blocks. + struct Lookup + { + Ranges< Tag_Index_Global > ranges; + Regular_Expression* value_regex; + bool limit_size; + uint64 blocks; + }; + std::vector< Lookup > lookups; + for (auto it = key_values.begin(); it != key_values.end(); ++it) + lookups.push_back(Lookup{ get_kv_req(it->first, it->second), 0, + check_keys_late == prefer_ranges || check_keys_late == ids_useful, 0 }); + if (check_keys_late != prefer_ranges) + { + for (auto it = keys.begin(); it != keys.end(); ++it) + lookups.push_back(Lookup{ get_k_req(*it), 0, check_keys_late == ids_useful, 0 }); + for (auto it = key_regexes.begin(); it != key_regexes.end(); ++it) + lookups.push_back(Lookup{ get_k_req(it->first), it->second, check_keys_late == ids_useful, 0 }); + } + uint64 remaining_blocks = 0; + for (auto it = lookups.begin(); it != lookups.end(); ++it) + { + it->blocks = tags_db.count_blocks(it->ranges); + remaining_blocks += it->blocks; + } + std::stable_sort(lookups.begin(), lookups.end(), + [](const Lookup& lhs, const Lookup& rhs) { return lhs.blocks < rhs.blocks; }); + + for (auto it = lookups.begin(); it != lookups.end(); ++it) + { + if (filtered && count_late_check_blocks< Skeleton, Id_Type, Index >(new_ids, rman) < remaining_blocks) + { + check_rest_late = true; + result_valid = true; + return new_ids; + } + if (it->value_regex) + filter_id_list(new_ids, filtered, tags_db.range_begin(it->ranges), tags_db.range_end(), + Trivial_Regex(), *it->value_regex, it->limit_size); + else + filter_id_list(new_ids, filtered, tags_db.range_begin(it->ranges), tags_db.range_end(), + Trivial_Regex(), Trivial_Regex(), it->limit_size); + if (!filtered) + return new_ids; + if (spatial_ranges) + keep_ids_inside(new_ids, *spatial_ranges); + if (new_ids.empty()) + { + result_valid = true; + return new_ids; + } + remaining_blocks -= it->blocks; + rman.health_check(stmt); + } + + if (check_keys_late != prefer_ranges) + { + for (auto it = regkey_regexes.begin(); it != regkey_regexes.end(); ++it) + { + Ranges< Tag_Index_Global > ranges = get_regk_req< Skeleton >(it->first, rman, stmt); + filter_id_list(new_ids, filtered, tags_db.range_begin(ranges), tags_db.range_end(), + *it->first, *it->second, check_keys_late == ids_useful); + if (!filtered) + return new_ids; + rman.health_check(stmt); + } + } + + result_valid = true; + return new_ids; + } + + // Handle simple Key-Value pairs + for (std::vector< std::pair< std::string, std::string > >::const_iterator kvit = key_values.begin(); kvit != key_values.end(); ++kvit) { @@ -399,7 +607,15 @@ std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( return new_ids; } else - filter_id_list(new_ids, filtered, collect_attic_kv(kvit, timestamp, tags_db, *attic_tags_db.obj)); + { + std::size_t limit = !filtered && (check_keys_late == prefer_ranges || check_keys_late == ids_useful) + ? 1024*1024 : 0; + std::map< Id_Type, std::pair< uint64, Uint31_Index > > attic_ids = collect_attic_kv( + kvit, timestamp, tags_db, *attic_tags_db.obj, filtered ? &new_ids : 0, limit); + if (limit && attic_ids.size() >= limit) + return new_ids; + filter_id_list(new_ids, filtered, attic_ids); + } rman.health_check(stmt); } @@ -419,7 +635,14 @@ std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( return new_ids; } else - filter_id_list(new_ids, filtered, collect_attic_k(kit, timestamp, tags_db, *attic_tags_db.obj)); + { + std::size_t limit = !filtered && check_keys_late == ids_useful ? 1024*1024 : 0; + std::map< Id_Type, std::pair< uint64, Uint31_Index > > attic_ids = collect_attic_k( + kit, timestamp, tags_db, *attic_tags_db.obj, filtered ? &new_ids : 0, limit); + if (limit && attic_ids.size() >= limit) + return new_ids; + filter_id_list(new_ids, filtered, attic_ids); + } rman.health_check(stmt); } @@ -438,7 +661,14 @@ std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( return new_ids; } else - filter_id_list(new_ids, filtered, collect_attic_kregv(krit, timestamp, tags_db, *attic_tags_db.obj)); + { + std::size_t limit = !filtered && check_keys_late == ids_useful ? 1024*1024 : 0; + std::map< Id_Type, std::pair< uint64, Uint31_Index > > attic_ids = collect_attic_kregv( + krit, timestamp, tags_db, *attic_tags_db.obj, filtered ? &new_ids : 0, limit); + if (limit && attic_ids.size() >= limit) + return new_ids; + filter_id_list(new_ids, filtered, attic_ids); + } rman.health_check(stmt); } @@ -771,7 +1001,7 @@ void progress_1( const std::vector< std::pair< Regular_Expression*, Regular_Expression* > >& regkey_nregexes, Id_Constraint< Id_Type >& ids, std::vector< Index >& range_vec, uint64 timestamp, Query_Filter_Strategy& check_keys_late, - Resource_Manager& rman, const Statement& stmt) + Resource_Manager& rman, const Statement& stmt, const Ranges< Index >* spatial_ranges = 0) { File_Properties* file_prop = current_global_tags_file_properties< Skeleton >(); File_Properties* attic_file_prop = attic_global_tags_file_properties< Skeleton >(); @@ -783,11 +1013,13 @@ void progress_1( && (!keys.empty() || !key_regexes.empty() || !regkey_regexes.empty()))) { bool result_valid = true; + bool check_rest_late = false; std::vector< std::pair< Id_Type, Uint31_Index > > id_idxs = - collect_ids< Skeleton, Id_Type >( + collect_ids< Skeleton, Id_Type, Index >( keys, key_values, key_regexes, regkey_regexes, - *file_prop, *attic_file_prop, rman, stmt, timestamp, check_keys_late, result_valid); - if (check_keys_late == ids_useful && !result_valid) + *file_prop, *attic_file_prop, rman, stmt, timestamp, check_keys_late, result_valid, check_rest_late, + spatial_ranges); + if ((check_keys_late == ids_useful && !result_valid) || check_rest_late) check_keys_late = prefer_ranges; ids.invert = !result_valid; diff --git a/src/overpass_api/data/way_geometry_store.cc b/src/overpass_api/data/way_geometry_store.cc index 2c539aa00..2136a8025 100644 --- a/src/overpass_api/data/way_geometry_store.cc +++ b/src/overpass_api/data/way_geometry_store.cc @@ -89,13 +89,7 @@ Way_Geometry_Store::Way_Geometry_Store std::map< Uint32_Index, std::vector< Node_Skeleton > > way_members_ = small_way_members(&query, rman, ways); // Order node ids by id. - for (std::map< Uint32_Index, std::vector< Node_Skeleton > >::iterator it = way_members_.begin(); - it != way_members_.end(); ++it) - { - for (std::vector< Node_Skeleton >::const_iterator iit = it->second.begin(); - iit != it->second.end(); ++iit) - nodes.push_back(Node(iit->id, it->first.val(), iit->ll_lower)); - } + move_to_node_positions(way_members_, nodes); sort(nodes.begin(), nodes.end(), Node_Comparator_By_Id()); } diff --git a/src/overpass_api/data/way_geometry_store.h b/src/overpass_api/data/way_geometry_store.h index 651ad8e13..00395dee5 100644 --- a/src/overpass_api/data/way_geometry_store.h +++ b/src/overpass_api/data/way_geometry_store.h @@ -40,7 +40,7 @@ class Way_Geometry_Store std::vector< Quad_Coord > get_geometry(const Way_Skeleton& way) const; private: - std::vector< Node > nodes; + std::vector< Node_Position > nodes; }; diff --git a/src/overpass_api/dispatch/db_timestamp.cc b/src/overpass_api/dispatch/db_timestamp.cc index c91f88151..cdba91fe3 100644 --- a/src/overpass_api/dispatch/db_timestamp.cc +++ b/src/overpass_api/dispatch/db_timestamp.cc @@ -41,31 +41,31 @@ class Output_Timestamp : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0) {} virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0) {} virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -73,12 +73,12 @@ class Output_Timestamp : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0) {} virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep) {} }; diff --git a/src/overpass_api/dispatch/resource_manager.cc b/src/overpass_api/dispatch/resource_manager.cc index 56ed22da6..30bd7d5ec 100644 --- a/src/overpass_api/dispatch/resource_manager.cc +++ b/src/overpass_api/dispatch/resource_manager.cc @@ -29,7 +29,7 @@ uint64 eval_map(const std::map< Uint32_Index, std::vector< Node_Skeleton > >& no uint64 size(0); for (std::map< Uint32_Index, std::vector< Node_Skeleton > >::const_iterator it(nodes.begin()); it != nodes.end(); ++it) - size += it->second.size()*8 + 64; + size += it->second.size()*eval_object_size((const Node_Skeleton*)0) + eval_index_size; return size; } @@ -39,7 +39,7 @@ uint64 eval_map(const std::map< Uint31_Index, std::vector< Way_Skeleton > >& way uint64 size(0); for (std::map< Uint31_Index, std::vector< Way_Skeleton > >::const_iterator it(ways.begin()); it != ways.end(); ++it) - size += it->second.size()*128 + 64; + size += it->second.size()*eval_object_size((const Way_Skeleton*)0) + eval_index_size; return size; } @@ -49,7 +49,7 @@ uint64 eval_map(const std::map< Uint31_Index, std::vector< Relation_Skeleton > > uint64 size(0); for (std::map< Uint31_Index, std::vector< Relation_Skeleton > >::const_iterator it(relations.begin()); it != relations.end(); ++it) - size += it->second.size()*192 + 64; + size += it->second.size()*eval_object_size((const Relation_Skeleton*)0) + eval_index_size; return size; } @@ -59,7 +59,7 @@ uint64 eval_map(const std::map< Uint32_Index, std::vector< Attic< Node_Skeleton uint64 size(0); for (std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >::const_iterator it(nodes.begin()); it != nodes.end(); ++it) - size += it->second.size()*16 + 64; + size += it->second.size()*eval_object_size((const Attic< Node_Skeleton >*)0) + eval_index_size; return size; } @@ -69,7 +69,7 @@ uint64 eval_map(const std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > uint64 size(0); for (std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > >::const_iterator it(ways.begin()); it != ways.end(); ++it) - size += it->second.size()*136 + 64; + size += it->second.size()*eval_object_size((const Attic< Way_Skeleton >*)0) + eval_index_size; return size; } @@ -79,7 +79,7 @@ uint64 eval_map(const std::map< Uint31_Index, std::vector< Attic< Relation_Skele uint64 size(0); for (std::map< Uint31_Index, std::vector< Attic< Relation_Skeleton > > >::const_iterator it(relations.begin()); it != relations.end(); ++it) - size += it->second.size()*200 + 64; + size += it->second.size()*eval_object_size((const Attic< Relation_Skeleton >*)0) + eval_index_size; return size; } @@ -89,7 +89,7 @@ uint64 eval_map(const std::map< Uint31_Index, std::vector< Area_Skeleton > >& ar uint64 size(0); for (std::map< Uint31_Index, std::vector< Area_Skeleton > >::const_iterator it(areas.begin()); it != areas.end(); ++it) - size += it->second.size()*128 + 64; + size += it->second.size()*eval_object_size((const Area_Skeleton*)0) + eval_index_size; return size; } diff --git a/src/overpass_api/dispatch/resource_manager.h b/src/overpass_api/dispatch/resource_manager.h index b897dc821..77ee330fe 100644 --- a/src/overpass_api/dispatch/resource_manager.h +++ b/src/overpass_api/dispatch/resource_manager.h @@ -159,6 +159,8 @@ class Resource_Manager bool health_check(const Statement& stmt, uint32 extra_time = 0, uint64 extra_space = 0); + uint64 get_max_allowed_space() const { return max_allowed_space; } + void set_limits(uint32 max_allowed_time_, uint64 max_allowed_space_) { max_allowed_time = max_allowed_time_; @@ -207,6 +209,18 @@ class Resource_Manager }; +// eval_map charges eval_index_size bytes per index plus eval_object_size per object. +// Keeping these in one place lets loops that only add objects keep the same total +// up to date instead of walking the whole map. +const uint64 eval_index_size = 64; +inline uint64 eval_object_size(const Node_Skeleton*) { return 8; } +inline uint64 eval_object_size(const Way_Skeleton*) { return 128; } +inline uint64 eval_object_size(const Relation_Skeleton*) { return 192; } +inline uint64 eval_object_size(const Attic< Node_Skeleton >*) { return 16; } +inline uint64 eval_object_size(const Attic< Way_Skeleton >*) { return 136; } +inline uint64 eval_object_size(const Attic< Relation_Skeleton >*) { return 200; } +inline uint64 eval_object_size(const Area_Skeleton*) { return 128; } + uint64 eval_map(const std::map< Uint32_Index, std::vector< Node_Skeleton > >& nodes); uint64 eval_map(const std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways); uint64 eval_map(const std::map< Uint31_Index, std::vector< Relation_Skeleton > >& relations); diff --git a/src/overpass_api/frontend/output_handler.h b/src/overpass_api/frontend/output_handler.h index 65204cb50..0cdf73e70 100644 --- a/src/overpass_api/frontend/output_handler.h +++ b/src/overpass_api/frontend/output_handler.h @@ -22,6 +22,7 @@ #include "../core/datatypes.h" #include "../core/geometry.h" +#include "../core/tag_list.h" struct Output_Mode @@ -50,6 +51,14 @@ const std::string& member_type_name(uint32 type); class Output_Handler { + static const Tag_List* as_tag_list(const std::vector< std::pair< std::string, std::string > >* tags, Tag_List& list) + { + if (!tags) + return 0; + make_tag_list(*tags, list); + return &list; + } + public: enum Feature_Action { keep, show_from, show_to, modify, push_away, pull_in, erase, create }; @@ -68,31 +77,31 @@ class Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0) = 0; virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0) = 0; virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -100,15 +109,57 @@ class Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0) = 0; virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep) = 0; + // For callers that hold their tags as pairs. + void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, + const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, + Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, + const Opaque_Geometry* new_geometry = 0, const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0) + { + Tag_List list, new_list; + print_item(skel, geometry, as_tag_list(tags, list), meta, users, mode, action, new_skel, new_geometry, + as_tag_list(new_tags, new_list), new_meta); + } + + void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, + const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, + Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, + const Opaque_Geometry* new_geometry = 0, const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0) + { + Tag_List list, new_list; + print_item(skel, geometry, as_tag_list(tags, list), meta, users, mode, action, new_skel, new_geometry, + as_tag_list(new_tags, new_list), new_meta); + } + + void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, + const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, + const std::map< uint32, std::string >* users, + Output_Mode mode, const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, + const Opaque_Geometry* new_geometry = 0, const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0) + { + Tag_List list, new_list; + print_item(skel, geometry, as_tag_list(tags, list), meta, roles, users, mode, action, new_skel, new_geometry, + as_tag_list(new_tags, new_list), new_meta); + } + + void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, + Output_Mode mode, const Feature_Action& action = keep) + { + Tag_List list; + print_item(skel, geometry, as_tag_list(tags, list), mode, action); + } + virtual std::string dump_config() const { return ""; } virtual ~Output_Handler() {} diff --git a/src/overpass_api/output_formats/fixed7.h b/src/overpass_api/output_formats/fixed7.h new file mode 100644 index 000000000..5f1ead0d7 --- /dev/null +++ b/src/overpass_api/output_formats/fixed7.h @@ -0,0 +1,88 @@ +/** Copyright 2026 the Overpass API contributors + * + * This file is part of Overpass_API. + * + * Overpass_API is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * Overpass_API is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Overpass_API. If not, see . + */ + +#ifndef DE__OSM3S___OVERPASS_API__OUTPUT_FORMATS__FIXED7_H +#define DE__OSM3S___OVERPASS_API__OUTPUT_FORMATS__FIXED7_H + +#include +#include +#include +#include + + +/* Writes a coordinate with exactly the same characters as + out< 0 || len < 8) + { + digits[len++] = '0' + (n % 10); + n /= 10; + } + int pos = 0; + if (std::signbit(value)) + buf[pos++] = '-'; + for (int i = len - 1; i >= 7; --i) + buf[pos++] = digits[i]; + buf[pos++] = '.'; + for (int i = 6; i >= 0; --i) + buf[pos++] = digits[i]; + buf[pos] = 0; + return pos; +} + + +inline std::ostream& operator<<(std::ostream& out, const Fixed7& f) +{ + out.setf(std::ios::fixed, std::ios::floatfield); + out.precision(7); + char buf[64]; + out.write(buf, format_fixed7(buf, f.value)); + return out; +} + + +#endif diff --git a/src/overpass_api/output_formats/output_csv.cc b/src/overpass_api/output_formats/output_csv.cc index 79be9a647..1dfc51c38 100644 --- a/src/overpass_api/output_formats/output_csv.cc +++ b/src/overpass_api/output_formats/output_csv.cc @@ -18,6 +18,7 @@ #include "../../expat/escape_json.h" #include "output_csv.h" +#include "fixed7.h" bool Output_CSV::write_http_headers() @@ -142,10 +143,10 @@ template< > void print_meta< int >(const std::string& keyfield, const int& meta, const std::map< uint32, std::string >* users) {} -std::string get_count_tag(const std::vector< std::pair< std::string, std::string> >* tags, std::string tag) +std::string get_count_tag(const Tag_List* tags, std::string tag) { if (tags) - for (std::vector< std::pair< std::string, std::string> >::const_iterator it_tags = tags->begin(); + for (Tag_List::const_iterator it_tags = tags->begin(); it_tags != tags->end(); ++it_tags) if (it_tags->first == tag) return it_tags->second; @@ -156,7 +157,7 @@ std::string get_count_tag(const std::vector< std::pair< std::string, std::string template< typename Id_Type, typename OSM_Element_Metadata_Skeleton > void process_csv_line(int otype, const std::string& type, Id_Type id, const Opaque_Geometry& geometry, const OSM_Element_Metadata_Skeleton* meta, - const std::vector< std::pair< std::string, std::string> >* tags, + const Tag_List* tags, const std::map< uint32, std::string >* users, const Csv_Settings& csv_settings, Output_Mode mode) @@ -168,7 +169,7 @@ void process_csv_line(int otype, const std::string& type, Id_Type id, const Opaq { if (tags) { - for (std::vector< std::pair< std::string, std::string> >::const_iterator it_tags = tags->begin(); + for (Tag_List::const_iterator it_tags = tags->begin(); it_tags != tags->end(); ++it_tags) { if (it_tags->first == it->first) @@ -197,13 +198,13 @@ void process_csv_line(int otype, const std::string& type, Id_Type id, const Opaq { if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER)) && geometry.has_center()) - std::cout<first == "lon") { if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER)) && geometry.has_center()) - std::cout< >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { process_csv_line(1, "node", skel.id, geometry, meta, tags, users, csv_settings, mode); @@ -246,14 +247,14 @@ void Output_CSV::print_item(const Node_Skeleton& skel, void Output_CSV::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { process_csv_line(2, "way", skel.id, geometry, meta, tags, users, csv_settings, mode); @@ -262,7 +263,7 @@ void Output_CSV::print_item(const Way_Skeleton& skel, void Output_CSV::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -270,7 +271,7 @@ void Output_CSV::print_item(const Relation_Skeleton& skel, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { process_csv_line(3, "relation", skel.id, geometry, meta, tags, users, csv_settings, mode); @@ -279,7 +280,7 @@ void Output_CSV::print_item(const Relation_Skeleton& skel, void Output_CSV::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action) { diff --git a/src/overpass_api/output_formats/output_csv.h b/src/overpass_api/output_formats/output_csv.h index aeb23e058..3b8f329f8 100644 --- a/src/overpass_api/output_formats/output_csv.h +++ b/src/overpass_api/output_formats/output_csv.h @@ -54,31 +54,31 @@ class Output_CSV : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0); virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0); virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -86,12 +86,12 @@ class Output_CSV : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0); virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep); diff --git a/src/overpass_api/output_formats/output_custom.cc b/src/overpass_api/output_formats/output_custom.cc index 0ac46c192..0dbf83e84 100644 --- a/src/overpass_api/output_formats/output_custom.cc +++ b/src/overpass_api/output_formats/output_custom.cc @@ -19,6 +19,7 @@ #include "../../expat/escape_xml.h" #include "../frontend/basic_formats.h" #include "output_custom.h" +#include "fixed7.h" #include #include @@ -262,7 +263,7 @@ std::string process_members(const std::string& raw_template, uint32 id, const Re else if (raw_template.substr(new_pos, 10) == "{{{role}}}") { std::map< uint32, std::string >::const_iterator rit = roles.find(entry.role); - result<second : "???"); + result<second : "???"); } else if (raw_template.substr(new_pos, 8) == "{{first:") ; @@ -329,9 +330,9 @@ std::string process_coords(const std::string& raw_template, uint32 id, double la else if (raw_template.substr(new_pos, 8) == "{{{id}}}") result< >* tags, + const Tag_List* tags, const std::vector< Node::Id_Type >* nds, const std::vector< Relation_Entry >* members, const std::map< uint32, std::string >* roles) @@ -478,7 +479,7 @@ std::string process_template(const std::string& raw_template, unsigned long long { if (tags != 0 && !tags->empty()) { - std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); + Tag_List::const_iterator it = tags->begin(); std::string first = extract_first(raw_template.substr(new_pos + 7, old_pos - new_pos - 9)); if (first != "" && it != tags->end()) @@ -561,14 +562,14 @@ void Output_Custom::write_footer() void Output_Custom::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { if (count == 0) @@ -639,14 +640,14 @@ unsigned int detect_zoom(const Opaque_Geometry& geometry) void Output_Custom::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { if (count == 0) @@ -677,7 +678,7 @@ void Output_Custom::print_item(const Way_Skeleton& skel, void Output_Custom::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -685,7 +686,7 @@ void Output_Custom::print_item(const Relation_Skeleton& skel, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { if (count == 0) @@ -716,7 +717,7 @@ void Output_Custom::print_item(const Relation_Skeleton& skel, void Output_Custom::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action) { diff --git a/src/overpass_api/output_formats/output_custom.h b/src/overpass_api/output_formats/output_custom.h index 512ae28cd..fa926a52a 100644 --- a/src/overpass_api/output_formats/output_custom.h +++ b/src/overpass_api/output_formats/output_custom.h @@ -45,31 +45,31 @@ class Output_Custom : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0); virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0); virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -77,12 +77,12 @@ class Output_Custom : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0); virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep); diff --git a/src/overpass_api/output_formats/output_json.cc b/src/overpass_api/output_formats/output_json.cc index 64a1afa35..af15ef1ba 100644 --- a/src/overpass_api/output_formats/output_json.cc +++ b/src/overpass_api/output_formats/output_json.cc @@ -20,6 +20,7 @@ #include "../core/settings.h" #include "../frontend/basic_formats.h" #include "output_json.h" +#include "fixed7.h" bool Output_JSON::write_http_headers() @@ -86,20 +87,20 @@ void print_meta_json(const OSM_Element_Metadata_Skeleton< Id_Type >& meta, ",\n \"changeset\": "<::const_iterator it = users.find(meta.user_id); if (it != users.end()) - std::cout<<",\n \"user\": \""<second)<<"\""; + std::cout<<",\n \"user\": \""<second)<<"\""; std::cout<<",\n \"uid\": "< >* tags) +void print_tags(const Tag_List* tags) { if (tags != 0 && !tags->empty()) { - std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); + Tag_List::const_iterator it = tags->begin(); std::cout<<",\n \"tags\": {" - "\n \""<first)<<"\": \""<second)<<"\""; + "\n \""<first)<<"\": \""<second)<<"\""; for (++it; it != tags->end(); ++it) - std::cout<<",\n \""<first)<<"\": \""<second)<<"\""; + std::cout<<",\n \""<first)<<"\": \""<second)<<"\""; std::cout<<"\n }"; } } @@ -107,14 +108,14 @@ void print_tags(const std::vector< std::pair< std::string, std::string > >* tags void Output_JSON::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { handle_first_elem(first_elem); @@ -124,8 +125,8 @@ void Output_JSON::print_item(const Node_Skeleton& skel, std::cout<<",\n \"id\": "< >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { handle_first_elem(first_elem); @@ -190,10 +191,8 @@ void Output_JSON::print_item(const Way_Skeleton& skel, for (uint i = 0; i < geometry.way_size(); ++i) { if (geometry.way_pos_is_valid(i)) - std::cout<<"\n { \"lat\": "< >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -218,7 +217,7 @@ void Output_JSON::print_item(const Relation_Skeleton& skel, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { handle_first_elem(first_elem); @@ -242,12 +241,12 @@ void Output_JSON::print_item(const Relation_Skeleton& skel, std::cout <<"\n {" "\n \"type\": \""<end() ? rit->second : "???") << "\""; + ",\n \"role\": \""<end() ? rit->second : "???") << "\""; if (skel.members[i].type == Relation_Entry::NODE && geometry.has_faithful_relation_geometry() && geometry.relation_pos_is_valid(i)) - std::cout<<",\n \"lat\": "<* line = geometry.get_line_geometry(); for (std::vector< Point_Double >::const_iterator it = line->begin(); it != line->end(); ++it) std::cout<<(it == line->begin() ? "" : ",")<<"\n"<lon<<", " - <lat<<"]"; + <lon)<<", " + <lat)<<"]"; std::cout<<"\n"<begin() ? "" : ",")<<"\n"<::const_iterator it = iti->begin(); it != iti->end(); ++it) std::cout<<(it == iti->begin() ? "" : ",")<<"\n"<lon<<", " - <lat<<"]"; + <lon)<<", " + <lat)<<"]"; std::cout<<"\n"< >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action) { diff --git a/src/overpass_api/output_formats/output_json.h b/src/overpass_api/output_formats/output_json.h index 2b3b2e18b..3b46b0ec5 100644 --- a/src/overpass_api/output_formats/output_json.h +++ b/src/overpass_api/output_formats/output_json.h @@ -44,31 +44,31 @@ class Output_JSON : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0); virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0); virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -76,12 +76,12 @@ class Output_JSON : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0); virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep); diff --git a/src/overpass_api/output_formats/output_popup.cc b/src/overpass_api/output_formats/output_popup.cc index 9e918b631..a7eab9929 100644 --- a/src/overpass_api/output_formats/output_popup.cc +++ b/src/overpass_api/output_formats/output_popup.cc @@ -24,11 +24,11 @@ #include -bool Tag_Filter::matches(const std::vector< std::pair< std::string, std::string > >* tags) const +bool Tag_Filter::matches(const Tag_List* tags) const { if (!tags) return false; - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); it != tags->end(); ++it) + for (Tag_List::const_iterator it = tags->begin(); it != tags->end(); ++it) { if (it->first == key && condition.matches(it->second)) return straight; @@ -37,21 +37,21 @@ bool Tag_Filter::matches(const std::vector< std::pair< std::string, std::string } -std::string link_if_any(const std::vector< std::pair< std::string, std::string > >& tags) +std::string link_if_any(const Tag_List& tags) { std::string link; - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) + for (Tag_List::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("www.") != std::string::npos) link = "http://" + it->second; } - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) + for (Tag_List::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("http://") != std::string::npos) link = it->second; } - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) + for (Tag_List::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("https://") != std::string::npos) link = it->second; @@ -62,11 +62,11 @@ std::string link_if_any(const std::vector< std::pair< std::string, std::string > std::string title_if_any(const std::string& link, const std::string& title_key, - const std::vector< std::pair< std::string, std::string > >& tags) + const Tag_List& tags) { std::string title; - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) + for (Tag_List::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->first == title_key) { @@ -105,7 +105,7 @@ template< > std::string elem_type< Relation_Skeleton >() { return "Relation"; } template< typename TSkel > std::string print(const std::string& title_key, - const TSkel& skel, const std::vector< std::pair< std::string, std::string > >* tags) + const TSkel& skel, const Tag_List* tags) { std::string link = tags ? link_if_any(*tags) : ""; std::string result = "\n

" + (tags ? title_if_any(link, title_key, *tags) : ""); @@ -124,7 +124,7 @@ std::string print(const std::string& title_key, if (tags) { - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); + for (Tag_List::const_iterator it = tags->begin(); it != tags->end(); ++it) result += it->first + ": " + it->second + "
\n"; } @@ -133,7 +133,7 @@ std::string print(const std::string& title_key, bool Category_Filter::consider(const Node_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags) + const Tag_List* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) @@ -156,7 +156,7 @@ bool Category_Filter::consider(const Node_Skeleton& skel, bool Category_Filter::consider(const Way_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags) + const Tag_List* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) @@ -179,7 +179,7 @@ bool Category_Filter::consider(const Way_Skeleton& skel, bool Category_Filter::consider(const Relation_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags) + const Tag_List* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) @@ -247,14 +247,14 @@ void Output_Popup::write_footer() void Output_Popup::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) @@ -267,14 +267,14 @@ void Output_Popup::print_item(const Node_Skeleton& skel, void Output_Popup::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) @@ -287,7 +287,7 @@ void Output_Popup::print_item(const Way_Skeleton& skel, void Output_Popup::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -295,7 +295,7 @@ void Output_Popup::print_item(const Relation_Skeleton& skel, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) @@ -308,7 +308,7 @@ void Output_Popup::print_item(const Relation_Skeleton& skel, void Output_Popup::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action) { diff --git a/src/overpass_api/output_formats/output_popup.h b/src/overpass_api/output_formats/output_popup.h index 412ca3353..a402194f4 100644 --- a/src/overpass_api/output_formats/output_popup.h +++ b/src/overpass_api/output_formats/output_popup.h @@ -35,7 +35,7 @@ class Tag_Filter Tag_Filter(const std::string& key_, const std::string& value_, bool straight_) : key(key_), straight(straight_), condition(value_, true) {} - bool matches(const std::vector< std::pair< std::string, std::string > >* tags) const; + bool matches(const Tag_List* tags) const; private: std::string key; @@ -62,9 +62,9 @@ struct Category_Filter void set_title_key(const std::string& title_key); void add_filter(const std::vector< Tag_Filter* >& conjunction) { filter_disjunction.push_back(conjunction); } - bool consider(const Node_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags); - bool consider(const Way_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags); - bool consider(const Relation_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags); + bool consider(const Node_Skeleton& skel, const Tag_List* tags); + bool consider(const Way_Skeleton& skel, const Tag_List* tags); + bool consider(const Relation_Skeleton& skel, const Tag_List* tags); std::string result() const { return output; } @@ -100,31 +100,31 @@ class Output_Popup : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0); virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0); virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -132,12 +132,12 @@ class Output_Popup : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0); virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep); diff --git a/src/overpass_api/output_formats/output_xml.cc b/src/overpass_api/output_formats/output_xml.cc index 6b8784ccc..464a17429 100644 --- a/src/overpass_api/output_formats/output_xml.cc +++ b/src/overpass_api/output_formats/output_xml.cc @@ -20,6 +20,7 @@ #include "../core/settings.h" #include "../frontend/basic_formats.h" #include "output_xml.h" +#include "fixed7.h" bool Output_XML::write_http_headers() @@ -65,10 +66,10 @@ void Output_XML::display_error(const std::string& text) void Output_XML::print_global_bbox(const Bbox_Double& bbox) { std::cout<<" \n\n"; } @@ -81,7 +82,7 @@ void print_meta_xml(const OSM_Element_Metadata_Skeleton< Id_Type >& meta, <<"\" changeset=\""<::const_iterator it = users.find(meta.user_id); if (it != users.end()) - std::cout<<" user=\""<second)<<"\""; + std::cout<<" user=\""<second)<<"\""; } @@ -140,7 +141,7 @@ void append_action(const Output_Handler::Feature_Action& action, bool is_new = f } -void print_tags(const std::vector< std::pair< std::string, std::string > >* tags, +void print_tags(const Tag_List* tags, Output_Mode mode, bool& inner_tags_printed) { if ((mode.mode & Output_Mode::TAGS) && tags && !tags->empty()) @@ -150,9 +151,9 @@ void print_tags(const std::vector< std::pair< std::string, std::string > >* tags std::cout<<">\n"; inner_tags_printed = true; } - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); + for (Tag_List::const_iterator it = tags->begin(); it != tags->end(); ++it) - std::cout<<" first)<<"\" v=\""<second)<<"\"/>\n"; + std::cout<<" first)<<"\" v=\""<second)<<"\"/>\n"; } } @@ -167,10 +168,10 @@ void print_bounds(const Opaque_Geometry& geometry, Output_Mode mode, bool& inner inner_tags_printed = true; } std::cout<<" \n"; } else if ((mode.mode & Output_Mode::CENTER) && geometry.has_center()) @@ -181,8 +182,8 @@ void print_bounds(const Opaque_Geometry& geometry, Output_Mode mode, bool& inner inner_tags_printed = true; } std::cout<<" \n"; } } @@ -219,8 +220,8 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode, bool& inn const std::vector< Point_Double >* line = geometry.get_line_geometry(); for (std::vector< Point_Double >::const_iterator it = line->begin(); it != line->end(); ++it) std::cout<lat<<"\"" - " lon=\""<lon<<"\"" + " lat=\""<lat)<<"\"" + " lon=\""<lon)<<"\"" "/>\n"; } else if ((mode.mode & Output_Mode::GEOMETRY) && geometry.has_multiline_geometry()) @@ -237,8 +238,8 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode, bool& inn std::cout<\n"; for (std::vector< Point_Double >::const_iterator it = iti->begin(); it != iti->end(); ++it) std::cout<lat<<"\"" - " lon=\""<lon<<"\"" + " lat=\""<lat)<<"\"" + " lon=\""<lon)<<"\"" "/>\n"; std::cout<\n"; } @@ -251,8 +252,8 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode, bool& inn inner_tags_printed = true; } std::cout<\n"; } else if ((mode.mode & Output_Mode::BOUNDS) && geometry.has_bbox()) @@ -263,10 +264,10 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode, bool& inn inner_tags_printed = true; } std::cout<<" \n"; } else if ((mode.mode & Output_Mode::CENTER) && geometry.has_center()) @@ -277,8 +278,8 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode, bool& inn inner_tags_printed = true; } std::cout<\n"; } } @@ -298,8 +299,8 @@ void print_members(const Way_Skeleton& skel, const Opaque_Geometry& geometry, { std::cout<<" \n"; } } @@ -322,13 +323,13 @@ void print_members(const Relation_Skeleton& skel, const Opaque_Geometry& geometr std::map< uint32, std::string >::const_iterator it = roles.find(skel.members[i].role); std::cout<<" second : "???")<<"\""; + <<"\" role=\""<second : "???")<<"\""; if (skel.members[i].type == Relation_Entry::NODE) { if (geometry.has_faithful_relation_geometry() && geometry.relation_pos_is_valid(i)) - std::cout<<" lat=\""<\n"; } else if (skel.members[i].type == Relation_Entry::WAY) @@ -349,8 +350,8 @@ void print_members(const Relation_Skeleton& skel, const Opaque_Geometry& geometr for (uint j = 0; j < geometry.relation_way_size(i); ++j) { if (geometry.relation_pos_is_valid(i, j)) - std::cout<<" \n"; + std::cout<<" \n"; else std::cout<<" \n"; } @@ -367,7 +368,7 @@ void print_members(const Relation_Skeleton& skel, const Opaque_Geometry& geometr void print_node(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode) @@ -377,8 +378,8 @@ void print_node(const Node_Skeleton& skel, std::cout<<" id=\""< >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode) @@ -417,7 +418,7 @@ void print_way(const Way_Skeleton& skel, void print_relation(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -463,14 +464,14 @@ void print_deleted(const std::string& type_name, const Id_Type& id, void Output_XML::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { prepend_action(action); @@ -493,14 +494,14 @@ void Output_XML::print_item(const Node_Skeleton& skel, void Output_XML::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { prepend_action(action); @@ -523,7 +524,7 @@ void Output_XML::print_item(const Way_Skeleton& skel, void Output_XML::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -531,7 +532,7 @@ void Output_XML::print_item(const Relation_Skeleton& skel, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { prepend_action(action); @@ -554,7 +555,7 @@ void Output_XML::print_item(const Relation_Skeleton& skel, void Output_XML::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action) { diff --git a/src/overpass_api/output_formats/output_xml.h b/src/overpass_api/output_formats/output_xml.h index cf5eb4f6d..2173d0256 100644 --- a/src/overpass_api/output_formats/output_xml.h +++ b/src/overpass_api/output_formats/output_xml.h @@ -54,31 +54,31 @@ class Output_XML : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0); virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0); virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -86,12 +86,12 @@ class Output_XML : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0); virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep); }; diff --git a/src/overpass_api/statements/area_query.cc b/src/overpass_api/statements/area_query.cc index 3e62b8799..a1897604f 100644 --- a/src/overpass_api/statements/area_query.cc +++ b/src/overpass_api/statements/area_query.cc @@ -31,6 +31,7 @@ #include "../core/index_computations.h" #include "../data/collect_members.h" #include "../data/tilewise_geometry.h" +#include #include "area_query.h" #include "coord_query.h" #include "make_area.h" @@ -189,12 +190,17 @@ std::map< Uint31_Index, std::vector< Way_Skeleton > > ways_contained_in( Tilewise_Const_Area_Iterator tai(potential_areas->ways, potential_areas->attic_ways, stmt, rman); std::map< Uint31_Index, std::vector< Way_Skeleton > > result; + if (tai.is_end()) + return result; + Tilewise_Way_Iterator twi(ways, std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > >(), stmt, rman); while (!twi.is_end()) { while (!tai.is_end() && tai.get_idx() < twi.get_idx()) tai.next(); - if (tai.is_end() || twi.get_idx() < tai.get_idx()) + if (tai.is_end()) + break; + if (twi.get_idx() < tai.get_idx()) { twi.next(); continue; @@ -229,12 +235,17 @@ std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > > ways_contained_in Tilewise_Const_Area_Iterator tai(potential_areas->ways, potential_areas->attic_ways, stmt, rman); std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > > result; + if (tai.is_end()) + return result; + Tilewise_Way_Iterator twi(std::map< Uint31_Index, std::vector< Way_Skeleton > >(), ways, stmt, rman); while (!twi.is_end()) { while (!tai.is_end() && tai.get_idx() < twi.get_idx()) tai.next(); - if (tai.is_end() || twi.get_idx() < tai.get_idx()) + if (tai.is_end()) + break; + if (twi.get_idx() < tai.get_idx()) { twi.next(); continue; @@ -592,6 +603,15 @@ void Area_Query_Statement::collect_nodes areas[area_it.object().id].push_back(area_it.object()); ++area_it; } + // The same blocks decoded once for this tile, for the point-in-area tests below. + std::map< Area_Skeleton::Id_Type, std::vector< Coord_Query_Statement::Decoded_Area_Block > > decoded; + for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); + it != areas.end(); ++it) + { + std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded[it->first]; + for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) + blocks.push_back(Coord_Query_Statement::Decoded_Area_Block(current_idx, *it2)); + } while (nodes_it != nodes.end() && nodes_it->first.val() < current_idx) { @@ -613,12 +633,13 @@ void Area_Query_Statement::collect_nodes it != areas.end(); ++it) { int inside = 0; - for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); - ++it2) + const std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded[it->first]; + for (std::vector< Coord_Query_Statement::Decoded_Area_Block >::const_iterator it2 = blocks.begin(); + it2 != blocks.end(); ++it2) { ++loop_count; - int check(Coord_Query_Statement::check_area_block(current_idx, *it2, ilat, ilon)); + int check(Coord_Query_Statement::check_area_block(*it2, ilat, ilon)); if (check == Coord_Query_Statement::HIT && add_border) { inside = 1; @@ -748,18 +769,31 @@ inline int longitude_a_intersects_inner } -int intersects_inner(const Area_Block& string_a, const Area_Block& string_b) +void decode_coords(const Area_Block& block, Decoded_Coords& coords) +{ + coords.clear(); + coords.reserve(block.coors.size()); + for (std::vector< uint64 >::const_iterator it = block.coors.begin(); it != block.coors.end(); ++it) + coords.push_back(std::make_pair(::ilat(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)), + ::ilon(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)))); +} + + +Coords_Bounds::Coords_Bounds(const Decoded_Coords& coords) + : min_lat(0xffffffffu), max_lat(0), min_lon(0xffffffffu), max_lon(0) { - std::vector< std::pair< uint32, uint32 > > coords_a; - for (std::vector< uint64 >::const_iterator it = string_a.coors.begin(); it != string_a.coors.end(); ++it) - coords_a.push_back(std::make_pair(::ilat(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)), - ::ilon(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)))); + for (Decoded_Coords::const_iterator it = coords.begin(); it != coords.end(); ++it) + { + min_lat = std::min(min_lat, it->first); + max_lat = std::max(max_lat, it->first); + min_lon = std::min(min_lon, it->second); + max_lon = std::max(max_lon, it->second); + } +} - std::vector< std::pair< uint32, uint32 > > coords_b; - for (std::vector< uint64 >::const_iterator it = string_b.coors.begin(); it != string_b.coors.end(); ++it) - coords_b.push_back(std::make_pair(::ilat(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)), - ::ilon(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)))); +int intersects_inner(const Decoded_Coords& coords_a, const Decoded_Coords& coords_b) +{ for (std::vector< std::pair< uint32, uint32 > >::size_type i = 0; i < coords_a.size()-1; ++i) { if (coords_a[i].second < coords_a[i+1].second) @@ -799,12 +833,9 @@ int intersects_inner(const Area_Block& string_a, const Area_Block& string_b) } -void has_inner_points(const Area_Block& string_a, const Area_Block& string_b, int& inside) +void has_inner_points(const Decoded_Coords& coords_a, const Coord_Query_Statement::Decoded_Area_Block& string_b, + int& inside) { - std::vector< std::pair< uint32, uint32 > > coords_a; - for (std::vector< uint64 >::const_iterator it = string_a.coors.begin(); it != string_a.coors.end(); ++it) - coords_a.push_back(std::make_pair(::ilat(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)), - ::ilon(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)))); // Check additionally the middle of the segment to also get segments // that run through the area @@ -812,7 +843,7 @@ void has_inner_points(const Area_Block& string_a, const Area_Block& string_b, in { uint32 ilat = (coords_a[i].first + coords_a[i+1].first)/2; uint32 ilon = (coords_a[i].second + coords_a[i+1].second)/2 + 0x80000000u; - int check = Coord_Query_Statement::check_area_block(0, string_b, ilat, ilon); + int check = Coord_Query_Statement::check_area_block(string_b, ilat, ilon); if (check & Coord_Query_Statement::HIT) inside = check; else if (check) @@ -835,19 +866,15 @@ void Area_Query_Statement::collect_ways std::map< Way::Id_Type, bool > ways_inside; + // Build each way's geometry once, for both its segments and its coordinates. std::map< Uint31_Index, std::vector< Area_Block > > way_segments; - for (typename std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = ways.begin(); it != ways.end(); ++it) - { - for (typename std::vector< Way_Skeleton >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - add_way_to_area_blocks(way_geometries.get_geometry(*it2), it2->id.val(), way_segments); - } - std::map< uint32, std::vector< std::pair< uint32, Way::Id_Type > > > way_coords_to_id; for (typename std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = ways.begin(); it != ways.end(); ++it) { for (typename std::vector< Way_Skeleton >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { std::vector< Quad_Coord > coords = way_geometries.get_geometry(*it2); + add_way_to_area_blocks(coords, it2->id.val(), way_segments); for (std::vector< Quad_Coord >::const_iterator it3 = coords.begin(); it3 != coords.end(); ++it3) way_coords_to_id[it3->ll_upper].push_back(std::make_pair(it3->ll_lower, it2->id)); } @@ -875,6 +902,15 @@ void Area_Query_Statement::collect_ways areas[area_it.object().id].push_back(area_it.object()); ++area_it; } + // The same blocks decoded once for this tile, for the point-in-area tests below. + std::map< Area_Skeleton::Id_Type, std::vector< Coord_Query_Statement::Decoded_Area_Block > > decoded; + for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); + it != areas.end(); ++it) + { + std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded[it->first]; + for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) + blocks.push_back(Coord_Query_Statement::Decoded_Area_Block(current_idx, *it2)); + } // check nodes while (nodes_it != way_coords_to_id.end() && nodes_it->first < current_idx) @@ -892,12 +928,13 @@ void Area_Query_Statement::collect_ways it != areas.end(); ++it) { int inside = 0; - for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); - ++it2) + const std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded[it->first]; + for (std::vector< Coord_Query_Statement::Decoded_Area_Block >::const_iterator it2 = blocks.begin(); + it2 != blocks.end(); ++it2) { ++loop_count; - int check(Coord_Query_Statement::check_area_block(current_idx, *it2, ilat, ilon)); + int check(Coord_Query_Statement::check_area_block(*it2, ilat, ilon)); if (check == Coord_Query_Statement::HIT) { inside = Coord_Query_Statement::HIT; @@ -913,10 +950,31 @@ void Area_Query_Statement::collect_ways ++nodes_it; } + // has_inner_points tests segment midpoints against the blocks decoded with ll_index 0. + std::map< Area_Skeleton::Id_Type, std::vector< Coord_Query_Statement::Decoded_Area_Block > > decoded_zero; + std::map< Area_Skeleton::Id_Type, std::vector< Decoded_Coords > > area_coords; + std::map< Area_Skeleton::Id_Type, std::vector< Coords_Bounds > > area_bounds; + for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); + it != areas.end(); ++it) + { + std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded_zero[it->first]; + std::vector< Decoded_Coords >& coords = area_coords[it->first]; + for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) + { + blocks.push_back(Coord_Query_Statement::Decoded_Area_Block(0, *it2)); + coords.push_back(Decoded_Coords()); + decode_coords(*it2, coords.back()); + area_bounds[it->first].push_back(Coords_Bounds(coords.back())); + } + } + // check segments + Decoded_Coords sit_coords; for (std::vector< Area_Block >::const_iterator sit = way_segments[Uint31_Index(current_idx)].begin(); sit != way_segments[Uint31_Index(current_idx)].end(); ++sit) { + decode_coords(*sit, sit_coords); + Coords_Bounds sit_bounds(sit_coords); std::map< Area::Id_Type, int > area_status; for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); it != areas.end(); ++it) @@ -931,7 +989,8 @@ void Area_Query_Statement::collect_ways // The endpoints are properly handled via the point-in-area test // Check additionally the middle of the segment to also get segments // that run through the area - int intersect = intersects_inner(*sit, *it2); + int intersect = sit_bounds.overlaps(area_bounds[it->first][it2 - it->second.begin()]) + ? intersects_inner(sit_coords, area_coords[it->first][it2 - it->second.begin()]) : 0; if (intersect == Coord_Query_Statement::INTERSECT) { ways_inside[Way::Id_Type(sit->id)] = true; @@ -945,7 +1004,7 @@ void Area_Query_Statement::collect_ways area_status[it2->id] = Coord_Query_Statement::HIT; break; } - has_inner_points(*sit, *it2, area_status[it2->id]); + has_inner_points(sit_coords, decoded_zero[it->first][it2 - it->second.begin()], area_status[it2->id]); } } for (std::map< Area::Id_Type, int >::const_iterator it = area_status.begin(); it != area_status.end(); ++it) diff --git a/src/overpass_api/statements/area_query.h b/src/overpass_api/statements/area_query.h index f47a3f047..5a62abb50 100644 --- a/src/overpass_api/statements/area_query.h +++ b/src/overpass_api/statements/area_query.h @@ -22,6 +22,7 @@ #include "../data/collect_members.h" #include "../data/utils.h" #include "../data/way_geometry_store.h" +#include "coord_query.h" #include "statement.h" #include @@ -120,8 +121,35 @@ class Area_Query_Statement : public Output_Statement }; -int intersects_inner(const Area_Block& string_a, const Area_Block& string_b); +// The coordinates of an Area_Block as (ilat, ilon) pairs, decoded once so that the tests +// below can run against many other blocks without decoding again. +typedef std::vector< std::pair< uint32, uint32 > > Decoded_Coords; +void decode_coords(const Area_Block& block, Decoded_Coords& coords); +int intersects_inner(const Decoded_Coords& coords_a, const Decoded_Coords& coords_b); -void has_inner_points(const Area_Block& string_a, const Area_Block& string_b, int& inside); +// The bounding box of decoded coordinates, to skip intersects_inner for pairs of chains +// that can't intersect or touch. +struct Coords_Bounds +{ + uint32 min_lat, max_lat, min_lon, max_lon; + explicit Coords_Bounds(const Decoded_Coords& coords); + + // False only if intersects_inner(this chain, rhs chain) must return 0. + // + // The latitude test deliberately allows a gap of up to 1 unit. Don't simplify it to a + // plain box overlap: for parallel segments, ordered_intersects_inner returns HIT when an + // endpoint lies within 1 unit of latitude of the other segment's line. Two east-west + // segments 1 unit apart touch by that rule, though their boxes don't overlap. + // Longitude needs no slack: ordered_a_intersects_inner and longitude_a_intersects_inner + // require overlapping longitude ranges before they test anything. + bool overlaps(const Coords_Bounds& rhs) const + { + return !((max_lat < rhs.min_lat && rhs.min_lat - max_lat > 1) + || (rhs.max_lat < min_lat && min_lat - rhs.max_lat > 1) + || max_lon < rhs.min_lon || rhs.max_lon < min_lon); + } +}; +void has_inner_points(const Decoded_Coords& coords_a, const Coord_Query_Statement::Decoded_Area_Block& string_b, + int& inside); #endif diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 43951f537..2f5d3aeab 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -35,13 +35,20 @@ template < class TIndex, class TObject > Ranges< TIndex > ranges(const std::map< TIndex, std::vector< TObject > >& elems) { + // Indexes whose vector is empty hold no objects and contribute no geometry. Filters + // often leave such entries behind, e.g. for attic data at other dates, and for + // relations they can be coarse indexes covering large areas, so skip them. Ranges< TIndex > result; - if (elems.empty()) + typename std::map< TIndex, std::vector< TObject > >::const_iterator it = elems.begin(); + while (it != elems.end() && it->second.empty()) + ++it; + if (it == elems.end()) return result; - std::pair< TIndex, TIndex > range = std::make_pair(elems.begin()->first, inc(elems.begin()->first)); - for (typename std::map< TIndex, std::vector< TObject > >::const_iterator - it = elems.begin(); it != elems.end(); ++it) + std::pair< TIndex, TIndex > range = std::make_pair(it->first, inc(it->first)); + for (; it != elems.end(); ++it) { + if (it->second.empty()) + continue; if (!(range.second < it->first)) range.second = inc(it->first); else @@ -52,7 +59,7 @@ Ranges< TIndex > ranges(const std::map< TIndex, std::vector< TObject > >& elems) } result.push_back(range.first, range.second); result.sort(); - + return result; } @@ -127,8 +134,7 @@ class Around_Constraint : public Query_Constraint public: Around_Constraint(Around_Statement& around_) : around(&around_), ranges_used(false) {} - Query_Filter_Strategy delivers_data(Resource_Manager& rman) - { return (around->get_radius() < 2000) ? prefer_ranges : ids_useful; } + Query_Filter_Strategy delivers_data(Resource_Manager& rman); bool get_ranges(Resource_Manager& rman, Ranges< Uint32_Index >& ranges); bool get_ranges(Resource_Manager& rman, Ranges< Uint31_Index >& ranges); @@ -143,6 +149,29 @@ class Around_Constraint : public Query_Constraint }; +/* Reading every object in the ranges and checking tags afterwards (prefer_ranges) only pays + off while the ranges are small. A small radius around a large input set, such as long + relations, can still cover a large area, so look at the area as well as the radius. Like + Bbox_Constraint, let the tag index select candidates (ids_useful) once the area exceeds + about one square degree: 65536 node index tiles of about 0.00275 by 0.0055 degrees. */ +Query_Filter_Strategy Around_Constraint::delivers_data(Resource_Manager& rman) +{ + if (around->get_radius() >= 2000) + return ids_useful; + + const Set* input = rman.get_set(around->get_source_name()); + Ranges< Uint32_Index > ranges = around->calc_ranges(input ? *input : Set(), rman); + uint64 tiles = 0; + for (auto it = ranges.begin(); it != ranges.end(); ++it) + { + tiles += uint64(it.upper_bound().val()) - it.lower_bound().val(); + if (tiles > 65536) + return ids_useful; + } + return prefer_ranges; +} + + bool Around_Constraint::get_ranges (Resource_Manager& rman, Ranges< Uint32_Index >& ranges) { @@ -224,8 +253,35 @@ void Around_Constraint::filter(Resource_Manager& rman, Set& into) } +/* Checks the query's time and memory limits after every 64k units of work, so that an + expensive around filter stops when the query runs out of time instead of running + to completion. A unit is about one comparison of a candidate's point or segment with + a point or segment of the input. Counting candidates alone isn't enough: a single long + way tested against a large input can take seconds. health_check throws when a limit + is exceeded. */ +class Periodic_Health_Check +{ +public: + Periodic_Health_Check(Resource_Manager& rman_, const Statement& stmt_) : rman(rman_), stmt(stmt_) {} + void tick(uint64 work = 1) + { + work_done += work; + if (work_done >= 64*1024) + { + work_done = 0; + rman.health_check(stmt); + } + } + +private: + Resource_Manager& rman; + const Statement& stmt; + uint64 work_done = 0; +}; + + template< typename Node_Skeleton > -void filter_nodes_expensive(const Around_Statement& around, +void filter_nodes_expensive(const Around_Statement& around, Periodic_Health_Check& check, std::map< Uint32_Index, std::vector< Node_Skeleton > >& nodes) { for (typename std::map< Uint32_Index, std::vector< Node_Skeleton > >::iterator it = nodes.begin(); @@ -235,6 +291,7 @@ void filter_nodes_expensive(const Around_Statement& around, for (typename std::vector< Node_Skeleton >::const_iterator iit = it->second.begin(); iit != it->second.end(); ++iit) { + check.tick(around.comparisons_per_test()); double lat(::lat(it->first.val(), iit->ll_lower)); double lon(::lon(it->first.val(), iit->ll_lower)); if (around.is_inside(lat, lon)) @@ -246,7 +303,7 @@ void filter_nodes_expensive(const Around_Statement& around, template< typename Way_Skeleton > -void filter_ways_expensive(const Around_Statement& around, +void filter_ways_expensive(const Around_Statement& around, Periodic_Health_Check& check, const Way_Geometry_Store& way_geometries, std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways) { @@ -257,7 +314,8 @@ void filter_ways_expensive(const Around_Statement& around, for (typename std::vector< Way_Skeleton >::const_iterator iit = it->second.begin(); iit != it->second.end(); ++iit) { - if (around.is_inside(way_geometries.get_geometry(*iit))) + check.tick(around.comparisons_per_test()); + if (around.is_inside(way_geometries.get_geometry(*iit), &check)) local_into.push_back(*iit); } it->second.swap(local_into); @@ -266,7 +324,7 @@ void filter_ways_expensive(const Around_Statement& around, template< typename Relation_Skeleton > -void filter_relations_expensive(const Around_Statement& around, +void filter_relations_expensive(const Around_Statement& around, Periodic_Health_Check& check, const std::vector< std::pair< Uint32_Index, const Node_Skeleton* > > node_members_by_id, const std::vector< std::pair< Uint31_Index, const Way_Skeleton* > > way_members_by_id, const Way_Geometry_Store& way_geometries, @@ -282,6 +340,7 @@ void filter_relations_expensive(const Around_Statement& around, for (std::vector< Relation_Entry >::const_iterator nit = iit->members.begin(); nit != iit->members.end(); ++nit) { + check.tick(around.comparisons_per_test()); if (nit->type == Relation_Entry::NODE) { const std::pair< Uint32_Index, const Node_Skeleton* >* second_nd = @@ -303,7 +362,7 @@ void filter_relations_expensive(const Around_Statement& around, binary_search_for_pair_id(way_members_by_id, nit->ref32()); if (!second_nd) continue; - if (around.is_inside(way_geometries.get_geometry(*second_nd->second))) + if (around.is_inside(way_geometries.get_geometry(*second_nd->second), &check)) { local_into.push_back(*iit); break; @@ -318,12 +377,28 @@ void filter_relations_expensive(const Around_Statement& around, void Around_Constraint::filter(const Statement& query, Resource_Manager& rman, Set& into) { + Periodic_Health_Check check(rman, query); const Set* input = rman.get_set(around->get_source_name()); const Set empty; around->calc_lat_lons(input ? *input : empty, *around, rman); - filter_nodes_expensive(*around, into.nodes); - filter_ways_expensive(*around, Way_Geometry_Store(into.ways, query, rman), into.ways); + filter_nodes_expensive(*around, check, into.nodes); + + // Only the ways whose index area isn't within the radius need their geometry + std::map< Uint31_Index, std::vector< Way_Skeleton > > ways_inside; + for (auto it = into.ways.begin(); it != into.ways.end(); ) + { + if (around->contains_index_area(it->first)) + { + ways_inside[it->first].swap(it->second); + it = into.ways.erase(it); + } + else + ++it; + } + filter_ways_expensive(*around, check, Way_Geometry_Store(into.ways, query, rman), into.ways); + for (auto it = ways_inside.begin(); it != ways_inside.end(); ++it) + into.ways[it->first].swap(it->second); Request_Context context(&query, rman); { @@ -348,15 +423,15 @@ void Around_Constraint::filter(const Statement& query, Resource_Manager& rman, S = order_by_id(way_members_.current, Order_By_Way_Id()); // Retrieve all nodes referred by the ways. - filter_relations_expensive(*around, node_members_by_id, way_members_by_id, + filter_relations_expensive(*around, check, node_members_by_id, way_members_by_id, Way_Geometry_Store(way_members_.current, query, rman), into.relations); } if (!into.attic_nodes.empty()) - filter_nodes_expensive(*around, into.attic_nodes); + filter_nodes_expensive(*around, check, into.attic_nodes); if (!into.attic_ways.empty()) - filter_ways_expensive(*around, Way_Geometry_Store(into.attic_ways, query, rman), into.attic_ways); + filter_ways_expensive(*around, check, Way_Geometry_Store(into.attic_ways, query, rman), into.attic_ways); if (!into.attic_relations.empty()) { @@ -378,7 +453,7 @@ void Around_Constraint::filter(const Statement& query, Resource_Manager& rman, S std::vector< std::pair< Uint31_Index, const Way_Skeleton* > > way_members_by_id = order_attic_by_id(way_members_, Order_By_Way_Id()); - filter_relations_expensive(*around, node_members_by_id, way_members_by_id, + filter_relations_expensive(*around, check, node_members_by_id, way_members_by_id, Way_Geometry_Store(way_members_, query, rman), into.attic_relations); } @@ -537,9 +612,9 @@ Around_Statement::~Around_Statement() } -std::vector< double > cartesian(double lat, double lon) +Vec3 cartesian(double lat, double lon) { - std::vector< double > result(3); + Vec3 result; result[0] = sin(lat/90.0*acos(0)); result[1] = cos(lat/90.0*acos(0))*sin(lon/90.0*acos(0)); @@ -549,7 +624,7 @@ std::vector< double > cartesian(double lat, double lon) } -void rescale(double a, std::vector< double >& v) +void rescale(double a, Vec3& v) { v[0] *= a; v[1] *= a; @@ -557,9 +632,9 @@ void rescale(double a, std::vector< double >& v) } -std::vector< double > sum(const std::vector< double >& v, const std::vector< double >& w) +Vec3 sum(const Vec3& v, const Vec3& w) { - std::vector< double > result(3); + Vec3 result; result[0] = v[0] + w[0]; result[1] = v[1] + w[1]; @@ -569,15 +644,15 @@ std::vector< double > sum(const std::vector< double >& v, const std::vector< dou } -double scalar_prod(const std::vector< double >& v, const std::vector< double >& w) +double scalar_prod(const Vec3& v, const Vec3& w) { return v[0]*w[0] + v[1]*w[1] + v[2]*w[2]; } -std::vector< double > cross_prod(const std::vector< double >& v, const std::vector< double >& w) +Vec3 cross_prod(const Vec3& v, const Vec3& w) { - std::vector< double > result(3); + Vec3 result; result[0] = v[1]*w[2] - v[2]*w[1]; result[1] = v[2]*w[0] - v[0]*w[2]; @@ -606,7 +681,7 @@ Prepared_Point::Prepared_Point } -double great_circle_line_dist(const Prepared_Segment& segment, const std::vector< double >& cartesian) +double great_circle_line_dist(const Prepared_Segment& segment, const Vec3& cartesian) { double scalar_prod_ = std::abs(scalar_prod(cartesian, segment.norm)) /sqrt(scalar_prod(segment.norm, segment.norm)); @@ -621,7 +696,7 @@ double great_circle_line_dist(const Prepared_Segment& segment, const std::vector double great_circle_line_dist(double llat1, double llon1, double llat2, double llon2, double plat, double plon) { - std::vector< double > norm = cross_prod(cartesian(llat1, llon1), cartesian(llat2, llon2)); + Vec3 norm = cross_prod(cartesian(llat1, llon1), cartesian(llat2, llon2)); double scalar_prod_ = std::abs(scalar_prod(cartesian(plat, plon), norm)) /sqrt(scalar_prod(norm, norm)); @@ -636,11 +711,11 @@ double great_circle_line_dist(double llat1, double llon1, double llat2, double l bool intersect(const Prepared_Segment& segment_a, const Prepared_Segment& segment_b) { - std::vector< double > intersection_pt = cross_prod(segment_a.norm, segment_b.norm); + Vec3 intersection_pt = cross_prod(segment_a.norm, segment_b.norm); rescale(1.0/sqrt(scalar_prod(intersection_pt, intersection_pt)), intersection_pt); - std::vector< double > asum = sum(segment_a.first_cartesian, segment_a.second_cartesian); - std::vector< double > bsum = sum(segment_b.first_cartesian, segment_b.second_cartesian); + Vec3 asum = sum(segment_a.first_cartesian, segment_a.second_cartesian); + Vec3 bsum = sum(segment_b.first_cartesian, segment_b.second_cartesian); return (std::abs(scalar_prod(asum, intersection_pt)) >= scalar_prod(asum, segment_a.first_cartesian) && std::abs(scalar_prod(bsum, intersection_pt)) >= scalar_prod(bsum, segment_b.first_cartesian)); @@ -650,18 +725,18 @@ bool intersect(const Prepared_Segment& segment_a, bool intersect(double alat1, double alon1, double alat2, double alon2, double blat1, double blon1, double blat2, double blon2) { - std::vector< double > a1 = cartesian(alat1, alon1); - std::vector< double > a2 = cartesian(alat2, alon2); - std::vector< double > norm_a = cross_prod(a1, a2); - std::vector< double > b1 = cartesian(blat1, blon1); - std::vector< double > b2 = cartesian(blat2, blon2); - std::vector< double > norm_b = cross_prod(b1, b2); - - std::vector< double > intersection_pt = cross_prod(norm_a, norm_b); + Vec3 a1 = cartesian(alat1, alon1); + Vec3 a2 = cartesian(alat2, alon2); + Vec3 norm_a = cross_prod(a1, a2); + Vec3 b1 = cartesian(blat1, blon1); + Vec3 b2 = cartesian(blat2, blon2); + Vec3 norm_b = cross_prod(b1, b2); + + Vec3 intersection_pt = cross_prod(norm_a, norm_b); rescale(1.0/sqrt(scalar_prod(intersection_pt, intersection_pt)), intersection_pt); - std::vector< double > asum = sum(a1, a2); - std::vector< double > bsum = sum(b1, b2); + Vec3 asum = sum(a1, a2); + Vec3 bsum = sum(b1, b2); return (std::abs(scalar_prod(asum, intersection_pt)) >= scalar_prod(asum, a1) && std::abs(scalar_prod(bsum, intersection_pt)) >= scalar_prod(bsum, b1)); @@ -676,24 +751,205 @@ Ranges< Uint32_Index > Around_Statement::calc_ranges(const Set& input, Resource_ else if (points.size() > 1) { std::vector< uint32 > nd_idxs; - std::map< Uint31_Index, std::vector< Way_Skeleton > > ways; - std::pair< Uint31_Index, std::vector< Way_Skeleton > > way; for (std::vector< Point_Double >::const_iterator it = points.begin(); it != points.end(); ++it) nd_idxs.push_back(::ll_upper_(it->lat, it->lon)); + // Build the polyline's range directly: ranges() skips entries without objects. Uint31_Index idx = Way::calc_index(nd_idxs); - way = std::make_pair(idx, std::vector< Way_Skeleton >()); - ways.insert(way); - return expand(calc_children(ranges(ways)), radius); + Ranges< Uint31_Index > way_ranges; + way_ranges.push_back(idx, inc(idx)); + return expand(calc_children(way_ranges), radius); } else + { + Ranges< Uint32_Index > relation_node_ranges; + Ranges< Uint31_Index > relation_way_ranges; + member_ranges(input, rman, relation_node_ranges, relation_way_ranges); return expand( - ranges(input.nodes).union_(ranges(input.attic_nodes)).union_( + ranges(input.nodes).union_(ranges(input.attic_nodes)).union_(relation_node_ranges).union_( calc_children( - ranges(input.ways).union_(ranges(input.attic_ways)).union_( - ranges(input.relations).union_(ranges(input.attic_relations))))), + ranges(input.ways).union_(ranges(input.attic_ways)).union_(relation_way_ranges))), radius); + } +} + + +void Around_Statement::member_ranges(const Set& input, Resource_Manager& rman, + Ranges< Uint32_Index >& node_ranges, Ranges< Uint31_Index >& way_ranges) const +{ + std::vector< Relation_Skeleton::Id_Type > relations; + for (auto it = input.relations.begin(); it != input.relations.end(); ++it) + for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) + relations.push_back(it2->id); + std::vector< std::pair< Relation_Skeleton::Id_Type, uint64 > > attic_relations; + for (auto it = input.attic_relations.begin(); it != input.attic_relations.end(); ++it) + for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) + attic_relations.push_back(std::make_pair(it2->id, it2->timestamp)); + + if (!member_ranges_known || member_ranges_timestamp != rman.get_desired_timestamp() + || member_ranges_relations != relations || member_ranges_attic_relations != attic_relations) + { + // The geometry of a relation is that of its direct node and way members (see + // calc_lat_lons), so take the ranges from their indexes. A relation's own index + // covers its whole extent, which for a long route or a boundary is a large area. + Ranges< Uint32_Index > new_node_ranges; + Ranges< Uint31_Index > new_way_ranges; + if (!input.relations.empty()) + { + Request_Context context(this, rman); + new_node_ranges = ranges(relation_node_members( + context, input.relations, {}, Ranges< Uint32_Index >::global(), {}, true).current); + new_way_ranges = ranges(relation_way_members( + context, input.relations, {}, Ranges< Uint31_Index >::global(), {}, true).current); + } + // The same for relations at a past date, with the members calc_lat_lons uses for them. + if (!input.attic_relations.empty()) + { + Request_Context context(this, rman); + new_node_ranges = new_node_ranges.union_(ranges(relation_node_members( + context, input.attic_relations, relation_node_member_indices({}, input.attic_relations)))); + new_way_ranges = new_way_ranges.union_(ranges(relation_way_members( + context, input.attic_relations, Ranges< Uint31_Index >::global()))); + } + member_node_ranges.swap(new_node_ranges); + member_way_ranges.swap(new_way_ranges); + member_ranges_relations.swap(relations); + member_ranges_attic_relations.swap(attic_relations); + member_ranges_timestamp = rman.get_desired_timestamp(); + member_ranges_known = true; + } + node_ranges = member_node_ranges; + way_ranges = member_way_ranges; +} + + +//----------------------------------------------------------------------------- + +/* Why reach boxes are enough. Let reach(X) be the bounding box of X's endpoints + widened by segment_reach(len(X), radius): the radius plus twice the most a + great-circle arc of that length can bulge out of its endpoints' bounding box, plus + one metre. A point has length 0. Every exact test only passes when the two objects' + reach boxes overlap: + + - Point P near segment S (is_inside(lat, lon)): the test requires + great_circle_line_dist(S, P) <= radius, and P within sqrt(len(S)^2 + radius^2) of + both endpoints of S. The second condition keeps P's foot on S's great circle + within sqrt(len(S)^2 + radius^2) - len(S) <= radius beyond either endpoint. So P + is within about 2 * radius of the arc S, hence within the arc's bounding box, + which lies within S's endpoint box widened by the bulge, widened by 2 * radius. + Overlap needs only one of the two boxes to be widened by that much; each is + widened by radius, so together they cover it. + - Segment C near point Q (is_inside(segment), first loop): the same test with the + roles swapped. + - Segments S and C intersect (intersect()): the crossing point lies on both arcs, + so within each arc's bounding box, which lies within its endpoint box widened by + the bulge. + + The widening uses a slightly larger distance than needed and the latitude closest + to the pole for the longitude scale, so the boxes are conservative. Boxes too + close to a pole, crossing the antimeridian or spanning many cells are never pruned. */ + +double Reach_Grid::segment_reach(double length, double radius, double lat1, double lat2) +{ + // A great-circle arc of length L deviates in latitude from its endpoints' bounding + // box by at most about L^2 * tan(latitude) / (8 * R). Beyond 50 km, or near a pole, + // keep the much wider bound of the arc's own length. + double poleward = std::max(std::abs(lat1), std::abs(lat2)); + if (length > 50000.0 || poleward >= 80.0) + return length + radius; + const double earth_radius = 10.0*1000*1000/acos(0); // as in great_circle_dist + double bulge = length * length * tan(poleward/90.0*acos(0)) / (8.0 * earth_radius); + return radius + 2.0 * bulge + 1.0; +} + + +Reach_Grid::Box Reach_Grid::reach_box(double lat1, double lon1, double lat2, double lon2, double reach) +{ + Box box; + // great_circle_dist uses 10,000 km per quarter meridian, so 1 degree of latitude is + // 1e7/90 m. A point within distance d is within d/(1e7/90) degrees of latitude. + double margin_deg = (reach * 1.02 + 1.0) / (10.0*1000*1000/90.0); + box.south = std::min(lat1, lat2) - margin_deg; + box.north = std::max(lat1, lat2) + margin_deg; + double poleward = std::max(std::abs(box.south), std::abs(box.north)); + double lon_margin_deg = poleward < 80.0 ? margin_deg / cos(poleward/90.0*acos(0)) : 360.0; + box.west = std::min(lon1, lon2) - lon_margin_deg; + box.east = std::max(lon1, lon2) + lon_margin_deg; + box.usable = poleward < 80.0 && margin_deg < 5.0 && std::abs(lon1 - lon2) < 180.0 + && box.west >= -180.0 && box.east <= 180.0; + return box; +} + + +bool Reach_Grid::cell_range(const Box& box, int64& lat0, int64& lat1, int64& lon0, int64& lon1) +{ + if (!box.usable) + return false; + lat0 = (int64)floor(box.south / cell_size); + lat1 = (int64)floor(box.north / cell_size); + lon0 = (int64)floor(box.west / cell_size); + lon1 = (int64)floor(box.east / cell_size); + return (lat1 - lat0 + 1) * (lon1 - lon0 + 1) <= max_cells; +} + + +void Reach_Grid::clear() +{ + cells.clear(); + always.clear(); + filed.clear(); + seen.clear(); + lookup = 0; + total = 0; +} + + +void Reach_Grid::add(const Box& box, uint32 id) +{ + ++total; + int64 lat0, lat1, lon0, lon1; + if (!cell_range(box, lat0, lat1, lon0, lon1)) + { + always.push_back(id); + return; + } + for (int64 i = lat0; i <= lat1; ++i) + { + for (int64 j = lon0; j <= lon1; ++j) + cells[key(i, j)].push_back(id); + } + filed.push_back(id); + if (seen.size() <= id) + seen.resize(id + 1, 0); +} + + +bool Reach_Grid::first_visit(uint32 id) const +{ + if (seen[id] == lookup) + return false; + seen[id] = lookup; + return true; +} + + +void Around_Statement::build_grids() +{ + point_grid.clear(); + for (uint32 i = 0; i < simple_lat_lons.size(); ++i) + { + const Prepared_Point& p = simple_lat_lons[i]; + point_grid.add(Reach_Grid::reach_box(p.lat, p.lon, p.lat, p.lon, radius), i); + } + segment_grid.clear(); + for (uint32 i = 0; i < simple_segments.size(); ++i) + { + const Prepared_Segment& s = simple_segments[i]; + double length = great_circle_dist(s.first_lat, s.first_lon, s.second_lat, s.second_lon); + segment_grid.add(Reach_Grid::reach_box(s.first_lat, s.first_lon, s.second_lat, s.second_lon, + Reach_Grid::segment_reach(length, radius, s.first_lat, s.second_lat)), i); + } } @@ -835,11 +1091,13 @@ void Around_Statement::calc_lat_lons(const Set& input, Statement& query, Resourc if (points.size() == 1) { add_coord(points[0].lat, points[0].lon, radius, radius_lat_lons, simple_lat_lons); + build_grids(); return; } else if (points.size() > 1) { add_way(points, radius, radius_lat_lons, simple_lat_lons, simple_segments); + build_grids(); return; } Request_Context context(&query, rman); @@ -869,11 +1127,62 @@ void Around_Statement::calc_lat_lons(const Set& input, Statement& query, Resourc = relation_way_members(context, input.attic_relations, Ranges< Uint31_Index >::global()); add_ways(way_members, Way_Geometry_Store(way_members, query, rman)); } + build_grids(); +} + + +// Whether the whole area of a way or relation index lies within the radius of one of the points. +// Every node of a way with that index is then inside, so the way matches without its geometry. +// Over a lat/lon box narrower than 180 degrees, the distance to a point is greatest at a corner: +// along a parallel or a meridian it grows towards the ends. +bool Around_Statement::contains_index_area(Uint31_Index idx) const +{ + if (radius <= 1. || !simple_segments.empty() || simple_lat_lons.empty() || simple_lat_lons.size() > 64) + return false; + + std::pair< Uint32_Index, Uint32_Index > bounds = calc_bbox_bounds(idx); + uint32 south_west = bounds.first.val(); + uint32 north_east = bounds.second.val() - 1; + double south = ::lat(south_west, 0u); + double north = ::lat(north_east, 0xffffffffu); + double west = ::lon(south_west, 0u); + double east = ::lon(north_east, 0xffffffffu); + if (east - west >= 180. || east < west) + return false; + + // A margin of 1 m against rounding. + double limit = radius - 1.; + for (std::vector< Prepared_Point >::const_iterator it = simple_lat_lons.begin(); it != simple_lat_lons.end(); ++it) + { + // is_inside only finds a point in the tiles add_coord registered it for: those of this bbox. + double point_south = it->lat - radius*(360.0/(40000.0*1000.0)); + double point_north = it->lat + radius*(360.0/(40000.0*1000.0)); + double scale_lat = it->lat > 0.0 ? point_north : point_south; + if (std::abs(scale_lat) >= 89.9) + continue; + double point_west = it->lon - radius*(360.0/(40000.0*1000.0))/cos(scale_lat/90.0*acos(0)); + double point_east = it->lon + radius*(360.0/(40000.0*1000.0))/cos(scale_lat/90.0*acos(0)); + if (point_west < -180. || point_east > 180. + || south < point_south || north > point_north || west < point_west || east > point_east) + continue; + + if (great_circle_dist(it->lat, it->lon, south, west) <= limit + && great_circle_dist(it->lat, it->lon, south, east) <= limit + && great_circle_dist(it->lat, it->lon, north, west) <= limit + && great_circle_dist(it->lat, it->lon, north, east) <= limit) + return true; + } + return false; } bool Around_Statement::is_inside(double lat, double lon) const { + // A great-circle distance is at least the difference in latitude, which great_circle_dist + // counts as 10,000 km per 90 degrees. Points farther apart than radius + 1 m in latitude + // can't match; the metre covers rounding in great_circle_dist. + const double max_lat_diff = (radius + 1.)*(90./(10.*1000.*1000.)); + std::map< Uint32_Index, std::vector< Point_Double > >::const_iterator mit = radius_lat_lons.find(::ll_upper_(lat, lon)); if (mit != radius_lat_lons.end()) @@ -881,16 +1190,18 @@ bool Around_Statement::is_inside(double lat, double lon) const for (std::vector< Point_Double >::const_iterator cit = mit->second.begin(); cit != mit->second.end(); ++cit) { + if (std::abs(cit->lat - lat) > max_lat_diff) + continue; if ((radius > 0 && great_circle_dist(cit->lat, cit->lon, lat, lon) <= radius) || (std::abs(cit->lat - lat) < 1e-7 && std::abs(cit->lon - lon) < 1e-7)) return true; } } - std::vector< double > coord_cartesian = cartesian(lat, lon); - for (std::vector< Prepared_Segment >::const_iterator - it = simple_segments.begin(); it != simple_segments.end(); ++it) + Vec3 coord_cartesian = cartesian(lat, lon); + return segment_grid.any(Reach_Grid::reach_box(lat, lon, lat, lon, radius), [&](uint32 id) { + const Prepared_Segment* it = &simple_segments[id]; if (great_circle_line_dist(*it, coord_cartesian) <= radius) { double gcdist = great_circle_dist @@ -900,41 +1211,38 @@ bool Around_Statement::is_inside(double lat, double lon) const great_circle_dist(lat, lon, it->second_lat, it->second_lon) <= limit) return true; } - } - - return false; + return false; + }); } bool Around_Statement::is_inside (double first_lat, double first_lon, double second_lat, double second_lon) const { Prepared_Segment segment(first_lat, first_lon, second_lat, second_lon); + double length = great_circle_dist(first_lat, first_lon, second_lat, second_lon); + Reach_Grid::Box box = Reach_Grid::reach_box(first_lat, first_lon, second_lat, second_lon, + Reach_Grid::segment_reach(length, radius, first_lat, second_lat)); - for (std::vector< Prepared_Point >::const_iterator cit = simple_lat_lons.begin(); - cit != simple_lat_lons.end(); ++cit) - { - if (great_circle_line_dist(segment, cit->cartesian) <= radius) - { - double gcdist = great_circle_dist(first_lat, first_lon, second_lat, second_lon); - double limit = sqrt(gcdist*gcdist + radius*radius); - if (great_circle_dist(cit->lat, cit->lon, first_lat, first_lon) <= limit && - great_circle_dist(cit->lat, cit->lon, second_lat, second_lon) <= limit) - return true; - } - } - - for (std::vector< Prepared_Segment >::const_iterator - cit = simple_segments.begin(); cit != simple_segments.end(); ++cit) - { - if (intersect(*cit, segment)) - return true; - } - - return false; + if (point_grid.any(box, [&](uint32 id) + { + const Prepared_Point* cit = &simple_lat_lons[id]; + if (great_circle_line_dist(segment, cit->cartesian) <= radius) + { + double gcdist = great_circle_dist(first_lat, first_lon, second_lat, second_lon); + double limit = sqrt(gcdist*gcdist + radius*radius); + if (great_circle_dist(cit->lat, cit->lon, first_lat, first_lon) <= limit && + great_circle_dist(cit->lat, cit->lon, second_lat, second_lon) <= limit) + return true; + } + return false; + })) + return true; + + return segment_grid.any(box, [&](uint32 id) { return intersect(simple_segments[id], segment); }); } -bool Around_Statement::is_inside(const std::vector< Quad_Coord >& way_geometry) const +bool Around_Statement::is_inside(const std::vector< Quad_Coord >& way_geometry, Periodic_Health_Check* check) const { std::vector< Quad_Coord >::const_iterator nit = way_geometry.begin(); if (nit == way_geometry.end()) @@ -946,6 +1254,8 @@ bool Around_Statement::is_inside(const std::vector< Quad_Coord >& way_geometry) double second_lat(::lat(it->ll_upper, it->ll_lower)); double second_lon(::lon(it->ll_upper, it->ll_lower)); + if (check) + check->tick(comparisons_per_test()); if (is_inside(second_lat, second_lon)) return true; } @@ -958,6 +1268,8 @@ bool Around_Statement::is_inside(const std::vector< Quad_Coord >& way_geometry) double second_lat(::lat(nit->ll_upper, nit->ll_lower)); double second_lon(::lon(nit->ll_upper, nit->ll_lower)); + if (check) + check->tick(comparisons_per_test()); if (is_inside(first_lat, first_lon, second_lat, second_lon)) return true; diff --git a/src/overpass_api/statements/around.h b/src/overpass_api/statements/around.h index d82f24b3c..fb411e804 100644 --- a/src/overpass_api/statements/around.h +++ b/src/overpass_api/statements/around.h @@ -19,9 +19,12 @@ #ifndef DE__OSM3S___OVERPASS_API__STATEMENTS__AROUND_H #define DE__OSM3S___OVERPASS_API__STATEMENTS__AROUND_H +#include #include #include #include +#include +#include #include #include "../data/collect_members.h" #include "../data/utils.h" @@ -29,15 +32,20 @@ #include "statement.h" +// A point or direction on the unit sphere, in Cartesian coordinates. A fixed-size +// array keeps the geometry tests free of heap allocations. +typedef std::array< double, 3 > Vec3; + + struct Prepared_Segment { double first_lat; double first_lon; double second_lat; double second_lon; - std::vector< double > first_cartesian; - std::vector< double > second_cartesian; - std::vector< double > norm; + Vec3 first_cartesian; + Vec3 second_cartesian; + Vec3 norm; Prepared_Segment(double first_lat, double first_lon, double second_lat, double second_lon); }; @@ -47,12 +55,111 @@ struct Prepared_Point { double lat; double lon; - std::vector< double > cartesian; + Vec3 cartesian; Prepared_Point(double lat, double lon); }; +/* A coarse lat/lon grid over the points and segments of an around statement's input + set. It only narrows down which entries the exact tests need to look at; it never + decides a match itself. + + Each entry is filed under every cell its "reach box" covers: its bounding box widened + by the radius plus a small margin for the bulge of a great-circle arc (see + segment_reach). A point or segment can only pass any of the exact + tests against an entry if their reach boxes overlap (see around.cc), so looking up the + cells of a candidate's reach box finds every entry that could match it. Entries whose + reach box is too large to file, or lies near a pole or the antimeridian, are kept in + a list that every lookup includes. */ +class Reach_Grid +{ +public: + struct Box + { + double south, west, north, east; + bool usable; // false: too large, polar or crossing the antimeridian + }; + + static Box reach_box(double lat1, double lon1, double lat2, double lon2, double reach); + + void clear(); + void add(const Box& box, uint32 id); + + // The reach to use for a segment of the given length: the radius plus a margin for + // how far a great-circle arc can bulge out of its endpoints' bounding box. + static double segment_reach(double length, double radius, double lat1, double lat2); + + // Calls f(id) once for every entry whose cells the box touches, plus the + // always-checked entries. Stops and returns true as soon as f returns true. + template< typename F > + bool any(const Box& box, F f) const; + +private: + static const int max_cells = 64; + static constexpr double cell_size = 0.01; + + static bool cell_range(const Box& box, int64& lat0, int64& lat1, int64& lon0, int64& lon1); + static int64 key(int64 lat_cell, int64 lon_cell) { return (lat_cell << 32) ^ (lon_cell & 0xffffffff); } + + std::unordered_map< int64, std::vector< uint32 > > cells; + std::vector< uint32 > always; + std::vector< uint32 > filed; // every id filed in cells, once each + uint32 total = 0; + + // An entry filed in several cells is passed to f only once per lookup: seen[id] holds + // the number of the last lookup that passed it. + mutable std::vector< uint32 > seen; + mutable uint32 lookup = 0; + bool first_visit(uint32 id) const; +}; + + +template< typename F > +bool Reach_Grid::any(const Box& box, F f) const +{ + for (uint32 id : always) + { + if (f(id)) + return true; + } + int64 lat0, lat1, lon0, lon1; + if (!cell_range(box, lat0, lat1, lon0, lon1)) + { + // The box is too large to look up cell by cell: check every filed entry once. + for (uint32 id : filed) + { + if (f(id)) + return true; + } + return false; + } + if (++lookup == 0) + { + std::fill(seen.begin(), seen.end(), 0); + lookup = 1; + } + for (int64 i = lat0; i <= lat1; ++i) + { + for (int64 j = lon0; j <= lon1; ++j) + { + auto it = cells.find(key(i, j)); + if (it == cells.end()) + continue; + for (uint32 id : it->second) + { + if (first_visit(id) && f(id)) + return true; + } + } + } + return false; +} + + +class Periodic_Health_Check; + + class Around_Statement : public Output_Statement { public: @@ -84,12 +191,35 @@ class Around_Statement : public Output_Statement Ranges< Uint32_Index > calc_ranges(const Set& input_nodes, Resource_Manager& rman) const; + private: + // The index ranges of the input relations' members, which calc_ranges needs. It runs + // several times per execution, so they are kept, together with what they depend on: + // the date, the ids of the current relations, and the ids and timestamps of the + // relations at a past date. + void member_ranges(const Set& input, Resource_Manager& rman, + Ranges< Uint32_Index >& node_ranges, Ranges< Uint31_Index >& way_ranges) const; + mutable bool member_ranges_known = false; + mutable uint64 member_ranges_timestamp = 0; + mutable std::vector< Relation_Skeleton::Id_Type > member_ranges_relations; + mutable std::vector< std::pair< Relation_Skeleton::Id_Type, uint64 > > member_ranges_attic_relations; + mutable Ranges< Uint32_Index > member_node_ranges; + mutable Ranges< Uint31_Index > member_way_ranges; + + public: + void calc_lat_lons(const Set& input_nodes, Statement& query, Resource_Manager& rman); bool is_inside(double lat, double lon) const; bool is_inside(double first_lat, double first_lon, double second_lat, double second_lon) const; - bool is_inside(const std::vector< Quad_Coord >& way_geometry) const; + // With check, ticks it for every point and segment of the way tested. + bool is_inside(const std::vector< Quad_Coord >& way_geometry, Periodic_Health_Check* check = 0) const; + // About how many comparisons testing one point or segment against the input takes. + // The grid (Reach_Grid) narrows a test to nearby entries, so the input's size + // overstates it; the cap keeps the time-limit check from running on every test. + uint64 comparisons_per_test() const + { return std::min< uint64 >(simple_lat_lons.size() + simple_segments.size() + 1, 1024); } + bool contains_index_area(Uint31_Index idx) const; double get_radius() const { return radius; } template< typename Node_Skeleton > @@ -140,6 +270,10 @@ class Around_Statement : public Output_Statement std::map< Uint32_Index, std::vector< Point_Double > > radius_lat_lons; std::vector< Prepared_Point > simple_lat_lons; std::vector< Prepared_Segment > simple_segments; + Reach_Grid point_grid; // ids are positions in simple_lat_lons + Reach_Grid segment_grid; // ids are positions in simple_segments + + void build_grids(); std::vector< Query_Constraint* > constraints; }; diff --git a/src/overpass_api/statements/bbox_query.cc b/src/overpass_api/statements/bbox_query.cc index 48e461de1..9de0d9ed6 100644 --- a/src/overpass_api/statements/bbox_query.cc +++ b/src/overpass_api/statements/bbox_query.cc @@ -224,6 +224,27 @@ const Ranges< Uint31_Index >& Bbox_Query_Statement::get_ranges_31() } +namespace +{ + // Moves the vectors of from into into, keeping indices left empty by filtering, as the + // unchunked path does (eval_map counts them). Chunks end at index boundaries, so an index is + // normally new to into; if not, its elements are appended. + template< typename Index, typename Object > + void move_into(std::map< Index, std::vector< Object > >& into, std::map< Index, std::vector< Object > >& from) + { + for (typename std::map< Index, std::vector< Object > >::iterator it = from.begin(); it != from.end(); ++it) + { + std::vector< Object >& target = into[it->first]; + if (target.empty()) + target.swap(it->second); + else + target.insert(target.end(), it->second.begin(), it->second.end()); + } + from.clear(); + } +} + + void Bbox_Query_Statement::execute(Resource_Manager& rman) { Set into; @@ -231,10 +252,33 @@ void Bbox_Query_Statement::execute(Resource_Manager& rman) Bbox_Constraint constraint(*this); Ranges< Uint32_Index > ranges; constraint.get_ranges(rman, ranges); - get_elements_from_db< Uint32_Index, Node_Skeleton >(ranges, *this, rman) - .swap(into.nodes, into.attic_nodes); - constraint.filter(rman, into); - filter_attic_elements(rman, rman.get_desired_timestamp(), into.nodes, into.attic_nodes); + if (rman.get_desired_timestamp() == NOW) + { + get_elements_from_db< Uint32_Index, Node_Skeleton >(ranges, *this, rman) + .swap(into.nodes, into.attic_nodes); + constraint.filter(rman, into); + filter_attic_elements(rman, rman.get_desired_timestamp(), into.nodes, into.attic_nodes); + } + else + { + // At a past date the candidates include every attic version in the box, far more than the + // result, so they are collected and filtered in chunks. + std::vector< Node_Skeleton::Id_Type > no_ids; + Collect_Items< Uint32_Index, Node_Skeleton > db_reader(no_ids, true, ranges, *this, rman); + Set chunk; + bool more = true; + while (more) + { + more = db_reader.get_chunk(chunk.nodes, chunk.attic_nodes); + constraint.filter(rman, chunk); + filter_attic_elements(rman, rman.get_desired_timestamp(), chunk.nodes, chunk.attic_nodes); + move_into(into.nodes, chunk.nodes); + move_into(into.attic_nodes, chunk.attic_nodes); + // into is not on the runtime stack, so count it here: a result over [maxsize:] then fails + // as soon as it is, not after the whole result is built. + rman.health_check(*this, 0, eval_map(into.nodes) + eval_map(into.attic_nodes)); + } + } transfer_output(rman, into); rman.health_check(*this); diff --git a/src/overpass_api/statements/changed.cc b/src/overpass_api/statements/changed.cc index 733294b66..7b73be65d 100644 --- a/src/overpass_api/statements/changed.cc +++ b/src/overpass_api/statements/changed.cc @@ -141,6 +141,17 @@ struct Trivial_Id_Predicate }; +template< typename Id_Type > +struct Known_Ids_Predicate +{ + Known_Ids_Predicate(const std::vector< Id_Type >& known_) : known(&known_) {} + bool operator()(Id_Type id) const { return std::binary_search(known->begin(), known->end(), id); } + +private: + const std::vector< Id_Type >* known; +}; + + template< typename Index, typename Skeleton > struct Ids_In_Set_Predicate { @@ -196,11 +207,29 @@ class Changed_Constraint : public Query_Constraint bool get_relation_ids (Resource_Manager& rman, std::vector< Relation_Skeleton::Id_Type >& ids); + // The changelog holds an entry per change, so a full id list can be far larger than the + // explicit ids other constraints allow. + bool narrows_by_known_ids() const { return true; } + bool get_node_ids_within(Resource_Manager& rman, + const std::vector< Node_Skeleton::Id_Type >& known, std::vector< Node_Skeleton::Id_Type >& ids); + bool get_way_ids_within(Resource_Manager& rman, + const std::vector< Way_Skeleton::Id_Type >& known, std::vector< Way_Skeleton::Id_Type >& ids); + bool get_relation_ids_within(Resource_Manager& rman, + const std::vector< Relation_Skeleton::Id_Type >& known, std::vector< Relation_Skeleton::Id_Type >& ids); + void filter(Resource_Manager& rman, Set& into); virtual ~Changed_Constraint() {} private: Changed_Statement* stmt; + // The ids get_*_ids_within found, kept for filter(): elements outside the known ids fail + // another constraint anyway, so filter() needn't read the changelog again. + std::vector< Node_Skeleton::Id_Type > node_ids_within; + std::vector< Way_Skeleton::Id_Type > way_ids_within; + std::vector< Relation_Skeleton::Id_Type > relation_ids_within; + bool node_ids_within_valid = false; + bool way_ids_within_valid = false; + bool relation_ids_within_valid = false; }; @@ -208,6 +237,7 @@ bool Changed_Constraint::get_node_ids(Resource_Manager& rman, std::vector< Node_ { ids = collect_changed_elements< Uint32_Index, Node_Skeleton >( stmt->get_since(rman), stmt->get_until(rman), Trivial_Id_Predicate< Node_Skeleton::Id_Type >(), rman); + node_ids_within_valid = false; return true; } @@ -216,6 +246,7 @@ bool Changed_Constraint::get_way_ids(Resource_Manager& rman, std::vector< Way_Sk { ids = collect_changed_elements< Uint31_Index, Way_Skeleton >( stmt->get_since(rman), stmt->get_until(rman), Trivial_Id_Predicate< Way_Skeleton::Id_Type >(), rman); + way_ids_within_valid = false; return true; } @@ -224,15 +255,51 @@ bool Changed_Constraint::get_relation_ids(Resource_Manager& rman, std::vector< R { ids = collect_changed_elements< Uint31_Index, Relation_Skeleton >( stmt->get_since(rman), stmt->get_until(rman), Trivial_Id_Predicate< Relation_Skeleton::Id_Type >(), rman); + relation_ids_within_valid = false; + return true; +} + + +bool Changed_Constraint::get_node_ids_within(Resource_Manager& rman, + const std::vector< Node_Skeleton::Id_Type >& known, std::vector< Node_Skeleton::Id_Type >& ids) +{ + ids = collect_changed_elements< Uint32_Index, Node_Skeleton >( + stmt->get_since(rman), stmt->get_until(rman), Known_Ids_Predicate< Node_Skeleton::Id_Type >(known), rman); + node_ids_within = ids; + node_ids_within_valid = true; + return true; +} + + +bool Changed_Constraint::get_way_ids_within(Resource_Manager& rman, + const std::vector< Way_Skeleton::Id_Type >& known, std::vector< Way_Skeleton::Id_Type >& ids) +{ + ids = collect_changed_elements< Uint31_Index, Way_Skeleton >( + stmt->get_since(rman), stmt->get_until(rman), Known_Ids_Predicate< Way_Skeleton::Id_Type >(known), rman); + way_ids_within = ids; + way_ids_within_valid = true; + return true; +} + + +bool Changed_Constraint::get_relation_ids_within(Resource_Manager& rman, + const std::vector< Relation_Skeleton::Id_Type >& known, std::vector< Relation_Skeleton::Id_Type >& ids) +{ + ids = collect_changed_elements< Uint31_Index, Relation_Skeleton >( + stmt->get_since(rman), stmt->get_until(rman), Known_Ids_Predicate< Relation_Skeleton::Id_Type >(known), rman); + relation_ids_within = ids; + relation_ids_within_valid = true; return true; } void Changed_Constraint::filter(Resource_Manager& rman, Set& into) { - if (!stmt->trivial()) + // Each type's changelog is scanned only if the set holds elements of that type: the scan can + // only keep elements that are already there. + if (!stmt->trivial() && !(into.nodes.empty() && into.attic_nodes.empty())) { - std::vector< Node_Skeleton::Id_Type > ids = + std::vector< Node_Skeleton::Id_Type > ids = node_ids_within_valid ? node_ids_within : collect_changed_elements< Uint32_Index, Node_Skeleton > (stmt->get_since(rman), stmt->get_until(rman), Ids_In_Set_Predicate< Uint32_Index, Node_Skeleton >(into.nodes, into.attic_nodes), rman); @@ -241,9 +308,9 @@ void Changed_Constraint::filter(Resource_Manager& rman, Set& into) filter_elems(ids, into.attic_nodes); } - if (!stmt->trivial()) + if (!stmt->trivial() && !(into.ways.empty() && into.attic_ways.empty())) { - std::vector< Way_Skeleton::Id_Type > ids = + std::vector< Way_Skeleton::Id_Type > ids = way_ids_within_valid ? way_ids_within : collect_changed_elements< Uint31_Index, Way_Skeleton > (stmt->get_since(rman), stmt->get_until(rman), Ids_In_Set_Predicate< Uint31_Index, Way_Skeleton >(into.ways, into.attic_ways), rman); @@ -252,9 +319,9 @@ void Changed_Constraint::filter(Resource_Manager& rman, Set& into) filter_elems(ids, into.attic_ways); } - if (!stmt->trivial()) + if (!stmt->trivial() && !(into.relations.empty() && into.attic_relations.empty())) { - std::vector< Relation_Skeleton::Id_Type > ids = + std::vector< Relation_Skeleton::Id_Type > ids = relation_ids_within_valid ? relation_ids_within : collect_changed_elements< Uint31_Index, Relation_Skeleton > (stmt->get_since(rman), stmt->get_until(rman), Ids_In_Set_Predicate< Uint31_Index, Relation_Skeleton >(into.relations, into.attic_relations), rman); diff --git a/src/overpass_api/statements/coord_query.cc b/src/overpass_api/statements/coord_query.cc index 136c96033..f9d131818 100644 --- a/src/overpass_api/statements/coord_query.cc +++ b/src/overpass_api/statements/coord_query.cc @@ -33,6 +33,7 @@ #include "../data/collect_items.h" #include "../data/tilewise_geometry.h" #include "coord_query.h" +#include bool Coord_Query_Statement::is_used_ = false; @@ -87,10 +88,36 @@ Coord_Query_Statement::Coord_Query_Statement the coordinates to the southern end of the block. If it is odd, the coordinate is inside the area, if not, they are not. */ -int Coord_Query_Statement::check_area_block - (uint32 ll_index, const Area_Block& area_block, - uint32 coord_lat, int32 coord_lon) +Coord_Query_Statement::Decoded_Area_Block::Decoded_Area_Block(uint32 ll_index, const Area_Block& area_block) + : min_lon(0), max_lon(0) +{ + lat.reserve(area_block.coors.size()); + lon.reserve(area_block.coors.size()); + for (std::vector< uint64 >::const_iterator it = area_block.coors.begin(); it != area_block.coors.end(); ++it) + { + lat.push_back(::ilat(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff))); + lon.push_back(::ilon(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff))); + } + if (!lon.empty()) + { + min_lon = *std::min_element(lon.begin(), lon.end()); + max_lon = *std::max_element(lon.begin(), lon.end()); + } +} + + +// The point-in-area test, shared by the raw and the decoded form of an area block. +// vertex(i, lat, lon) yields the decoded coordinates of the i-th of the block's n vertices. +template< typename Vertex > +int check_area_block_vertices(std::vector< uint64 >::size_type n, Vertex vertex, + uint32 coord_lat, int32 coord_lon) { + const int HIT = Coord_Query_Statement::HIT; + const int TOGGLE_EAST = Coord_Query_Statement::TOGGLE_EAST; + const int TOGGLE_WEST = Coord_Query_Statement::TOGGLE_WEST; + if (n == 0) + return 0; + // An area block is a chain of segments. We consider each // segment individually. This falls into different cases, determined by // the relative position of the intersection of the segment and a straight @@ -105,15 +132,14 @@ int Coord_Query_Statement::check_area_block // only either the western or the eastern side. We are part of the area if in the // end the western or eastern side have an odd state. int state = 0; - std::vector< uint64 >::const_iterator it(area_block.coors.begin()); - uint32 lat = ::ilat(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff)); - int32 lon = ::ilon(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff)); - while (++it != area_block.coors.end()) + uint32 lat; + int32 lon; + vertex(0, lat, lon); + for (std::vector< uint64 >::size_type i = 1; i < n; ++i) { uint32 last_lat = lat; int32 last_lon = lon; - lon = ::ilon(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff)); - lat = ::ilat(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff)); + vertex(i, lat, lon); if (last_lon < lon) { @@ -185,6 +211,37 @@ int Coord_Query_Statement::check_area_block } + +int Coord_Query_Statement::check_area_block + (const Decoded_Area_Block& area_block, uint32 coord_lat, int32 coord_lon) +{ + // No segment can affect a coordinate outside the block's longitude range: every case + // except (1) needs coord_lon within a segment's longitude span. So the result is 0. + if (area_block.lat.empty() || coord_lon < area_block.min_lon || coord_lon > area_block.max_lon) + return 0; + return check_area_block_vertices(area_block.lat.size(), + [&area_block](std::vector< uint64 >::size_type i, uint32& lat, int32& lon) + { + lat = area_block.lat[i]; + lon = area_block.lon[i]; + }, coord_lat, coord_lon); +} + + +int Coord_Query_Statement::check_area_block + (uint32 ll_index, const Area_Block& area_block, + uint32 coord_lat, int32 coord_lon) +{ + return check_area_block_vertices(area_block.coors.size(), + [ll_index, &area_block](std::vector< uint64 >::size_type i, uint32& lat, int32& lon) + { + uint64 c = area_block.coors[i]; + lat = ::ilat(ll_index | ((c>>32)&0xff), (c & 0xffffffff)); + lon = ::ilon(ll_index | ((c>>32)&0xff), (c & 0xffffffff)); + }, coord_lat, coord_lon); +} + + void register_coord(double lat, double lon, std::set< Uint31_Index >& req, std::map< Uint31_Index, std::vector< std::pair< double, double > > >& coord_per_req) { diff --git a/src/overpass_api/statements/coord_query.h b/src/overpass_api/statements/coord_query.h index ec9c83146..21c40ec17 100644 --- a/src/overpass_api/statements/coord_query.h +++ b/src/overpass_api/statements/coord_query.h @@ -45,6 +45,22 @@ class Coord_Query_Statement : public Output_Statement (uint32 ll_index, const Area_Block& area_block, uint32 coord_lat, int32 coord_lon); + /* An area block with its vertices decoded once, for testing many coordinates against + it. Decoding packed coordinates dominated the cost of testing each coordinate against + the raw block. */ + struct Decoded_Area_Block + { + Decoded_Area_Block(uint32 ll_index, const Area_Block& area_block); + std::vector< uint32 > lat; + std::vector< int32 > lon; + int32 min_lon; + int32 max_lon; + }; + // Same result as check_area_block(ll_index, area_block, coord_lat, coord_lon) for the block + // decoded with that ll_index. + static int check_area_block + (const Decoded_Area_Block& area_block, uint32 coord_lat, int32 coord_lon); + // Used as bitmasks. const static int HIT = 1; const static int TOGGLE_EAST = 2; diff --git a/src/overpass_api/statements/filter.cc b/src/overpass_api/statements/filter.cc index 9eb6d7ecc..cd66816b3 100644 --- a/src/overpass_api/statements/filter.cc +++ b/src/overpass_api/statements/filter.cc @@ -34,6 +34,11 @@ class Filter_Constraint : public Query_Constraint bool get_ranges(Resource_Manager& rman, Ranges< Uint31_Index >& ranges) { return false; } void filter(Resource_Manager& rman, Set& into) {} void filter(const Statement& query, Resource_Manager& rman, Set& into); + bool filter_needs_geometry() const override + { + return stmt && stmt->get_criterion() + && (stmt->get_criterion()->request_context().object_usage & Set_Usage::GEOMETRY); + } virtual ~Filter_Constraint() {} private: diff --git a/src/overpass_api/statements/newer.cc b/src/overpass_api/statements/newer.cc index 5a0068356..a13e25bfa 100644 --- a/src/overpass_api/statements/newer.cc +++ b/src/overpass_api/statements/newer.cc @@ -38,6 +38,7 @@ class Newer_Constraint : public Query_Constraint Query_Filter_Strategy delivers_data(Resource_Manager& rman) { return ids_required; } void filter(const Statement& query, Resource_Manager& rman, Set& into); + bool filter_reads_only_metadata() const override { return true; } virtual ~Newer_Constraint() {} private: diff --git a/src/overpass_api/statements/polygon_query.cc b/src/overpass_api/statements/polygon_query.cc index 8a215789d..c7f2353cd 100644 --- a/src/overpass_api/statements/polygon_query.cc +++ b/src/overpass_api/statements/polygon_query.cc @@ -361,6 +361,11 @@ void Polygon_Query_Statement::collect_nodes(std::map< Uint32_Index, std::vector< areas.push_back(block); ++area_it; } + // The same segments decoded once for this tile, for the node tests below. + std::vector< Coord_Query_Statement::Decoded_Area_Block > areas_in_tile; + areas_in_tile.reserve(areas.size()); + for (std::vector< Area_Block >::const_iterator ait = areas.begin(); ait != areas.end(); ++ait) + areas_in_tile.push_back(Coord_Query_Statement::Decoded_Area_Block(current_idx, *ait)); while (nodes_it != nodes.end() && nodes_it->first.val() < current_idx) { @@ -383,7 +388,7 @@ void Polygon_Query_Statement::collect_nodes(std::map< Uint32_Index, std::vector< for (std::vector< Area_Block >::const_iterator it = areas.begin(); it != areas.end(); ++it) { - int check(Coord_Query_Statement::check_area_block(current_idx, *it, ilat, ilon)); + int check(Coord_Query_Statement::check_area_block(areas_in_tile[it - areas.begin()], ilat, ilon)); if (check == Coord_Query_Statement::HIT && add_border) { inside = 1; @@ -413,7 +418,9 @@ void Polygon_Query_Statement::collect_ways const Way_Geometry_Store& way_geometries, bool add_border, const Statement& query, Resource_Manager& rman) { + // Build each way's geometry once, for both its coordinates and its segments. std::map< uint32, std::vector< std::pair< uint32, Way::Id_Type > > > way_coords_to_id; + std::map< Uint31_Index, std::vector< Area_Block > > way_segments; for (typename std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = ways.begin(); it != ways.end(); ++it) { for (typename std::vector< Way_Skeleton >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) @@ -421,6 +428,7 @@ void Polygon_Query_Statement::collect_ways std::vector< Quad_Coord > coords = way_geometries.get_geometry(*it2); for (std::vector< Quad_Coord >::const_iterator it3 = coords.begin(); it3 != coords.end(); ++it3) way_coords_to_id[it3->ll_upper].push_back(std::make_pair(it3->ll_lower, it2->id)); + add_way_to_area_blocks(coords, it2->id.val(), way_segments); } } @@ -428,13 +436,6 @@ void Polygon_Query_Statement::collect_ways std::vector< Aligned_Segment >::const_iterator area_it = segments.begin(); - std::map< Uint31_Index, std::vector< Area_Block > > way_segments; - for (typename std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = ways.begin(); it != ways.end(); ++it) - { - for (typename std::vector< Way_Skeleton >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - add_way_to_area_blocks(way_geometries.get_geometry(*it2), it2->id.val(), way_segments); - } - std::map< Way::Id_Type, bool > ways_inside; // Fill node_status with the area related status of each node and segment @@ -452,6 +453,23 @@ void Polygon_Query_Statement::collect_ways areas.push_back(block); ++area_it; } + // The same segments decoded once for this tile, for the node tests below. + std::vector< Coord_Query_Statement::Decoded_Area_Block > areas_in_tile; + areas_in_tile.reserve(areas.size()); + for (std::vector< Area_Block >::const_iterator ait = areas.begin(); ait != areas.end(); ++ait) + areas_in_tile.push_back(Coord_Query_Statement::Decoded_Area_Block(current_idx, *ait)); + // The same segments decoded once for this tile, for the segment tests below. + std::vector< Decoded_Coords > area_coords(areas.size()); + std::vector< Coords_Bounds > area_bounds; + area_bounds.reserve(areas.size()); + std::vector< Coord_Query_Statement::Decoded_Area_Block > areas_decoded; + areas_decoded.reserve(areas.size()); + for (std::vector< Area_Block >::size_type i = 0; i < areas.size(); ++i) + { + decode_coords(areas[i], area_coords[i]); + area_bounds.push_back(Coords_Bounds(area_coords[i])); + areas_decoded.push_back(Coord_Query_Statement::Decoded_Area_Block(0, areas[i])); + } // check nodes while (nodes_it != way_coords_to_id.end() && nodes_it->first < current_idx) @@ -470,7 +488,7 @@ void Polygon_Query_Statement::collect_ways for (std::vector< Area_Block >::const_iterator it2 = areas.begin(); it2 != areas.end(); ++it2) { - int check(Coord_Query_Statement::check_area_block(current_idx, *it2, ilat, ilon)); + int check(Coord_Query_Statement::check_area_block(areas_in_tile[it2 - areas.begin()], ilat, ilon)); if (check == Coord_Query_Statement::HIT) { inside = Coord_Query_Statement::HIT; @@ -486,9 +504,12 @@ void Polygon_Query_Statement::collect_ways } // check segments + Decoded_Coords sit_coords; for (std::vector< Area_Block >::const_iterator sit = way_segments[Uint31_Index(current_idx)].begin(); sit != way_segments[Uint31_Index(current_idx)].end(); ++sit) { + decode_coords(*sit, sit_coords); + Coords_Bounds sit_bounds(sit_coords); int inside = 0; for (std::vector< Area_Block >::const_iterator it = areas.begin(); it != areas.end(); ++it) @@ -498,7 +519,8 @@ void Polygon_Query_Statement::collect_ways // The endpoints are properly handled via the point-in-area test // Check additionally the middle of the segment to also get segments // that run through the area - int intersect = intersects_inner(*sit, *it); + int intersect = sit_bounds.overlaps(area_bounds[it - areas.begin()]) + ? intersects_inner(sit_coords, area_coords[it - areas.begin()]) : 0; if (intersect == Coord_Query_Statement::INTERSECT) { ways_inside[Way::Id_Type(sit->id)] = true; @@ -512,7 +534,7 @@ void Polygon_Query_Statement::collect_ways inside = 0; break; } - has_inner_points(*sit, *it, inside); + has_inner_points(sit_coords, areas_decoded[it - areas.begin()], inside); } if ((inside && (!(inside & Coord_Query_Statement::HIT))) || (inside && add_border)) diff --git a/src/overpass_api/statements/print.cc b/src/overpass_api/statements/print.cc index 9d5e92c6a..75e1ef295 100644 --- a/src/overpass_api/statements/print.cc +++ b/src/overpass_api/statements/print.cc @@ -260,7 +260,7 @@ Extra_Data::~Extra_Data() void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Node_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Node_Skeleton::Id_Type >* meta = 0) { output.print_item(skel, Point_Geometry(::lat(ll_upper, skel.ll_lower), ::lon(ll_upper, skel.ll_lower)), @@ -269,7 +269,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Way_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Way_Skeleton::Id_Type >* meta = 0) { Geometry_From_Quad_Coords broker; @@ -280,7 +280,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Attic< Way_Skeleton >& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Way_Skeleton::Id_Type >* meta = 0) { Geometry_From_Quad_Coords broker; @@ -291,7 +291,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Relation_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Relation_Skeleton::Id_Type >* meta = 0) { Geometry_From_Quad_Coords broker; @@ -302,7 +302,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Attic< Relation_Skeleton >& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Relation_Skeleton::Id_Type >* meta = 0) { Geometry_From_Quad_Coords broker; @@ -313,7 +313,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Area_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Area_Skeleton::Id_Type >* meta = 0) { Derived_Skeleton derived("area", Uint64(skel.id.val())); @@ -322,7 +322,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Derived_Structure& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Derived_Skeleton::Id_Type >* meta = 0) { if (skel.get_geometry()) @@ -377,7 +377,7 @@ void tags_quadtile_ { if (++element_count > limit) return; - print_item(extra_data, output, item_it->first.val(), *it2, tag_store.get(item_it->first, *it2), + print_item(extra_data, output, item_it->first.val(), *it2, tag_store.get_refs(item_it->first, *it2), meta_printer.get(item_it->first, it2->id)); } ++item_it; @@ -405,7 +405,7 @@ void tags_quadtile_attic_ { if (++element_count > limit) return; - print_item(extra_data, output, item_it->first.val(), *it2, tag_store.get(item_it->first, *it2), + print_item(extra_data, output, item_it->first.val(), *it2, tag_store.get_refs(item_it->first, *it2), meta_printer.get(item_it->first, it2->id, it2->timestamp)); } ++item_it; @@ -413,75 +413,107 @@ void tags_quadtile_attic_ } -template< class TComp > -struct Skeleton_Comparator_By_Id { - bool operator() (const std::pair< const TComp*, uint32 >& a, - const std::pair< const TComp*, uint32 >& b) - { - return (a.first->id < b.first->id); - } -}; - - -template< typename Index, typename Object > -struct Maybe_Attic_Ref +// Number of elements in a set, so that the id-sorted references below can be reserved exactly: +// grown by doubling, they reach up to about twice their size, plus the old copy while they grow. +template< class Index, class Object > +std::size_t count_items(const std::map< Index, std::vector< Object > >& items) { -public: - Maybe_Attic_Ref(Index idx_, const Object* obj_, uint64 timestamp_) - : idx(idx_), obj(obj_), timestamp(timestamp_) {} - - Index idx; - const Object* obj; - uint64 timestamp; - - bool operator<(const Maybe_Attic_Ref& rhs) const { return obj->id < rhs.obj->id; } -}; + std::size_t count = 0; + for (typename std::map< Index, std::vector< Object > >::const_iterator + it(items.begin()); it != items.end(); ++it) + count += it->second.size(); + return count; +} +// The elements of a set in id order, current elements and then attic elements for equal ids as +// std::sort leaves them. Each element is referenced in 8 bytes: the number of its index's entry in a +// table of the set's non-empty vectors, current ones first, and its position in that vector. A +// pointer and an index took 16 bytes per element, and 24 with the timestamp of an attic element. template< class Index, class Object > -std::vector< std::pair< const Object*, uint32 > > collect_items_by_id( - const std::map< Index, std::vector< Object > >& items) +class Items_By_Id { - std::vector< std::pair< const Object*, uint32 > > items_by_id; +public: + Items_By_Id(const std::map< Index, std::vector< Object > >& items) + { + refs.reserve(count_items(items)); + add_entries(items); + current_count = entries.size(); + sort_refs(); + } - for (typename std::map< Index, std::vector< Object > >::const_iterator - it(items.begin()); it != items.end(); ++it) + Items_By_Id(const std::map< Index, std::vector< Object > >& items, + const std::map< Index, std::vector< Attic< Object > > >& attic_items) { - for (typename std::vector< Object >::const_iterator it2(it->second.begin()); - it2 != it->second.end(); ++it2) - items_by_id.push_back(std::make_pair(&(*it2), it->first.val())); + refs.reserve(count_items(items) + count_items(attic_items)); + add_entries(items); + current_count = entries.size(); + add_entries(attic_items); + sort_refs(); } - sort(items_by_id.begin(), items_by_id.end(), - Skeleton_Comparator_By_Id< Object >()); - return items_by_id; -} + std::size_t size() const { return refs.size(); } + const Object& obj(std::size_t i) const { return get(refs[i]); } + Index idx(std::size_t i) const { return entries[refs[i].entry].idx; } + // NOW for a current element. + uint64 timestamp(std::size_t i) const + { + return refs[i].entry < current_count ? NOW + : static_cast< const Attic< Object >& >(get(refs[i])).timestamp; + } +private: + struct Ref + { + Ref(uint32 entry_, uint32 pos_) : entry(entry_), pos(pos_) {} + uint32 entry; + uint32 pos; + }; -template< class Index, class Object > -std::vector< Maybe_Attic_Ref< Index, Object > > collect_items_by_id( - const std::map< Index, std::vector< Object > >& items, - const std::map< Index, std::vector< Attic< Object > > >& attic_items) -{ - std::vector< Maybe_Attic_Ref< Index, Object > > items_by_id; - for (typename std::map< Index, std::vector< Object > >::const_iterator - it(items.begin()); it != items.end(); ++it) + // The address of the Object part of the vector's first element, and the size of its elements: + // that of Object for current elements, of Attic< Object > for attic elements. Looking up both + // kinds the same way keeps the sort's comparisons free of branches. + struct Entry { - for (typename std::vector< Object >::const_iterator it2(it->second.begin()); - it2 != it->second.end(); ++it2) - items_by_id.push_back(Maybe_Attic_Ref< Index, Object >(it->first, &(*it2), NOW)); + Entry(const char* first_, uint32 size_, Index idx_) : first(first_), size(size_), idx(idx_) {} + const char* first; + uint32 size; + Index idx; + }; + + std::vector< Entry > entries; + std::size_t current_count; + std::vector< Ref > refs; + + const Object& get(const Ref& ref) const + { + const Entry& entry = entries[ref.entry]; + return *reinterpret_cast< const Object* >(entry.first + std::size_t(ref.pos) * entry.size); } - for (typename std::map< Index, std::vector< Attic< Object > > >::const_iterator - it(attic_items.begin()); it != attic_items.end(); ++it) + + // Appends the references in the order of the set, as before, so that equal ids keep their order. + template< class Elem > + void add_entries(const std::map< Index, std::vector< Elem > >& items) { - for (typename std::vector< Attic< Object > >::const_iterator it2(it->second.begin()); - it2 != it->second.end(); ++it2) - items_by_id.push_back(Maybe_Attic_Ref< Index, Object >(it->first, &(*it2), it2->timestamp)); + for (typename std::map< Index, std::vector< Elem > >::const_iterator + it(items.begin()); it != items.end(); ++it) + { + if (it->second.empty()) + continue; + uint32 entry = entries.size(); + const Object& first = it->second.front(); + entries.push_back(Entry(reinterpret_cast< const char* >(&first), sizeof(Elem), it->first)); + for (uint32 pos = 0; pos < it->second.size(); ++pos) + refs.push_back(Ref(entry, pos)); + } } - sort(items_by_id.begin(), items_by_id.end()); - return items_by_id; -} + void sort_refs() + { + std::sort(refs.begin(), refs.end(), + [this](const Ref& a, const Ref& b) { return get(a).id < get(b).id; }); + } +}; template< class Index, class Object > @@ -489,14 +521,14 @@ void by_id (const std::map< Index, std::vector< Object > >& items, Output_Handler& output, Transaction& transaction, Extra_Data& extra_data, uint32 limit, uint32& element_count) { - std::vector< std::pair< const Object*, uint32 > > items_by_id = collect_items_by_id(items); + Items_By_Id< Index, Object > items_by_id(items); // iterate over the result for (uint32 i(0); i < items_by_id.size(); ++i) { if (++element_count > limit) return; - print_item(extra_data, output, items_by_id[i].second, *(items_by_id[i].first)); + print_item(extra_data, output, items_by_id.idx(i).val(), items_by_id.obj(i)); } } @@ -508,18 +540,18 @@ void by_id Output_Handler& output, Transaction& transaction, Extra_Data& extra_data, uint32 limit, uint32& element_count) { - std::vector< Maybe_Attic_Ref< Index, Object > > items_by_id = collect_items_by_id(items, attic_items); + Items_By_Id< Index, Object > items_by_id(items, attic_items); // iterate over the result for (uint32 i(0); i < items_by_id.size(); ++i) { if (++element_count > limit) return; - if (items_by_id[i].timestamp == NOW) - print_item(extra_data, output, items_by_id[i].idx.val(), *items_by_id[i].obj); + if (items_by_id.timestamp(i) == NOW) + print_item(extra_data, output, items_by_id.idx(i).val(), items_by_id.obj(i)); else - print_item(extra_data, output, items_by_id[i].idx.val(), - Attic< Object >(*items_by_id[i].obj, items_by_id[i].timestamp)); + print_item(extra_data, output, items_by_id.idx(i).val(), + Attic< Object >(items_by_id.obj(i), items_by_id.timestamp(i))); } } @@ -597,7 +629,7 @@ void tags_by_id Resource_Manager& rman, Meta_Collector< Index, typename Object::Id_Type >* meta_printer, Tag_Store< Index, Object >& tag_store, uint32 limit, uint32& element_count) { - std::vector< std::pair< const Object*, uint32 > > items_by_id = collect_items_by_id(items); + Items_By_Id< Index, Object > items_by_id(items); // iterate over the result for (typename Object::Id_Type id_pos; id_pos < items_by_id.size(); id_pos += FLUSH_SIZE) @@ -605,13 +637,13 @@ void tags_by_id // Disable health_check: This ensures that a result will be always printed completely //rman.health_check(*this); - typename Object::Id_Type lower_id_bound(items_by_id[id_pos.val()].first->id); + typename Object::Id_Type lower_id_bound(items_by_id.obj(id_pos.val()).id); typename Object::Id_Type upper_id_bound; if (id_pos + FLUSH_SIZE < items_by_id.size()) - upper_id_bound = items_by_id[(id_pos + FLUSH_SIZE).val()].first->id; + upper_id_bound = items_by_id.obj((id_pos + FLUSH_SIZE).val()).id; else { - upper_id_bound = items_by_id[items_by_id.size()-1].first->id; + upper_id_bound = items_by_id.obj(items_by_id.size()-1).id; ++upper_id_bound; } @@ -633,10 +665,10 @@ void tags_by_id return; typename std::set< OSM_Element_Metadata_Skeleton< typename Object::Id_Type > >::const_iterator meta_it = metadata.lower_bound(OSM_Element_Metadata_Skeleton< typename Object::Id_Type > - (items_by_id[i.val()].first->id)); - print_item(extra_data, output, items_by_id[i.val()].second, *(items_by_id[i.val()].first), - tag_store.get(Index(items_by_id[i.val()].second), *items_by_id[i.val()].first), - (meta_it != metadata.end() && meta_it->ref == items_by_id[i.val()].first->id) ? + (items_by_id.obj(i.val()).id)); + print_item(extra_data, output, items_by_id.idx(i.val()).val(), items_by_id.obj(i.val()), + tag_store.get_refs(items_by_id.idx(i.val()), items_by_id.obj(i.val())), + (meta_it != metadata.end() && meta_it->ref == items_by_id.obj(i.val()).id) ? &*meta_it : 0); } } @@ -651,7 +683,7 @@ void tags_by_id_attic Extra_Data& extra_data, uint32 FLUSH_SIZE, Output_Handler& output, Resource_Manager& rman, Transaction& transaction, uint32 limit, uint32& element_count) { - std::vector< Maybe_Attic_Ref< Index, Object > > items_by_id = collect_items_by_id(current_items, attic_items); + Items_By_Id< Index, Object > items_by_id(current_items, attic_items); Tag_Store< Index, Object > current_tag_store(transaction); Tag_Store< Index, Object > attic_tag_store(transaction); @@ -666,13 +698,13 @@ void tags_by_id_attic // Disable health_check: This ensures that a result will be always printed completely //rman.health_check(*this); - typename Object::Id_Type lower_id_bound(items_by_id[id_pos.val()].obj->id); + typename Object::Id_Type lower_id_bound(items_by_id.obj(id_pos.val()).id); typename Object::Id_Type upper_id_bound; if (id_pos + FLUSH_SIZE < items_by_id.size()) - upper_id_bound = items_by_id[(id_pos + FLUSH_SIZE).val()].obj->id; + upper_id_bound = items_by_id.obj((id_pos + FLUSH_SIZE).val()).id; else { - upper_id_bound = items_by_id[items_by_id.size()-1].obj->id; + upper_id_bound = items_by_id.obj(items_by_id.size()-1).id; ++upper_id_bound; } @@ -695,24 +727,24 @@ void tags_by_id_attic { if (++element_count > limit) return; - if (items_by_id[i.val()].timestamp == NOW) + if (items_by_id.timestamp(i.val()) == NOW) { typename std::set< OSM_Element_Metadata_Skeleton< typename Object::Id_Type > >::const_iterator meta_it = only_current_metadata.lower_bound(OSM_Element_Metadata_Skeleton< typename Object::Id_Type > - (items_by_id[i.val()].obj->id)); - print_item(extra_data, output, items_by_id[i.val()].idx.val(), *items_by_id[i.val()].obj, - current_tag_store.get(items_by_id[i.val()].idx, *items_by_id[i.val()].obj), - (meta_it != only_current_metadata.end() && meta_it->ref == items_by_id[i.val()].obj->id) ? + (items_by_id.obj(i.val()).id)); + print_item(extra_data, output, items_by_id.idx(i.val()).val(), items_by_id.obj(i.val()), + current_tag_store.get_refs(items_by_id.idx(i.val()), items_by_id.obj(i.val())), + (meta_it != only_current_metadata.end() && meta_it->ref == items_by_id.obj(i.val()).id) ? &*meta_it : 0); } else { typename std::set< OSM_Element_Metadata_Skeleton< typename Object::Id_Type > >::const_iterator meta_it = find_matching_metadata(attic_metadata, - items_by_id[i.val()].obj->id, items_by_id[i.val()].timestamp); - print_item(extra_data, output, items_by_id[i.val()].idx.val(), - Attic< Object >(*items_by_id[i.val()].obj, items_by_id[i.val()].timestamp), - attic_tag_store.get(items_by_id[i.val()].idx, *items_by_id[i.val()].obj), + items_by_id.obj(i.val()).id, items_by_id.timestamp(i.val())); + print_item(extra_data, output, items_by_id.idx(i.val()).val(), + Attic< Object >(items_by_id.obj(i.val()), items_by_id.timestamp(i.val())), + attic_tag_store.get_refs(items_by_id.idx(i.val()), items_by_id.obj(i.val())), meta_it != attic_metadata.end() ? &*meta_it : 0); } } diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 76b2d190f..7fab61512 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -97,6 +97,18 @@ Query_Statement::~Query_Statement() } +std::string Query_Statement::block_signature() const +{ + std::string result = to_string(type); + for (std::vector< Statement* >::const_iterator it = substatements.begin(); it != substatements.end(); ++it) + { + if (*it && !dynamic_cast< Has_Kv_Statement* >(*it)) + result += (*it)->dump_ql_in_query(""); + } + return result; +} + + void Query_Statement::add_statement(Statement* statement, std::string text) { assure_no_text(text, this->get_name()); @@ -209,7 +221,7 @@ void filter_ids_by_ntags key_it = keys.begin(); while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(tag_it)) == coarse_index)) { if (tag_it.index().key != last_key) { @@ -260,7 +272,7 @@ void filter_ids_by_ntags ++tag_it; } while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(tag_it)) == coarse_index)) ++tag_it; sort(removed_ids.begin(), removed_ids.end()); @@ -291,18 +303,18 @@ void filter_ids_by_ntags timestamps[*it]; while ((!(tag_it == items_db.range_end())) && - ((tag_it.index().index) & 0x7fffff00) == coarse_index && + (tag_coarse_index(tag_it)) == coarse_index && tag_it.index().key < key_it->first) ++tag_it; while ((!(attic_tag_it == attic_items_db.range_end())) && - ((attic_tag_it.index().index) & 0x7fffff00) == coarse_index && + (tag_coarse_index(attic_tag_it)) == coarse_index && attic_tag_it.index().key < key_it->first) ++attic_tag_it; bool valid = false; std::string last_value = void_tag_value() + " "; while ((!(tag_it == items_db.range_end())) && - ((tag_it.index().index) & 0x7fffff00) == coarse_index && + (tag_coarse_index(tag_it)) == coarse_index && tag_it.index().key == key_it->first) { if (std::binary_search(new_ids.begin(), new_ids.end(), tag_it.object())) @@ -330,7 +342,7 @@ void filter_ids_by_ntags last_value = void_tag_value() + " "; while ((!(attic_tag_it == attic_items_db.range_end())) && - ((attic_tag_it.index().index) & 0x7fffff00) == coarse_index && + (tag_coarse_index(attic_tag_it)) == coarse_index && attic_tag_it.index().key == key_it->first) { if (std::binary_search(new_ids.begin(), new_ids.end(), Id_Type(attic_tag_it.object()))) @@ -373,10 +385,10 @@ void filter_ids_by_ntags } } while ((!(tag_it == items_db.range_end())) && - ((tag_it.index().index) & 0x7fffff00) == coarse_index) + (tag_coarse_index(tag_it)) == coarse_index) ++tag_it; while ((!(attic_tag_it == attic_items_db.range_end())) && - ((attic_tag_it.index().index) & 0x7fffff00) == coarse_index) + (tag_coarse_index(attic_tag_it)) == coarse_index) ++attic_tag_it; } @@ -450,6 +462,23 @@ void filter_by_ids( } +template< class TIndex, class TObject > +void fill_cell_ids(std::vector< typename TObject::Id_Type >& ids, + typename std::map< TIndex, std::vector< TObject > >::const_iterator& item_it, + const std::map< TIndex, std::vector< TObject > >& items, uint32 coarse_index) +{ + while (item_it != items.end() && (item_it->first.val() & 0x7fffff00) == coarse_index) + { + for (typename std::vector< TObject >::const_iterator eit = item_it->second.begin(); + eit != item_it->second.end(); ++eit) + ids.push_back(eit->id); + ++item_it; + } + std::sort(ids.begin(), ids.end()); + ids.erase(std::unique(ids.begin(), ids.end()), ids.end()); +} + + template< class TIndex, class TObject > void Query_Statement::filter_by_tags (std::map< TIndex, std::vector< TObject > >& items, @@ -461,14 +490,23 @@ void Query_Statement::filter_by_tags && key_nregexes.empty() && key_nvalues.empty()) return; - // generate set of relevant coarse indices + // One entry per coarse index, but its ids are filled in only when that cell is filtered, so the + // candidates' ids are never all held at once. std::map< uint32, std::vector< typename TObject::Id_Type > > ids_by_coarse; - generate_ids_by_coarse(ids_by_coarse, items); + for (typename std::map< TIndex, std::vector< TObject > >::const_iterator it = items.begin(); it != items.end(); ++it) + ids_by_coarse.insert(ids_by_coarse.end(), std::make_pair(it->first.val() & 0x7fffff00, + std::vector< typename TObject::Id_Type >())); if (timestamp != NOW) - generate_ids_by_coarse(ids_by_coarse, *attic_items); - - // formulate range query - Ranges< Tag_Index_Local > ranges = formulate_range_query(ids_by_coarse); + { + for (typename std::map< TIndex, std::vector< Attic< TObject > > >::const_iterator it = attic_items->begin(); + it != attic_items->end(); ++it) + ids_by_coarse.insert(std::make_pair(it->first.val() & 0x7fffff00, + std::vector< typename TObject::Id_Type >())); + } + typename std::map< TIndex, std::vector< TObject > >::const_iterator cell_item_it = items.begin(); + typename std::map< TIndex, std::vector< Attic< TObject > > >::const_iterator cell_attic_it; + if (attic_items) + cell_attic_it = attic_items->begin(); // prepare straight keys std::map< std::string, std::pair< std::string, std::vector< Regular_Expression* > > > key_union; @@ -482,6 +520,10 @@ void Query_Statement::filter_by_tags it = key_regexes.begin(); it != key_regexes.end(); ++it) key_union[it->first].second.push_back(it->second); + // formulate range query: read only the entries of these keys, unless a key regex must see every key + Ranges< Tag_Index_Local > ranges = regkey_regexes.empty() + ? formulate_range_query(ids_by_coarse, key_union) : formulate_range_query(ids_by_coarse); + // iterate over the result std::map< TIndex, std::vector< TObject > > result; std::map< TIndex, std::vector< Attic< TObject > > > attic_result; @@ -501,6 +543,7 @@ void Query_Statement::filter_by_tags coarse_count = 0; rman.health_check(*this); } + fill_cell_ids(it->second, cell_item_it, items, it->first); filter_ids_by_tags(key_union, regkey_regexes, items_db, tag_it, it->first, it->second); } } @@ -518,6 +561,8 @@ void Query_Statement::filter_by_tags coarse_count = 0; rman.health_check(*this); } + fill_cell_ids(it->second, cell_item_it, items, it->first); + fill_cell_ids(it->second, cell_attic_it, *attic_items, it->first); filter_ids_by_tags(key_union, regkey_regexes, timestamp, items_db, tag_it, attic_items_db, attic_tag_it, it->first, it->second); } @@ -542,7 +587,8 @@ void Query_Statement::filter_by_tags result.clear(); attic_result.clear(); coarse_count = 0; - auto ntag_it = items_db.range_begin(ranges); + Ranges< Tag_Index_Local > nranges = formulate_range_query(ids_by_coarse, nkey_union); + auto ntag_it = items_db.range_begin(nranges); if (timestamp == NOW) { @@ -561,7 +607,7 @@ void Query_Statement::filter_by_tags { Block_Backend< Tag_Index_Local, Attic< typename TObject::Id_Type > > attic_items_db (transaction.data_index(attic_file_prop)); - auto attic_ntag_it = attic_items_db.range_begin(ranges); + auto attic_ntag_it = attic_items_db.range_begin(nranges); for (typename std::map< uint32, std::vector< typename TObject::Id_Type > >::iterator it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) @@ -826,6 +872,42 @@ void Query_Statement::collect_elems(Answer_State& answer_state, Set& into, Resou } +// The id map holds a fixed number of ids per block and decompresses one block at a time, so +// looking ids up costs about one block per distinct block they fall in. +template< typename Index, typename Skeleton > +bool exact_indices_pay_off(const std::vector< typename Skeleton::Id_Type >& ids, + const Ranges< Index >& coarse_ranges, Resource_Manager& rman) +{ + if (ids.empty() || coarse_ranges.is_global()) + return false; + Random_File_Index* map = rman.get_transaction()->random_index(current_skeleton_file_properties< Skeleton >()); + uint64 ids_per_block = map->get_block_size() * map->get_compression_factor() / Index::max_size_of(); + uint64 map_blocks = 0; + uint64 last_block = ~uint64(0); + for (auto it = ids.begin(); it != ids.end(); ++it) + { + uint64 block = it->val() / ids_per_block; + if (block != last_block) + ++map_blocks; + last_block = block; + } + Block_Backend< Index, Skeleton > skeletons_db + (rman.get_transaction()->data_index(current_skeleton_file_properties< Skeleton >())); + return 2*map_blocks < skeletons_db.count_blocks(coarse_ranges); +} + + +template< typename Index > +Ranges< Index > exact_ranges(const std::vector< Index >& idxs) +{ + Ranges< Index > result; + for (auto it = idxs.begin(); it != idxs.end(); ++it) + result.push_back(*it, inc(*it)); + result.sort(); + return result; +} + + template< typename Index > Ranges< Index > intersect_ranges(const Ranges< Index >& range_a, std::vector< Index >& range_vec) { @@ -835,10 +917,43 @@ Ranges< Index > intersect_ranges(const Ranges< Index >& range_a, std::vector< In for (auto it = range_a.begin(); it != range_a.end(); ++it) sum += difference(it.lower_bound(), it.upper_bound()); - if (sum/256 < range_vec.size()) + // range_vec holds the coarse index (256 tiles) of every candidate in the database, many sharing + // a cell. Count only the distinct cells that overlap range_a: comparing all candidates with + // range_a's cells skipped the intersection for any tag with more matches anywhere than range_a + // has cells, however few of them lie in range_a. + // With more candidates than range_a has tiles, nearly every cell holds one anyway, and + // filtering them would cost more than it saves. + if (sum < range_vec.size()) return range_a; - std::sort(range_vec.begin(), range_vec.end()); + // range_a can hold overlapping ranges (Ranges::union_ doesn't merge them), so merge them + // here: the search below needs upper bounds that increase. + std::vector< std::pair< Index, Index > > raw; + for (auto it = range_a.begin(); it != range_a.end(); ++it) + raw.push_back(std::make_pair(it.lower_bound(), it.upper_bound())); + std::sort(raw.begin(), raw.end()); + std::vector< std::pair< Index, Index > > bounds; + for (auto it = raw.begin(); it != raw.end(); ++it) + { + if (!bounds.empty() && !(bounds.back().second < it->first)) + bounds.back().second = std::max(bounds.back().second, it->second); + else + bounds.push_back(*it); + } + std::vector< Index > inside; + for (auto it = range_vec.begin(); it != range_vec.end(); ++it) + { + auto b = std::upper_bound(bounds.begin(), bounds.end(), *it, + [](const Index& x, const std::pair< Index, Index >& r) { return x < r.second; }); + if (b != bounds.end() && b->first < Index(it->val() + 0x100)) + inside.push_back(*it); + } + std::sort(inside.begin(), inside.end()); + inside.erase(std::unique(inside.begin(), inside.end()), inside.end()); + range_vec.swap(inside); + + if (sum/256 < range_vec.size()) + return range_a; auto it_a = range_a.begin(); auto it_vec = range_vec.begin(); @@ -905,9 +1020,27 @@ void Query_Statement::apply_all_filters( set_progress(8); rman.health_check(*this); + // All filters only remove elements, so their order does not change the result. + // Metadata-only filters go first, so that geometry is built for fewer elements, and (if:) + // filters that need geometry go last, after the other filters have built theirs. + for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); + it != constraints.end(); ++it) + { + if ((*it)->filter_reads_only_metadata()) + (*it)->filter(*this, rman, into); + } + for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); + it != constraints.end(); ++it) + { + if (!(*it)->filter_reads_only_metadata() && !(*it)->filter_needs_geometry()) + (*it)->filter(*this, rman, into); + } for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); it != constraints.end(); ++it) - (*it)->filter(*this, rman, into); + { + if (!(*it)->filter_reads_only_metadata() && (*it)->filter_needs_geometry()) + (*it)->filter(*this, rman, into); + } } @@ -918,6 +1051,125 @@ void filter_elems_for_closed_ways(Set& arg) } +// Restricts ids to the ids every constraint allows. Constraints whose id lists are expensive to +// build are asked last and get the explicit ids the others allow, if any, so they can leave out +// the rest. +template< typename Id > +void restrict_to_constraint_ids( + const std::vector< Query_Constraint* >& constraints, Resource_Manager& rman, + bool (Query_Constraint::*get_ids)(Resource_Manager&, std::vector< Id >&), + bool (Query_Constraint::*get_ids_within)(Resource_Manager&, const std::vector< Id >&, std::vector< Id >&), + Id_Constraint< Id >& ids, Answer_State& answer_state) +{ + for (int pass = 0; pass < 2; ++pass) + { + for (std::vector< Query_Constraint* >::const_iterator it = constraints.begin(); + it != constraints.end() && answer_state < data_collected; ++it) + { + if ((*it)->narrows_by_known_ids() != (pass == 1)) + continue; + std::vector< Id > constraint_ids; + bool restricts = (pass == 1 && !ids.invert) + ? ((*it)->*get_ids_within)(rman, ids.ids, constraint_ids) + : ((*it)->*get_ids)(rman, constraint_ids); + if (restricts) + { + ids.restrict_to(constraint_ids); + if (ids.empty()) + answer_state = data_collected; + } + } + } +} + + +// Ids of current elements in the coarse cells of ranges that carry every positive tag filter +// (keys, key-values, key-regexes), read from the local tag index alone: the late tag check can +// then collect just these instead of every element in the ranges. Returns false where it doesn't +// apply: no positive filter, or ranges spanning too many cells. +template< typename Index, typename Id_Type > +bool ids_from_local_tags( + const std::vector< std::string >& keys, + const std::vector< std::pair< std::string, std::string > >& key_values, + const std::vector< std::pair< std::string, Regular_Expression* > >& key_regexes, + const Ranges< Index >& ranges, const File_Properties& local_tags_file, + Resource_Manager& rman, std::vector< Id_Type >& result) +{ + if (keys.empty() && key_values.empty() && key_regexes.empty()) + return false; + + std::vector< uint32 > cells; + for (auto it = ranges.begin(); it != ranges.end(); ++it) + { + // Uint31_Index orders by the low 31 bits first, so its ranges are spans of those bits; the + // local tag index files elements under (index & 0x7fffff00) for both kinds of index. + uint32 lower = it.lower_bound().val(); + uint32 upper = it.upper_bound().val() - 1; + if (std::is_same< Index, Uint31_Index >::value) + { + lower &= 0x7fffffff; + upper = it.upper_bound().val() & 0x7fffffff; + } + else if ((lower ^ upper) & 0x80000000) + return false; + if (upper < lower) + return false; + for (uint64 cell = lower & 0x7fffff00; cell <= (upper & 0x7fffff00); cell += 0x100) + { + cells.push_back(cell); + if (cells.size() > 64*1024) + return false; + } + } + std::sort(cells.begin(), cells.end()); + cells.erase(std::unique(cells.begin(), cells.end()), cells.end()); + + Block_Backend< Tag_Index_Local, Id_Type > tags_db(rman.get_transaction()->data_index(&local_tags_file)); + std::vector< std::vector< Id_Type > > per_filter; + auto collect = [&](const std::string& key, const std::string* value, Regular_Expression* value_regex) + { + Ranges< Tag_Index_Local > tag_ranges; + for (auto cell = cells.begin(); cell != cells.end(); ++cell) + { + if (value) + tag_ranges.push_back({ *cell, key, *value }, { *cell, key, *value + std::string(1, '\0') }); + else + tag_ranges.push_back({ *cell, key, "" }, { *cell, key + std::string(1, '\0'), "" }); + } + tag_ranges.sort(); + std::vector< Id_Type > ids; + for (auto it = tags_db.range_begin(tag_ranges); !(it == tags_db.range_end()); ++it) + { + if (it.index().value == void_tag_value()) + continue; + if (value_regex && !value_regex->matches(it.index().value)) + continue; + ids.push_back(it.object()); + } + std::sort(ids.begin(), ids.end()); + ids.erase(std::unique(ids.begin(), ids.end()), ids.end()); + per_filter.push_back(std::move(ids)); + }; + for (auto it = key_values.begin(); it != key_values.end(); ++it) + collect(it->first, &it->second, 0); + for (auto it = keys.begin(); it != keys.end(); ++it) + collect(*it, 0, 0); + for (auto it = key_regexes.begin(); it != key_regexes.end(); ++it) + collect(it->first, 0, it->second); + + std::sort(per_filter.begin(), per_filter.end(), + [](const std::vector< Id_Type >& lhs, const std::vector< Id_Type >& rhs) { return lhs.size() < rhs.size(); }); + result.swap(per_filter.front()); + for (auto it = per_filter.begin() + 1; it != per_filter.end() && !result.empty(); ++it) + { + std::vector< Id_Type > both; + std::set_intersection(result.begin(), result.end(), it->begin(), it->end(), std::back_inserter(both)); + result.swap(both); + } + return true; +} + + void Query_Statement::execute(Resource_Manager& rman) { Cpu_Timer cpu(rman, 1); @@ -950,11 +1202,25 @@ void Query_Statement::execute(Resource_Manager& rman) std::vector< Uint31_Index > way_range_vec_31; std::vector< Uint31_Index > relation_range_vec_31; + // Known before the tag lookup, which drops candidates outside them. + Ranges< Uint32_Index > node_ranges = Ranges< Uint32_Index >::global(); + Ranges< Uint31_Index > way_ranges = Ranges< Uint31_Index >::global(); + Ranges< Uint31_Index > rel_ranges = Ranges< Uint31_Index >::global(); + for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); it != constraints.end(); ++it) + { + if (type & QUERY_NODE) + node_ranges.intersect((*it)->get_node_ranges(rman)).swap(node_ranges); + if (type & QUERY_WAY) + way_ranges.intersect((*it)->get_way_ranges(rman)).swap(way_ranges); + if (type & QUERY_RELATION) + rel_ranges.intersect((*it)->get_relation_ranges(rman)).swap(rel_ranges); + } + if (type & QUERY_NODE) { progress_1< Node_Skeleton, Node::Id_Type, Uint32_Index >( keys, key_values, key_regexes, regkey_regexes, key_nvalues, key_nregexes, regkey_nregexes, - node_ids, range_vec_32, timestamp, check_keys_late, rman, *this); + node_ids, range_vec_32, timestamp, check_keys_late, rman, *this, node_ranges.is_global() ? 0 : &node_ranges); if (node_ids.empty()) node_answer_state = data_collected; collect_nodes(node_ids, node_answer_state, into, rman); @@ -963,7 +1229,7 @@ void Query_Statement::execute(Resource_Manager& rman) { progress_1< Way_Skeleton, Way::Id_Type, Uint31_Index >( keys, key_values, key_regexes, regkey_regexes, key_nvalues, key_nregexes, regkey_nregexes, - way_ids, way_range_vec_31, timestamp, check_keys_late, rman, *this); + way_ids, way_range_vec_31, timestamp, check_keys_late, rman, *this, way_ranges.is_global() ? 0 : &way_ranges); if (way_ids.empty()) way_answer_state = data_collected; collect_elems(QUERY_WAY, way_ids, way_answer_state, into, rman); @@ -974,7 +1240,7 @@ void Query_Statement::execute(Resource_Manager& rman) { progress_1< Relation_Skeleton, Relation::Id_Type, Uint31_Index >( keys, key_values, key_regexes, regkey_regexes, key_nvalues, key_nregexes, regkey_nregexes, - relation_ids, relation_range_vec_31, timestamp, check_keys_late, rman, *this); + relation_ids, relation_range_vec_31, timestamp, check_keys_late, rman, *this, rel_ranges.is_global() ? 0 : &rel_ranges); if (relation_ids.empty()) relation_answer_state = data_collected; collect_elems(QUERY_RELATION, relation_ids, relation_answer_state, into, rman); @@ -1007,47 +1273,17 @@ void Query_Statement::execute(Resource_Manager& rman) rman.health_check(*this); if ((type & QUERY_NODE) && check_keys_late == prefer_ranges) - { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end() && node_answer_state < data_collected; ++it) - { - std::vector< Node::Id_Type > constraint_node_ids; - if ((*it)->get_node_ids(rman, constraint_node_ids)) - { - node_ids.restrict_to(constraint_node_ids); - if (node_ids.empty()) - node_answer_state = data_collected; - } - } - } + restrict_to_constraint_ids< Node::Id_Type >(constraints, rman, + &Query_Constraint::get_node_ids, &Query_Constraint::get_node_ids_within, + node_ids, node_answer_state); if ((type & QUERY_WAY) && check_keys_late == prefer_ranges) - { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end() && way_answer_state < data_collected; ++it) - { - std::vector< Way::Id_Type > constraint_way_ids; - if ((*it)->get_way_ids(rman, constraint_way_ids)) - { - way_ids.restrict_to(constraint_way_ids); - if (way_ids.empty()) - way_answer_state = data_collected; - } - } - } + restrict_to_constraint_ids< Way::Id_Type >(constraints, rman, + &Query_Constraint::get_way_ids, &Query_Constraint::get_way_ids_within, + way_ids, way_answer_state); if ((type & QUERY_RELATION) && check_keys_late == prefer_ranges) - { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end() && relation_answer_state < data_collected; ++it) - { - std::vector< Relation::Id_Type > constraint_relation_ids; - if ((*it)->get_relation_ids(rman, constraint_relation_ids)) - { - relation_ids.restrict_to(constraint_relation_ids); - if (relation_ids.empty()) - relation_answer_state = data_collected; - } - } - } + restrict_to_constraint_ids< Relation::Id_Type >(constraints, rman, + &Query_Constraint::get_relation_ids, &Query_Constraint::get_relation_ids_within, + relation_ids, relation_answer_state); if ((type & QUERY_AREA) && check_keys_late == prefer_ranges) { for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); @@ -1063,36 +1299,58 @@ void Query_Statement::execute(Resource_Manager& rman) } } - Ranges< Uint32_Index > node_ranges = Ranges< Uint32_Index >::global(); - Ranges< Uint31_Index > way_ranges = Ranges< Uint31_Index >::global(); - Ranges< Uint31_Index > rel_ranges = Ranges< Uint31_Index >::global(); - - if ((type & QUERY_NODE) && node_answer_state < data_collected) + // The global tag index gives only each candidate's coarse cell. Their exact indices from the + // id map narrow the blocks to read further, when the map blocks read are fewer than those saved. + if ((type & QUERY_NODE) && node_answer_state < data_collected && !range_vec_32.empty()) { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end(); ++it) - node_ranges.intersect((*it)->get_node_ranges(rman)).swap(node_ranges); - - if (!range_vec_32.empty()) - intersect_ranges(node_ranges, range_vec_32).swap(node_ranges); + intersect_ranges(node_ranges, range_vec_32).swap(node_ranges); + if (timestamp == NOW && !node_ids.invert && exact_indices_pay_off< Uint32_Index, Node_Skeleton >(node_ids.ids, node_ranges, rman)) + node_ranges.intersect(exact_ranges(get_indexes_< Uint32_Index, Node_Skeleton >(node_ids.ids, rman))).swap(node_ranges); } - if ((type & QUERY_WAY) && way_answer_state < data_collected) + if ((type & QUERY_WAY) && way_answer_state < data_collected && !way_range_vec_31.empty()) { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end(); ++it) - way_ranges.intersect((*it)->get_way_ranges(rman)).swap(way_ranges); - - if (!way_range_vec_31.empty()) - intersect_ranges(way_ranges, way_range_vec_31).swap(way_ranges); + intersect_ranges(way_ranges, way_range_vec_31).swap(way_ranges); + if (timestamp == NOW && !way_ids.invert && exact_indices_pay_off< Uint31_Index, Way_Skeleton >(way_ids.ids, way_ranges, rman)) + way_ranges.intersect(exact_ranges(get_indexes_< Uint31_Index, Way_Skeleton >(way_ids.ids, rman))).swap(way_ranges); } - if ((type & QUERY_RELATION) && relation_answer_state < data_collected) + if ((type & QUERY_RELATION) && relation_answer_state < data_collected && !relation_range_vec_31.empty()) { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end(); ++it) - rel_ranges.intersect((*it)->get_relation_ranges(rman)).swap(rel_ranges); + intersect_ranges(rel_ranges, relation_range_vec_31).swap(rel_ranges); + if (timestamp == NOW && !relation_ids.invert && exact_indices_pay_off< Uint31_Index, Relation_Skeleton >(relation_ids.ids, rel_ranges, rman)) + rel_ranges.intersect(exact_ranges(get_indexes_< Uint31_Index, Relation_Skeleton >(relation_ids.ids, rman))).swap(rel_ranges); + } - if (!relation_range_vec_31.empty()) - intersect_ranges(rel_ranges, relation_range_vec_31).swap(rel_ranges); + // Tags checked late over ranges: find the matching ids from the local tag index first, so that + // collection skips the other elements without decoding them. + if (check_keys_late == prefer_ranges && timestamp == NOW) + { + if ((type & QUERY_NODE) && node_answer_state < data_collected && node_ids.invert && node_ids.ids.empty() + && !node_ranges.is_global() + && ids_from_local_tags(keys, key_values, key_regexes, node_ranges, + *osm_base_settings().NODE_TAGS_LOCAL, rman, node_ids.ids)) + { + node_ids.invert = false; + if (node_ids.ids.empty()) + node_answer_state = data_collected; + } + if ((type & QUERY_WAY) && way_answer_state < data_collected && way_ids.invert && way_ids.ids.empty() + && !way_ranges.is_global() + && ids_from_local_tags(keys, key_values, key_regexes, way_ranges, + *osm_base_settings().WAY_TAGS_LOCAL, rman, way_ids.ids)) + { + way_ids.invert = false; + if (way_ids.ids.empty()) + way_answer_state = data_collected; + } + if ((type & QUERY_RELATION) && relation_answer_state < data_collected && relation_ids.invert + && relation_ids.ids.empty() && !rel_ranges.is_global() + && ids_from_local_tags(keys, key_values, key_regexes, rel_ranges, + *osm_base_settings().RELATION_TAGS_LOCAL, rman, relation_ids.ids)) + { + relation_ids.invert = false; + if (relation_ids.ids.empty()) + relation_answer_state = data_collected; + } } set_progress(3); diff --git a/src/overpass_api/statements/query.h b/src/overpass_api/statements/query.h index 9634ccafc..e4047d396 100644 --- a/src/overpass_api/statements/query.h +++ b/src/overpass_api/statements/query.h @@ -83,6 +83,9 @@ class Query_Statement : public Output_Statement static bool area_query_exists() { return area_query_exists_; } + // The query's type and its filters other than tag filters, as QL, e.g. "node(around:100,51.0,7.0)". + std::string block_signature() const; + static std::string to_string(int type) { if (type == QUERY_NODE) diff --git a/src/overpass_api/statements/recurse.cc b/src/overpass_api/statements/recurse.cc index e5d5de1c3..b4fb369a7 100644 --- a/src/overpass_api/statements/recurse.cc +++ b/src/overpass_api/statements/recurse.cc @@ -374,6 +374,11 @@ Timeless< Uint31_Index, Relation_Skeleton > collect_relations current_ids.swap(children_ids); } + // Without input relations no relation can have one as a member: skip the scan of all relations + // (and at a past date, the reconstruction of all their old versions). + if (current_ids.empty()) + return result; + Request_Context context(&stmt, rman); if (!invert_ids) collect_items_flat(context, @@ -422,6 +427,10 @@ Timeless< Uint31_Index, Relation_Skeleton > collect_relations current_ids.swap(children_ids); } + // Without input relations no relation can have one as a member. + if (current_ids.empty()) + return result; + if (!invert_ids) collect_items_flat(context, And_Predicate< Relation_Skeleton, @@ -591,7 +600,7 @@ Ranges< Uint31_Index > Recurse_Constraint::get_way_ranges(Resource_Manager& rman if (stmt->get_type() == RECURSE_RELATION_WAY || stmt->get_type() == RECURSE_RELATION_NWR || stmt->get_type() == RECURSE_RELATION_NW || stmt->get_type() == RECURSE_RELATION_WR) return relation_way_member_indices(input->relations, input->attic_relations); - else if (stmt->get_type() == RECURSE_NODE_WAY) + else if (stmt->get_type() == RECURSE_NODE_WAY || stmt->get_type() == RECURSE_NODE_WR) return extract_parent_indices(input->nodes, input->attic_nodes); return Ranges< Uint31_Index >::global(); @@ -604,7 +613,7 @@ Ranges< Uint31_Index > Recurse_Constraint::get_relation_ranges(Resource_Manager& if (!input) return Ranges< Uint31_Index >(); - if (stmt->get_type() == RECURSE_NODE_RELATION) + if (stmt->get_type() == RECURSE_NODE_RELATION || stmt->get_type() == RECURSE_NODE_WR) return extract_parent_indices(input->nodes, input->attic_nodes); else if (stmt->get_type() == RECURSE_WAY_RELATION) return extract_parent_indices(input->ways, input->attic_ways); @@ -697,7 +706,8 @@ bool Recurse_Constraint::get_data relation_relation_members( context, input->relations, input->attic_relations, ranges, ids, invert_ids, &role_id) .swap(into.relations, into.attic_relations); - else if (stmt->get_type() == RECURSE_NODE_RELATION) + else if (stmt->get_type() == RECURSE_NODE_RELATION + || (stmt->get_type() == RECURSE_NODE_WR && type == QUERY_RELATION)) collect_relations( query, rman, input->nodes, input->attic_nodes, Relation_Entry::NODE, ids, invert_ids, role_id) .swap(into.relations, into.attic_relations); @@ -753,10 +763,12 @@ bool Recurse_Constraint::get_data rel_rels.swap(into.relations, into.attic_relations); } } - else if (stmt->get_type() == RECURSE_NODE_WAY) + else if (stmt->get_type() == RECURSE_NODE_WAY + || (stmt->get_type() == RECURSE_NODE_WR && type == QUERY_WAY)) collect_ways(context, input->nodes, input->attic_nodes, stmt->get_pos(), ids, invert_ids) .swap(into.ways, into.attic_ways); - else if (stmt->get_type() == RECURSE_NODE_RELATION) + else if (stmt->get_type() == RECURSE_NODE_RELATION + || (stmt->get_type() == RECURSE_NODE_WR && type == QUERY_RELATION)) collect_relations(query, rman, input->nodes, input->attic_nodes, Relation_Entry::NODE, ids, invert_ids) .swap(into.relations, into.attic_relations); else if (stmt->get_type() == RECURSE_WAY_RELATION) @@ -923,8 +935,8 @@ void Recurse_Constraint::filter(Resource_Manager& rman, Set& into) .filter_items(Id_Predicate< Way_Skeleton >( relation_way_member_ids(input->relations, input->attic_relations))) .swap(into.ways, into.attic_ways); - else if (stmt->get_type() == RECURSE_NODE_WAY || stmt->get_type() == RECURSE_UP - || stmt->get_type() == RECURSE_UP_REL) + else if (stmt->get_type() == RECURSE_NODE_WAY || stmt->get_type() == RECURSE_NODE_WR + || stmt->get_type() == RECURSE_UP || stmt->get_type() == RECURSE_UP_REL) Timeless< Uint31_Index, Way_Skeleton >{}.swap(into.ways, into.attic_ways) .filter_items(Get_Parent_Ways_Predicate(extract_ids(input->nodes, input->attic_nodes), stmt->get_pos())) .swap(into.ways, into.attic_ways); @@ -937,7 +949,7 @@ void Recurse_Constraint::filter(Resource_Manager& rman, Set& into) .filter_items(Id_Predicate< Relation_Skeleton >( relation_relation_member_ids(input->relations, input->attic_relations))) .swap(into.relations, into.attic_relations); - else if (stmt->get_type() == RECURSE_NODE_RELATION) + else if (stmt->get_type() == RECURSE_NODE_RELATION || stmt->get_type() == RECURSE_NODE_WR) Timeless< Uint31_Index, Relation_Skeleton >{}.swap(into.relations, into.attic_relations) .filter_items(Get_Parent_Rels_Predicate( extract_ids(input->nodes, input->attic_nodes), Relation_Entry::NODE)) @@ -1404,15 +1416,10 @@ void Recurse_Statement::execute(Resource_Manager& rman) source_ways.set_union(result_ways.swap(into.ways, into.attic_ways).sort()); result_ways.swap(into.ways, into.attic_ways); } - Timeless< Uint32_Index, Node_Skeleton > rel_nodes = relation_node_members( - context, into.relations, into.attic_relations, Ranges< Uint32_Index >::global(), {}, true); + // The relations' node members and the ways' nodes, in one pass over the node blocks. + Timeless< Uint32_Index, Node_Skeleton > rel_nodes = relation_and_way_node_members( + context, into.relations, into.attic_relations, source_ways.current, source_ways.attic); rel_nodes.sort(); - { - Timeless< Uint32_Index, Node_Skeleton > more_nodes - = way_members(context, source_ways.current, source_ways.attic, 0, - Ranges< Uint32_Index >::global(), {}, true); - rel_nodes.set_union(more_nodes.sort()); - } keep_matching_skeletons(rel_nodes.current, rel_nodes.attic, rman.get_desired_timestamp()); rel_nodes.swap(into.nodes, into.attic_nodes); } diff --git a/src/overpass_api/statements/statement.h b/src/overpass_api/statements/statement.h index 7f162c781..d6012ce1a 100644 --- a/src/overpass_api/statements/statement.h +++ b/src/overpass_api/statements/statement.h @@ -101,6 +101,22 @@ class Query_Constraint (Resource_Manager& rman, std::vector< Area_Skeleton::Id_Type >& ids) { return false; } + // A constraint whose id lists are expensive to build returns true. Query_Statement then asks + // it after the other constraints, through the get_*_ids_within functions, and passes the ids + // those allow. + virtual bool narrows_by_known_ids() const { return false; } + // Like get_*_ids, but may leave out ids that aren't in known (sorted), since the caller + // intersects the result with known anyway. The defaults ignore known. + virtual bool get_node_ids_within(Resource_Manager& rman, + const std::vector< Node_Skeleton::Id_Type >& known, std::vector< Node_Skeleton::Id_Type >& ids) + { return get_node_ids(rman, ids); } + virtual bool get_way_ids_within(Resource_Manager& rman, + const std::vector< Way_Skeleton::Id_Type >& known, std::vector< Way_Skeleton::Id_Type >& ids) + { return get_way_ids(rman, ids); } + virtual bool get_relation_ids_within(Resource_Manager& rman, + const std::vector< Relation_Skeleton::Id_Type >& known, std::vector< Relation_Skeleton::Id_Type >& ids) + { return get_relation_ids(rman, ids); } + virtual bool get_data(const Statement& query, Resource_Manager& rman, Set& into, const Ranges< Uint32_Index >& ranges, const std::vector< Node::Id_Type >& ids, @@ -120,6 +136,12 @@ class Query_Constraint // to minimize the number of elements that need to be processed. virtual void filter(const Statement& query, Resource_Manager& rman, Set& into) {} + // True if the expensive filter only looks at the elements' metadata, never at + // their geometry. Such filters run before the others: reading metadata costs far + // less than building geometry, so they shrink the set before geometry is built. + virtual bool filter_reads_only_metadata() const { return false; } + virtual bool filter_needs_geometry() const { return false; } + virtual ~Query_Constraint() {} }; diff --git a/src/overpass_api/statements/union.cc b/src/overpass_api/statements/union.cc index 323522429..9d88162b8 100644 --- a/src/overpass_api/statements/union.cc +++ b/src/overpass_api/statements/union.cc @@ -26,6 +26,9 @@ #include "../data/abstract_processing.h" #include "../data/utils.h" +#include "../../template_db/block_cache.h" +#include "../../template_db/transaction.h" +#include "query.h" #include "union.h" @@ -63,8 +66,53 @@ void Union_Statement::add_statement(Statement* statement, std::string text) } +namespace +{ + // Query statements of one type with the same filters apart from tag filters read the same blocks. + bool rereads_expected(const std::vector< Statement* >& substatements) + { + std::map< std::string, int > count; + for (std::vector< Statement* >::const_iterator it = substatements.begin(); it != substatements.end(); ++it) + { + const Query_Statement* query = dynamic_cast< const Query_Statement* >(*it); + if (query && ++count[query->block_signature()] >= 2) + return true; + } + return false; + } + + struct Rereads_Expected_Guard + { + Rereads_Expected_Guard(Resource_Manager& rman, bool active) + { + if (!active) + return; + // A quarter of [maxsize:], outside its accounting like other auxiliary structures. + uint64 limit = rman.get_max_allowed_space() > 0 ? rman.get_max_allowed_space()/4 : 32ull*1024*1024; + Transaction* transactions[] = { rman.get_transaction(), rman.get_area_transaction() }; + for (Transaction* transaction : transactions) + { + Block_Cache* cache = transaction ? transaction->block_cache() : 0; + if (cache) + { + cache->begin_rereads(limit); + caches.push_back(cache); + } + } + } + ~Rereads_Expected_Guard() + { + for (Block_Cache* cache : caches) + cache->end_rereads(); + } + std::vector< Block_Cache* > caches; + }; +} + + void Union_Statement::execute(Resource_Manager& rman) { + Rereads_Expected_Guard guard(rman, rereads_expected(substatements)); rman.push_stack_frame(); rman.move_outward(get_result_name(), get_result_name()); diff --git a/src/overpass_api/statements/user.cc b/src/overpass_api/statements/user.cc index a4fea93b6..e4a21c18c 100644 --- a/src/overpass_api/statements/user.cc +++ b/src/overpass_api/statements/user.cc @@ -48,10 +48,25 @@ class User_Constraint : public Query_Constraint bool get_relation_ids(Resource_Manager& rman, std::vector< Relation_Skeleton::Id_Type >& ids) override; void filter(const Statement& query, Resource_Manager& rman, Set& into) override; + bool filter_reads_only_metadata() const override { return true; } virtual ~User_Constraint() {} private: User_Statement* user; + + // The ids of the objects the users touched depend only on the users, so they are + // the same for the whole query. They are kept after first use and shared by + // get_*_ids and filter, which otherwise each read all of the users' metadata. + bool node_ids_known = false; + bool way_ids_known = false; + bool relation_ids_known = false; + std::vector< Node_Skeleton::Id_Type > touched_node_ids; + std::vector< Way_Skeleton::Id_Type > touched_way_ids; + std::vector< Relation_Skeleton::Id_Type > touched_relation_ids; + + const std::vector< Node_Skeleton::Id_Type >& touched_nodes(Resource_Manager& rman); + const std::vector< Way_Skeleton::Id_Type >& touched_ways(Resource_Manager& rman); + const std::vector< Relation_Skeleton::Id_Type >& touched_relations(Resource_Manager& rman); }; @@ -186,31 +201,6 @@ void calc_ranges_31 } -void calc_ranges_both - (Ranges< Uint32_Index >& node_req, Ranges< Uint31_Index >& other_req, - const std::set< Uint32_Index >& user_ids, Transaction& transaction) -{ - - Block_Backend< Uint32_Index, Uint31_Index, std::set< Uint32_Index >::const_iterator > user_db - (transaction.data_index(meta_settings().USER_INDICES)); - for (auto user_it = user_db.discrete_begin(user_ids.begin(), user_ids.end()); - !(user_it == user_db.discrete_end()); ++user_it) - { - if ((user_it.object().val() & 0x80000000) == 0) - { - node_req.push_back(Uint32_Index(user_it.object().val()), Uint32_Index(user_it.object().val() + 0x100)); - other_req.push_back(Uint31_Index(user_it.object().val()), Uint31_Index(user_it.object().val() + 0x100)); - } - else if ((user_it.object().val() & 0xff) == 0) - other_req.push_back(Uint31_Index(user_it.object().val()), Uint31_Index(user_it.object().val() + 0x100)); - else - other_req.push_back(Uint31_Index(user_it.object().val()), Uint31_Index(user_it.object().val() + 1)); - } - node_req.sort(); - other_req.sort(); -} - - void User_Constraint::filter(const Statement& query, Resource_Manager& rman, Set& into) { std::set< Uint32_Index > user_ids = user->get_ids(*rman.get_transaction()); @@ -235,24 +225,17 @@ void User_Constraint::filter(const Statement& query, Resource_Manager& rman, Set } else { - Ranges< Uint32_Index > node_ranges; - Ranges< Uint31_Index > other_ranges; - calc_ranges_both(node_ranges, other_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); - if (!into.nodes.empty() || !into.attic_nodes.empty()) Timeless< Uint32_Index, Node_Skeleton >{ into.nodes, into.attic_nodes }.filter_by_id( - touched_ids_by_users< Uint32_Index, Node_Skeleton >( - rman, node_ranges, user->get_ids(*rman.get_transaction()))) + touched_nodes(rman)) .swap(into.nodes, into.attic_nodes); if (!into.ways.empty() || !into.attic_ways.empty()) Timeless< Uint31_Index, Way_Skeleton >{ into.ways, into.attic_ways }.filter_by_id( - touched_ids_by_users< Uint31_Index, Way_Skeleton >( - rman, other_ranges, user->get_ids(*rman.get_transaction()))) + touched_ways(rman)) .swap(into.ways, into.attic_ways); if (!into.relations.empty() || !into.attic_relations.empty()) Timeless< Uint31_Index, Relation_Skeleton >{ into.relations, into.attic_relations }.filter_by_id( - touched_ids_by_users< Uint31_Index, Relation_Skeleton >( - rman, other_ranges, user->get_ids(*rman.get_transaction()))) + touched_relations(rman)) .swap(into.relations, into.attic_relations); } @@ -434,15 +417,53 @@ bool User_Constraint::get_ranges(Resource_Manager& rman, Ranges< Uint31_Index >& } -bool User_Constraint::get_node_ids(Resource_Manager& rman, std::vector< Node_Skeleton::Id_Type >& ids) +const std::vector< Node_Skeleton::Id_Type >& User_Constraint::touched_nodes(Resource_Manager& rman) { - if (user->get_criterion() == User_Statement::touched) + if (!node_ids_known) { Ranges< Uint32_Index > node_ranges; calc_ranges_32(node_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); + touched_node_ids = touched_ids_by_users< Uint32_Index, Node_Skeleton >( + rman, node_ranges, user->get_ids(*rman.get_transaction())); + node_ids_known = true; + } + return touched_node_ids; +} - touched_ids_by_users< Uint32_Index, Node_Skeleton >( - rman, node_ranges, user->get_ids(*rman.get_transaction())).swap(ids); + +const std::vector< Way_Skeleton::Id_Type >& User_Constraint::touched_ways(Resource_Manager& rman) +{ + if (!way_ids_known) + { + Ranges< Uint31_Index > other_ranges; + calc_ranges_31(other_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); + touched_way_ids = touched_ids_by_users< Uint31_Index, Way_Skeleton >( + rman, other_ranges, user->get_ids(*rman.get_transaction())); + way_ids_known = true; + } + return touched_way_ids; +} + + +const std::vector< Relation_Skeleton::Id_Type >& User_Constraint::touched_relations(Resource_Manager& rman) +{ + if (!relation_ids_known) + { + Ranges< Uint31_Index > other_ranges; + calc_ranges_31(other_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); + touched_relation_ids = touched_ids_by_users< Uint31_Index, Relation_Skeleton >( + rman, other_ranges, user->get_ids(*rman.get_transaction())); + relation_ids_known = true; + } + return touched_relation_ids; +} + + +bool User_Constraint::get_node_ids(Resource_Manager& rman, std::vector< Node_Skeleton::Id_Type >& ids) +{ + if (user->get_criterion() == User_Statement::touched) + { + ids = touched_nodes(rman); return true; } return false; @@ -453,11 +474,7 @@ bool User_Constraint::get_way_ids(Resource_Manager& rman, std::vector< Way_Skele { if (user->get_criterion() == User_Statement::touched) { - Ranges< Uint31_Index > other_ranges; - calc_ranges_31(other_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); - - touched_ids_by_users< Uint31_Index, Way_Skeleton >( - rman, other_ranges, user->get_ids(*rman.get_transaction())).swap(ids); + ids = touched_ways(rman); return true; } return false; @@ -468,11 +485,7 @@ bool User_Constraint::get_relation_ids(Resource_Manager& rman, std::vector< Rela { if (user->get_criterion() == User_Statement::touched) { - Ranges< Uint31_Index > other_ranges; - calc_ranges_31(other_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); - - touched_ids_by_users< Uint31_Index, Relation_Skeleton >( - rman, other_ranges, user->get_ids(*rman.get_transaction())).swap(ids); + ids = touched_relations(rman); return true; } return false; diff --git a/src/template_db/block_backend.h b/src/template_db/block_backend.h index 910ebbce0..0c982dafd 100644 --- a/src/template_db/block_backend.h +++ b/src/template_db/block_backend.h @@ -25,6 +25,8 @@ #include #include +#include +#include #include @@ -35,18 +37,17 @@ struct Idx_Handle : obj(0), ptr_to_raw(0) {} ~Idx_Handle() { - delete obj; + clear(); } void set_ptr(uint8* ptr) { - delete obj; - obj = 0; + clear(); ptr_to_raw = ptr; } const Object& object() const { if (!obj) - obj = new Object(ptr_to_raw); + obj = new (&storage) Object(ptr_to_raw); return *obj; } uint8* get_ptr_to_raw() const @@ -59,9 +60,18 @@ struct Idx_Handle Idx_Handle& operator=(const Idx_Handle& rhs) { set_ptr(rhs.ptr_to_raw); + return *this; } private: + void clear() + { + if (obj) + obj->~Object(); + obj = 0; + } + + mutable typename std::aligned_storage< sizeof(Object), alignof(Object) >::type storage; mutable Object* obj; uint8* ptr_to_raw; }; @@ -94,6 +104,10 @@ struct Block_Backend_Basic_Iterator { return idx_cache.object(); } + uint8* index_raw() const + { + return idx_cache.get_ptr_to_raw(); + } const Object& object() { return obj_cache.object(); @@ -331,10 +345,9 @@ struct Discrete_Idx_Assessor bool is_relevant(uint8* ptr) { - Index idx((void*)ptr); - while (index_it != index_end && *index_it < idx) + while (index_it != index_end && index_it->less((void*)ptr)) ++index_it; - return index_it != index_end && *index_it == idx; + return index_it != index_end && index_it->leq((void*)ptr); } private: @@ -406,10 +419,10 @@ struct Range_Idx_Assessor bool is_relevant(uint8* ptr) { - Index idx((void*)ptr); - while (index_it != index_end && !(idx < index_it.upper_bound())) + // bound.leq(ptr) is !(idx < bound) for the index stored at ptr. + while (index_it != index_end && index_it.upper_bound().leq((void*)ptr)) ++index_it; - return index_it != index_end && !(idx < index_it.lower_bound()) && idx < index_it.upper_bound(); + return index_it != index_end && index_it.lower_bound().leq((void*)ptr); } private: @@ -518,6 +531,16 @@ struct Block_Backend Range_Iterator range_begin(const Ranges< TIndex >& arg) { return Range_Iterator(file_blocks, arg.begin(), arg.end(), block_size); } + // From the block index alone: nothing is read or decompressed. + uint64 count_blocks(const Ranges< TIndex >& arg) + { + uint64 count = 0; + auto end = file_blocks.template range_end< typename Ranges< TIndex >::Iterator >(); + for (auto it = file_blocks.range_begin(arg.begin(), arg.end()); !(it == end); ++it) + ++count; + return count; + } + const Range_Iterator& range_end() const { return *range_end_it; } template< typename Container > diff --git a/src/template_db/block_cache.h b/src/template_db/block_cache.h new file mode 100644 index 000000000..43c92e886 --- /dev/null +++ b/src/template_db/block_cache.h @@ -0,0 +1,79 @@ +/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. + * + * This file is part of Overpass_API. + * + * Overpass_API is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * Overpass_API is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Overpass_API. If not, see . + */ + +#ifndef DE__OSM3S___TEMPLATE_DB__BLOCK_CACHE_H +#define DE__OSM3S___TEMPLATE_DB__BLOCK_CACHE_H + +#include "types.h" + +#include +#include +#include + + +// Decompressed blocks of a transaction's read-only files, kept while a statement runs that will +// re-read them. Nothing is evicted; once limit bytes are kept, further blocks are not. +class Block_Cache +{ +public: + Block_Cache() : rereads_expected(0), bytes(0), limit(0) {} + + void begin_rereads(uint64 limit_) + { + if (rereads_expected == 0 || limit_ < limit) + limit = limit_; + ++rereads_expected; + } + void end_rereads() { --rereads_expected; } + + const std::vector< uint8 >* find(const void* file, uint32 pos) const + { + if (blocks.empty()) + return 0; + std::map< std::pair< const void*, uint32 >, std::vector< uint8 > >::const_iterator it + = blocks.find(std::make_pair(file, pos)); + return it == blocks.end() ? 0 : &it->second; + } + + void offer(const void* file, uint32 pos, const uint8* data, uint64 size) + { + if (rereads_expected > 0 && bytes + size <= limit) + { + blocks[std::make_pair(file, pos)].assign(data, data + size); + bytes += size; + } + } + + void clear() + { + blocks.clear(); + bytes = 0; + } + +private: + Block_Cache(const Block_Cache&); + Block_Cache& operator=(const Block_Cache&); + + int rereads_expected; + uint64 bytes; + uint64 limit; + std::map< std::pair< const void*, uint32 >, std::vector< uint8 > > blocks; +}; + + +#endif diff --git a/src/template_db/file_blocks.h b/src/template_db/file_blocks.h index b214b52f0..07308f38f 100644 --- a/src/template_db/file_blocks.h +++ b/src/template_db/file_blocks.h @@ -19,6 +19,7 @@ #ifndef DE__OSM3S___TEMPLATE_DB__FILE_BLOCKS_H #define DE__OSM3S___TEMPLATE_DB__FILE_BLOCKS_H +#include "block_cache.h" #include "file_blocks_index.h" #include "types.h" #include "lz4_wrapper.h" @@ -818,6 +819,21 @@ uint64* File_Blocks< TIndex, TIterator >::read_block_ if (sigterm_status()) throw File_Error(0, "-", "SIGTERM received"); + // Blocks read without the index check continue a large object and don't start with their size. + Block_Cache* cache = rd_idx && check_idx && compression_method != File_Blocks_Index_Base::NO_COMPRESSION + ? rd_idx->block_cache : 0; + if (cache) + { + const std::vector< uint8 >* cached = cache->find(rd_idx, block.pos()); + if (cached) + { + memcpy(buffer_, &(*cached)[0], cached->size()); + ++read_count_; + ++global_read_counter(); + return buffer_; + } + } + if (compression_method == File_Blocks_Index_Base::NO_COMPRESSION) { data_file.seek((int64)(block.pos()) * block_size, "File_Blocks::read_block::1"); @@ -871,6 +887,10 @@ uint64* File_Blocks< TIndex, TIterator >::read_block_ out<<"File_Blocks::read_block: Index inconsistent at offset "<<((int64)(block.pos()) * block_size + 8); throw File_Error(block.pos(), rd_idx ? rd_idx->get_data_file_name() : wr_idx->get_data_file_name(), out.str()); } + if (cache) + // Readers stop at the block's used size, its first word; keep only those bytes. + cache->offer(rd_idx, block.pos(), (const uint8*)buffer_, + std::min< uint64 >(std::max< uint32 >(*(uint32*)buffer_, 8), (uint64)block_size * compression_factor)); ++read_count_; ++global_read_counter(); return buffer_; diff --git a/src/template_db/transaction.h b/src/template_db/transaction.h index c9931e03e..01c5b280a 100644 --- a/src/template_db/transaction.h +++ b/src/template_db/transaction.h @@ -19,6 +19,7 @@ #ifndef DE__OSM3S___TEMPLATE_DB__TRANSACTION_H #define DE__OSM3S___TEMPLATE_DB__TRANSACTION_H +#include "block_cache.h" #include "random_file.h" #include @@ -34,6 +35,7 @@ class Transaction virtual File_Blocks_Index_Base* data_index(const File_Properties*) = 0; virtual Random_File_Index* random_index(const File_Properties*) = 0; virtual std::string get_db_dir() const = 0; + virtual Block_Cache* block_cache() { return 0; } }; @@ -49,6 +51,7 @@ class Nonsynced_Transaction : public Transaction void flush(); std::string get_db_dir() const { return db_dir; } + Block_Cache* block_cache() { return &block_cache_; } private: std::map< const File_Properties*, File_Blocks_Index_Base* > @@ -58,6 +61,7 @@ class Nonsynced_Transaction : public Transaction Access_Mode access_mode; bool use_shadow; std::string file_name_extension, db_dir; + Block_Cache block_cache_; }; @@ -89,6 +93,13 @@ inline void Nonsynced_Transaction::flush() it = random_files.begin(); it != random_files.end(); ++it) delete it->second; random_files.clear(); + block_cache_.clear(); +} + + +inline bool ends_with(const std::string& s, const std::string& suffix) +{ + return s.size() >= suffix.size() && s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0; } @@ -102,7 +113,13 @@ inline File_Blocks_Index_Base* Nonsynced_Transaction::data_index File_Blocks_Index_Base* data_index = fp->new_data_index(access_mode, use_shadow, db_dir, file_name_extension); if (data_index != 0) + { + // Statements of a union read the same skeleton and local tag blocks, but look up different + // tags in the global tag index, so its blocks are rarely read again: don't cache them. + if (access_mode == Access_Mode::readonly && !ends_with(fp->get_file_name_trunk(), "_tags_global")) + data_index->block_cache = &block_cache_; data_files[fp] = data_index; + } return data_index; } diff --git a/src/template_db/types.h b/src/template_db/types.h index 969a6d815..4118f8910 100644 --- a/src/template_db/types.h +++ b/src/template_db/types.h @@ -71,8 +71,13 @@ struct File_Properties_Exception }; +class Block_Cache; + + struct File_Blocks_Index_Base { + File_Blocks_Index_Base() : block_cache(0) {} + virtual bool empty() const = 0; virtual ~File_Blocks_Index_Base() {} @@ -88,6 +93,9 @@ struct File_Blocks_Index_Base static const int ZLIB_COMPRESSION = 1; static const int LZ4_COMPRESSION = 2; static const unsigned int IDX_HEADER_LENGTH = 8; + + // Set by the transaction for read-only files. + Block_Cache* block_cache; };