Debian Codegraph @

src/uk/me/parabola/imgfmt/app/net/RouteArc.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 uk.me.parabola.imgfmt.app.ImgFileWriter;
18 import uk.me.parabola.log.Logger;
19
20 /**
21 * An arc joins two nodes within a {@link RouteCenter}. This may be renamed
22 * to a Segment.
23 * The arc also references the road that it is a part of.
24 *
25 * There are also links between nodes in different centers.
26 *
27 * @author Steve Ratcliffe
28 */
29 public class RouteArc {
30 private static final Logger log = Logger.getLogger(RouteArc.class);
31
32 // Flags A
33 private static final int FLAG_HASNET = 0x80;
34 private static final int FLAG_FORWARD = 0x40;
35 private static final int MASK_DESTCLASS = 0x7;
36 public static final int MASK_CURVE_LEN = 0x38;
37
38 // Flags B
39 private static final int FLAG_LAST_LINK = 0x80;
40 private static final int FLAG_EXTERNAL = 0x40;
41
42 private int offset;
43
44 // heading / bearing: -180 <= val < +180
45 private float initialHeading; // degrees (A-> B in an arc ABCD)
46 private final float directHeading; // degrees (A-> D in an arc ABCD)
47
48 private final RoadDef roadDef;
49
50 // The nodes that this arc comes from and goes to
51 private final RouteNode source;
52 private final RouteNode dest;
53
54 // The index in Table A describing this arc.
55 private int indexA;
56 // The index in Table B that this arc goes via, if external.
57 private int indexB;
58
59 private int flagA;
60 private int flagB;
61
62 private final boolean haveCurve;
63 private final int length;
64 private final byte lengthRatio;
65 private final int pointsHash;
66 private boolean isForward;
67 private final float lengthInMeter;
68
69 private boolean isDirect;
70
71 // this field may limit the arcs destination class
72 private byte maxDestClass = -1;
73
74 // pointer to the reverse arc if this is a direct arc
75 private RouteArc reverseArc;
76
77 /**
78 * Create a new arc. An arc can contain multiple points (eg. A->B->C->D->E)
79 * @param roadDef The road that this arc segment is part of.
80 * @param source The source node. (A)
81 * @param dest The destination node (E).
82 * @param initialBearing The initial heading (signed degrees) (A->B)
83 * @param directBearing The direct heading (signed degrees) (A->E)
84 * @param arcLength the length of the arc in meter (A->B->C->D->E)
85 * @param pathLength the length of the arc in meter (summed length for additional arcs)
86 * @param directLength the length of the arc in meter (A-E)
87 * @param pointsHash
88 */
89 public RouteArc(RoadDef roadDef,
90 RouteNode source, RouteNode dest,
91 double initialBearing, double directBearing,
92 double arcLength,
93 double pathLength,
94 double directLength,
95 int pointsHash) {
96 this.isDirect = true; // unless changed
97 this.roadDef = roadDef;
98 this.source = source;
99 this.dest = dest;
100 this.initialHeading = initialBearing >= 180 ? (float)(initialBearing - 360) : (float)initialBearing;
101 // bearingTo can return +180 and inversions elsewhere simply adds 180 so return to normalised (-180 <= deg < +180)
102 this.directHeading = directBearing >= 180 ? (float)(directBearing - 360) : (float)directBearing;
103 int len = NODHeader.metersToRaw(arcLength);
104 if (len >= (1 << 22)) {
105 log.error("Way " + roadDef.getName() + " (id " + roadDef.getId() + ") contains an arc whose length (" + len + " units) is too big to be encoded, using length",((1 << 22) - 1));
106 len = (1 << 22) - 1;
107 }
108 this.length = len;
109 this.lengthInMeter = (float) arcLength;
110 this.pointsHash = pointsHash;
111 // calculate length ratio between way length on road and direct distance between end points
112 int ratio = 0;
113 int pathEncoded = NODHeader.metersToRaw(pathLength);
114 if (pathEncoded >= 2){
115 int directEncoded = NODHeader.metersToRaw(directLength);
116 if (pathEncoded > directEncoded){
117 ratio = (int) Math.min(31, Math.round(32.0d * directLength/ pathLength));
118 }
119 }
120 if (ratio == 0 && len >= (1 << 14))
121 ratio = 0x1f; // force encoding of curve info for very long arcs
122 lengthRatio = (byte)ratio;
123 haveCurve = lengthRatio > 0;
124 }
125
126 public float getInitialHeading() {
127 return initialHeading;
128 }
129
130 public float getDirectHeading() {
131 return directHeading;
132 }
133
134 public void setInitialHeading(float ih) {
135 initialHeading = ih;
136 }
137
138 public void modInitialHeading(float adjust) {
139 initialHeading += adjust;
140 if (initialHeading >= 180)
141 initialHeading -= 360;
142 else if (initialHeading < -180)
143 initialHeading += 360;
144 }
145
146 public float getFinalHeading() {
147 float fh = 0;
148 if (lengthInMeter != 0){
149 fh = getReverseArc().getInitialHeading() + 180;
150 if (fh >= 180)
151 fh -= 360;
152 }
153 return fh;
154 }
155
156 public RouteNode getSource() {
157 return source;
158 }
159
160 public RouteNode getDest() {
161 return dest;
162 }
163
164 public int getLength() {
165 return length;
166 }
167
168 public int getPointsHash() {
169 return pointsHash;
170 }
171
172 /**
173 * Provide an upper bound for the written size in bytes.
174 */
175 public int boundSize() {
176
177 int[] lendat = encodeLength();
178 //TODO: take into account that initialHeading and indexA are not always written
179 // 1 (flagA) + 1-2 (offset) + 1 (indexA) + 1 (initialHeading)
180 int size = 5 + lendat.length;
181 if(haveCurve)
182 size += encodeCurve().length;
183 return size;
184 }
185
186 /**
187 * Is this an arc within the RouteCenter?
188 */
189 public boolean isInternal() {
190 // we might check that setInternal has been called before
191 return (flagB & FLAG_EXTERNAL) == 0;
192 }
193
194 public void setInternal(boolean internal) {
195 if (internal)
196 flagB &= ~FLAG_EXTERNAL;
197 else
198 flagB |= FLAG_EXTERNAL;
199 }
200
201
202 /**
203 * Set this arc's index into Table A.
204 */
205 public void setIndexA(int indexA) {
206 this.indexA = indexA;
207 }
208
209 /**
210 * Get this arc's index into Table A.
211 *
212 * Required for writing restrictions (Table C).
213 */
214 public int getIndexA() {
215 return indexA;
216 }
217
218 /**
219 * Set this arc's index into Table B. Applies to external arcs only.
220 */
221 public void setIndexB(int indexB) {
222 assert !isInternal() : "Trying to set index on internal arc.";
223 this.indexB = indexB;
224 }
225
226 /**
227 * Get this arc's index into Table B.
228 *
229 * Required for writing restrictions (Table C).
230 */
231 public int getIndexB() {
232 return indexB; // ??? & 0xff;
233 }
234
235 public int getArcDestClass(){
236 return Math.min(getRoadDef().getRoadClass(), dest.getGroup());
237 }
238
239 public float getLengthInMeter(){
240 return lengthInMeter;
241 }
242
243 public static byte directionFromDegrees(float dir) {
244 return (byte) Math.round(dir * 256 / 360);
245 }
246
247 /*
248 * return heading as value 0..15, where 0 is North +-11.25 degrees
249 */
250 public static int compactDirFromDegrees(float dir) {
251 return ((directionFromDegrees(dir) + 8) >> 4) & 0x0f;
252 }
253
254 /**
255 * RouteArc binary format has various space saving measures:
256 * 1/ flag on first arc to indicate compactDirs format is used for all arcs in the RouteNode.
257 * 2/ flag on subsequent arcs to indicate a change in indexA==road. Uses the same bit as above.
258 * 3/ flag isForward - the arc destination is further along the line.
259 *
260 * indexA is written for the first arc and when indexA changes.
261 * initialHeading is 'required' for a new indexA or a change in isForward.
262 * NB: addArcsToMajorRoads() adds arcs with the same indexA, initialHeading and isForward.
263 * compactDirs uses 4 bits for the initialHeading rather than 8, giving 16 possible headings
264 * rather than 256. These are grouped in pairs, with the other 4 bits are being used for the
265 * next 'required' initialHeading, independent of changes to indexA/isForward.
266 * There doesn't seem to be any detectable behaviour change in using a compactDirs pair for the
267 * forward and reverse heading for the same road.
268 */
269 public void write(ImgFileWriter writer, RouteArc lastArc, boolean useCompactDirs, Byte compactedDir) {
270 boolean first = lastArc == null;
271 if (first){
272 if (useCompactDirs)
273 flagA |= FLAG_HASNET; // first arc: the 1 tells us that initial directions are in compacted format
274 } else {
275 if (lastArc.getRoadDef() != this.getRoadDef())
276 flagA |= FLAG_HASNET; // not first arc: the 1 tells us that we have to read table A
277
278 }
279
280 if (isForward)
281 flagA |= FLAG_FORWARD;
282
283 offset = writer.position();
284 if(log.isDebugEnabled())
285 log.debug("writing arc at", offset, ", flagA=", Integer.toHexString(flagA));
286
287 // fetch destination class -- will have been set correctly by now
288 setDestinationClass(getArcDestClass());
289
290 // determine how to write length and curve bit
291 int[] lendat = encodeLength();
292
293 writer.put1u(flagA);
294 if (isInternal()) {
295 // space for 14 bit node offset, written in writeSecond.
296 writer.put1u(flagB);
297 writer.put1u(0);
298 } else {
299 if(indexB < 0 || indexB >= 0x3f) {
300 writer.put1u(flagB | 0x3f);
301 writer.put1u(indexB);
302 }
303 else
304 writer.put1u(flagB | indexB);
305 }
306
307 // only write out the local net index if it is the first arc or else if newDir is set.
308 if (first || lastArc.indexA != this.indexA)
309 writer.put1u(indexA);
310
311 if(log.isDebugEnabled())
312 log.debug("writing length", length);
313 for (int aLendat : lendat)
314 writer.put((byte) aLendat);
315
316 if (first || lastArc.indexA != this.indexA || lastArc.isForward != isForward){
317 if (useCompactDirs){
318 // determine if we have to write direction info
319 if (compactedDir != null)
320 writer.put(compactedDir); // composite byte = dont check
321 } else {
322 writer.put(directionFromDegrees(initialHeading));
323 }
324 }
325 if (haveCurve) {
326 int[] curvedat = encodeCurve();
327 for (int aCurvedat : curvedat)
328 writer.put((byte) aCurvedat);
329 }
330 }
331
332 /**
333 * Second pass over the nodes in this RouteCenter.
334 * Node offsets are now all known, so we can write the pointers
335 * for internal arcs.
336 */
337 public void writeSecond(ImgFileWriter writer) {
338 if (!isInternal())
339 return;
340
341 writer.position(offset + 1L);
342 int val = flagB << 8;
343 int diff = dest.getOffsetNod1() - source.getOffsetNod1();
344 assert diff < 0x2000 && diff >= -0x2000
345 : "relative pointer too large for 14 bits (source offset = " + source.getOffsetNod1() + ", dest offset = " + dest.getOffsetNod1() + ")";
346 val |= diff & 0x3fff;
347
348 // We write this big endian
349 if(log.isDebugEnabled())
350 log.debug("val is", Integer.toHexString(val));
351 writer.put1u(val >> 8);
352 writer.put1u(val & 0xff);
353 }
354
355 /*
356 * length and curve flag are stored in a variety of ways, involving
357 * 1. flagA & 0x38 (3 bits)
358 * 2. 1-3 bytes following the possible Table A index
359 *
360 * There's even more different encodings supposedly.
361 */
362 private int[] encodeLength() {
363 int[] lendat;
364 if(length < 0x300 || (length < 0x400 && !haveCurve)) {
365 // 10 bit length optional curve
366 // clear bits
367 flagA &= ~0x38;
368
369 if(haveCurve)
370 flagA |= 0x20;
371 flagA |= (length >> 5) & 0x18; // top two bits of length (at least one must be zero)
372 lendat = new int[1]; // one byte of data
373 lendat[0] = length; // bottom 8 bits of length
374 assert (flagA & 0x38) != 0x38;
375 } else {
376 flagA |= 0x38; // all three bits set
377 if(length >= (1 << 14)) {
378 // 22 bit length with curve
379 lendat = new int[3]; // three bytes of data
380 lendat[0] = 0xC0 | (length & 0x3f); // 0x80 set, 0x40 set, 6 low bits of length
381 lendat[1] = (length >> 6) & 0xff; // 8 more bits of length
382 lendat[2] = (length >> 14) & 0xff; // 8 more bits of length
383 }
384 else if(haveCurve) {
385 // 15 bit length with curve
386 lendat = new int[2]; // two bytes of data
387 lendat[0] = (length & 0x7f); // 0x80 not set, 7 low bits of length
388 lendat[1] = (length >> 7) & 0xff; // 8 more bits of length
389 }
390 else {
391 // 14 bit length no curve
392 lendat = new int[2]; // two bytes of data
393 lendat[0] = 0x80 | (length & 0x3f); // 0x80 set, 0x40 not set, 6 low bits of length
394 lendat[1] = (length >> 6) & 0xff; // 8 more bits of length
395 }
396 }
397 return lendat;
398 }
399
400 /**
401 * Encode the curve data into a sequence of bytes.
402 * Curve data contains a ratio between arc length and direct distance
403 * and the direct bearing. This is typically encode in one byte,
404 * for extreme ratios two bytes are used.
405 */
406 private int[] encodeCurve() {
407 assert lengthRatio != 0;
408 int[] curveData;
409 int dh = directionFromDegrees(directHeading);
410 if (lengthRatio >= 1 && lengthRatio <= 17) {
411 // two byte curve data neeeded
412 curveData = new int[2];
413 curveData[0] = lengthRatio;
414 curveData[1] = dh;
415
416 } else {
417 // use compacted form
418 int compactedRatio = lengthRatio / 2 - 8;
419 assert compactedRatio > 0 && compactedRatio < 8;
420 curveData = new int[1];
421 curveData[0] = (compactedRatio << 5) | ((dh >> 3) & 0x1f);
422
423 /* check math:
424 int dhx = curveData[0] & 0x1f;
425 int decodedDirectHeading = (dhx <16) ? dhx << 3 : -(256 - (dhx<<3));
426 if ((byte) (dh & 0xfffffff8) != (byte) decodedDirectHeading)
427 log.error("failed to encode direct heading", directHeading, dh, decodedDirectHeading);
428 int ratio = (curveData[0] & 0xe0) >> 5;
429 if (ratio != compactedRatio)
430 log.error("failed to encode length ratio", lengthRatio, compactedRatio, ratio);
431 */
432 }
433 return curveData;
434 }
435
436 public RoadDef getRoadDef() {
437 return roadDef;
438 }
439
440 public void setForward() {
441 isForward = true;
442 }
443
444 public boolean isForward() {
445 return isForward;
446 }
447
448 public void setLast() {
449 flagB |= FLAG_LAST_LINK;
450 }
451
452 protected void setDestinationClass(int destinationClass) {
453 if(log.isDebugEnabled())
454 log.debug("setting destination class", destinationClass);
455 flagA |= (destinationClass & MASK_DESTCLASS);
456 }
457
458 public void setIndirect() {
459 this.isDirect = false;
460
461 }
462
463 public boolean isDirect() {
464 return isDirect;
465 }
466
467 public void setMaxDestClass(int destClass) {
468 if (this.maxDestClass < 0)
469 this.maxDestClass = (byte) destClass;
470 else if (destClass < maxDestClass)
471 maxDestClass = (byte)destClass;
472 }
473
474 @Override
475 public String toString() {
476 return "RouteArc [" + (isForward ? "->":"<-") + (isDirect ? "direct":"indirect")
477 + roadDef + " " + dest + "]";
478 }
479
480 public RouteArc getReverseArc() {
481 return reverseArc;
482 }
483
484 public void setReverseArc(RouteArc reverseArc) {
485 this.reverseArc = reverseArc;
486 }
487 }