001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import org.openstreetmap.josm.data.coor.LatLon;
005import org.openstreetmap.josm.data.osm.BBox;
006
007/**
008 * Fast index to look up properties of the earth surface.
009 *
010 * It is expected that there is a relatively slow method to look up the property
011 * for a certain coordinate and that there are larger areas with a uniform
012 * property.
013 *
014 * This index tries to find rectangles with uniform property and caches them.
015 * Rectangles are subdivided, if there are different properties within.
016 * (Up to a maximum level, when the slow method is used again.)
017 *
018 * @param <T> the property (like land/water or nation)
019 */
020public class GeoPropertyIndex<T> {
021
022    private final int maxLevel;
023    private final GeoProperty<T> geoProp;
024    private final GPLevel<T> root;
025    private GPLevel<T> lastLevelUsed;
026
027    private static final boolean DEBUG = false;
028
029    /**
030     * Create new GeoPropertyIndex.
031     * @param geoProp the input property that should be made faster by this index
032     * @param maxLevel max level
033     */
034    public GeoPropertyIndex(GeoProperty<T> geoProp, int maxLevel) {
035        this.geoProp = geoProp;
036        this.maxLevel = maxLevel;
037        this.root = new GPLevel<>(0, new BBox(-180, -90, 180, 90), null, this);
038        this.lastLevelUsed = root;
039    }
040
041    /**
042     * Look up the property for a certain point.
043     * This gives the same result as {@link GeoProperty#get(LatLon)}, but
044     * should be faster.
045     * @param ll the point coordinates
046     * @return property value at that point
047     */
048    public T get(LatLon ll) {
049        return lastLevelUsed.get(ll);
050    }
051
052    /**
053     * Gets the index of the given coordinate. Only used internally
054     * @param ll The lat/lon coordinate
055     * @param level The scale level
056     * @return The index for that position
057     */
058    public static int index(LatLon ll, int level) {
059        long noParts = 1L << level;
060        long x = ((long) ((ll.lon() + 180.0) * noParts / 360.0)) & 1;
061        long y = ((long) ((ll.lat() + 90.0) * noParts / 180.0)) & 1;
062        return (int) (2 * x + y);
063    }
064
065    protected static class GPLevel<T> {
066        private final T val;
067        private final int level;
068        private final BBox bbox;
069        private final GPLevel<T> parent;
070        private final GeoPropertyIndex<T> owner;
071
072        // child order by index is sw, nw, se, ne
073        private GPLevel<T>[] children;
074
075        public GPLevel(int level, BBox bbox, GPLevel<T> parent, GeoPropertyIndex<T> owner) {
076            this.level = level;
077            this.bbox = bbox;
078            this.parent = parent;
079            this.owner = owner;
080            this.val = owner.geoProp.get(bbox);
081        }
082
083        public T get(LatLon ll) {
084            if (isInside(ll))
085                return getBounded(ll);
086            if (DEBUG) System.err.print("up["+level+"]");
087            return parent != null ? parent.get(ll) : null;
088        }
089
090        private T getBounded(LatLon ll) {
091            if (DEBUG) System.err.print("GPLevel["+level+"]"+bbox+" ");
092            if (!isInside(ll)) {
093                throw new AssertionError("Point "+ll+" should be inside "+bbox);
094            }
095            if (val != null) {
096                if (DEBUG) System.err.println(" hit! "+val);
097                owner.lastLevelUsed = this;
098                return val;
099            }
100            if (level >= owner.maxLevel) {
101                if (DEBUG) System.err.println(" max level reached !");
102                return owner.geoProp.get(ll);
103            }
104
105            if (children == null) {
106                @SuppressWarnings("unchecked")
107                GPLevel<T>[] tmp = new GPLevel[4];
108                this.children = tmp;
109            }
110
111            int idx = index(ll, level+1);
112            if (children[idx] == null) {
113            double lon1, lat1;
114                switch (idx) {
115                    case 0:
116                        lon1 = bbox.getTopLeftLon();
117                        lat1 = bbox.getBottomRightLat();
118                        break;
119                    case 1:
120                        lon1 = bbox.getTopLeftLon();
121                        lat1 = bbox.getTopLeftLat();
122                        break;
123                    case 2:
124                        lon1 = bbox.getBottomRightLon();
125                        lat1 = bbox.getBottomRightLat();
126                        break;
127                    case 3:
128                        lon1 = bbox.getBottomRightLon();
129                        lat1 = bbox.getTopLeftLat();
130                        break;
131                    default:
132                        throw new AssertionError();
133                }
134                if (DEBUG) System.err.println(" - new with idx "+idx);
135                LatLon center = bbox.getCenter();
136                BBox b = new BBox(lon1, lat1, center.lon(), center.lat());
137                children[idx] = new GPLevel<>(level + 1, b, this, owner);
138            }
139            return children[idx].getBounded(ll);
140        }
141
142        /**
143         * Checks, if a point is inside this tile.
144         * Makes sure, that neighboring tiles do not overlap, i.e. a point exactly
145         * on the border of two tiles must be inside exactly one of the tiles.
146         * @param ll the coordinates of the point
147         * @return true, if it is inside of the box
148         */
149        boolean isInside(LatLon ll) {
150            return bbox.getTopLeftLon() <= ll.lon() &&
151                    (ll.lon() < bbox.getBottomRightLon() || (ll.lon() == 180.0 && bbox.getBottomRightLon() == 180.0)) &&
152                    bbox.getBottomRightLat() <= ll.lat() &&
153                    (ll.lat() < bbox.getTopLeftLat() || (ll.lat() == 90.0 && bbox.getTopLeftLat() == 90.0));
154        }
155
156        @Override
157        public String toString() {
158            return "GPLevel [val=" + val + ", level=" + level + ", bbox=" + bbox + ']';
159        }
160    }
161
162    @Override
163    public String toString() {
164        return "GeoPropertyIndex [maxLevel=" + maxLevel + ", geoProp=" + geoProp + ", root=" + root + ", lastLevelUsed="
165                + lastLevelUsed + ']';
166    }
167}