Search in sources :

Example 6 with MultipolygonBuilder

use of net.osmand.data.MultipolygonBuilder in project OsmAnd-tools by osmandapp.

the class CombineSRTMIntoFile method process.

private static void process(BinaryMapDataObject country, List<BinaryMapDataObject> boundaries, String downloadName, File directoryWithSRTMFiles, File directoryWithTargetFiles, boolean dryRun) throws IOException, SQLException, InterruptedException, IllegalArgumentException, XmlPullParserException {
    final String suffix = "_" + IndexConstants.BINARY_MAP_VERSION + IndexConstants.BINARY_SRTM_MAP_INDEX_EXT;
    String name = country.getName();
    final File targetFile = new File(directoryWithTargetFiles, Algorithms.capitalizeFirstLetterAndLowercase(downloadName + suffix));
    if (targetFile.exists()) {
        System.out.println("Already processed " + name);
        return;
    }
    Set<String> srtmFileNames = new TreeSet<String>();
    QuadRect qr = new QuadRect(180, -90, -180, 90);
    MultipolygonBuilder bld = new MultipolygonBuilder();
    bld.addOuterWay(convertToWay(country));
    updateBbox(country, qr);
    if (boundaries != null) {
        for (BinaryMapDataObject o : boundaries) {
            bld.addOuterWay(convertToWay(o));
            updateBbox(o, qr);
        }
    }
    Multipolygon polygon = bld.build();
    System.out.println("RINGS OF MULTIPOLYGON ARE " + polygon.areRingsComplete());
    int rightLon = (int) Math.floor(qr.right);
    int leftLon = (int) Math.floor(qr.left);
    int bottomLat = (int) Math.floor(qr.bottom);
    int topLat = (int) Math.floor(qr.top);
    boolean onetile = leftLon == rightLon && bottomLat == topLat;
    for (int lon = leftLon; lon <= rightLon; lon++) {
        for (int lat = bottomLat; lat <= topLat; lat++) {
            boolean isOut = !polygon.containsPoint(lat + 0.5, lon + 0.5) && !onetile;
            if (isOut) {
                LatLon bl = new LatLon(lat, lon);
                LatLon br = new LatLon(lat, lon + 1);
                LatLon tr = new LatLon(lat + 1, lon + 1);
                LatLon tl = new LatLon(lat + 1, lon);
                for (Ring r : polygon.getOuterRings()) {
                    List<Node> border = r.getBorder();
                    Node prev = border.get(border.size() - 1);
                    for (int i = 0; i < border.size() && isOut; i++) {
                        Node n = border.get(i);
                        if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), tr, tl)) {
                            isOut = false;
                        } else if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), tr, br)) {
                            isOut = false;
                        } else if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), bl, tl)) {
                            isOut = false;
                        } else if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), br, bl)) {
                            isOut = false;
                        }
                        prev = n;
                    }
                    if (!isOut) {
                        break;
                    }
                }
            }
            if (!isOut) {
                final String filename = getFileName(lon, lat);
                srtmFileNames.add(filename);
            }
        }
    }
    System.out.println();
    System.out.println("PROCESSING " + name + " lon [" + leftLon + " - " + rightLon + "] lat [" + bottomLat + " - " + topLat + "] TOTAL " + srtmFileNames.size() + " files " + srtmFileNames);
    System.out.println("-----------------------------");
    if (dryRun) {
        return;
    }
    // final File work = new File(directoryWithTargetFiles, "work");
    // Map<File, String> mp = new HashMap<File, String>();
    // long length = 0;
    List<File> files = new ArrayList<File>();
    for (String file : srtmFileNames) {
        final File fl = new File(directoryWithSRTMFiles, file + ".osm.bz2");
        if (!fl.exists()) {
            System.err.println("!! Missing " + name + " because " + file + " doesn't exist");
        } else {
            files.add(fl);
        // File ttf = new File(fl.getParentFile(), Algorithms.capitalizeFirstLetterAndLowercase(file) + "_"+ name + ".obf");
        // mp.put(ttf, null);
        }
    }
    // be independent of previous results
    new File(targetFile.getParentFile(), IndexCreator.TEMP_NODES_DB).delete();
    RTree.clearCache();
    IndexCreator ic = new IndexCreator(targetFile.getParentFile());
    if (srtmFileNames.size() > 100) {
        ic.setDialects(DBDialect.SQLITE, DBDialect.SQLITE);
    } else {
        ic.setDialects(DBDialect.SQLITE_IN_MEMORY, DBDialect.SQLITE_IN_MEMORY);
    }
    ic.setIndexMap(true);
    ic.setRegionName(name + " contour lines");
    ic.setMapFileName(targetFile.getName());
    ic.setBoundary(polygon);
    ic.setZoomWaySmoothness(2);
    ic.generateIndexes(files.toArray(new File[files.size()]), new ConsoleProgressImplementation(1), null, MapZooms.parseZooms("11-12;13-"), new MapRenderingTypesEncoder(targetFile.getName()), log, true, false);
// if(length > Integer.MAX_VALUE) {
// System.err.println("!! Can't process " + name + " because too big");
// } else {
// BinaryInspector.combineParts(targetFile, mp);
// }
// for(String file : srtmFileNames) {
// final File fl = new File(work, file);
// fl.delete();
// }
}
Also used : Node(net.osmand.osm.edit.Node) ArrayList(java.util.ArrayList) IndexCreator(net.osmand.data.preparation.IndexCreator) QuadRect(net.osmand.data.QuadRect) ConsoleProgressImplementation(net.osmand.impl.ConsoleProgressImplementation) LatLon(net.osmand.data.LatLon) MapRenderingTypesEncoder(net.osmand.osm.MapRenderingTypesEncoder) BinaryMapDataObject(net.osmand.binary.BinaryMapDataObject) TreeSet(java.util.TreeSet) Ring(net.osmand.data.Ring) File(java.io.File) Multipolygon(net.osmand.data.Multipolygon) MultipolygonBuilder(net.osmand.data.MultipolygonBuilder)

Example 7 with MultipolygonBuilder

use of net.osmand.data.MultipolygonBuilder in project OsmAnd-tools by osmandapp.

the class IndexVectorMapCreator method indexMultiPolygon.

/**
 * index a multipolygon into the database
 * only multipolygons without admin_level and with type=multipolygon are indexed
 * broken multipolygons are also indexed, inner ways are sometimes left out, broken rings are split and closed
 * broken multipolygons will normally be logged
 * @param e the entity to index
 * @param tags
 * @param ctx the database context
 * @throws SQLException
 */
private void indexMultiPolygon(Relation e, Map<String, String> tags, OsmDbAccessorContext ctx) throws SQLException {
    // Don't handle things that aren't multipolygon, and nothing administrative
    if (!("multipolygon".equals(tags.get(OSMTagKey.TYPE.getValue())) || "protected_area".equals(tags.get("boundary")) || "low_emission_zone".equals(tags.get("boundary")) || "national_park".equals(tags.get("boundary")) || "danger_area".equals(tags.get("military")))) {
        return;
    }
    if (tags.get(OSMTagKey.ADMIN_LEVEL.getValue()) != null) {
        return;
    }
    tags = new LinkedHashMap<>(tags);
    // some big islands are marked as multipolygon - don't process them (only keep coastlines)
    boolean polygonIsland = "multipolygon".equals(tags.get(OSMTagKey.TYPE.getValue())) && "island".equals(tags.get(OSMTagKey.PLACE.getValue()));
    if (polygonIsland) {
        int coastlines = 0;
        int otherWays = 0;
        ctx.loadEntityRelation((Relation) e);
        List<Entity> me = e.getMemberEntities("outer");
        for (Entity es : me) {
            if (es instanceof Way && !((Way) es).getEntityIds().isEmpty()) {
                boolean coastline = "coastline".equals(tags.get(OSMTagKey.NATURAL.getValue()));
                if (coastline) {
                    coastlines++;
                } else {
                    otherWays++;
                }
            }
        }
        if (coastlines > 0) {
            // don't index all coastlines
            if (otherWays != 0) {
                log.error(String.format("Wrong coastline (island) relation %d has %d coastlines out of %d entries", e.getId(), coastlines, otherWays + coastlines));
                return;
            }
            if (e.getMembers("inner").size() > 0) {
                log.error(String.format("Wrong coastline (island) relation %d has inner ways", e.getId()));
                return;
            }
            log.info(String.format("Relation %s %d consists only of coastlines so it was skipped.", tags.get(OSMTagKey.NAME.getValue()), e.getId()));
            return;
        }
    }
    ctx.loadEntityRelation((Relation) e);
    MultipolygonBuilder original = createMultipolygonBuilder(e);
    try {
        renderingTypes.encodeEntityWithType(false, tags, mapZooms.getLevel(0).getMaxZoom(), typeUse, addtypeUse, namesUse, tempNameUse);
    } catch (RuntimeException es) {
        es.printStackTrace();
        return;
    }
    List<Map<String, String>> splitEntities = renderingTypes.splitTags(tags, EntityType.valueOf(e));
    // Don't add multipolygons with an unknown type
    if (typeUse.size() == 0) {
        return;
    }
    excludeFromMainIteration(original.getOuterWays());
    if (settings.keepOnlySeaObjects && !checkBelongsToSeaWays(original.getOuterWays())) {
        return;
    }
    // excludeFromMainIteration(original.getInnerWays()); // fix issue with different type of swamp inside each other (inner ring has same tag as multipolygon but has a different meaning)
    // Rings with different types (inner or outer) in one ring will be logged in the previous case
    // The Rings are only composed by type, so if one way gets in a different Ring, the rings will be incomplete
    List<Multipolygon> multipolygons = original.splitPerOuterRing(logMapDataWarn);
    for (Multipolygon m : multipolygons) {
        assert m.getOuterRings().size() == 1;
        // Log the fact that Rings aren't complete, but continue with the relation, try to close it as well as possible
        if (!m.areRingsComplete()) {
            logMapDataWarn.warn("In multipolygon  " + e.getId() + " there are incompleted ways");
        }
        Ring out = m.getOuterRings().get(0);
        if (out.getBorder().size() == 0) {
            logMapDataWarn.warn("Multipolygon has an outer ring that can't be formed: " + e.getId());
            // don't index this
            continue;
        }
        // innerWays are new closed ways
        List<List<Node>> innerWays = new ArrayList<List<Node>>();
        for (Ring r : m.getInnerRings()) {
            innerWays.add(r.getBorder());
        }
        // don't use the relation ids. Create new onesgetInnerRings
        Map<String, String> stags = splitEntities == null ? tags : splitEntities.get(0);
        long assignId = assignIdForMultipolygon((Relation) e);
        createMultipolygonObject(stags, out, innerWays, assignId);
        if (splitEntities != null) {
            for (int i = 1; i < splitEntities.size(); i++) {
                Map<String, String> splitTags = splitEntities.get(i);
                while (generatedIds.contains(assignId)) {
                    assignId += 2;
                }
                generatedIds.add(assignId);
                createMultipolygonObject(splitTags, out, innerWays, assignId);
            }
        }
    }
}
Also used : Entity(net.osmand.osm.edit.Entity) Node(net.osmand.osm.edit.Node) TIntArrayList(gnu.trove.list.array.TIntArrayList) ArrayList(java.util.ArrayList) Way(net.osmand.osm.edit.Way) Ring(net.osmand.data.Ring) TIntArrayList(gnu.trove.list.array.TIntArrayList) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) TreeMap(java.util.TreeMap) Multipolygon(net.osmand.data.Multipolygon) MultipolygonBuilder(net.osmand.data.MultipolygonBuilder)

Example 8 with MultipolygonBuilder

use of net.osmand.data.MultipolygonBuilder in project OsmAnd-tools by osmandapp.

the class IndexVectorMapCreator method createMultipolygonBuilder.

public static MultipolygonBuilder createMultipolygonBuilder(Entity e) {
    // create a multipolygon object for this
    MultipolygonBuilder original = new MultipolygonBuilder();
    original.setId(e.getId());
    // fill the multipolygon with all ways from the Relation
    for (RelationMember es : ((Relation) e).getMembers()) {
        if (es.getEntity() instanceof Way) {
            // $NON-NLS-1$
            boolean inner = "inner".equals(es.getRole());
            if (inner) {
                original.addInnerWay((Way) es.getEntity());
            } else if ("outer".equals(es.getRole())) {
                original.addOuterWay((Way) es.getEntity());
            }
        }
    }
    return original;
}
Also used : Relation(net.osmand.osm.edit.Relation) RelationMember(net.osmand.osm.edit.Relation.RelationMember) Way(net.osmand.osm.edit.Way) MultipolygonBuilder(net.osmand.data.MultipolygonBuilder)

Example 9 with MultipolygonBuilder

use of net.osmand.data.MultipolygonBuilder in project OsmAnd-tools by osmandapp.

the class IndexRouteCreator method addLowEmissonZoneRelation.

private void addLowEmissonZoneRelation(Relation e) {
    MultipolygonBuilder multipolygonBuilder = IndexVectorMapCreator.createMultipolygonBuilder(e);
    Multipolygon lowEmissionZone = multipolygonBuilder.build();
    if (lowEmissionZone != null) {
        QuadRect bbox = lowEmissionZone.getLatLonBbox();
        QuadRect flippedBbox = flipBbox(bbox);
        lowEmissionZones.insert(lowEmissionZone, flippedBbox);
    }
}
Also used : Multipolygon(net.osmand.data.Multipolygon) QuadRect(net.osmand.data.QuadRect) MultipolygonBuilder(net.osmand.data.MultipolygonBuilder)

Example 10 with MultipolygonBuilder

use of net.osmand.data.MultipolygonBuilder in project OsmAnd-tools by osmandapp.

the class SplitHillshadeIntoRegions method process.

private static void process(BinaryMapDataObject country, List<BinaryMapDataObject> boundaries, String downloadName, File sqliteFile, File directoryWithTargetFiles, String prefix, boolean dryRun) throws IOException, SQLException, InterruptedException, IllegalArgumentException, XmlPullParserException {
    String name = country.getName();
    String dwName = prefix + Algorithms.capitalizeFirstLetterAndLowercase(downloadName) + ".sqlitedb";
    Set<Long> tileNames = new TreeSet<>();
    final File targetFile = new File(directoryWithTargetFiles, dwName);
    if (targetFile.exists()) {
        System.out.println("Already processed " + name);
        return;
    }
    QuadRect qr = new QuadRect(180, -90, -180, 90);
    MultipolygonBuilder bld = new MultipolygonBuilder();
    if (boundaries != null) {
        for (BinaryMapDataObject o : boundaries) {
            bld.addOuterWay(convertToWay(o));
            updateBbox(o, qr);
        }
    } else {
        bld.addOuterWay(convertToWay(country));
        updateBbox(country, qr);
    }
    Multipolygon polygon = bld.build();
    int rightLon = (int) Math.floor(MapUtils.getTileNumberX(MAX_ZOOM, qr.right));
    int leftLon = (int) Math.floor(MapUtils.getTileNumberX(MAX_ZOOM, qr.left));
    int bottomLat = (int) Math.floor(MapUtils.getTileNumberY(MAX_ZOOM, qr.bottom));
    int topLat = (int) Math.floor(MapUtils.getTileNumberY(MAX_ZOOM, qr.top));
    boolean onetile = leftLon == rightLon && bottomLat == topLat;
    for (int tileX = leftLon; tileX <= rightLon; tileX++) {
        for (int tileY = topLat; tileY <= bottomLat; tileY++) {
            double llon = MapUtils.getLongitudeFromTile(MAX_ZOOM, tileX);
            double rlon = MapUtils.getLongitudeFromTile(MAX_ZOOM, tileX + 1);
            double tlat = MapUtils.getLatitudeFromTile(MAX_ZOOM, tileY);
            double blat = MapUtils.getLatitudeFromTile(MAX_ZOOM, tileY + 1);
            boolean isOut = !polygon.containsPoint(tlat / 2 + blat / 2, llon / 2 + rlon / 2) && !onetile;
            if (isOut) {
                LatLon bl = new LatLon(blat, llon);
                LatLon br = new LatLon(blat, rlon);
                LatLon tr = new LatLon(tlat, rlon);
                LatLon tl = new LatLon(tlat, llon);
                for (Ring r : polygon.getOuterRings()) {
                    List<Node> border = r.getBorder();
                    Node prev = border.get(border.size() - 1);
                    for (int i = 0; i < border.size() && isOut; i++) {
                        Node n = border.get(i);
                        if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), tr, tl)) {
                            isOut = false;
                        } else if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), tr, br)) {
                            isOut = false;
                        } else if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), bl, tl)) {
                            isOut = false;
                        } else if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), br, bl)) {
                            isOut = false;
                        }
                        prev = n;
                    }
                    if (!isOut) {
                        break;
                    }
                }
            }
            if (!isOut) {
                int x = tileX;
                int y = tileY;
                for (int z = MAX_ZOOM; z >= MIN_ZOOM; z--) {
                    tileNames.add(pack(x, y, z));
                    x = x >> 1;
                    y = y >> 1;
                }
            }
        }
    }
    System.out.println();
    System.out.println("-----------------------------");
    System.out.println("PROCESSING " + name + " lon [" + leftLon + " - " + rightLon + "] lat [" + bottomLat + " - " + topLat + "] TOTAL " + tileNames.size() + " files ");
    if (dryRun) {
        return;
    }
    procFile(sqliteFile, targetFile, tileNames);
}
Also used : Node(net.osmand.osm.edit.Node) QuadRect(net.osmand.data.QuadRect) LatLon(net.osmand.data.LatLon) BinaryMapDataObject(net.osmand.binary.BinaryMapDataObject) TreeSet(java.util.TreeSet) Ring(net.osmand.data.Ring) File(java.io.File) Multipolygon(net.osmand.data.Multipolygon) MultipolygonBuilder(net.osmand.data.MultipolygonBuilder)

Aggregations

MultipolygonBuilder (net.osmand.data.MultipolygonBuilder)11 Multipolygon (net.osmand.data.Multipolygon)7 Node (net.osmand.osm.edit.Node)7 Way (net.osmand.osm.edit.Way)6 ArrayList (java.util.ArrayList)5 QuadRect (net.osmand.data.QuadRect)5 Ring (net.osmand.data.Ring)5 Relation (net.osmand.osm.edit.Relation)4 RelationMember (net.osmand.osm.edit.Relation.RelationMember)4 TIntArrayList (gnu.trove.list.array.TIntArrayList)3 File (java.io.File)3 TreeSet (java.util.TreeSet)3 BinaryMapDataObject (net.osmand.binary.BinaryMapDataObject)3 LatLon (net.osmand.data.LatLon)3 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 List (java.util.List)2 Map (java.util.Map)2 TreeMap (java.util.TreeMap)2