001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.osm;
003
004import java.util.ArrayList;
005import java.util.Arrays;
006import java.util.Collection;
007import java.util.Iterator;
008import java.util.LinkedHashSet;
009import java.util.List;
010import java.util.NoSuchElementException;
011import java.util.stream.IntStream;
012
013import org.openstreetmap.josm.data.IQuadBucketType;
014import org.openstreetmap.josm.data.coor.ILatLon;
015import org.openstreetmap.josm.data.coor.LatLon;
016import org.openstreetmap.josm.data.coor.QuadTiling;
017import org.openstreetmap.josm.tools.Logging;
018import org.openstreetmap.josm.tools.Utils;
019
020/**
021 * Note: bbox of primitives added to QuadBuckets has to stay the same. In case of coordinate change, primitive must
022 * be removed and re-added.
023 *
024 * This class is (no longer) thread safe.
025 * @param <T> type of object extending {@link IQuadBucketType}.
026 * @since 2165 ({@link IPrimitive} only), 17459 for {@link IQuadBucketType}
027 */
028public class QuadBuckets<T extends IQuadBucketType> implements Collection<T> {
029    private static final boolean CONSISTENCY_TESTING = false;
030    private static final byte NW_INDEX = 1;
031    private static final byte NE_INDEX = 3;
032    private static final byte SE_INDEX = 2;
033    private static final byte SW_INDEX = 0;
034
035    static void abort(String s) {
036        throw new AssertionError(s);
037    }
038
039    private static final int MAX_OBJECTS_PER_NODE = 48;
040
041    static class QBLevel<T extends IQuadBucketType> extends BBox {
042        private final byte level;
043        private final byte index;
044        private final long quad;
045        private final QBLevel<T> parent;
046        private boolean isLeaf = true;
047
048        private List<T> content;
049        // child order by index is sw, nw, se, ne
050        private QBLevel<T> nw, ne, sw, se;
051
052        private QBLevel<T> getChild(byte index) {
053            switch (index) {
054            case NE_INDEX:
055                if (ne == null) {
056                    ne = new QBLevel<>(this, index);
057                }
058                return ne;
059            case NW_INDEX:
060                if (nw == null) {
061                    nw = new QBLevel<>(this, index);
062                }
063                return nw;
064            case SE_INDEX:
065                if (se == null) {
066                    se = new QBLevel<>(this, index);
067                }
068                return se;
069            case SW_INDEX:
070                if (sw == null) {
071                    sw = new QBLevel<>(this, index);
072                }
073                return sw;
074            default:
075                return null;
076            }
077        }
078
079        @SuppressWarnings("unchecked")
080        private QBLevel<T>[] getChildren() {
081            return new QBLevel[] {sw, nw, se, ne};
082        }
083
084        @Override
085        public String toString() {
086            return super.toString() + '[' + level + "]: ";
087        }
088
089        /**
090         * Constructor for root node
091         */
092        QBLevel() {
093            super(-180, 90, 180, -90);
094            level = 0;
095            index = 0;
096            quad = 0;
097            parent = null;
098        }
099
100        QBLevel(QBLevel<T> parent, byte index) {
101            this.parent = parent;
102            this.level = (byte) (parent.level + 1);
103            this.index = index;
104
105            int shift = (QuadTiling.NR_LEVELS - level) * 2;
106            long quadpart = (long) index << shift;
107            this.quad = parent.quad | quadpart;
108            LatLon bottomLeft = QuadTiling.tile2LatLon(this.quad);
109            xmin = bottomLeft.lon();
110            ymin = bottomLeft.lat();
111            xmax = xmin + parent.width() / 2;
112            ymax = ymin + parent.height() / 2;
113        }
114
115        QBLevel<T> findBucket(BBox bbox) {
116            if (!hasChildren())
117                return this;
118            else {
119                byte idx = bbox.getIndex(level);
120                if (idx == -1)
121                    return this;
122                QBLevel<T> child = getChild(idx);
123                if (child == null)
124                    return this;
125                return child.findBucket(bbox);
126            }
127        }
128
129        boolean removeContent(T o) {
130            // If two threads try to remove item at the same time from different buckets of this QBLevel,
131            // it might happen that one thread removes bucket but don't remove parent because it still sees
132            // another bucket set. Second thread do the same. Due to thread memory caching, it's possible that
133            // changes made by threads will show up in children array too late, leading to QBLevel with all children
134            // set to null
135            if (content == null)
136                return false;
137            boolean ret = this.content.remove(o);
138            if (this.content.isEmpty()) {
139                this.content = null;
140            }
141            if (this.canRemove()) {
142                this.removeFromParent();
143            }
144            return ret;
145        }
146
147        /*
148         * There is a race between this and qb.nextContentNode().
149         * If nextContentNode() runs into this bucket, it may attempt to null out 'children' because it thinks this is a dead end.
150         */
151        void doSplit() {
152            List<T> tmpcontent = content;
153            content = null;
154
155            for (T o : tmpcontent) {
156                byte idx = o.getBBox().getIndex(level);
157                if (idx == -1) {
158                    doAddContent(o);
159                } else {
160                    QBLevel<T> child = getChild(idx);
161                    if (child != null)
162                        child.doAdd(o);
163                }
164            }
165            isLeaf = false; // It's not enough to check children because all items could end up in this level (index == -1)
166        }
167
168        boolean doAddContent(T o) {
169            // The split_lock will keep two concurrent calls from overwriting content
170            if (content == null) {
171                content = new ArrayList<>();
172            }
173            return content.add(o);
174        }
175
176        boolean matches(final T o, final BBox searchBbox) {
177            // Avoid allocations for point (AKA Node) objects
178            if (o instanceof ILatLon) {
179                return searchBbox.contains((ILatLon) o);
180            }
181            return o.getBBox().intersects(searchBbox);
182        }
183
184        private void searchContents(BBox searchBbox, List<T> result) {
185            /*
186             * It is possible that this was created in a split
187             * but never got any content populated.
188             */
189            if (content == null)
190                return;
191
192            for (T o : content) {
193                if (matches(o, searchBbox)) {
194                    result.add(o);
195                }
196            }
197        }
198
199        /*
200         * This is stupid. I tried to have a QBLeaf and QBBranch
201         * class descending from a QBLevel. It's more than twice
202         * as slow. So, this throws OO out the window, but it
203         * is fast. Runtime type determination must be slow.
204         */
205        boolean isLeaf() {
206            return isLeaf;
207        }
208
209        boolean hasChildren() {
210            return nw != null || ne != null || sw != null || se != null;
211        }
212
213        QBLevel<T> findNextSibling() {
214            return (parent == null) ? null : parent.firstSiblingOf(this);
215        }
216
217        boolean hasContent() {
218            return content != null;
219        }
220
221        QBLevel<T> nextSibling() {
222            QBLevel<T> next = this;
223            QBLevel<T> sibling = next.findNextSibling();
224            // Walk back up the tree to find the next sibling node.
225            // It may be either a leaf or branch.
226            while (sibling == null) {
227                next = next.parent;
228                if (next == null) {
229                    break;
230                }
231                sibling = next.findNextSibling();
232            }
233            return sibling;
234        }
235
236        QBLevel<T> firstChild() {
237            if (sw != null)
238                return sw;
239            if (nw != null)
240                return nw;
241            if (se != null)
242                return se;
243            return ne;
244        }
245
246        QBLevel<T> firstSiblingOf(final QBLevel<T> child) {
247            switch (child.index) {
248            case SW_INDEX:
249                if (nw != null)
250                    return nw;
251                if (se != null)
252                    return se;
253                return ne;
254            case NW_INDEX:
255                if (se != null)
256                    return se;
257                return ne;
258            case SE_INDEX:
259                return ne;
260            default:
261                return null;
262            }
263        }
264
265        QBLevel<T> nextNode() {
266            if (!this.hasChildren())
267                return this.nextSibling();
268            return this.firstChild();
269        }
270
271        QBLevel<T> nextContentNode() {
272            QBLevel<T> next = this.nextNode();
273            if (next == null)
274                return next;
275            if (next.hasContent())
276                return next;
277            return next.nextContentNode();
278        }
279
280        void doAdd(T o) {
281            if (CONSISTENCY_TESTING) {
282                if (o instanceof Node && !matches(o, this)) {
283                    o.getBBox().getIndex(level);
284                    o.getBBox().getIndex(level - 1);
285                    abort("\nobject " + o + " does not belong in node at level: " + level + " bbox: " + super.toString());
286                }
287            }
288            doAddContent(o);
289            if (level < QuadTiling.NR_LEVELS && isLeaf() && content.size() > MAX_OBJECTS_PER_NODE) {
290                doSplit();
291            }
292        }
293
294        void add(T o) {
295            findBucket(o.getBBox()).doAdd(o);
296        }
297
298        private void search(QuadBuckets<T> buckets, BBox searchBbox, List<T> result) {
299            if (!this.intersects(searchBbox))
300                return;
301            else if (this.bounds(searchBbox)) {
302                buckets.searchCache = this;
303            }
304
305            if (this.hasContent()) {
306                searchContents(searchBbox, result);
307            }
308
309            //TODO Coincidence vector should be calculated here and only buckets that match search_bbox should be checked
310
311            if (nw != null) {
312                nw.search(buckets, searchBbox, result);
313            }
314            if (ne != null) {
315                ne.search(buckets, searchBbox, result);
316            }
317            if (se != null) {
318                se.search(buckets, searchBbox, result);
319            }
320            if (sw != null) {
321                sw.search(buckets, searchBbox, result);
322            }
323        }
324
325        public String quads() {
326            return Long.toHexString(quad);
327        }
328
329        int indexOf(QBLevel<T> findThis) {
330            QBLevel<T>[] children = getChildren();
331            return IntStream.range(0, QuadTiling.TILES_PER_LEVEL)
332                    .filter(i -> children[i] == findThis)
333                    .findFirst().orElse(-1);
334        }
335
336        void removeFromParent() {
337            if (parent == null)
338                return;
339
340            if (!canRemove()) {
341                abort("attempt to remove non-empty child: " + this.content + ' ' + Arrays.toString(this.getChildren()));
342            }
343
344            if (parent.nw == this) {
345                parent.nw = null;
346            } else if (parent.ne == this) {
347                parent.ne = null;
348            } else if (parent.sw == this) {
349                parent.sw = null;
350            } else if (parent.se == this) {
351                parent.se = null;
352            }
353
354            if (parent.canRemove()) {
355                parent.removeFromParent();
356            }
357        }
358
359        boolean canRemove() {
360            return Utils.isEmpty(content) && !this.hasChildren();
361        }
362    }
363
364    private QBLevel<T> root;
365    private QBLevel<T> searchCache;
366    private int size;
367    private Collection<T> invalidBBoxPrimitives;
368
369    /**
370     * Constructs a new {@code QuadBuckets}.
371     */
372    public QuadBuckets() {
373        clear();
374    }
375
376    @Override
377    public final void clear() {
378        root = new QBLevel<>();
379        invalidBBoxPrimitives = new LinkedHashSet<>();
380        searchCache = null;
381        size = 0;
382    }
383
384    @Override
385    public boolean add(T n) {
386        if (n.getBBox().isValid()) {
387            root.add(n);
388        } else {
389            invalidBBoxPrimitives.add(n);
390        }
391        size++;
392        return true;
393    }
394
395    @Override
396    @SuppressWarnings("ModifyCollectionInEnhancedForLoop")
397    public boolean retainAll(Collection<?> objects) {
398        for (T o : this) {
399            if (objects.contains(o)) {
400                continue;
401            }
402            // In theory this could cause a ConcurrentModificationException
403            // but we never had such bug report in 8 years (since r2263)
404            if (!this.remove(o)) {
405                return false;
406            }
407        }
408        return true;
409    }
410
411    @Override
412    public boolean removeAll(Collection<?> objects) {
413        return objects.stream().map(this::remove).reduce(false, (a, b) -> a || b);
414    }
415
416    @Override
417    public boolean addAll(Collection<? extends T> objects) {
418        return objects.stream().map(this::add).reduce(false, (a, b) -> a || b);
419    }
420
421    @Override
422    public boolean containsAll(Collection<?> objects) {
423        return objects.stream().allMatch(this::contains);
424    }
425
426    @Override
427    public boolean remove(Object o) {
428        @SuppressWarnings("unchecked")
429        T t = (T) o;
430        searchCache = null; // Search cache might point to one of removed buckets
431        QBLevel<T> bucket = root.findBucket(t.getBBox());
432        boolean removed = bucket.removeContent(t);
433        if (!removed) {
434            removed = invalidBBoxPrimitives.remove(o);
435        }
436        if (removed) {
437            size--;
438        }
439        return removed;
440    }
441
442    @Override
443    public boolean contains(Object o) {
444        @SuppressWarnings("unchecked")
445        T t = (T) o;
446        if (!t.getBBox().isValid()) {
447            return invalidBBoxPrimitives.contains(o);
448        }
449        QBLevel<T> bucket = root.findBucket(t.getBBox());
450        return bucket != null && bucket.content != null && bucket.content.contains(t);
451    }
452
453    /**
454     * Converts to list.
455     * @return elements as list
456     */
457    public List<T> toList() {
458        return new ArrayList<>(this);
459    }
460
461    @Override
462    public Object[] toArray() {
463        // Don't call toList() -- in some cases, this can produce an infinite loop
464        // For example, ArrayList may call toArray to get the initial array. However, since we are
465        // creating a new ArrayList in toList with `this`, this creates an infinite recursion loop.
466        // So a `toArray` call becomes `toArray -> toList -> toArray -> toList -> toArray -> ...`
467        // For more information, see #20587.
468        return this.stream().toArray();
469    }
470
471    @Override
472    public <A> A[] toArray(A[] template) {
473        return this.toList().toArray(template);
474    }
475
476    class QuadBucketIterator implements Iterator<T> {
477        private QBLevel<T> currentNode;
478        private int contentIndex;
479        private final Iterator<T> invalidBBoxIterator = invalidBBoxPrimitives.iterator();
480        boolean fromInvalidBBoxPrimitives;
481        QuadBuckets<T> qb;
482
483        final QBLevel<T> nextContentNode(QBLevel<T> q) {
484            if (q == null)
485                return null;
486            QBLevel<T> orig = q;
487            QBLevel<T> next;
488            next = q.nextContentNode();
489            if (orig == next) {
490                abort("got same leaf back leaf: " + q.isLeaf());
491            }
492            return next;
493        }
494
495        QuadBucketIterator(QuadBuckets<T> qb) {
496            if (!qb.root.hasChildren() || qb.root.hasContent()) {
497                currentNode = qb.root;
498            } else {
499                currentNode = nextContentNode(qb.root);
500            }
501            this.qb = qb;
502        }
503
504        @Override
505        public boolean hasNext() {
506            if (this.peek() == null) {
507                fromInvalidBBoxPrimitives = true;
508                return invalidBBoxIterator.hasNext();
509            }
510            return true;
511        }
512
513        T peek() {
514            if (currentNode == null)
515                return null;
516            while ((currentNode.content == null) || (contentIndex >= currentNode.content.size())) {
517                contentIndex = 0;
518                currentNode = nextContentNode(currentNode);
519                if (currentNode == null) {
520                    break;
521                }
522            }
523            if (currentNode == null || currentNode.content == null)
524                return null;
525            return currentNode.content.get(contentIndex);
526        }
527
528        @Override
529        public T next() {
530            if (fromInvalidBBoxPrimitives) {
531                return invalidBBoxIterator.next();
532            }
533            T ret = peek();
534            if (ret == null)
535                throw new NoSuchElementException();
536            contentIndex++;
537            return ret;
538        }
539
540        @Override
541        public void remove() {
542            if (fromInvalidBBoxPrimitives) {
543                invalidBBoxIterator.remove();
544                qb.size--;
545            } else {
546                // two uses
547                // 1. Back up to the thing we just returned
548                // 2. move the index back since we removed
549                //    an element
550                contentIndex--;
551                T object = peek();
552                if (currentNode.removeContent(object))
553                    qb.size--;
554
555            }
556        }
557    }
558
559    @Override
560    public Iterator<T> iterator() {
561        return new QuadBucketIterator(this);
562    }
563
564    @Override
565    public int size() {
566        return size;
567    }
568
569    @Override
570    public boolean isEmpty() {
571        return size == 0;
572    }
573
574    /**
575     * Search the tree for objects in the bbox (or crossing the bbox if they are ways)
576     * @param searchBbox the bbox
577     * @return List of primitives within the bbox (or crossing the bbox if they are ways). Can be empty, but not null.
578     */
579    public List<T> search(BBox searchBbox) {
580        List<T> ret = new ArrayList<>();
581        if (searchBbox == null || !searchBbox.isValid()) {
582            return ret;
583        }
584
585        // Doing this cuts down search cost on a real-life data set by about 25%
586        if (searchCache == null) {
587            searchCache = root;
588        }
589        // Walk back up the tree when the last search spot can not cover the current search
590        while (searchCache != null && !searchCache.bounds(searchBbox)) {
591            searchCache = searchCache.parent;
592        }
593
594        if (searchCache == null) {
595            searchCache = root;
596            Logging.info("bbox: " + searchBbox + " is out of the world");
597        }
598
599        // Save parent because searchCache might change during search call
600        QBLevel<T> tmp = searchCache.parent;
601
602        searchCache.search(this, searchBbox, ret);
603
604        // A way that spans this bucket may be stored in one
605        // of the nodes which is a parent of the search cache
606        while (tmp != null) {
607            tmp.searchContents(searchBbox, ret);
608            tmp = tmp.parent;
609        }
610        return ret;
611    }
612}