Add observers to GraphReader.

This commit is contained in:
Holt59 2018-02-27 23:23:22 +01:00
parent 7b2f3f3549
commit 823ed07770
6 changed files with 450 additions and 207 deletions

View File

@ -14,157 +14,186 @@ import org.insa.graph.RoadInformation.RoadType;
public class BinaryGraphReaderV2 extends BinaryReader implements GraphReader { public class BinaryGraphReaderV2 extends BinaryReader implements GraphReader {
// Map version and magic number targeted for this reader. // Map version and magic number targeted for this reader.
private static final int VERSION = 5; private static final int VERSION = 5;
private static final int MAGIC_NUMBER = 0x208BC3B3; private static final int MAGIC_NUMBER = 0x208BC3B3;
/** /**
* Convert a character to its corresponding road type. * Convert a character to its corresponding road type.
* *
* @param ch Character to convert. * @param ch Character to convert.
* *
* @return Road type corresponding to ch. * @return Road type corresponding to ch.
* *
* @see http://wiki.openstreetmap.org/wiki/Highway_tag_usage. * @see http://wiki.openstreetmap.org/wiki/Highway_tag_usage.
*/ */
public static RoadType toRoadType(char ch) { public static RoadType toRoadType(char ch) {
switch (ch) { switch (ch) {
case 'a': return RoadType.MOTORWAY; case 'a':
case 'b': return RoadType.TRUNK; return RoadType.MOTORWAY;
case 'c': return RoadType.PRIMARY; case 'b':
case 'd': return RoadType.SECONDARY; return RoadType.TRUNK;
case 'e': return RoadType.MOTORWAY_LINK; case 'c':
case 'f': return RoadType.TRUNK_LINK; return RoadType.PRIMARY;
case 'g': return RoadType.PRIMARY_LINK; case 'd':
case 'h': return RoadType.SECONDARY_LINK; return RoadType.SECONDARY;
case 'i': return RoadType.TERTIARY; case 'e':
case 'j': return RoadType.RESIDENTIAL; return RoadType.MOTORWAY_LINK;
case 'k': return RoadType.UNCLASSIFIED; case 'f':
case 'l': return RoadType.ROAD; return RoadType.TRUNK_LINK;
case 'm': return RoadType.LIVING_STREET; case 'g':
case 'n': return RoadType.SERVICE; return RoadType.PRIMARY_LINK;
case 'o': return RoadType.ROUNDABOUT; case 'h':
case 'z': return RoadType.COASTLINE; return RoadType.SECONDARY_LINK;
} case 'i':
return RoadType.UNCLASSIFIED; return RoadType.TERTIARY;
} case 'j':
return RoadType.RESIDENTIAL;
case 'k':
return RoadType.UNCLASSIFIED;
case 'l':
return RoadType.ROAD;
case 'm':
return RoadType.LIVING_STREET;
case 'n':
return RoadType.SERVICE;
case 'o':
return RoadType.ROUNDABOUT;
case 'z':
return RoadType.COASTLINE;
}
return RoadType.UNCLASSIFIED;
}
/** /**
* Create a new BinaryGraphReader using the given DataInputStream. * Create a new BinaryGraphReader using the given DataInputStream.
* *
* @param dis * @param dis
*/ */
public BinaryGraphReaderV2(DataInputStream dis) { public BinaryGraphReaderV2(DataInputStream dis) {
super(MAGIC_NUMBER, VERSION, dis); super(MAGIC_NUMBER, VERSION, dis);
} }
@Override @Override
public Graph read() throws IOException { public Graph read() throws IOException {
// Read and check magic number and file version. // Read and check magic number and file version.
checkMagicNumberOrThrow(dis.readInt()); checkMagicNumberOrThrow(dis.readInt());
checkVersionOrThrow(dis.readInt()); checkVersionOrThrow(dis.readInt());
// Read map id. // Read map id.
int mapId = dis.readInt(); int mapId = dis.readInt();
// Number of descriptors and nodes. observers.forEach((observer) -> observer.notifyStartReading(mapId));
int nbDesc = dis.readInt();
int nbNodes = dis.readInt();
// Number of successors for each nodes. // Number of descriptors and nodes.
int[] nbSuccessors = new int[nbNodes]; int nbDesc = dis.readInt();
int nbNodes = dis.readInt();
// Construct an array list with initial capacity of nbNodes. // Number of successors for each nodes.
ArrayList<Node> nodes = new ArrayList<Node>(nbNodes); int[] nbSuccessors = new int[nbNodes];
int nbTotalSuccessors = 0;
// Read nodes. // Construct an array list with initial capacity of nbNodes.
for (int node = 0; node < nbNodes; ++node) { ArrayList<Node> nodes = new ArrayList<Node>(nbNodes);
float longitude = ((float)dis.readInt ()) / 1E6f;
float latitude = ((float)dis.readInt ()) / 1E6f;
nbSuccessors[node] = dis.readUnsignedByte();
nodes.add(new Node(node, new Point(longitude, latitude)));
}
// Check format. // Read nodes.
checkByteOrThrow(255); observers.forEach((observer) -> observer.notifyStartReadingNodes(nbNodes));
for (int node = 0; node < nbNodes; ++node) {
float longitude = ((float) dis.readInt()) / 1E6f;
float latitude = ((float) dis.readInt()) / 1E6f;
nbSuccessors[node] = dis.readUnsignedByte();
nbTotalSuccessors += nbSuccessors[node];
final Node aNode = new Node(node, new Point(longitude, latitude));
nodes.add(aNode);
observers.forEach((observer) -> observer.notifyNewNodeRead(aNode));
}
// Read descriptors. // Check format.
RoadInformation[] descs = new RoadInformation[nbDesc]; checkByteOrThrow(255);
// Read // Read descriptors.
for (int descr = 0; descr < nbDesc; ++descr) { RoadInformation[] descs = new RoadInformation[nbDesc];
descs[descr] = readRoadInformation();
}
// Check format. // Read
checkByteOrThrow(254); observers.forEach((observer) -> observer.notifyStartReadingDescriptors(nbDesc));
for (int descr = 0; descr < nbDesc; ++descr) {
final RoadInformation roadinf = readRoadInformation();
descs[descr] = roadinf;
observers.forEach((observer) -> observer.notifyNewDescriptorRead(roadinf));
}
// Read successors and convert to arcs. // Check format.
for (int node = 0; node < nbNodes; ++node) { checkByteOrThrow(254);
for (int succ = 0; succ < nbSuccessors[node]; ++succ) {
// Read target node number. // Read successors and convert to arcs.
int destNode = this.read24bits(); final int copyNbTotalSuccesors = nbTotalSuccessors; // Stupid Java...
observers.forEach((observer) -> observer.notifyStartReadingArcs(copyNbTotalSuccesors));
for (int node = 0; node < nbNodes; ++node) {
for (int succ = 0; succ < nbSuccessors[node]; ++succ) {
// Read information number. // Read target node number.
int descrNum = this.read24bits(); int destNode = this.read24bits();
// Length of the arc. // Read information number.
int length = dis.readUnsignedShort(); int descrNum = this.read24bits();
// Number of segments. // Length of the arc.
int nbSegments = dis.readUnsignedShort(); int length = dis.readUnsignedShort();
// Chain of points corresponding to the segments. // Number of segments.
ArrayList<Point> points = new ArrayList<Point>(nbSegments + 2); int nbSegments = dis.readUnsignedShort();
points.add(nodes.get(node).getPoint());
for (int seg = 0; seg < nbSegments; ++seg) { // Chain of points corresponding to the segments.
Point lastPoint = points.get(points.size() - 1); ArrayList<Point> points = new ArrayList<Point>(nbSegments + 2);
points.add(nodes.get(node).getPoint());
float dlon = (dis.readShort()) / 2.0e5f; for (int seg = 0; seg < nbSegments; ++seg) {
float dlat = (dis.readShort()) / 2.0e5f; Point lastPoint = points.get(points.size() - 1);
points.add(new Point(lastPoint.getLongitude() + dlon, float dlon = (dis.readShort()) / 2.0e5f;
lastPoint.getLatitude() + dlat)); float dlat = (dis.readShort()) / 2.0e5f;
}
points.add(nodes.get(destNode).getPoint()); points.add(new Point(lastPoint.getLongitude() + dlon, lastPoint.getLatitude() + dlat));
}
RoadInformation info = descs[descrNum]; points.add(nodes.get(destNode).getPoint());
Node orig = nodes.get(node);
Node dest = nodes.get(destNode);
// Add successor to initial arc. RoadInformation info = descs[descrNum];
new Arc(orig, dest, length, info, points); Node orig = nodes.get(node);
Node dest = nodes.get(destNode);
// And reverse arc if its a two-way road. // Add successor to initial arc.
if (!info.isOneWay()) { Arc arc = new Arc(orig, dest, length, info, points);
// Add without segments.
ArrayList<Point> rPoints = new ArrayList<Point>(points);
Collections.reverse(rPoints);
new Arc(dest, orig, length, info, rPoints);
}
} // And reverse arc if its a two-way road.
} if (!info.isOneWay()) {
// Add without segments.
ArrayList<Point> rPoints = new ArrayList<Point>(points);
Collections.reverse(rPoints);
new Arc(dest, orig, length, info, rPoints);
}
observers.forEach((observer) -> observer.notifyNewArcRead(arc));
}
}
// Check format. // Check format.
checkByteOrThrow(253); checkByteOrThrow(253);
return new Graph(mapId, nodes); observers.forEach((observer) -> observer.notifyEndReading());
}
/** return new Graph(mapId, nodes);
* Read the next road information from the stream. }
*
* @throws IOException /**
*/ * Read the next road information from the stream.
private RoadInformation readRoadInformation() throws IOException { *
char type = (char)dis.readUnsignedByte(); * @throws IOException
int x = dis.readUnsignedByte() ; */
return new RoadInformation(toRoadType(type), (x & 0x80) > 0, (x & 0x7F) * 5, dis.readUTF()); private RoadInformation readRoadInformation() throws IOException {
} char type = (char) dis.readUnsignedByte();
int x = dis.readUnsignedByte();
return new RoadInformation(toRoadType(type), (x & 0x80) > 0, (x & 0x7F) * 5, dis.readUTF());
}
} }

View File

@ -2,66 +2,77 @@ package org.insa.graph.io;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public abstract class BinaryReader { public abstract class BinaryReader {
// Map version and magic number targeted for this reader. // Map version and magic number targeted for this reader.
private int version; private int version;
private int magicNumber; private int magicNumber;
// InputStream // InputStream
protected DataInputStream dis; protected DataInputStream dis;
protected BinaryReader(int magicNumber, int version, DataInputStream dis) { // List of observers
this.magicNumber = magicNumber; protected List<GraphReaderObserver> observers = new ArrayList<>();
this.version = version;
this.dis = dis;
}
/** protected BinaryReader(int magicNumber, int version, DataInputStream dis) {
* @param version this.magicNumber = magicNumber;
* @throws BadVersionException this.version = version;
*/ this.dis = dis;
public void checkVersionOrThrow(int version) throws BadVersionException { }
if (this.version != version) {
throw new BadVersionException(version, this.version);
}
}
/** /**
* @param magicNumber * {@inheritDoc}
* @throws BadMagicNumberException */
*/ public void addObserver(GraphReaderObserver observer) {
public void checkMagicNumberOrThrow(int magicNumber) throws BadMagicNumberException { observers.add(observer);
if (this.magicNumber != magicNumber) { }
throw new BadMagicNumberException(magicNumber, this.magicNumber);
}
}
/** /**
* Check if the next byte in the input stream correspond to the * @param version
* given byte. This function consumes the next byte in the input * @throws BadVersionException
* stream. */
* public void checkVersionOrThrow(int version) throws BadVersionException {
* @param i Byte to check against. if (this.version != version) {
* throw new BadVersionException(version, this.version);
* @throws IOException }
*/ }
public void checkByteOrThrow(int i) throws IOException {
if (dis.readUnsignedByte() != i) {
throw new BadFormatException();
}
}
/** /**
* Read 24 bits from the stream and return the corresponding integer value. * @param magicNumber
* * @throws BadMagicNumberException
* @return Integer value read from the next 24 bits of the stream. */
* public void checkMagicNumberOrThrow(int magicNumber) throws BadMagicNumberException {
* @throws IOException if (this.magicNumber != magicNumber) {
*/ throw new BadMagicNumberException(magicNumber, this.magicNumber);
protected int read24bits() throws IOException { }
int x = dis.readUnsignedShort() ; }
return (x << 8) | dis.readUnsignedByte() ;
} /**
* Check if the next byte in the input stream correspond to the given byte. This
* function consumes the next byte in the input stream.
*
* @param i Byte to check against.
*
* @throws IOException
*/
public void checkByteOrThrow(int i) throws IOException {
if (dis.readUnsignedByte() != i) {
throw new BadFormatException();
}
}
/**
* Read 24 bits from the stream and return the corresponding integer value.
*
* @return Integer value read from the next 24 bits of the stream.
*
* @throws IOException
*/
protected int read24bits() throws IOException {
int x = dis.readUnsignedShort();
return (x << 8) | dis.readUnsignedByte();
}
} }

View File

@ -6,6 +6,13 @@ import org.insa.graph.Graph;
public interface GraphReader { public interface GraphReader {
/**
* Add a new observer to this graph reader.
*
* @param observer
*/
public void addObserver(GraphReaderObserver observer);
/** /**
* Read a graph an returns it. * Read a graph an returns it.
* *

View File

@ -0,0 +1,64 @@
package org.insa.graph.io;
import org.insa.graph.Arc;
import org.insa.graph.Node;
import org.insa.graph.RoadInformation;
public interface GraphReaderObserver {
/**
* Notify observer about information on the graph, this method is always the
* first called
*
* @param mapId ID of the graph.
*/
public void notifyStartReading(int mapId);
/**
* Notify that the graph has been fully read.
*/
public void notifyEndReading();
/**
* Notify that the reader is starting to read node.
*
* @param nNodes Number of nodes to read.
*/
public void notifyStartReadingNodes(int nNodes);
/**
* Notify that a new nodes has been read.
*
* @param node
*/
public void notifyNewNodeRead(Node node);
/**
* Notify that the reader is starting to read descriptor/road informations.
*
* @param nDesc Number of descriptors to read.
*/
public void notifyStartReadingDescriptors(int nDesc);
/**
* Notify that a new descriptor has been read.
*
* @param desc
*/
public void notifyNewDescriptorRead(RoadInformation desc);
/**
* Notify that the reader is starting to read arcs.
*
* @param nArcs Number of arcs to read (!= number of arcs in the graph).
*/
public void notifyStartReadingArcs(int nArcs);
/**
* Notify that a new arc has been read.
*
* @param arc
*/
public void notifyNewArcRead(Arc arc);
}

View File

@ -0,0 +1,131 @@
package org.insa.graphics;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.border.EmptyBorder;
import org.insa.graph.Arc;
import org.insa.graph.Node;
import org.insa.graph.RoadInformation;
import org.insa.graph.io.GraphReaderObserver;
/**
* One-time use GraphReaderObserver that display progress in three different
* JProgressBar.
*
* @author Mikael
*
*/
public class GraphReaderProgressBar extends JDialog implements GraphReaderObserver {
/**
*
*/
private static final long serialVersionUID = -1;
// Index...
private static final int NODE = 0, DESC = 1, ARC = 2;
// Progress bar
private final JProgressBar[] progressBars = new JProgressBar[3];
// Current element read, and modulo.
private int[] counters = new int[] { 0, 0, 0 };
private int[] modulos = new int[3];
public GraphReaderProgressBar(JFrame owner) {
super(owner);
this.setVisible(false);
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
final String[] infos = { "nodes", "road informations", "arcs" };
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.setBorder(new EmptyBorder(15, 15, 15, 15));
pane.add(Box.createVerticalGlue());
for (int i = 0; i < 3; ++i) {
JLabel label = new JLabel("Reading " + infos[i] + "... ");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
progressBars[i] = new JProgressBar();
progressBars[i].setAlignmentX(Component.LEFT_ALIGNMENT);
pane.add(label);
pane.add(progressBars[i]);
}
pane.add(Box.createVerticalGlue());
pane.setPreferredSize(new Dimension(300, 120));
setContentPane(pane);
// setModal(true);
setLocationRelativeTo(owner);
pack();
}
@Override
public void notifyStartReading(int mapId) {
setTitle(String.format("Reading graph %#x... ", mapId));
setVisible(true);
}
@Override
public void notifyEndReading() {
setVisible(false);
}
protected void initProgressBar(int index, int max) {
progressBars[index].setMaximum(max);
modulos[index] = max / 100;
}
protected void incCounter(int index) {
counters[index] += 1;
if (counters[index] % modulos[index] == 0) {
progressBars[index].setValue(counters[index]);
}
}
@Override
public void notifyStartReadingNodes(int nNodes) {
initProgressBar(NODE, nNodes);
}
@Override
public void notifyNewNodeRead(Node node) {
incCounter(NODE);
}
@Override
public void notifyStartReadingDescriptors(int nDesc) {
initProgressBar(DESC, nDesc);
}
@Override
public void notifyNewDescriptorRead(RoadInformation desc) {
incCounter(DESC);
}
@Override
public void notifyStartReadingArcs(int nArcs) {
initProgressBar(ARC, nArcs);
}
@Override
public void notifyNewArcRead(Arc arc) {
incCounter(ARC);
}
}

View File

@ -518,6 +518,7 @@ public class MainWindow extends JFrame {
else { else {
reader = new BinaryGraphReader(stream); reader = new BinaryGraphReader(stream);
} }
reader.addObserver(new GraphReaderProgressBar(MainWindow.this));
try { try {
graph = reader.read(); graph = reader.read();
} }