Search in sources :

Example 1 with Entity

use of net.osmand.osm.edit.Entity in project OsmAnd-tools by osmandapp.

the class MapRouterLayer method selfRoute.

public List<Way> selfRoute(LatLon start, LatLon end, List<LatLon> intermediates, List<RouteSegmentResult> previousRoute, RouteCalculationMode rm) {
    List<Way> res = new ArrayList<Way>();
    long time = System.currentTimeMillis();
    List<File> files = new ArrayList<File>();
    for (File f : Algorithms.getSortedFilesVersions(new File(DataExtractionSettings.getSettings().getBinaryFilesDir()))) {
        if (f.getName().endsWith(".obf")) {
            files.add(f);
        }
    }
    final boolean animateRoutingCalculation = DataExtractionSettings.getSettings().isAnimateRouting();
    if (animateRoutingCalculation) {
        nextTurn.setVisible(true);
        playPauseButton.setVisible(true);
        stopButton.setVisible(true);
        pause = true;
        playPauseButton.setText("Play");
    }
    stop = false;
    if (files.isEmpty()) {
        JOptionPane.showMessageDialog(OsmExtractionUI.MAIN_APP.getFrame(), "Please specify obf file in settings", "Obf file not found", JOptionPane.ERROR_MESSAGE);
        return null;
    }
    System.out.println("Self made route from " + start + " to " + end);
    if (start != null && end != null) {
        try {
            BinaryMapIndexReader[] rs = new BinaryMapIndexReader[files.size()];
            int it = 0;
            for (File f : files) {
                // $NON-NLS-1$ //$NON-NLS-2$
                RandomAccessFile raf = new RandomAccessFile(f, "r");
                rs[it++] = new BinaryMapIndexReader(raf, f);
            }
            String m = DataExtractionSettings.getSettings().getRouteMode();
            String[] props = m.split("\\,");
            RoutePlannerFrontEnd router = new RoutePlannerFrontEnd(USE_OLD_ROUTING);
            Map<String, String> paramsR = new LinkedHashMap<String, String>();
            for (String p : props) {
                if (p.contains("=")) {
                    paramsR.put(p.split("=")[0], p.split("=")[1]);
                } else {
                    paramsR.put(p, "true");
                }
            }
            RoutingConfiguration config = DataExtractionSettings.getSettings().getRoutingConfig().build(props[0], /*RoutingConfiguration.DEFAULT_MEMORY_LIMIT*/
            1000, paramsR);
            PrecalculatedRouteDirection precalculatedRouteDirection = null;
            // Test gpx precalculation
            // LatLon[] lts = parseGPXDocument("/home/victor/projects/osmand/temp/esya.gpx");
            // start = lts[0];
            // end = lts[lts.length - 1];
            // System.out.println("Start " + start + " end " + end);
            // precalculatedRouteDirection = PrecalculatedRouteDirection.build(lts, config.router.getMaxDefaultSpeed());
            // precalculatedRouteDirection.setFollowNext(true);
            // config.planRoadDirection = 1;
            // Test initial direction
            // config.initialDirection = 90d / 180d * Math.PI; // EAST
            // config.initialDirection = 180d / 180d * Math.PI; // SOUTH
            // config.initialDirection = -90d / 180d * Math.PI; // WEST
            // config.initialDirection = 0 / 180d * Math.PI; // NORTH
            // config.NUMBER_OF_DESIRABLE_TILES_IN_MEMORY = 300;
            // config.ZOOM_TO_LOAD_TILES = 14;
            final RoutingContext ctx = router.buildRoutingContext(config, DataExtractionSettings.getSettings().useNativeRouting() ? NativeSwingRendering.getDefaultFromSettings() : null, rs, rm);
            ctx.leftSideNavigation = false;
            ctx.previouslyCalculatedRoute = previousRoute;
            log.info("Use " + config.routerName + "mode for routing");
            final DataTileManager<Entity> points = new DataTileManager<Entity>(11);
            map.setPoints(points);
            ctx.setVisitor(createSegmentVisitor(animateRoutingCalculation, points));
            // Choose native or not native
            long nt = System.nanoTime();
            startProgressThread(ctx);
            try {
                List<RouteSegmentResult> searchRoute = router.searchRoute(ctx, start, end, intermediates, precalculatedRouteDirection);
                throwExceptionIfRouteNotFound(ctx, searchRoute);
                System.out.println("External native time " + (System.nanoTime() - nt) / 1.0e9f);
                if (animateRoutingCalculation) {
                    playPauseButton.setVisible(false);
                    nextTurn.setText("FINISH");
                    waitNextPress();
                    nextTurn.setText(">>");
                }
                this.previousRoute = searchRoute;
                calculateResult(res, searchRoute);
            } finally {
                ctx.calculationProgress.isCancelled = true;
            }
        } catch (Exception e) {
            ExceptionHandler.handle(e);
        } finally {
            playPauseButton.setVisible(false);
            nextTurn.setVisible(false);
            stopButton.setVisible(false);
            if (map.getPoints() != null) {
                map.getPoints().clear();
            }
        }
        System.out.println("Finding self routes " + res.size() + " " + (System.currentTimeMillis() - time) + " ms");
    }
    return res;
}
Also used : Entity(net.osmand.osm.edit.Entity) ArrayList(java.util.ArrayList) Way(net.osmand.osm.edit.Way) LinkedHashMap(java.util.LinkedHashMap) RoutingContext(net.osmand.router.RoutingContext) DataTileManager(net.osmand.data.DataTileManager) RouteSegmentResult(net.osmand.router.RouteSegmentResult) PrecalculatedRouteDirection(net.osmand.router.PrecalculatedRouteDirection) BinaryMapIndexReader(net.osmand.binary.BinaryMapIndexReader) Point(java.awt.Point) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) RandomAccessFile(java.io.RandomAccessFile) RoutingConfiguration(net.osmand.router.RoutingConfiguration) RoutePlannerFrontEnd(net.osmand.router.RoutePlannerFrontEnd) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 2 with Entity

use of net.osmand.osm.edit.Entity in project OsmAnd-tools by osmandapp.

the class IndexCreator method indexRelations.

private void indexRelations(OsmDbAccessor accessor, IProgress progress) throws SQLException, InterruptedException {
    if (indexAddress || indexMap || indexRouting || indexPOI || indexTransport) {
        // $NON-NLS-1$
        setGeneralProgress(progress, "[30 / 100]");
        // $NON-NLS-1$
        progress.startTask(Messages.getString("IndexCreator.PREINDEX_BOUNDARIES_RELATIONS"), accessor.getAllRelations());
        accessor.iterateOverEntities(progress, EntityType.RELATION, new OsmDbVisitor() {

            @Override
            public void iterateEntity(Entity e, OsmDbAccessorContext ctx) throws SQLException {
                if (indexAddress) {
                    // indexAddressCreator.indexAddressRelation((Relation) e, ctx); streets needs loaded boundaries !!!
                    indexAddressCreator.indexBoundariesRelation(e, ctx);
                }
                if (indexMap) {
                    indexMapCreator.indexMapRelationsAndMultiPolygons(e, ctx);
                }
                if (indexRouting) {
                    indexRouteCreator.indexRelations(e, ctx);
                }
                if (indexPOI) {
                    indexPoiCreator.iterateRelation((Relation) e, ctx);
                }
                if (indexTransport) {
                    indexTransportCreator.indexRelations((Relation) e, ctx);
                }
            }
        });
        if (indexMap) {
            indexMapCreator.createMapIndexTableIndexes(mapConnection);
        }
        if (indexAddress) {
            // $NON-NLS-1$
            setGeneralProgress(progress, "[40 / 100]");
            // $NON-NLS-1$
            progress.startTask(Messages.getString("IndexCreator.PREINDEX_BOUNDARIES_WAYS"), accessor.getAllWays());
            accessor.iterateOverEntities(progress, EntityType.WAY_BOUNDARY, new OsmDbVisitor() {

                @Override
                public void iterateEntity(Entity e, OsmDbAccessorContext ctx) throws SQLException {
                    indexAddressCreator.indexBoundariesRelation(e, ctx);
                }
            });
            // $NON-NLS-1$
            setGeneralProgress(progress, "[42 / 100]");
            // $NON-NLS-1$
            progress.startTask(Messages.getString("IndexCreator.BIND_CITIES_AND_BOUNDARIES"), 100);
            // finish up the boundaries and cities
            indexAddressCreator.tryToAssignBoundaryToFreeCities(progress);
            // $NON-NLS-1$
            setGeneralProgress(progress, "[45 / 100]");
            // $NON-NLS-1$
            progress.startTask(Messages.getString("IndexCreator.PREINDEX_ADRESS_MAP"), accessor.getAllRelations());
            accessor.iterateOverEntities(progress, EntityType.RELATION, new OsmDbVisitor() {

                @Override
                public void iterateEntity(Entity e, OsmDbAccessorContext ctx) throws SQLException {
                    indexAddressCreator.indexAddressRelation((Relation) e, ctx);
                }
            });
            indexAddressCreator.commitToPutAllCities();
        }
    }
}
Also used : Entity(net.osmand.osm.edit.Entity) Relation(net.osmand.osm.edit.Relation) SQLException(java.sql.SQLException) OsmDbVisitor(net.osmand.data.preparation.OsmDbAccessor.OsmDbVisitor)

Example 3 with Entity

use of net.osmand.osm.edit.Entity in project OsmAnd-tools by osmandapp.

the class IndexRouteCreator method indexRelations.

public void indexRelations(Entity e, OsmDbAccessorContext ctx) throws SQLException {
    indexHighwayRestrictions(e, ctx);
    if (e instanceof Relation) {
        tagsTransformer.handleRelationPropogatedTags((Relation) e, renderingTypes, ctx, EntityConvertApplyType.ROUTING);
        Map<String, String> tags = renderingTypes.transformTags(e.getTags(), EntityType.RELATION, EntityConvertApplyType.ROUTING);
        if ("enforcement".equals(tags.get("type")) && "maxspeed".equals(tags.get("enforcement"))) {
            ctx.loadEntityRelation((Relation) e);
            Iterator<RelationMember> from = ((Relation) e).getMembers("from").iterator();
            // mark as speed cameras
            while (from.hasNext()) {
                Entity n = from.next().getEntity();
                if (n instanceof Node) {
                    tagsTransformer.registerPropogatedTag(new EntityId(EntityType.NODE, n.getId()), "highway", "speed_camera");
                }
            }
        }
    }
}
Also used : EntityId(net.osmand.osm.edit.Entity.EntityId) Entity(net.osmand.osm.edit.Entity) Relation(net.osmand.osm.edit.Relation) RelationMember(net.osmand.osm.edit.Relation.RelationMember) Node(net.osmand.osm.edit.Node)

Example 4 with Entity

use of net.osmand.osm.edit.Entity in project OsmAnd-tools by osmandapp.

the class OsmBaseStoragePbf method parseOSMPbf.

public synchronized void parseOSMPbf(final InputStream stream, final IProgress progress, final boolean entityInfo) throws IOException {
    BinaryParser parser = new BinaryParser() {

        public void updateProgress(int count) {
            progressEntity += count;
            if (progress != null && progressEntity > moduleProgress && !progress.isIndeterminate()) {
                try {
                    progressEntity = 0;
                    progress.remaining(stream.available());
                } catch (IOException e) {
                    progress.startWork(-1);
                }
            }
        }

        public void registerEntity(EntityType type, Entity e, EntityInfo info) {
            EntityId entityId = new EntityId(type, e.getId());
            if (acceptEntityToLoad(entityId, e)) {
                Entity oldEntity = entities.put(entityId, e);
                if (info != null) {
                    OsmBaseStoragePbf.this.entityInfo.put(entityId, info);
                }
                if (!supressWarnings && oldEntity != null) {
                    // $NON-NLS-1$ //$NON-NLS-2$
                    throw new UnsupportedOperationException("Entity with id=" + oldEntity.getId() + " is duplicated in osm map");
                }
            }
        }

        @Override
        protected void parse(HeaderBlock header) {
        }

        // $NON-NLS-1$
        private DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

        @Override
        protected void parseDense(DenseNodes n) {
            EntityInfo info = null;
            long changeset = 0;
            long timestamp = 0;
            int uid = 0;
            int user = 0;
            long id = 0;
            long lat = 0;
            long lon = 0;
            int keyInd = 0;
            boolean tagsEmpty = n.getKeysValsCount() == 0;
            for (int i = 0; i < n.getIdCount(); i++) {
                id += n.getId(i);
                lat += n.getLat(i);
                lon += n.getLon(i);
                Node node = new Node(parseLat(lat), parseLon(lon), id);
                if (entityInfo && n.getDenseinfo() != null) {
                    info = new EntityInfo();
                    changeset += n.getDenseinfo().getChangeset(i);
                    timestamp += n.getDenseinfo().getTimestamp(i);
                    uid += n.getDenseinfo().getUid(i);
                    user += n.getDenseinfo().getUserSid(i);
                    // $NON-NLS-1$
                    info.setChangeset(String.valueOf(changeset));
                    info.setTimestamp(format.format(new Date(date_granularity * (timestamp))));
                    info.setUser(getStringById(user));
                    // $NON-NLS-1$
                    info.setUid(String.valueOf(uid));
                    // $NON-NLS-1$
                    info.setVersion(String.valueOf(n.getDenseinfo().getVersion(i)));
                    // $NON-NLS-1$
                    info.setVisible("true");
                }
                if (!tagsEmpty) {
                    while (n.getKeysVals(keyInd) != 0) {
                        String key = getStringById(n.getKeysVals(keyInd));
                        String val = getStringById(n.getKeysVals(keyInd + 1));
                        node.putTag(key, val);
                        keyInd += 2;
                    }
                    keyInd++;
                }
                registerEntity(EntityType.NODE, node, info);
            }
            updateProgress(n.getIdCount());
        }

        protected EntityInfo parseEntityInfo(Info i) {
            EntityInfo info = new EntityInfo();
            // $NON-NLS-1$
            info.setChangeset(String.valueOf(i.getChangeset()));
            info.setTimestamp(format.format(getDate(i)));
            info.setUser(getStringById(i.getUserSid()));
            // $NON-NLS-1$
            info.setUid(String.valueOf(i.getUid()));
            // $NON-NLS-1$
            info.setVersion(String.valueOf(i.getVersion()));
            // $NON-NLS-1$
            info.setVisible("true");
            return info;
        }

        @Override
        protected void parseNodes(List<crosby.binary.Osmformat.Node> n) {
            EntityInfo info = null;
            int nsize = n.size();
            for (int i = 0; i < nsize; i++) {
                crosby.binary.Osmformat.Node nod = n.get(i);
                Node e = new Node(parseLat(nod.getLat()), parseLon(nod.getLon()), nod.getId());
                for (int j = 0; j < nod.getKeysCount(); j++) {
                    String key = getStringById(nod.getKeys(j));
                    String val = getStringById(nod.getVals(j));
                    e.putTag(key, val);
                }
                if (entityInfo) {
                    info = parseEntityInfo(nod.getInfo());
                }
                registerEntity(EntityType.NODE, e, info);
            }
            updateProgress(nsize);
        }

        @Override
        protected void parseRelations(List<crosby.binary.Osmformat.Relation> r) {
            EntityInfo info = null;
            int rsize = r.size();
            for (int i = 0; i < rsize; i++) {
                crosby.binary.Osmformat.Relation rel = r.get(i);
                Relation e = new Relation(rel.getId());
                long id = 0;
                for (int j = 0; j < rel.getMemidsCount(); j++) {
                    id += rel.getMemids(j);
                    String role = getStringById(rel.getRolesSid(j));
                    MemberType t = rel.getTypes(j);
                    EntityType ts = EntityType.NODE;
                    switch(t) {
                        case NODE:
                            ts = EntityType.NODE;
                            break;
                        case WAY:
                            ts = EntityType.WAY;
                            break;
                        case RELATION:
                            ts = EntityType.RELATION;
                            break;
                    }
                    e.addMember(id, ts, role);
                }
                for (int j = 0; j < rel.getKeysCount(); j++) {
                    String key = getStringById(rel.getKeys(j));
                    String val = getStringById(rel.getVals(j));
                    e.putTag(key, val);
                }
                if (entityInfo) {
                    info = parseEntityInfo(rel.getInfo());
                }
                registerEntity(EntityType.RELATION, e, info);
            }
            updateProgress(rsize);
        }

        @Override
        protected void parseWays(List<crosby.binary.Osmformat.Way> w) {
            EntityInfo info = null;
            int wsize = w.size();
            for (int i = 0; i < wsize; i++) {
                crosby.binary.Osmformat.Way way = w.get(i);
                Way e = new Way(way.getId());
                long id = 0;
                for (int j = 0; j < way.getRefsCount(); j++) {
                    id += way.getRefs(j);
                    e.addNode(id);
                }
                for (int j = 0; j < way.getKeysCount(); j++) {
                    String key = getStringById(way.getKeys(j));
                    String val = getStringById(way.getVals(j));
                    e.putTag(key, val);
                }
                if (entityInfo) {
                    info = parseEntityInfo(way.getInfo());
                }
                registerEntity(EntityType.WAY, e, info);
            }
            updateProgress(wsize);
        }

        @Override
        public void complete() {
        }
    };
    this.progressEntity = 0;
    this.entities.clear();
    this.entityInfo.clear();
    if (progress != null) {
        progress.startWork(stream.available());
    }
    BlockInputStream bis = new BlockInputStream(stream, parser);
    bis.process();
    if (progress != null) {
        progress.finishTask();
    }
    completeReading();
}
Also used : Entity(net.osmand.osm.edit.Entity) HeaderBlock(crosby.binary.Osmformat.HeaderBlock) Node(net.osmand.osm.edit.Node) Way(net.osmand.osm.edit.Way) Relation(net.osmand.osm.edit.Relation) BlockInputStream(crosby.binary.file.BlockInputStream) List(java.util.List) BinaryParser(crosby.binary.BinaryParser) IOException(java.io.IOException) EntityInfo(net.osmand.osm.edit.EntityInfo) Info(crosby.binary.Osmformat.Info) Date(java.util.Date) EntityType(net.osmand.osm.edit.Entity.EntityType) EntityId(net.osmand.osm.edit.Entity.EntityId) MemberType(crosby.binary.Osmformat.Relation.MemberType) EntityInfo(net.osmand.osm.edit.EntityInfo) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) DenseNodes(crosby.binary.Osmformat.DenseNodes) SimpleDateFormat(java.text.SimpleDateFormat)

Example 5 with Entity

use of net.osmand.osm.edit.Entity in project OsmAnd-tools by osmandapp.

the class FixAdminLevel0 method process.

private static void process(File read, File write) throws IOException, XMLStreamException, XmlPullParserException {
    OsmBaseStorage storage = new OsmBaseStorage();
    storage.parseOSM(new FileInputStream(read), new ConsoleProgressImplementation());
    Map<EntityId, Entity> entities = new HashMap<EntityId, Entity>(storage.getRegisteredEntities());
    long id = -1;
    for (EntityId e : entities.keySet()) {
        Entity es = storage.getRegisteredEntities().get(e);
        if (e.getId() < id) {
            id = e.getId() - 1;
        }
        if (e.getType() == EntityType.WAY) {
            processWay((Way) es);
        }
    }
    for (String country : countryNames.keySet()) {
        List<Way> list = countryNames.get(country);
        for (Way w : list) {
            LatLon latLon = OsmMapUtils.getMathWeightCenterForNodes(w.getNodes());
            // LatLon latLon = w.getLatLon();
            Node node = new Node(latLon.getLatitude(), latLon.getLongitude(), id--);
            node.putTag("name", country);
            node.putTag("place", "country");
            storage.getRegisteredEntities().put(EntityId.valueOf(node), node);
        }
    }
    OsmStorageWriter writer = new OsmStorageWriter();
    writer.saveStorage(new FileOutputStream(write), storage, null, true);
}
Also used : OsmStorageWriter(net.osmand.osm.io.OsmStorageWriter) Entity(net.osmand.osm.edit.Entity) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Node(net.osmand.osm.edit.Node) ConsoleProgressImplementation(net.osmand.impl.ConsoleProgressImplementation) FileInputStream(java.io.FileInputStream) Way(net.osmand.osm.edit.Way) EntityId(net.osmand.osm.edit.Entity.EntityId) LatLon(net.osmand.data.LatLon) OsmBaseStorage(net.osmand.osm.io.OsmBaseStorage) FileOutputStream(java.io.FileOutputStream)

Aggregations

Entity (net.osmand.osm.edit.Entity)32 Way (net.osmand.osm.edit.Way)15 EntityId (net.osmand.osm.edit.Entity.EntityId)14 Node (net.osmand.osm.edit.Node)14 Relation (net.osmand.osm.edit.Relation)14 LinkedHashMap (java.util.LinkedHashMap)10 LatLon (net.osmand.data.LatLon)9 FileInputStream (java.io.FileInputStream)7 OsmBaseStorage (net.osmand.osm.io.OsmBaseStorage)7 Point (java.awt.Point)6 File (java.io.File)6 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 RelationMember (net.osmand.osm.edit.Relation.RelationMember)6 FileOutputStream (java.io.FileOutputStream)4 RandomAccessFile (java.io.RandomAccessFile)4 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)3 InputStream (java.io.InputStream)3 ResultSet (java.sql.ResultSet)3