Debian Codegraph @

src/uk/me/parabola/imgfmt/app/trergn/Subdivision.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 Steve Ratcliffe
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 *
14 * Author: Steve Ratcliffe
15 * Create date: 07-Dec-2006
16 */
17 package uk.me.parabola.imgfmt.app.trergn;
18
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.List;
22
23 import uk.me.parabola.imgfmt.Utils;
24 import uk.me.parabola.imgfmt.app.Area;
25 import uk.me.parabola.imgfmt.app.Coord;
26 import uk.me.parabola.imgfmt.app.ImgFileReader;
27 import uk.me.parabola.imgfmt.app.ImgFileWriter;
28 import uk.me.parabola.imgfmt.app.Label;
29 import uk.me.parabola.imgfmt.app.lbl.LBLFile;
30 import uk.me.parabola.log.Logger;
31
32 /**
33 * The map is divided into areas, depending on the zoom level. These are
34 * known as subdivisions.
35 *
36 * A subdivision 'belongs' to a zoom level and cannot be interpreted correctly
37 * without knowing the <i>bitsPerCoord</i> of the associated zoom level.
38 *
39 * Subdivisions also form a tree as subdivisions are further divided at
40 * lower levels. The subdivisions need to know their child divisions
41 * because this information is represented in the map.
42 *
43 * @author Steve Ratcliffe
44 */
45 public class Subdivision {
46 private static final Logger log = Logger.getLogger(Subdivision.class);
47
48 private static final int MAP_POINT = 0;
49 private static final int MAP_INDEXED_POINT = 1;
50 private static final int MAP_LINE = 2;
51 private static final int MAP_SHAPE = 3;
52
53 private final LBLFile lblFile;
54 private final RGNFile rgnFile;
55
56 // The start pointer is set for read and write. The end pointer is only
57 // set for subdivisions that are read from a file.
58 private int startRgnPointer;
59 private int endRgnPointer;
60
61 private int lastMapElement;
62
63 // The zoom level contains the number of bits per coordinate which is
64 // critical for scaling quantities by.
65 private final Zoom zoomLevel;
66
67 private boolean hasPoints;
68 private boolean hasIndPoints;
69 private boolean hasPolylines;
70 private boolean hasPolygons;
71 private boolean hasRoadRefs;
72
73 private int numPolylines;
74
75 // The location of the central point, not scaled AFAIK
76 private final int longitude;
77 private final int latitude;
78
79 // The width and the height in map units scaled by the bits-per-coordinate
80 // that applies at the map level.
81 private final int width;
82 private final int height;
83
84 private int number;
85
86 // Set if this is the last one.
87 private boolean last;
88
89 private final List<Subdivision> divisions = new ArrayList<>();
90
91 private int extTypeAreasOffset;
92 private int extTypeLinesOffset;
93 private int extTypePointsOffset;
94 private int extTypeAreasSize;
95 private int extTypeLinesSize;
96 private int extTypePointsSize;
97
98 /**
99 * Subdivisions can not be created directly, use either the
100 * {@link #topLevelSubdivision} or {@link #createSubdivision} factory
101 * methods.
102 *
103 * @param ifiles The internal files.
104 * @param area The area this subdivision should cover.
105 * @param z The zoom level.
106 */
107 private Subdivision(InternalFiles ifiles, Area area, Zoom z) {
108 this.lblFile = ifiles.getLblFile();
109 this.rgnFile = ifiles.getRgnFile();
110
111 this.zoomLevel = z;
112
113 int shift = getShift();
114 int mask = getMask();
115
116 // Calculate the center, move it right and up so that it lies on a point
117 // which is divisible by 2 ^shift
118 this.latitude = Utils.roundUp((area.getMinLat() + area.getMaxLat())/2, shift);
119 this.longitude = Utils.roundUp((area.getMinLong() + area.getMaxLong())/2, shift);
120 int w = 2 * (longitude - area.getMinLong());
121 int h = 2 * (latitude - area.getMinLat());
122
123 // encode the values for the img format
124 w = ((w + 1)/2 + mask) >> shift;
125 h = ((h + 1)/2 + mask) >> shift;
126
127 if (w > 0x7fff) {
128 log.warn("Subdivision width is " + w + " at " + getCenter().toOSMURL());
129 w = 0x7fff;
130 }
131 if (w < 0) { // think can get this from empty/unbounded maps
132 log.error("Subdivision neg width", w, "min=", area.getMinLong(), "mid=", longitude, "max=", area.getMaxLong(), "shift=", shift, "mask=", mask, "@", getCenter().toOSMURL());
133 w = 0x7fff;
134 }
135
136 if (h > 0xffff) {
137 log.warn("Subdivision height is " + h + " at " + getCenter().toOSMURL());
138 h = 0xffff;
139 }
140 if (h < 0) { // think can get this from empty/unbounded maps
141 log.error("Subdivision neg height", h, "min=", area.getMinLat(), "mid=", latitude, "max=", area.getMaxLat(),
142 "shift=", shift, "mask=", mask, "@", getCenter().toOSMURL());
143 h = 0xffff;
144 }
145
146 this.width = w;
147 this.height = h;
148 }
149
150 private Subdivision(Zoom z, SubdivData data) {
151 lblFile = null;
152 rgnFile = null;
153 zoomLevel = z;
154 latitude = data.getLat();
155 longitude = data.getLon();
156 this.width = data.getWidth();
157 this.height = data.getHeight();
158
159 startRgnPointer = data.getRgnPointer();
160 endRgnPointer = data.getEndRgnOffset();
161
162 int elem = data.getFlags();
163 if ((elem & 0x10) != 0)
164 setHasPoints(true);
165 if ((elem & 0x20) != 0)
166 setHasIndPoints(true);
167 if ((elem & 0x40) != 0)
168 setHasPolylines(true);
169 if ((elem & 0x80) != 0)
170 setHasPolygons(true);
171 if ((elem & 0x1) != 0) // from top bit in height
172 setHasRoadRefs(true);
173 }
174
175 /**
176 * Create a subdivision at a given zoom level.
177 *
178 * @param ifiles The RGN and LBL ifiles.
179 * @param area The (unshifted) area that the subdivision covers.
180 * @param zoom The zoom level that this division occupies.
181 *
182 * @return A new subdivision.
183 */
184 public Subdivision createSubdivision(InternalFiles ifiles,
185 Area area, Zoom zoom)
186 {
187 Subdivision div = new Subdivision(ifiles, area, zoom);
188 zoom.addSubdivision(div);
189 addSubdivision(div);
190 return div;
191 }
192
193 /**
194 * This should be called only once per map to create the top level
195 * subdivision. The top level subdivision covers the whole map and it
196 * must be empty.
197 *
198 * @param ifiles The LBL and RGN ifiles.
199 * @param area The area bounded by the map.
200 * @param zoom The zoom level which must be the highest (least detailed)
201 * zoom in the map.
202 *
203 * @return The new subdivision.
204 */
205 public static Subdivision topLevelSubdivision(InternalFiles ifiles,
206 Area area, Zoom zoom)
207 {
208 Subdivision div = new Subdivision(ifiles, area, zoom);
209 zoom.addSubdivision(div);
210 return div;
211 }
212
213 /**
214 * Create a subdivision that only contains the number. This is only
215 * used when reading cities and similar such usages that do not really
216 * require the full subdivision to be present.
217 * @param number The subdivision number.
218 * @return An empty subdivision. Any operation other than getting the
219 * subdiv number is likely to fail.
220 */
221 public static Subdivision createEmptySubdivision(int number) {
222 Subdivision sd = new Subdivision(null, new SubdivData(0,0,0,0,0,0,0));
223 sd.setNumber(number);
224 return sd;
225 }
226
227 public static Subdivision readSubdivision(Zoom zoom, SubdivData subdivData) {
228 return new Subdivision(zoom, subdivData);
229 }
230
231 public Zoom getZoom() {
232 return zoomLevel;
233 }
234
235 /**
236 * Get the shift value, that is the number of bits to left shift by for
237 * values that need to be saved shifted in the file. Related to the
238 * resolution.
239 *
240 * @return The shift value. It is 24 minus the number of bits per coord.
241 * @see #getResolution()
242 */
243 public final int getShift() {
244 return 24 - zoomLevel.getResolution();
245 }
246
247 /**
248 * Get the shift mask. The bits that will be lost due to the resolution
249 * shift level.
250 *
251 * @return A bit mask with the lower <i>shift</i> bits set.
252 */
253 protected int getMask() {
254 return (1 << getShift()) - 1;
255 }
256
257 /**
258 * Get the resolution of this division. Resolution goes from 1 to 24
259 * and the higher the number the more detail there is.
260 *
261 * @return The resolution.
262 */
263 public final int getResolution() {
264 return zoomLevel.getResolution();
265 }
266
267 /**
268 * Format this record to the file.
269 *
270 * @param file The file to write to.
271 */
272 public void write(ImgFileWriter file) {
273 log.debug("write subdiv", latitude, longitude);
274 file.put3u(startRgnPointer);
275 file.put1u(getType());
276 Utils.put3sLongitude(file, longitude);
277 file.put3s(latitude);
278
279 assert width <= 0x7fff;
280 assert height <= 0xffff;
281 file.put2u(width | ((last) ? 0x8000 : 0));
282 file.put2u(height);
283
284 if (!divisions.isEmpty()) {
285 file.put2u(getNextLevel());
286 }
287 }
288
289 public Point createPoint(String name) {
290 Point p = new Point(this);
291 Label label = lblFile.newLabel(name);
292
293 p.setLabel(label);
294 return p;
295 }
296
297 public Polyline createLine(String[] labels) {
298 // don't be tempted to "trim()" the name as it zaps the highway shields
299 Label label = lblFile.newLabel(labels[0]);
300 String nameSansGC = Label.stripGarminCodes(labels[0]);
301 Polyline pl = new Polyline(this);
302
303 pl.setLabel(label);
304
305 if(labels[1] != null) {
306 // ref may contain multiple ids separated by ";"
307 int maxSetIdx = 3;
308 if (labels[3] == null) {
309 if (labels[2] == null) {
310 maxSetIdx = 1;
311 } else {
312 maxSetIdx = 2;
313 }
314 }
315
316 String[] refs = Arrays.copyOfRange(labels, 1, maxSetIdx+1);
317 if(refs.length == 1) {
318 // don't bother to add a single ref that looks the
319 // same as the name (sans shield) because it doesn't
320 // change the routing directions
321 String tr = refs[0].trim();
322 String trSansGC = Label.stripGarminCodes(tr);
323 if(trSansGC.length() > 0 &&
324 !trSansGC.equalsIgnoreCase(nameSansGC)) {
325 pl.addRefLabel(lblFile.newLabel(tr));
326 }
327 }
328 else if (refs.length > 1){
329 // multiple refs, always add the first so that it will
330 // be used in routing instructions when the name has a
331 // shield prefix
332 pl.addRefLabel(lblFile.newLabel(refs[0].trim()));
333
334 // only add the remaining refs if they differ from the
335 // name (sans shield)
336 for(int i = 1; i < refs.length; ++i) {
337 String tr = refs[i].trim();
338 String trSansGC = Label.stripGarminCodes(tr);
339 if(trSansGC.length() > 0 &&
340 !trSansGC.equalsIgnoreCase(nameSansGC)) {
341 pl.addRefLabel(lblFile.newLabel(tr));
342 }
343 }
344 }
345 }
346 return pl;
347 }
348
349 public void setPolylineNumber(Polyline pl) {
350 pl.setNumber(++numPolylines);
351 }
352
353 public Polygon createPolygon(String name) {
354 Label label = lblFile.newLabel(name);
355 Polygon pg = new Polygon(this);
356
357 pg.setLabel(label);
358 return pg;
359 }
360
361 public void setNumber(int n) {
362 number = n;
363 }
364
365 public void setLast(boolean last) {
366 this.last = last;
367 }
368
369 public void setStartRgnPointer(int startRgnPointer) {
370 this.startRgnPointer = startRgnPointer;
371 }
372
373 public int getStartRgnPointer() {
374 return startRgnPointer;
375 }
376
377 public int getEndRgnPointer() {
378 return endRgnPointer;
379 }
380
381 public int getLongitude() {
382 return longitude;
383 }
384
385 public int getLatitude() {
386 return latitude;
387 }
388
389 public void setHasPoints(boolean hasPoints) {
390 this.hasPoints = hasPoints;
391 }
392
393 public void setHasIndPoints(boolean hasIndPoints) {
394 this.hasIndPoints = hasIndPoints;
395 }
396
397 public void setHasPolylines(boolean hasPolylines) {
398 this.hasPolylines = hasPolylines;
399 }
400
401 public void setHasPolygons(boolean hasPolygons) {
402 this.hasPolygons = hasPolygons;
403 }
404
405 public void setHasRoadRefs(boolean hasRoeadRefs) {
406 this.hasRoadRefs = hasRoeadRefs;
407 }
408
409 public boolean hasPoints() {
410 return hasPoints;
411 }
412
413 public boolean hasIndPoints() {
414 return hasIndPoints;
415 }
416
417 public boolean hasPolylines() {
418 return hasPolylines;
419 }
420
421 public boolean hasPolygons() {
422 return hasPolygons;
423 }
424
425 public boolean hasRoadRefs() {
426 return hasRoadRefs;
427 }
428
429 /**
430 * Needed if it exists and is not first, ie there is a points
431 * section.
432 * @return true if pointer needed
433 */
434 public boolean needsIndPointPtr() {
435 return hasIndPoints && hasPoints;
436 }
437
438 /**
439 * Needed if it exists and is not first, ie there is a points or
440 * indexed points section.
441 * @return true if pointer needed.
442 */
443 public boolean needsPolylinePtr() {
444 return hasPolylines && (hasPoints || hasIndPoints);
445 }
446
447 /**
448 * Needed if it exists and is not first, ie there is a points or
449 * indexed points or polyline section.
450 * @return true if pointer needed.
451 */
452 public boolean needsPolygonPtr() {
453 return hasPolygons && (hasPoints || hasIndPoints || hasPolylines);
454 }
455
456 /**
457 * As this is last in the list it is needed if it exists and there
458 * is another section.
459 * @return true if pointer needed.
460 */
461 public boolean needsRoadRefPtr() {
462 return hasRoadRefs && (hasPoints || hasIndPoints || hasPolylines || hasPolygons);
463 }
464
465 public String toString() {
466 return "Sub" + zoomLevel + '(' + getCenter().toOSMURL() + ')';
467 }
468 /**
469 * Get a type that shows if this area has lines, points etc.
470 *
471 * @return A code showing what kinds of element are in this subdivision.
472 */
473 private int getType() {
474 int b = 0;
475 if (hasPoints)
476 b |= 0x10;
477 if (hasIndPoints)
478 b |= 0x20;
479 if (hasPolylines)
480 b |= 0x40;
481 if (hasPolygons)
482 b |= 0x80;
483
484 return b;
485 }
486 /**
487 * Get the number of the first subdivision at the next level.
488 * @return The first subdivision at the next level.
489 */
490 private int getNextLevel() {
491 return divisions.get(0).getNumber();
492 }
493
494 public boolean hasNextLevel() {
495 return !divisions.isEmpty();
496 }
497
498 public int getExtTypeAreasOffset() {
499 return extTypeAreasOffset;
500 }
501
502 public int getExtTypeLinesOffset() {
503 return extTypeLinesOffset;
504 }
505
506 public int getExtTypePointsOffset() {
507 return extTypePointsOffset;
508 }
509
510 public int getExtTypeAreasSize() {
511 return extTypeAreasSize;
512 }
513
514 public int getExtTypeLinesSize() {
515 return extTypeLinesSize;
516 }
517
518 public int getExtTypePointsSize() {
519 return extTypePointsSize;
520 }
521
522 public void startDivision() {
523 rgnFile.startDivision(this);
524 extTypeAreasOffset = rgnFile.getExtTypeAreasSize();
525 extTypeLinesOffset = rgnFile.getExtTypeLinesSize();
526 extTypePointsOffset = rgnFile.getExtTypePointsSize();
527 assert extTypeAreasOffset >= 0;
528 assert extTypeLinesOffset >= 0;
529 assert extTypePointsOffset >= 0;
530
531 }
532
533 public void endDivision() {
534 extTypeAreasSize = rgnFile.getExtTypeAreasSize() - extTypeAreasOffset;
535 extTypeLinesSize = rgnFile.getExtTypeLinesSize() - extTypeLinesOffset;
536 extTypePointsSize = rgnFile.getExtTypePointsSize() - extTypePointsOffset;
537 assert extTypeAreasSize >= 0;
538 assert extTypeLinesSize >= 0;
539 assert extTypePointsSize >= 0;
540 }
541
542 public void writeExtTypeOffsetsRecord(ImgFileWriter file) {
543 file.put4(extTypeAreasOffset);
544 file.put4(extTypeLinesOffset);
545 file.put4(extTypePointsOffset);
546 int kinds = 0;
547 if(extTypeAreasSize != 0)
548 ++kinds;
549 if(extTypeLinesSize != 0)
550 ++kinds;
551 if(extTypePointsSize != 0)
552 ++kinds;
553 file.put1u(kinds);
554 }
555
556 public void writeLastExtTypeOffsetsRecord(ImgFileWriter file) {
557 file.put4(rgnFile.getExtTypeAreasSize());
558 file.put4(rgnFile.getExtTypeLinesSize());
559 file.put4(rgnFile.getExtTypePointsSize());
560 file.put1u(0);
561 }
562
563 /**
564 * Read offsets for extended type data and set sizes for predecessor sub-div.
565 * Corresponds to {@link #writeExtTypeOffsetsRecord(ImgFileWriter)}
566 * @param reader the reader
567 * @param sdPrev the pred. sub-div or null
568 * @param size the record size
569 * @param tre7Magic the magic value from TRE7 section
570 */
571 public void readExtTypeOffsetsRecord(ImgFileReader reader, Subdivision sdPrev, int size, int tre7Magic) {
572 long nextPos = reader.position() + size;
573 if ((tre7Magic & 0x1) != 0)
574 extTypeAreasOffset = reader.get4();
575 if ((tre7Magic & 0x2) != 0)
576 extTypeLinesOffset = reader.get4();
577 if ((tre7Magic & 0x4) != 0)
578 extTypePointsOffset = reader.get4();
579 reader.position(nextPos);
580 assert extTypeAreasOffset >= 0;
581 assert extTypeLinesOffset >= 0;
582 assert extTypePointsOffset >= 0;
583
584 if (sdPrev != null){
585 sdPrev.extTypeAreasSize = extTypeAreasOffset - sdPrev.extTypeAreasOffset;
586 sdPrev.extTypeLinesSize = extTypeLinesOffset - sdPrev.extTypeLinesOffset;
587 sdPrev.extTypePointsSize = extTypePointsOffset - sdPrev.extTypePointsOffset;
588 assert sdPrev.extTypeAreasSize >= 0;
589 assert sdPrev.extTypeLinesSize >= 0;
590 assert sdPrev.extTypePointsSize >= 0;
591 }
592 }
593 /**
594 * Set the sizes for the extended type data. See {@link #writeLastExtTypeOffsetsRecord(ImgFileWriter)}
595 * @param reader the reader
596 * @param size the record size
597 * @param tre7Magic the magic value from TRE7 section
598 */
599 public void readLastExtTypeOffsetsRecord(ImgFileReader reader, int size, int tre7Magic) {
600 long nextPos = reader.position() + size;
601 if ((tre7Magic & 0x1) != 0)
602 extTypeAreasSize = reader.get4() - extTypeAreasOffset;
603 if ((tre7Magic & 0x2) != 0)
604 extTypeLinesSize = reader.get4() - extTypeLinesOffset;
605 if ((tre7Magic & 0x4) != 0)
606 extTypePointsSize = reader.get4() - extTypePointsOffset;
607 assert extTypeAreasSize >= 0;
608 assert extTypeLinesSize >= 0;
609 assert extTypePointsSize >= 0;
610 reader.position(nextPos);
611 }
612
613 /**
614 * Add this subdivision as our child at the next level. Each subdivision
615 * can be further divided into smaller divisions. They form a tree like
616 * arrangement.
617 *
618 * @param sd One of our subdivisions.
619 */
620 private void addSubdivision(Subdivision sd) {
621 divisions.add(sd);
622 }
623
624 public int getNumber() {
625 return number;
626 }
627
628 /**
629 * We are starting to draw the points. These must be done first.
630 */
631 public void startPoints() {
632 if (lastMapElement > MAP_POINT)
633 throw new IllegalStateException("Points must be drawn first");
634
635 lastMapElement = MAP_POINT;
636 }
637
638 /**
639 * We are starting to draw the lines. These must be done before
640 * polygons.
641 */
642 public void startIndPoints() {
643 if (lastMapElement > MAP_INDEXED_POINT)
644 throw new IllegalStateException("Indexed points must be done before lines and polygons");
645
646 lastMapElement = MAP_INDEXED_POINT;
647
648 rgnFile.setIndPointPtr();
649 }
650
651 /**
652 * We are starting to draw the lines. These must be done before
653 * polygons.
654 */
655 public void startLines() {
656 if (lastMapElement > MAP_LINE)
657 throw new IllegalStateException("Lines must be done before polygons");
658
659 lastMapElement = MAP_LINE;
660
661 rgnFile.setPolylinePtr();
662 }
663
664 /**
665 * We are starting to draw the shapes. This is done last.
666 */
667 public void startShapes() {
668
669 lastMapElement = MAP_SHAPE;
670
671 rgnFile.setPolygonPtr();
672 }
673
674 /**
675 * Convert an absolute Lat to a local, shifted value
676 */
677 public int roundLatToLocalShifted(int absval) {
678 int shift = getShift();
679 int val = absval - getLatitude();
680 val += ((1 << shift) / 2);
681 return (val >> shift);
682 }
683
684 /**
685 * Convert an absolute Lon to a local, shifted value
686 */
687 public int roundLonToLocalShifted(int absval) {
688 int shift = getShift();
689 int val = absval - getLongitude();
690 val += ((1 << shift) / 2);
691 return (val >> shift);
692 }
693
694
695 public Coord getCenter(){
696 return new Coord(getLatitude(),getLongitude());
697 }
698
699 /**
700 * Get the unshifted width of the subdivision.
701 * @return The true (unshifted) width.
702 */
703 public int getWidth() {
704 return width << getShift();
705 }
706
707 /**
708 * Get the unshifted height of the subdivision.
709 * @return The true (unshifted) height.
710 */
711 public int getHeight() {
712 return height << getShift();
713 }
714 }