Debian Codegraph @

src/uk/me/parabola/imgfmt/app/net/RouteNode.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2008
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * Create date: 07-Jul-2008
14 */
15 package uk.me.parabola.imgfmt.app.net;
16
17 import java.util.ArrayDeque;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.Deque;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.logging.Level;
24
25 import it.unimi.dsi.fastutil.ints.IntArrayList;
26 import uk.me.parabola.imgfmt.Utils;
27 import uk.me.parabola.imgfmt.app.Coord;
28 import uk.me.parabola.imgfmt.app.CoordNode;
29 import uk.me.parabola.imgfmt.app.ImgFileWriter;
30 import uk.me.parabola.log.Logger;
31
32 /**
33 * A routing node with its connections to other nodes via roads.
34 *
35 * @author Steve Ratcliffe
36 */
37 public class RouteNode implements Comparable<RouteNode> {
38 private static final Logger log = Logger.getLogger(RouteNode.class);
39
40 /*
41 * 1. instantiate
42 * 2. setCoord, addArc
43 * arcs, coords set
44 * 3. write
45 * node offsets set in all nodes
46 * 4. writeSecond
47 */
48
49 // Values for the first flag byte at offset 1
50 private static final int MAX_DEST_CLASS_MASK = 0x07;
51 private static final int F_BOUNDARY = 0x08;
52 private static final int F_RESTRICTIONS = 0x10;
53 private static final int F_LARGE_OFFSETS = 0x20;
54 private static final int F_ARCS = 0x40;
55 // only used internally in mkgmap
56 private static final int F_DISCARDED = 0x100; // node has been discarded
57
58 private int offsetNod1 = -1;
59
60 // arcs from this node
61 private final List<RouteArc> arcs = new ArrayList<>(4);
62 // restrictions at (via) this node
63 private final List<RouteRestriction> restrictions = new ArrayList<>();
64
65 private int flags;
66
67 private final CoordNode coord;
68 private int latOff;
69 private int lonOff;
70
71 // contains the maximum of roads this node is on, written with the flags
72 // field. It is also used for the calculation of the destination class on
73 // arcs.
74 private byte nodeClass;
75
76 private byte nodeGroup = -1;
77
78 private boolean useCompactDirs = false; // AngleChecker might change
79
80 public RouteNode(Coord coord) {
81 this.coord = (CoordNode) coord;
82 setBoundary(this.coord.getOnBoundary() || this.coord.getOnCountryBorder());
83 }
84
85 private boolean haveLargeOffsets() {
86 return (flags & F_LARGE_OFFSETS) != 0;
87 }
88
89 protected void setBoundary(boolean b) {
90 if (b)
91 flags |= F_BOUNDARY;
92 else
93 flags &= (~F_BOUNDARY) & 0xff;
94 }
95
96 public boolean isBoundary() {
97 return (flags & F_BOUNDARY) != 0;
98 }
99
100 public void addArc(RouteArc arc) {
101 arcs.add(arc);
102 byte cl = (byte) arc.getRoadDef().getRoadClass();
103 if(log.isDebugEnabled())
104 log.debug("adding arc", arc.getRoadDef(), cl);
105 if (cl > nodeClass)
106 nodeClass = cl;
107 flags |= F_ARCS;
108 }
109
110 public void addRestriction(RouteRestriction restr) {
111 restrictions.add(restr);
112 flags |= F_RESTRICTIONS;
113 }
114
115 /**
116 * get all direct arcs to the given node and the given way id
117 * @param otherNode
118 * @param roadId
119 * @return list with the direct arcs
120 */
121 public List<RouteArc> getDirectArcsTo(RouteNode otherNode, long roadId) {
122 List<RouteArc> result = new ArrayList<>();
123 for (RouteArc a : arcs) {
124 if (a.isDirect() && a.getDest() == otherNode && a.getRoadDef().getId() == roadId) {
125 result.add(a);
126 }
127 }
128 return result;
129 }
130
131 /**
132 * get all direct arcs on a given way id
133 * @param roadId
134 * @return @return list with the direct arcs
135 */
136 public List<RouteArc> getDirectArcsOnWay(long roadId) {
137 List<RouteArc> result = new ArrayList<>();
138 for (RouteArc a : arcs) {
139 if (a.isDirect() && a.getRoadDef().getId() == roadId) {
140 result.add(a);
141 }
142 }
143 return result;
144 }
145
146 /**
147 * Find arc to given node on given road.
148 * @param otherNode
149 * @param roadDef
150 * @return
151 */
152 public RouteArc getDirectArcTo(RouteNode otherNode, RoadDef roadDef) {
153 for (RouteArc a : arcs) {
154 if (a.isDirect() && a.getDest() == otherNode && a.getRoadDef() == roadDef) {
155 return a;
156 }
157 }
158 return null;
159 }
160
161 /**
162 * Provide an upper bound to the size (in bytes) that
163 * writing this node will take.
164 *
165 * Should be called only after arcs and restrictions
166 * have been set. The size of arcs depends on whether
167 * or not they are internal to the RoutingCenter.
168 */
169 public int boundSize() {
170 return 1 // table pointer
171 + 1 // flags
172 + 4 // assume large offsets required
173 + arcsSize()
174 + restrSize();
175 }
176
177 private int arcsSize() {
178 return arcs.stream().mapToInt(RouteArc::boundSize).sum();
179 }
180
181 private int restrSize() {
182 return 2*restrictions.size();
183 }
184
185 /**
186 * Writes a nod1 entry.
187 */
188 public void write(ImgFileWriter writer) {
189 // boolean diagNodeArcs = false;
190 // if (log.isInfoEnabled()) {
191 // String areaName = null;
192 // if (isClose(51.182575, -1.388928, 0.002))
193 // areaName = "A303 lead off/on";
194 // else if (isClose(51.012253, -1.087559, 0.0008))
195 // areaName = "West Meon";
196 // else if (isClose(51.064075, -1.380348, 0.0001))
197 // areaName = "Woodmans";
198 // if (areaName != null) {
199 // diagNodeArcs = true;
200 // log.info("diagNodeArcs", areaName, this, "compactDirs", useCompactDirs, "nArcs", arcs.size(), "cl", nodeClass);
201 // }
202 // }
203 if(log.isDebugEnabled())
204 log.debug("writing node, first pass, nod1", coord.getId());
205 offsetNod1 = writer.position();
206 assert offsetNod1 < 0x1000000 : "node offset doesn't fit in 3 bytes";
207
208 assert (flags & F_DISCARDED) == 0 : "attempt to write discarded node";
209
210 writer.put1u(0); // will be overwritten later
211 flags |= (nodeClass & MAX_DEST_CLASS_MASK); // max. road class of any outgoing road
212 if (flags == 0) {
213 // avoids possible case that low flag and flags are both 0 when node has no arcs
214 flags |= F_LARGE_OFFSETS;
215 }
216 writer.put1u(flags);
217
218 if (haveLargeOffsets()) {
219 writer.put4((latOff << 16) | (lonOff & 0xffff));
220 } else {
221 writer.put3s((latOff << 12) | (lonOff & 0xfff));
222 }
223
224 if (!arcs.isEmpty()) {
225 IntArrayList initialHeadings = new IntArrayList(arcs.size()+1);
226 RouteArc lastArc = null;
227 if (useCompactDirs) {
228 for (RouteArc arc: arcs) {
229 if (lastArc == null || lastArc.getIndexA() != arc.getIndexA() || lastArc.isForward() != arc.isForward())
230 initialHeadings.add(RouteArc.compactDirFromDegrees(arc.getInitialHeading()));
231 lastArc = arc;
232 }
233 initialHeadings.add(0); // add dummy 0 so that we don't have to check for existence
234 lastArc = null;
235 }
236 arcs.get(arcs.size() - 1).setLast();
237 int index = 0;
238 for (RouteArc arc: arcs){
239 Byte compactedDir = null;
240 if (useCompactDirs && (lastArc == null || lastArc.getIndexA() != arc.getIndexA() || lastArc.isForward() != arc.isForward())){
241 if (index % 2 == 0)
242 compactedDir = (byte) (initialHeadings.getInt(index) | (initialHeadings.getInt(index+1)<<4));
243 index++;
244 }
245 // if (diagNodeArcs)
246 // log.info(arc, arc.getIndexA(), arc.getInitialHeading(), RouteArc.compactDirFromDegrees(arc.getInitialHeading()), compactedDir, "cl", arc.getRoadDef().getRoadClass());
247 arc.write(writer, lastArc, useCompactDirs, compactedDir);
248 lastArc = arc;
249 }
250 }
251
252 if (!restrictions.isEmpty()) {
253 restrictions.get(restrictions.size() - 1).setLast();
254 for (RouteRestriction restr : restrictions)
255 restr.writeOffset(writer);
256 }
257 }
258
259 /**
260 * Writes a nod3 /nod4 entry.
261 */
262 public void writeNod3OrNod4(ImgFileWriter writer) {
263 assert isBoundary() : "trying to write nod3 for non-boundary node";
264
265 Utils.put3sLongitude(writer, coord.getLongitude());
266 writer.put3s(coord.getLatitude());
267 writer.put3u(offsetNod1);
268 }
269
270 public void discard() {
271 // mark the node as having been discarded
272 flags |= F_DISCARDED;
273 if (isBoundary()) {
274 log.error("intermal error? boundary node at", coord, "is discarded");
275 }
276 }
277
278 public boolean isDiscarded() {
279 return (flags & F_DISCARDED) != 0;
280 }
281
282 public int getOffsetNod1() {
283 if((flags & F_DISCARDED) != 0) {
284 // return something so that the program can continue
285 return 0;
286 }
287 assert offsetNod1 != -1: "failed for node " + coord.getId() + " at " + coord;
288 return offsetNod1;
289 }
290
291 public void setOffsets(Coord centralPoint) {
292 if(log.isDebugEnabled())
293 log.debug("center", centralPoint, ", coord", coord);
294 setLatOff(coord.getLatitude() - centralPoint.getLatitude());
295 setLonOff(coord.getLongitude() - centralPoint.getLongitude());
296 }
297
298 public Coord getCoord() {
299 return coord;
300 }
301
302 private void checkOffSize(int off) {
303 if (off > 0x7ff || off < -0x800)
304 // does off fit in signed 12 bit quantity?
305 flags |= F_LARGE_OFFSETS;
306 // does off fit in signed 16 bit quantity?
307 assert (off <= 0x7fff && off >= -0x8000);
308 }
309
310 private void setLatOff(int latOff) {
311 if(log.isDebugEnabled())
312 log.debug("lat off", Integer.toHexString(latOff));
313 this.latOff = latOff;
314 checkOffSize(latOff);
315 }
316
317 private void setLonOff(int lonOff) {
318 if(log.isDebugEnabled())
319 log.debug("long off", Integer.toHexString(lonOff));
320 this.lonOff = lonOff;
321 checkOffSize(lonOff);
322 }
323
324 /**
325 * Second pass over the nodes. Fill in pointers and Table A indices.
326 */
327 public void writeSecond(ImgFileWriter writer) {
328 for (RouteArc arc : arcs)
329 arc.writeSecond(writer);
330 }
331
332 /**
333 * Return the node's class, which is the maximum of
334 * classes of the roads it's on.
335 */
336 public int getNodeClass() {
337 return nodeClass;
338 }
339
340 public Iterable<RouteArc> arcsIteration() {
341 return arcs::iterator;
342 }
343
344 public List<RouteRestriction> getRestrictions() {
345 return restrictions;
346 }
347
348 public String toString() {
349 return String.valueOf(coord.getId()) + "@" + coord.toOSMURL();
350 }
351
352 /*
353 * For sorting node entries in NOD 3.
354 */
355 public int compareTo(RouteNode otherNode) {
356 return coord.compareTo(otherNode.getCoord());
357 }
358
359 public void reportSimilarArcs() {
360 for(int i = 0; i < arcs.size(); ++i) {
361 RouteArc arci = arcs.get(i);
362 RoadDef rdi = arci.getRoadDef();
363 if (!arci.isDirect() || rdi.isSynthesised())
364 continue;
365 for(int j = i + 1; j < arcs.size(); ++j) {
366 RouteArc arcj = arcs.get(j);
367 RoadDef rdj = arcj.getRoadDef();
368 if (!arcj.isDirect() || rdj.isSynthesised())
369 continue;
370 if(arci.getDest() == arcj.getDest() &&
371 arci.getLength() == arcj.getLength() &&
372 arci.getPointsHash() == arcj.getPointsHash() &&
373 !rdi.messagePreviouslyIssued("Similar arcs")) {
374 log.diagnostic("Similar arcs " + rdi + " and " + rdj + " found at " + coord.toOSMURL());
375 }
376 }
377 }
378 }
379
380 /**
381 * For each arc on the road, check if we can add indirect arcs to
382 * other nodes of the same road. This is done if the other node
383 * lies on a different road with a higher road class than the
384 * highest other road of the target node of the arc. We do this
385 * for both forward and reverse arcs. Multiple indirect arcs
386 * may be added for each Node. An indirect arc will
387 * always point to a higher road than the previous arc.
388 * The length and direct bearing of the additional arc is measured
389 * from the target node of the preceding arc to the new target node.
390 *
391 * Arcs for the same road/direction must be inserted directly after the
392 * direct arc and this allows the optimisation of initial bearing not being
393 * written. Note that this routine is called after AngleChecker.fixSharpAngles
394 * so the bearings will be consistent anyway.
395 *
396 * @param road
397 */
398 public void addArcsToMajorRoads(RoadDef road){
399 assert road.getNode() == this;
400 RouteNode current = this;
401 // the nodes of this road
402 List<RouteNode> nodes = new ArrayList<>();
403 // the forward arcs of this road
404 List<RouteArc> forwardArcs = new ArrayList<>();
405 // will contain the highest other road of each node
406 IntArrayList forwardArcPositions = new IntArrayList();
407 List<RouteArc> reverseArcs = new ArrayList<>();
408 IntArrayList reverseArcPositions = new IntArrayList();
409
410 // collect the nodes of the road and remember the arcs between them
411 nodes.add(current);
412 while (current != null){
413 RouteNode next = null;
414 for (int i = 0; i < current.arcs.size(); i++){
415 RouteArc arc = current.arcs.get(i);
416 if (arc.getRoadDef() == road && arc.isDirect()){
417 if (arc.isForward()){
418 next = arc.getDest();
419 nodes.add(next);
420 forwardArcs.add(arc);
421 forwardArcPositions.add(i);
422 } else {
423 reverseArcPositions.add(i);
424 reverseArcs.add(arc);
425 }
426 }
427 }
428 current = next;
429 }
430
431 if (nodes.size() < 3)
432 return;
433 ArrayList<RouteArc> newArcs = new ArrayList<>();
434 IntArrayList arcPositions = forwardArcPositions;
435 List<RouteArc> roadArcs = forwardArcs;
436 for (int dir = 0; dir < 2; dir++){
437 // forward arcs first
438 for (int i = 0; i + 2 < nodes.size(); i++){
439 RouteNode sourceNode = nodes.get(i); // original source node of direct arc
440 RouteNode stepNode = nodes.get(i+1);
441 RouteArc arcToStepNode = roadArcs.get(i);
442 assert arcToStepNode.getDest() == stepNode;
443 int currentClass = arcToStepNode.getArcDestClass();
444 int finalClass = road.getRoadClass();
445 if (finalClass <= currentClass)
446 continue;
447 newArcs.clear();
448 double partialArcLength = 0;
449 double pathLength = arcToStepNode.getLengthInMeter();
450 for (int j = i+2; j < nodes.size(); j++){
451 RouteArc arcToDest = roadArcs.get(j-1);
452 partialArcLength += arcToDest.getLengthInMeter();
453 pathLength += arcToDest.getLengthInMeter();
454 int cl = nodes.get(j).getGroup();
455 if (cl > currentClass){
456 if (cl > finalClass)
457 cl = finalClass;
458 currentClass = cl;
459 // create indirect arc from node i+1 to node j
460 RouteNode destNode = nodes.get(j);
461 Coord c1 = sourceNode.getCoord();
462 Coord c2 = destNode.getCoord();
463 RouteArc newArc = new RouteArc(road,
464 sourceNode,
465 destNode,
466 roadArcs.get(i).getInitialHeading(), // not used
467 c1.bearingTo(c2),
468 partialArcLength, // from stepNode to destNode on road
469 pathLength, // from sourceNode to destNode on road
470 c1.distance(c2),
471 c1.hashCode() + c2.hashCode());
472 if (arcToStepNode.isDirect())
473 arcToStepNode.setMaxDestClass(0);
474 else
475 newArc.setMaxDestClass(cl);
476 if (dir == 0)
477 newArc.setForward();
478 newArc.setIndirect();
479 newArcs.add(newArc);
480 arcToStepNode = newArc;
481
482 partialArcLength = 0;
483 if (cl >= finalClass)
484 break;
485 }
486 }
487 if (!newArcs.isEmpty()) {
488 int directArcPos = arcPositions.getInt(i);
489 assert nodes.get(i).arcs.get(directArcPos).isDirect();
490 assert nodes.get(i).arcs.get(directArcPos).getRoadDef() == newArcs.get(0).getRoadDef();
491 assert nodes.get(i).arcs.get(directArcPos).isForward() == newArcs.get(0).isForward();
492 nodes.get(i).arcs.addAll(directArcPos + 1, newArcs);
493 if (dir == 0 && i > 0){
494 // check if the inserted arcs change the position of the direct reverse arc
495 int reverseArcPos = reverseArcPositions.getInt(i-1); // i-1 because first node doesn't have reverse arc
496 if (directArcPos < reverseArcPos)
497 reverseArcPositions.set(i - 1, reverseArcPos + newArcs.size());
498 }
499 }
500 }
501 if (dir > 0)
502 break;
503 // reverse the arrays for the other direction
504 Collections.reverse(reverseArcs);
505 Collections.reverse(reverseArcPositions);
506 Collections.reverse(nodes);
507 arcPositions = reverseArcPositions;
508 roadArcs = reverseArcs;
509 }
510 }
511
512 /**
513 * Find the class group of the node. Rules:
514 * 1. Find the highest class which is used more than once.
515 * 2. Otherwise: use the class if the only one, or else the n-1 class.
516 * (eg: if [1,] then use 1, if [1,2,] then use 1, if [1,2,3,] then use 2.
517 *
518 * @return the class group
519 */
520 public int getGroup() {
521 if (nodeGroup < 0){
522 if (arcs.isEmpty()) {
523 nodeGroup = 0;
524 return nodeGroup;
525 }
526 HashSet<RoadDef> roads = new HashSet<>();
527 for (RouteArc arc: arcs){
528 roads.add(arc.getRoadDef());
529 }
530 int[] classes = new int[5];
531 int numClasses = 0;
532 // find highest class that is used more than once
533 for (RoadDef road: roads){
534 int cl = road.getRoadClass();
535 int n = ++classes[cl];
536 if (n == 1)
537 numClasses++;
538 else if (n > 1 && cl > nodeGroup)
539 nodeGroup = (byte) cl;
540 }
541 if (nodeGroup >= 0)
542 return nodeGroup;
543 if (numClasses == 1)
544 nodeGroup = nodeClass; // only one class
545 else {
546 // find n-1 class
547 int n = 0;
548 for (int cl = 4; cl >= 0; cl--){
549 if (classes[cl] > 0){
550 if (n == 1){
551 nodeGroup = (byte) cl;
552 break;
553 }
554 n++;
555 }
556 }
557 }
558 }
559 return nodeGroup;
560 }
561
562 public List<RouteArc> getArcs() {
563 return arcs;
564 }
565
566 @Override
567 public int hashCode() {
568 return getCoord().getId();
569 }
570
571 public List<RouteArc> getDirectArcsBetween(RouteNode otherNode) {
572 List<RouteArc> result = new ArrayList<>();
573 for(RouteArc a : arcs){
574 if(a.isDirect() && a.getDest() == otherNode){
575 result.add(a);
576 }
577 }
578 return result;
579 }
580
581 /** used to find routing island, but may also be used for other checks */
582 private int visitId;
583
584 public int getVisitID() {
585 return visitId;
586 }
587
588 public void visitNet(int visitId, List<RouteNode> visited) {
589 if (this.visitId != visitId) {
590 Deque<RouteNode> toVisit = new ArrayDeque<>();
591 toVisit.add(this);
592 while(!toVisit.isEmpty()) {
593 RouteNode n = toVisit.pop();
594 if (n.visitId != visitId) {
595 n.arcs.forEach(a -> toVisit.addLast(a.getDest()));
596 visited.add(n);
597 n.visitId = visitId;
598 }
599 }
600 }
601 }
602
603
604 public void setUseCompactDirs(boolean newValue) {
605 useCompactDirs = newValue;
606 }
607
608 public boolean getUseCompactDirs() {
609 return useCompactDirs;
610 }
611
612 public void setRoadClass(int roadClass) {
613 nodeClass = (byte) roadClass;
614 }
615
616 public static boolean isWarningLogged() {
617 return log.isLoggable(Level.WARNING);
618 }
619
620 // /**
621 // * simple-minded quick test for enabling RouteNode diagnostic for an area of interest.
622 // * leeway is in degrees
623 // */
624 // private boolean isClose(double latitude, double longitude, double leeway) {
625 // double nodeLat = coord.getLatDegrees();
626 // double nodeLon = coord.getLonDegrees();
627 // return nodeLat >= latitude - leeway && nodeLat <= latitude + leeway &&
628 // nodeLon >= longitude - leeway && nodeLon <= longitude + leeway;
629 // }
630 }