diff --git a/mock/src/main/java/seng302/App.java b/mock/src/main/java/seng302/App.java index 760aa734..3f1dd06d 100644 --- a/mock/src/main/java/seng302/App.java +++ b/mock/src/main/java/seng302/App.java @@ -3,30 +3,21 @@ package seng302; import javafx.application.Application; import javafx.stage.Stage; - import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import seng302.DataInput.PolarParser; import seng302.DataInput.XMLReader; -import seng302.Exceptions.InvalidPolarFileException; import seng302.Model.Event; import seng302.Model.Polars; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.*; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.TransformerException; import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; public class App extends Application { @@ -51,16 +42,10 @@ public class App extends Application { Event raceEvent = new Event(raceXML, regattaXML, boatXML, boatPolars); raceEvent.start(); - } catch (IOException e) { - e.printStackTrace(); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } catch (SAXException e) { - e.printStackTrace(); - } catch (TransformerException e) { - e.printStackTrace(); - } catch (InvalidPolarFileException e) { + } catch (Exception e) { + //Catch all exceptions, print, and exit. e.printStackTrace(); + System.exit(1); } } diff --git a/mock/src/main/java/seng302/Constants.java b/mock/src/main/java/seng302/Constants.java index 3cec6d11..ab86b6d4 100644 --- a/mock/src/main/java/seng302/Constants.java +++ b/mock/src/main/java/seng302/Constants.java @@ -8,20 +8,42 @@ public class Constants { /** * Multiply by this factor to convert nautical miles to meters. + *
* Divide by this factor to convert meters to nautical miles. + *
* 1 nautical mile = 1852 meters. */ public static final int NMToMetersConversion = 1852; - public static final int PRE_RACE_WAIT_TIME = 18000; - + + /** * Multiply by this factor to convert Knots to millimeters per second. + *
* Divide by this factor to convert millimeters per second to Knots. + *
* 1 knot = 514.444 millimeters per second. */ public static final double KnotsToMMPerSecond = 514.444; - public static final int TEST_VELOCITIES[] = new int[] { 30, 15, 64, 52, 25, 24 }; + /** + * The race pre-start time, in milliseconds. 3 minutes. + */ + public static final long RacePreStartTime = 3 * 60 * 1000; + + + /** + * The race preparatory time, in milliseconds. 1 minutes. + */ + public static final long RacePreparatoryTime = 1 * 60 * 1000; + + + /** + * The number of milliseconds in one hour. + */ + public static long OneHourMilliseconds = 1 * 60 * 60 * 1000; + + + } diff --git a/mock/src/main/java/seng302/DataInput/PolarParser.java b/mock/src/main/java/seng302/DataInput/PolarParser.java index 20724f43..59878edd 100644 --- a/mock/src/main/java/seng302/DataInput/PolarParser.java +++ b/mock/src/main/java/seng302/DataInput/PolarParser.java @@ -5,6 +5,7 @@ package seng302.DataInput; */ import seng302.Exceptions.InvalidPolarFileException; +import seng302.Model.Bearing; import seng302.Model.Polars; import java.io.*; @@ -83,10 +84,17 @@ public class PolarParser { //Add angle+speed=velocity estimate to polar table. try { + //Add the polar value to the polar table - polarTable.addEstimate( Double.parseDouble(row[0]), Double.parseDouble(row[i]), Double.parseDouble(row[i + 1])); + double windSpeedKnots = Double.parseDouble(row[0]); + double angleDegrees = Double.parseDouble(row[i]); + Bearing angle = Bearing.fromDegrees(angleDegrees); + double boatSpeedKnots = Double.parseDouble(row[i + 1]); + polarTable.addEstimate(windSpeedKnots, angle, boatSpeedKnots); + } catch (NumberFormatException e) { throw new InvalidPolarFileException("Could not convert (Row,Col): (" + rowNumber + "," + i +") = " + row[i] + " to a double.", e); + } } diff --git a/mock/src/main/java/seng302/DataInput/RaceXMLReader.java b/mock/src/main/java/seng302/DataInput/RaceXMLReader.java index 60b01d79..08fa73a7 100644 --- a/mock/src/main/java/seng302/DataInput/RaceXMLReader.java +++ b/mock/src/main/java/seng302/DataInput/RaceXMLReader.java @@ -204,6 +204,7 @@ public class RaceXMLReader extends XMLReader implements RaceDataSource { lastCompoundMark = currentCompoundMark; legName = getCompoundMarkName(getCompoundMarkID(markXML)); } + } private void readCourseLimit() { diff --git a/mock/src/main/java/seng302/Model/Angle.java b/mock/src/main/java/seng302/Model/Angle.java index 4dc027f8..8fa767dd 100644 --- a/mock/src/main/java/seng302/Model/Angle.java +++ b/mock/src/main/java/seng302/Model/Angle.java @@ -4,7 +4,7 @@ package seng302.Model; * This represents an angle. * Has functions to return angle as either degrees or radians. */ -public class Angle { +public class Angle implements Comparable { /** * The angle stored in this object. @@ -62,4 +62,69 @@ public class Angle { public double radians() { return Math.toRadians(this.degrees); } + + + + /** + * Returns true if two Angle objects have equal values. + * @param obj Other angle object to compare. + * @return True if they are equal, false otherwise. + */ + @Override + public boolean equals(Object obj) { + //Cast other side. + Angle other = (Angle) obj; + + //Compare values. + if (this.degrees() == other.degrees()) { + return true; + } else { + return false; + } + } + + + /** + * Returns an int describing the ordering between this angle object, and another. + * @param o Other angle to compare to. + * @return {@literal int < 0} if this angle is less than the other angle, {@literal int > 0} if this angle is greater than the other angle, and {@literal int = 0} if this angle is equal to the other angle, + */ + @Override + public int compareTo(Angle o) { + + if (this.degrees() < o.degrees()) { + return -1; + } else if (this.degrees() > o.degrees()) { + return 1; + } else { + return 0; + } + + } + + + /** + * Converts an angle to an angle in a given periodic interval (e.g., degrees have a periodic interval of 360, radians have a periodic interval of 2Pi) of [lowerBound, upperBound). + * @param angle The angle to convert. + * @param lowerBound The lower bound of the interval. + * @param upperBound The upper bound of the interval. + * @param period The period of the interval. + * @return The angle in the desired periodic interval. + */ + public static double toPeriodicInterval(double angle, double lowerBound, double upperBound, double period) { + + + while (angle >= upperBound) { + //Too large. + angle -= period; + } + + while (angle < lowerBound) { + //Too small. + angle += period; + } + + return angle; + + } } diff --git a/mock/src/main/java/seng302/Model/Azimuth.java b/mock/src/main/java/seng302/Model/Azimuth.java index 0f252ebc..cbbaa2e6 100644 --- a/mock/src/main/java/seng302/Model/Azimuth.java +++ b/mock/src/main/java/seng302/Model/Azimuth.java @@ -4,8 +4,9 @@ package seng302.Model; /** * Represents an azimuth. - * This is the angle between north and a target point. - * It has the interval [-180, 180), and clockwise from north is positive. + * If treated as an absolute azimuth this is the angle between north and a target point. + * If treated as a relative azimuth, this is the angle between from one target point to the other. + * It has the interval [-180, 180) degrees, and clockwise is positive. */ public class Azimuth extends Angle{ @@ -29,15 +30,7 @@ public class Azimuth extends Angle{ */ public static double toAzimuthInterval(double degrees) { - if (degrees >= 180) { - //Too large. - degrees -= 360; - } else if (degrees < -180) { - //Too small. - degrees += 360; - } - - return degrees; + return Angle.toPeriodicInterval(degrees, -180d, 180d, 360d); } /** @@ -63,4 +56,13 @@ public class Azimuth extends Angle{ } + /** + * Constructs an Azimuth object from a Bearing object. + * @param bearing Bearing object to read value from. + * @return Azimuth object. + */ + public static Azimuth fromBearing(Bearing bearing) { + return Azimuth.fromDegrees(bearing.degrees()); + } + } diff --git a/mock/src/main/java/seng302/Model/Bearing.java b/mock/src/main/java/seng302/Model/Bearing.java index 0f25b747..27ff1235 100644 --- a/mock/src/main/java/seng302/Model/Bearing.java +++ b/mock/src/main/java/seng302/Model/Bearing.java @@ -2,8 +2,9 @@ package seng302.Model; /** * Represents a bearing. Also known as a heading. - * This is the angle between north and a target point. - * Has the interval [0, 360), and clockwise from north is positive. + * If treated as an absolute bearing this is the angle between north and a target point. + * If treated as a relative bearing, this is the angle between from one target point to the other. + * Has the interval [0, 360) degrees, and clockwise is positive. */ public class Bearing extends Angle { @@ -27,15 +28,7 @@ public class Bearing extends Angle { */ public static double toBearingInterval(double degrees) { - if (degrees >= 360) { - //Too large. - degrees -= 360; - } else if (degrees < 0) { - //Too small. - degrees += 360; - } - - return degrees; + return Angle.toPeriodicInterval(degrees, -0d, 360d, 360d); } /** @@ -61,4 +54,13 @@ public class Bearing extends Angle { } + /** + * Constructs a Bearing object from an Azimuth object. + * @param azimuth Azimuth object to read value from. + * @return Bearing object. + */ + public static Bearing fromAzimuth(Azimuth azimuth) { + return Bearing.fromDegrees(azimuth.degrees()); + } + } diff --git a/mock/src/main/java/seng302/Model/Boat.java b/mock/src/main/java/seng302/Model/Boat.java index c3a13878..9c3eb895 100644 --- a/mock/src/main/java/seng302/Model/Boat.java +++ b/mock/src/main/java/seng302/Model/Boat.java @@ -1,7 +1,7 @@ package seng302.Model; -import org.geotools.referencing.GeodeticCalculator; import seng302.Constants; +import seng302.Networking.Messages.Enums.BoatStatusEnum; /** @@ -20,10 +20,9 @@ public class Boat { private double currentSpeed; /** - * The current heading of the boat. - * TODO bearing + * The current bearing/heading of the boat. */ - private double heading; + private Bearing bearing; /** * The current position of the boat. @@ -56,7 +55,7 @@ public class Boat { * The time, in milliseconds, that has elapsed during the current leg. * TODO milliseconds */ - private double timeElapsedInCurrentLeg; + private long timeElapsedInCurrentLeg; /** * The timestamp, in milliseconds, of when the boat finished the race. @@ -66,14 +65,9 @@ public class Boat { private long timeFinished = -1; /** - * Whether or not the boat has finished the race. + * The current status of the boat. */ - private boolean hasFinishedRace = false; - - /** - * Whether or not the boat has started the race. - */ - private boolean hasStartedRace = false; + private BoatStatusEnum status; /** * This stores a boat's polars table. @@ -101,53 +95,41 @@ public class Boat { this.name = name; this.sourceID = sourceID; this.polars = polars; - } + this.bearing = Bearing.fromDegrees(0d); + + this.status = BoatStatusEnum.UNDEFINED; + } /** - * Calculate the heading depending on the calculated azimuth value - * @return The azimuth value which is greater than 0 + * Calculate the bearing of the boat to its next marker. + * @return The bearing to the next marker. */ - public double calculateHeading() { - double azimuth = GPSCoordinate.calculateAzimuth(currentLeg.getStartCompoundMark().getAverageGPSCoordinate(), - currentLeg.getEndCompoundMark().getAverageGPSCoordinate()); + public Bearing calculateBearingToNextMarker() { - //Azimuth is in the interval (-180, 180), but we need a heading in the interval [0, 360). - if (azimuth < 0) { - return azimuth + 360; - } + //Get the start and end points. + GPSCoordinate currentPosition = this.getCurrentPosition(); + GPSCoordinate nextMarkerPosition = this.getCurrentLeg().getEndCompoundMark().getAverageGPSCoordinate(); - return azimuth; - } + //Calculate bearing. + Bearing bearing = GPSCoordinate.calculateBearing(currentPosition, nextMarkerPosition); - /** - * Calculate the heading depending on the calculated azimuth value - * @return The azimuth value which is greater than 0 - */ - public double calculateBearingToDestination() { - double azimuth = GPSCoordinate.calculateAzimuth(this.currentPosition, - currentLeg.getEndCompoundMark().getAverageGPSCoordinate()); - - if (azimuth >= 0) { - return azimuth; - } else { - return azimuth + 360; - } + return bearing; } + /** - * Calculates the distance between the boat and its target marker in nautical miles (1.852 km). + * Calculates the distance between the boat and its target marker in nautical miles. * @return The distance (in nautical miles) between the boat and its target marker. */ public double calculateDistanceToNextMarker() { - GeodeticCalculator calc = new GeodeticCalculator(); - - GPSCoordinate startMarker = this.getCurrentPosition(); + //Get start and end markers. + GPSCoordinate startPosition = this.getCurrentPosition(); //When boats finish, their "current leg" doesn't have an end marker. if (this.getCurrentLeg().getEndCompoundMark() == null) { @@ -156,101 +138,183 @@ public class Boat { GPSCoordinate endMarker = this.getCurrentLeg().getEndCompoundMark().getAverageGPSCoordinate(); - //Add points to calculator. - calc.setStartingGeographicPoint(startMarker.getLongitude(), startMarker.getLatitude()); - calc.setDestinationGeographicPoint(endMarker.getLongitude(), endMarker.getLatitude()); - //Convert meters to nautical miles. - return calc.getOrthodromicDistance() / Constants.NMToMetersConversion; + //Calculate distance. + double distanceNauticalMiles = GPSCoordinate.calculateDistanceNauticalMiles(startPosition, endMarker); + + return distanceNauticalMiles; } + + /** + * Returns the name of the boat/team. + * @return Name of the boat/team. + */ public String getName() { return name; } + /** + * Sets the name of the boat/team. + * @param name Name of the boat/team. + */ public void setName(String name) { this.name = name; } + + /** + * Returns the current speed of the boat, in knots. + * @return The current speed of the boat, in knots. + */ public double getCurrentSpeed() { return currentSpeed; } + /** + * Sets the speed of the boat, in knots. + * @param currentSpeed The new speed of the boat, in knots. + */ public void setCurrentSpeed(double currentSpeed) { this.currentSpeed = currentSpeed; } + /** + * Gets the country/team abbreviation of the boat. + * @return The country/team abbreviation of the boat. + */ public String getCountry() { return country; } + /** + * Sets the country/team abbreviation of the boat. + * @param country The new country/team abbreviation for the boat. + */ public void setCountry(String country) { this.country = country; } + + /** + * Returns the source ID of the boat. + * @return The source ID of the boat. + */ public int getSourceID() { return sourceID; } + /** + * Sets the source ID of the boat. + * @param sourceID The new source ID for the boat. + */ public void setSourceID(int sourceID) { this.sourceID = sourceID; } + /** + * Returns the current leg of the race the boat is in. + * @return The current leg of the race the boat is in. + */ public Leg getCurrentLeg() { return currentLeg; } + /** + * Sets the current leg of the race the boat is in. + * Clears time elapsed in current leg and distance travelled in current leg. + * @param currentLeg The new leg of the race the boat is in. + */ public void setCurrentLeg(Leg currentLeg) { this.currentLeg = currentLeg; + this.setTimeElapsedInCurrentLeg(0); + this.setDistanceTravelledInLeg(0); } + + /** + * Returns the distance, in meters, the boat has travelled in the current leg. + * @return The distance, in meters, the boat has travelled in the current leg. + */ public double getDistanceTravelledInLeg() { return distanceTravelledInLeg; } + /** + * Sets the distance, in meters, the boat has travelled in the current leg. + * @param distanceTravelledInLeg The distance, in meters, the boat has travelled in the current leg. + */ public void setDistanceTravelledInLeg(double distanceTravelledInLeg) { this.distanceTravelledInLeg = distanceTravelledInLeg; } + /** + * Returns the current position of the boat. + * @return The current position of the boat. + */ public GPSCoordinate getCurrentPosition() { return currentPosition; } + /** + * Sets the current position of the boat. + * @param currentPosition The new position for the boat. + */ public void setCurrentPosition(GPSCoordinate currentPosition) { this.currentPosition = currentPosition; } + + /** + * Gets the timestamp, in milliseconds, at which the boat finished the race. + * @return The timestamp, in milliseconds, at which the boat finished the race. + */ public long getTimeFinished() { return timeFinished; } + /** + * Sets the timestamp, in milliseconds, at which the boat finished the race. + * @param timeFinished The timestamp, in milliseconds, at which the boat finished the race. + */ public void setTimeFinished(long timeFinished) { this.timeFinished = timeFinished; } - public boolean isHasStartedRace() { - return hasStartedRace; - } - public void setHasStartedRace(boolean hasStartedRace) { - this.hasStartedRace = hasStartedRace; - } - public double getHeading() { - return heading; + + /** + * Returns the current bearing of the boat. + * @return The current bearing of the boat. + */ + public Bearing getBearing() { + return bearing; } - public void setHeading(double heading) { - this.heading = heading; + /** + * Sets the current bearing of the boat. + * @param bearing The new bearing of the boat. + */ + public void setBearing(Bearing bearing) { + this.bearing = bearing; } + /** + * Returns the polars table for this boat. + * @return The polars table for this boat. + */ public Polars getPolars() { return polars; } + /** + * Sets the polars table for this boat. + * @param polars The new polars table for this boat. + */ public void setPolars(Polars polars) { this.polars = polars; } @@ -271,4 +335,111 @@ public class Boat { public void setTimeSinceTackChange(long timeSinceTackChange) { this.timeSinceTackChange = timeSinceTackChange; } + + + /** + * Returns the time, in milliseconds, that has elapsed since the boat started the current leg. + * @return The time, in milliseconds, that has elapsed since the boat started the current leg. + */ + public long getTimeElapsedInCurrentLeg() { + return timeElapsedInCurrentLeg; + } + + /** + * Sets the time, in milliseconds, that has elapsed since the boat started the current leg. + * @param timeElapsedInCurrentLeg The new time, in milliseconds, that has elapsed since the boat started the current leg. + */ + public void setTimeElapsedInCurrentLeg(long timeElapsedInCurrentLeg) { + this.timeElapsedInCurrentLeg = timeElapsedInCurrentLeg; + } + + + /** + * Returns the status of the boat. + * @return The sttus of the boat. + */ + public BoatStatusEnum getStatus() { + return status; + } + + /** + * Sets the status of the boat. + * @param status The new status of the boat. + */ + public void setStatus(BoatStatusEnum status) { + this.status = status; + } + + + /** + * Moves the boat meters forward in the direction that it is facing + * @param meters The number of meters to move forward. + * @param milliseconds The number of milliseconds to advance the boat's timers by. + */ + public void moveForwards(double meters, long milliseconds) { + + + //Update the boat's time since last tack. + this.setTimeSinceTackChange(this.getTimeSinceTackChange() + milliseconds); + + //Update the time into the current leg. + this.setTimeElapsedInCurrentLeg(this.getTimeElapsedInCurrentLeg() + milliseconds); + + //Update the distance into the current leg. + this.setDistanceTravelledInLeg(this.getDistanceTravelledInLeg() + meters); + + //Updates the current position of the boat. + GPSCoordinate newPosition = GPSCoordinate.calculateNewPosition(this.getCurrentPosition(), meters, Azimuth.fromBearing(this.getBearing())); + this.setCurrentPosition(newPosition); + + } + + + /** + * Sets the boats speed and bearing to those in the given VMG. + * @param newVMG The new VMG to use for the boat - contains speed and bearing. + */ + public void setVMG(VMG newVMG) { + this.setBearing(newVMG.getBearing()); + this.setCurrentSpeed(newVMG.getSpeed()); + this.setTimeSinceTackChange(0); + } + + + /** + * Calculates the number of nautical miles the boat will travel in a given time slice. + * E.g., in 53 milliseconds a boat may travel 0.0002 nautical miles. + * @param timeSlice The timeslice to use. + * @return The distance travelled, in nautical miles, over the given timeslice. + */ + public double calculateNauticalMilesTravelled(long timeSlice) { + + //The proportion of one hour the current timeslice is. + //This will be a low fractional number, so we need to go from long -> double. + double hourProportion = ((double) timeSlice) / Constants.OneHourMilliseconds; + + //Calculates the distance travelled, in nautical miles, in the current timeslice. + //distanceTravelledNM = speed (nm p hr) * time taken to update loop + double distanceTravelledNM = this.getCurrentSpeed() * hourProportion; + + return distanceTravelledNM; + } + + /** + * Calculates the number of meters the boat will travel in a given time slice. + * E.g., in 53 milliseconds a boat may travel 0.02 meters. + * @param timeSlice The timeslice to use. + * @return The distance travelled, in meters, over the given timeslice. + */ + public double calculateMetersTravelled(long timeSlice) { + + //Calculate the distance travelled, in nautical miles. + double distanceTravelledNM = this.calculateNauticalMilesTravelled(timeSlice); + + //Convert to meters. + double distanceTravelledMeters = distanceTravelledNM * Constants.NMToMetersConversion; + + return distanceTravelledMeters; + } + } diff --git a/mock/src/main/java/seng302/Model/CompoundMark.java b/mock/src/main/java/seng302/Model/CompoundMark.java index 68e4a5ca..546ed079 100644 --- a/mock/src/main/java/seng302/Model/CompoundMark.java +++ b/mock/src/main/java/seng302/Model/CompoundMark.java @@ -1,61 +1,110 @@ package seng302.Model; -import org.geotools.referencing.GeodeticCalculator; -import java.awt.geom.Point2D; /** - * Created by esa46 on 29/03/17. + * Represents a compound mark - that is, either one or two individual marks which form a single compound mark. */ -public class CompoundMark extends Marker{ +public class CompoundMark { - private GPSCoordinate averageGPSCoordinate; + /** + * The first mark in the compound mark. + */ private Mark mark1; - private Mark mark2 = null; + /** + * The second mark in the compound mark. + */ + private Mark mark2; + + /** + * The average coordinate of the compound mark. + */ + private GPSCoordinate averageGPSCoordinate; + + + /** + * Constructs a compound mark from a single mark. + * @param mark1 The individual mark that comprises this compound mark. + */ public CompoundMark(Mark mark1) { - super(mark1.getPosition()); this.mark1 = mark1; this.averageGPSCoordinate = calculateAverage(); } + + /** + * Constructs a compound mark from a pair of marks. + * @param mark1 The first individual mark that comprises this compound mark. + * @param mark2 The second individual mark that comprises this compound mark. + */ public CompoundMark(Mark mark1, Mark mark2) { - super(mark1.getPosition(), mark2.getPosition()); this.mark1 = mark1; this.mark2 = mark2; this.averageGPSCoordinate = calculateAverage(); } - public Mark getMark1Source() { return mark1; } - public Mark getMark2Source() { return mark2; } + /** + * Returns the first mark of the compound mark. + * @return The first mark of the compound mark. + */ + public Mark getMark1() { + return mark1; + } + + /** + * Returns the second mark of the compound mark. + * @return The second mark of the compound mark. + */ + public Mark getMark2() { + return mark2; + } - public GPSCoordinate getMark1() { + + /** + * Returns the position of the first mark in the compound mark. + * @return The position of the first mark in the compound mark. + */ + public GPSCoordinate getMark1Position() { return mark1.getPosition(); } - public GPSCoordinate getMark2() { + /** + * Returns the position of the second mark in the compound mark. + * @return The position of the second mark in the compound mark. + */ + public GPSCoordinate getMark2Position() { return mark2.getPosition(); } + + /** + * Returns the average coordinate of the compound mark. + * @return The average coordinate of the compound mark. + */ public GPSCoordinate getAverageGPSCoordinate() { return averageGPSCoordinate; } + + /** + * Calculates the average coordinate of the compound mark. + * @return The average coordinate of the compound mark. + */ private GPSCoordinate calculateAverage() { - if(mark2 != null) { - GeodeticCalculator calc = new GeodeticCalculator(); - calc.setStartingGeographicPoint(mark1.getPosition().getLongitude(), mark1.getPosition().getLatitude()); - calc.setDestinationGeographicPoint(mark2.getPosition().getLongitude(), mark2.getPosition().getLatitude()); - double azimuth = calc.getAzimuth(); - double distance = calc.getOrthodromicDistance(); - - GeodeticCalculator middleCalc = new GeodeticCalculator(); - middleCalc.setStartingGeographicPoint(mark1.getPosition().getLongitude(), mark1.getPosition().getLatitude()); - middleCalc.setDirection(azimuth, distance / 2); - Point2D middlePoint = middleCalc.getDestinationGeographicPoint(); - return new GPSCoordinate(middlePoint.getY(), middlePoint.getX()); - } else return mark1.getPosition(); + + //If the compound mark only contains one mark, the average is simply the first mark's position. + if (this.mark2 == null) { + return this.getMark1Position(); + } + + + //Otherwise, calculate the average of both marks. + GPSCoordinate averageCoordinate = GPSCoordinate.calculateAverageCoordinate(this.getMark1Position(), this.getMark2Position()); + + return averageCoordinate; + } } diff --git a/mock/src/main/java/seng302/Model/GPSCoordinate.java b/mock/src/main/java/seng302/Model/GPSCoordinate.java index da8fbd3c..3f9527e2 100644 --- a/mock/src/main/java/seng302/Model/GPSCoordinate.java +++ b/mock/src/main/java/seng302/Model/GPSCoordinate.java @@ -1,23 +1,34 @@ package seng302.Model; import org.geotools.referencing.GeodeticCalculator; +import org.opengis.geometry.DirectPosition; +import seng302.Constants; +import java.awt.geom.Point2D; import java.util.Comparator; import java.util.List; /** - * GPS Coordinate for the world map. + * GPS Coordinate for the world map, containing a longitude and latitude. * Created by esa46 on 15/03/17. */ public class GPSCoordinate { + /** + * The latitude of the coordinate. + */ private double latitude; + + /** + * The longitude of the coordinate. + */ private double longitude; + + /** - * Constructor Method - * - * @param latitude latitude the coordinate is located at. + * Constructs a GPSCoordinate from a latitude and longitude value. + * @param latitude Latitude the coordinate is located at. * @param longitude Longitude that the coordinate is located at. */ public GPSCoordinate(double latitude, double longitude) { @@ -25,6 +36,8 @@ public class GPSCoordinate { this.longitude = longitude; } + + /** * Gets the Latitude that the Coordinate is at. * @@ -74,6 +87,8 @@ public class GPSCoordinate { return result; } + + /** * Calculates min and max values and passed it to calculate if coordinate is in the boundary * @param coordinate coordinate of interest @@ -120,6 +135,7 @@ public class GPSCoordinate { } } + /** * Helper function to find if a point is in a boundary * @param boundaryA The first coordinate of the boundary. @@ -156,20 +172,125 @@ public class GPSCoordinate { } + /** * Calculates the azimuth between two points. - * This is an angle in the interval (-180, 180), with - * - * @return the direction that the boat is heading towards in degrees (-180 to 180). + * @param start The starting point. + * @param end The ending point. + * @return The azimuth from the start point to the end point. */ - public static double calculateAzimuth(GPSCoordinate start, GPSCoordinate end) { + public static Azimuth calculateAzimuth(GPSCoordinate start, GPSCoordinate end) { GeodeticCalculator calc = new GeodeticCalculator(); calc.setStartingGeographicPoint(start.getLongitude(), start.getLatitude()); calc.setDestinationGeographicPoint(end.getLongitude(), end.getLatitude()); - return calc.getAzimuth(); + return Azimuth.fromDegrees(calc.getAzimuth()); } + + + /** + * Calculates the bearing between two points. + * @param start The starting point. + * @param end The ending point. + * @return The Bearing from the start point to the end point. + */ + public static Bearing calculateBearing(GPSCoordinate start, GPSCoordinate end) { + + //Calculates the azimuth between the two points. + Azimuth azimuth = GPSCoordinate.calculateAzimuth(start, end); + + //And converts it into a bearing. + return Bearing.fromAzimuth(azimuth); + } + + + /** + * Calculates the distance, in meters, between two points. + * Note: all other distance calculations (e.g., nautical miles between two points) should use this, and convert from meters to their desired unit. + * @param start The starting point. + * @param end The ending point. + * @return The distance, in meters, between the two given points. + */ + public static double calculateDistanceMeters(GPSCoordinate start, GPSCoordinate end) { + + GeodeticCalculator calc = new GeodeticCalculator(); + + calc.setStartingGeographicPoint(start.getLongitude(), start.getLatitude()); + calc.setDestinationGeographicPoint(end.getLongitude(), end.getLatitude()); + + double distanceMeters = calc.getOrthodromicDistance(); + + return distanceMeters; + } + + + /** + * Calculates the distance, in nautical miles, between two points. + * @param start The starting point. + * @param end The ending point. + * @return The distance, in nautical miles, between the two given points. + */ + public static double calculateDistanceNauticalMiles(GPSCoordinate start, GPSCoordinate end) { + //Find distance in meters. + double distanceMeters = GPSCoordinate.calculateDistanceMeters(start, end); + + //Convert to nautical miles. + double distanceNauticalMiles = distanceMeters / Constants.NMToMetersConversion; + + return distanceNauticalMiles; + } + + + /** + * Calculates the GPS position an entity will be at, given a starting position, distance (in meters), and an azimuth. + * + * @param oldCoordinates GPS coordinates of the entity's starting position. + * @param distanceMeters The distance in meters. + * @param azimuth The entity's current azimuth. + * @return The entity's new coordinate. + */ + public static GPSCoordinate calculateNewPosition(GPSCoordinate oldCoordinates, double distanceMeters, Azimuth azimuth) { + + + GeodeticCalculator calc = new GeodeticCalculator(); + + //Set starting position. + calc.setStartingGeographicPoint(oldCoordinates.getLongitude(), oldCoordinates.getLatitude()); + + //Set direction. + calc.setDirection(azimuth.degrees(), distanceMeters); + + //Get the destination. + Point2D destinationPoint = calc.getDestinationGeographicPoint(); + + return new GPSCoordinate(destinationPoint.getY(), destinationPoint.getX()); + } + + + /** + * Calculates the average coordinate of two coordinates. + * @param point1 The first coordinate to average. + * @param point2 The second coordinate to average. + * @return The average of the two coordinates. + */ + public static GPSCoordinate calculateAverageCoordinate(GPSCoordinate point1, GPSCoordinate point2) { + + //Calculate distance between them. + double distanceMeters = GPSCoordinate.calculateDistanceMeters(point1, point2); + //We want the average, so get half the distance between points. + distanceMeters = distanceMeters / 2d; + + //Calculate azimuth between them. + Azimuth azimuth = GPSCoordinate.calculateAzimuth(point1, point2); + + //Calculate the middle coordinate. + GPSCoordinate middleCoordinate = GPSCoordinate.calculateNewPosition(point1, distanceMeters, azimuth); + + return middleCoordinate; + + } + } diff --git a/mock/src/main/java/seng302/Model/Leg.java b/mock/src/main/java/seng302/Model/Leg.java index 22c5adce..8e784164 100644 --- a/mock/src/main/java/seng302/Model/Leg.java +++ b/mock/src/main/java/seng302/Model/Leg.java @@ -1,102 +1,127 @@ package seng302.Model; -import org.geotools.referencing.GeodeticCalculator; -import seng302.Constants; - /** - * Created by cbt24 on 6/03/17. + * Represents a leg of a race. */ public class Leg { - private String name; //nautical miles - private double distance; - private Marker startCompoundMark; - private Marker endCompoundMark; + + /** + * The name of the leg. + */ + private String name; + + /** + * The distance of the leg, in nautical miles. + */ + private double distanceNauticalMiles; + + /** + * The starting marker of the leg. + */ + private CompoundMark startCompoundMark; + + /** + * The ending marking of the leg. + */ + private CompoundMark endCompoundMark; + + /** + * The leg number within a race. + */ private int legNumber; + + /** - * Leg Initialiser + * Constructs a leg from a name, start marker, end marker, and leg number. * - * @param name Name of the Leg - * @param start marker - * @param end marker - * @param number Leg's position in race + * @param name Name of the Leg. + * @param start Starting marker of the leg. + * @param end Ending marker of the leg. + * @param number Leg's position within the race. */ - public Leg(String name, Marker start, Marker end, int number) { + public Leg(String name, CompoundMark start, CompoundMark end, int number) { this.name = name; this.startCompoundMark = start; this.endCompoundMark = end; this.legNumber = number; - calculateDistance(); + this.calculateLegDistance(); } + /** - * Construction Method + * Constructs a leg from a name and leg number. + * This is currently used for constructing "dummy" DNF and Finish legs. * - * @param name Name of the Leg - * @param number leg number + * @param name Name of the leg. + * @param number Leg's position within the race. */ public Leg(String name, int number) { this.name = name; this.legNumber = number; } + /** - * Returns the name of the Leg - * - * @return Returns the name of the Leg + * Returns the name of the Leg. + * @return The name of the Leg. */ public String getName() { return name; } + /** - * Get the distance in nautical miles - * - * @return Returns the total distance of the leg. + * Get the distance in nautical miles. + * @return The total distance of the leg. */ - public double getDistance() { - return distance; + public double getDistanceNauticalMiles() { + return distanceNauticalMiles; } + /** - * Returns the leg number that the leg exists in the Race - * - * @return Returns the Leg + * Returns the leg number of the leg within a race. + * @return The leg number of the leg within a race */ public int getLegNumber() { return legNumber; } - public Marker getStartCompoundMark() { + /** + * Returns the starting marker of the leg. + * @return The starting marker of the leg. + */ + public CompoundMark getStartCompoundMark() { return startCompoundMark; } - public void setStartCompoundMark(Marker startCompoundMark) { - this.startCompoundMark = startCompoundMark; - } - public Marker getEndCompoundMark() { + /** + * Returns the ending marker of the leg. + * @return The ending marker of the leg. + */ + public CompoundMark getEndCompoundMark() { return endCompoundMark; } - public void setEndCompoundMark(Marker endCompoundMark) { - this.endCompoundMark = endCompoundMark; - } + /** - * Calculates the distance that the legs are in nautical miles (1.852 km). + * Calculates the distance of the leg, in nautical miles. */ - public void calculateDistance() { + public void calculateLegDistance() { - GeodeticCalculator calc = new GeodeticCalculator(); - //Load start and end of leg + //Gets the start and end coordinates. GPSCoordinate startMarker = this.startCompoundMark.getAverageGPSCoordinate(); GPSCoordinate endMarker = this.endCompoundMark.getAverageGPSCoordinate(); - calc.setStartingGeographicPoint(startMarker.getLongitude(), startMarker.getLatitude()); - calc.setDestinationGeographicPoint(endMarker.getLongitude(), endMarker.getLatitude()); - this.distance = calc.getOrthodromicDistance() / Constants.NMToMetersConversion; + + //Calculates the distance between markers. + double distanceNauticalMiles = GPSCoordinate.calculateDistanceNauticalMiles(startMarker, endMarker); + + this.distanceNauticalMiles = distanceNauticalMiles; } diff --git a/mock/src/main/java/seng302/Model/Mark.java b/mock/src/main/java/seng302/Model/Mark.java index 8a09493d..e2a8c7e7 100644 --- a/mock/src/main/java/seng302/Model/Mark.java +++ b/mock/src/main/java/seng302/Model/Mark.java @@ -1,28 +1,64 @@ package seng302.Model; /** - * Created by cbt24 on 10/05/17. + * Represents an individual mark. + * Has a source ID, name, and position. */ public class Mark { + + /** + * The source ID of the mark. + */ private int sourceID; + + /** + * The name of the mark. + */ private String name; + + /** + * The position of the mark. + */ private GPSCoordinate position; + + + /** + * Constructs a mark with a given source ID, name, and position. + * @param sourceID The source ID of the mark. + * @param name The name of the mark. + * @param position The position of the mark. + */ public Mark(int sourceID, String name, GPSCoordinate position) { this.sourceID = sourceID; this.name = name; this.position = position; } + + /** + * Returns the name of the mark. + * @return The name of the mark. + */ public String getName() { return name; } + /** + * Returns the source ID of the mark. + * @return The source ID of the mark. + */ public int getSourceID() { return sourceID; } + /** + * Returns the position of the mark. + * @return The position of the mark. + */ public GPSCoordinate getPosition() { return position; } + + } diff --git a/mock/src/main/java/seng302/Model/Marker.java b/mock/src/main/java/seng302/Model/Marker.java deleted file mode 100644 index 3be606dd..00000000 --- a/mock/src/main/java/seng302/Model/Marker.java +++ /dev/null @@ -1,75 +0,0 @@ -package seng302.Model; - -import org.geotools.referencing.GeodeticCalculator; - -import java.awt.geom.Point2D; - -/** - * Created by esa46 on 29/03/17. - */ -public class Marker { - - private GPSCoordinate averageGPSCoordinate; - private GPSCoordinate mark1; - private GPSCoordinate mark2; - private String name; - private boolean doubleMarker = false; - - public Marker(GPSCoordinate mark1) { - - this.mark1 = mark1; - this.mark2 = mark1; - this.averageGPSCoordinate = calculateAverage(); - - } - - public Marker(GPSCoordinate mark1, GPSCoordinate mark2) { - - this.mark1 = mark1; - this.mark2 = mark2; - this.averageGPSCoordinate = calculateAverage(); - - } - - public Marker(String name, GPSCoordinate mark1, GPSCoordinate mark2) { - - this.name = name; - this.mark1 = mark1; - this.mark2 = mark2; - this.averageGPSCoordinate = calculateAverage(); - - } - - public GPSCoordinate getMark1() { - return mark1; - } - - public GPSCoordinate getMark2() { - return mark2; - } - - public GPSCoordinate getAverageGPSCoordinate() { - return averageGPSCoordinate; - } - - public String getName() { - return name; - } - - private GPSCoordinate calculateAverage() { - - GeodeticCalculator calc = new GeodeticCalculator(); - calc.setStartingGeographicPoint(mark1.getLongitude(), mark1.getLatitude()); - calc.setDestinationGeographicPoint(mark2.getLongitude(), mark2.getLatitude()); - double azimuth = calc.getAzimuth(); - double distance = calc.getOrthodromicDistance(); - - GeodeticCalculator middleCalc = new GeodeticCalculator(); - middleCalc.setStartingGeographicPoint(mark1.getLongitude(), mark1.getLatitude()); - middleCalc.setDirection(azimuth, distance / 2); - Point2D middlePoint = middleCalc.getDestinationGeographicPoint(); - return new GPSCoordinate(middlePoint.getY(), middlePoint.getX()); - - } - -} \ No newline at end of file diff --git a/mock/src/main/java/seng302/Model/Polars.java b/mock/src/main/java/seng302/Model/Polars.java index 4f35b8d6..1e3251f3 100644 --- a/mock/src/main/java/seng302/Model/Polars.java +++ b/mock/src/main/java/seng302/Model/Polars.java @@ -16,14 +16,14 @@ public class Polars { /** * Internal store of data. Maps {@literal Pair} to boatSpeed. */ - private Map, Double> polarValues = new HashMap<>(); + private Map, Double> polarValues = new HashMap<>(); /** * Stores a list of angles from the polar table - this is used during the calculateVMG function. * Maps between windSpeed and a list of angles for that wind speed. */ - private HashMap> polarAngles = new HashMap<>(); + private HashMap> polarAngles = new HashMap<>(); @@ -42,7 +42,7 @@ public class Polars { * @param relativeWindAngle The relative wind angle between the wind direction + 180 degrees and the boat's direction of the estimate. * @param boatSpeed The boat speed of the estimate. */ - public void addEstimate(double trueWindSpeed, double relativeWindAngle, double boatSpeed){ + public void addEstimate(double trueWindSpeed, Bearing relativeWindAngle, double boatSpeed) { //We also add the same values with a complementary angle (e.g., angle = 50, complement = 360 - 50 = 310). This is because the data file contains angles [0, 180), but we need [0, 360). @@ -52,19 +52,17 @@ public class Polars { } //Add estimate to map. - Pair newKeyPositive = new Pair(trueWindSpeed, relativeWindAngle); - polarValues.put(newKeyPositive, boatSpeed); + Pair newKeyPositive = new Pair<>(trueWindSpeed, relativeWindAngle); + this.polarValues.put(newKeyPositive, boatSpeed); + + //Get the "negative" bearing - that is, the equivalent bearing between [180, 360). + Bearing negativeBearing = Bearing.fromDegrees(360d - relativeWindAngle.degrees()); - double negativeAngle = 360d - relativeWindAngle; - //This essentially does angle modulo 360, to get something in the interval [0, 360). - while (negativeAngle >= 360d) { - negativeAngle -= 360d; - } //Ensure that the positive and negative angles aren't the same (e.g., pos = 0, neg = 360 - 0 = 0. - if (negativeAngle != relativeWindAngle) { - Pair newKeyNegative = new Pair(trueWindSpeed, negativeAngle); - polarValues.put(newKeyNegative, boatSpeed); + if (!negativeBearing.equals(relativeWindAngle)) { + Pair newKeyNegative = new Pair<>(trueWindSpeed, negativeBearing); + this.polarValues.put(newKeyNegative, boatSpeed); } @@ -73,8 +71,8 @@ public class Polars { this.polarAngles.get(trueWindSpeed).add(relativeWindAngle); } - if (!this.polarAngles.get(trueWindSpeed).contains(negativeAngle)) { - this.polarAngles.get(trueWindSpeed).add(negativeAngle); + if (!this.polarAngles.get(trueWindSpeed).contains(negativeBearing)) { + this.polarAngles.get(trueWindSpeed).add(negativeBearing); } @@ -83,39 +81,45 @@ public class Polars { /** - * Calculates the VMG for a given wind angle, wind speed, and angle to destination. Will only return VMGs that have a true bearing (angle) within a given bound - this is to ensure that you can calculate VMGs without going out of bounds. If you don't care about bearing bounds, simply pass in lower = 0, upper = 360. + * Calculates the VMG for a given wind angle, wind speed, and angle to destination. Will only return VMGs that have a true bearing (angle) within a given bound - this is to ensure that you can calculate VMGs without going out of bounds. + *
+ * If you don't care about bearing bounds, simply pass in lower = 0, upper = 359.9. + *
+ * Passing in lower = 0, upper = 0, or lower = 0, upper = 360 will both be treated the same as lower = 0, upper = 359.99999. *

- * The resulting angle of the VMG will be within the interval [bearingLowerBound, bearingUpperBound). Note the exclusive end of interval. + * The resulting angle of the VMG will be within the interval [bearingLowerBound, bearingUpperBound]. *

- * If the lower bound is greater than the upper bound (e.g., lower = 70, upper = 55), then it checks that {@literal VMGAngle >= lower OR VMGAngle < upper} (e.g., {@literal [70, 55) means angle >= 70, OR angle < 55}). + * If the lower bound is greater than the upper bound (e.g., lower = 70, upper = 55), then it checks that {@literal VMGAngle >= lower OR VMGAngle <= upper} (e.g., {@literal [70, 55] means angle >= 70, OR angle =< 55}). *

* Returns a VMG with 0 speed and 0 bearing if there are no VMGs with {@literal velocity > 0} in the acceptable bearing bounds. - * @param trueWindAngle The current true wind angle. Interval is [0, 360). + * @param trueWindAngle The current true wind angle. * @param trueWindSpeed The current true wind speed. Knots. - * @param destinationAngle The angle between the boat and the destination point. Interval is [0, 360). - * @param bearingLowerBound The lowest bearing (angle) that the boat may travel on. Interval is [0, 360). - * @param bearingUpperBound The highest bearing (angle) that the boat may travel on. Interval is [0, 360]. Note the inclusive end of interval. + * @param destinationAngle The angle between the boat and the destination point. + * @param bearingLowerBound The lowest bearing (angle) that the boat may travel on. + * @param bearingUpperBound The highest bearing (angle) that the boat may travel on. * @return The VMG. */ - public VMG calculateVMG(double trueWindAngle, double trueWindSpeed, double destinationAngle, double bearingLowerBound, double bearingUpperBound) { + public VMG calculateVMG(Bearing trueWindAngle, double trueWindSpeed, Bearing destinationAngle, Bearing bearingLowerBound, Bearing bearingUpperBound) { //Sorts polar angles. - for (List angles : this.polarAngles.values()) { + for (List angles : this.polarAngles.values()) { angles.sort(null); } - - //Get the lower bound into the interval [0, 360) - bearingLowerBound = ((bearingLowerBound % 360d) + 360d) % 360d; - //We use a bound of [lower, upper), so we allow the upper to be 360 degrees. - if (bearingUpperBound != 360d) { - bearingUpperBound = ((bearingUpperBound % 360d) + 360d) % 360d; + //If the user enters [0, 360] for their bounds, there won't be any accepted angles, as Bearing(360) turn into Bearing(0) (it has the interval [0, 360)). + //So if both bearing bounds are zero, we assume that the user wanted [0, 360) for the interval. + //So, we give them Bearing(359.99999) as the upper bound. + if ((bearingLowerBound.degrees() == 0d) && (bearingUpperBound.degrees() == 0d)) { + bearingUpperBound = Bearing.fromDegrees(359.99999d); } - //If the lower bound is greater than the upper bound, we have a "flipped" interval. That is for, e.g., [70, 55) the lower bound is greater than the upper bound, and so it checks that (VMGAngle >= 70 OR VMGAngle < 55), instead of (VMGAngle >= 70 AND VMGAngle < 55). + + + + //If the lower bound is greater than the upper bound, we have a "flipped" interval. That is for, e.g., [70, 55] the lower bound is greater than the upper bound, and so it checks that (VMGAngle >= 70 OR VMGAngle =< 55), instead of (VMGAngle >= 70 AND VMGAngle =< 55). boolean flippedInterval = false; - if (bearingLowerBound > bearingUpperBound) { + if (bearingLowerBound.degrees() > bearingUpperBound.degrees()) { flippedInterval = true; } @@ -127,7 +131,7 @@ public class Polars { //This indicates whether or not we've managed to find a wind speed larger than the current wind speed (the upper bound) in the Polars table (in cases where the current wind speed is larger than any in the file we will never find an upper bound). boolean foundUpperBoundWindSpeed = false; boolean foundLowerBoundWindSpeed = false; - for (Pair key : this.polarValues.keySet()) { + for (Pair key : this.polarValues.keySet()) { //The key is Pair, so pair.key is windSpeed. double currentPolarSpeed = key.getKey(); @@ -167,37 +171,35 @@ public class Polars { for (double polarWindSpeed : windSpeedBounds) { //The list of polar angles for this wind speed. - List polarAngles = this.polarAngles.get(polarWindSpeed); + List polarAngles = this.polarAngles.get(polarWindSpeed); double bestVMGVelocity = 0; double bestVMGSpeed = 0; - double bestVMGAngle = 0; + Bearing bestVMGAngle = Bearing.fromDegrees(0d); //Calculate the VMG for all possible angles at this wind speed. - for (double angle = 0; angle < 360; angle += 0.1) { + for (double angleDegree = 0; angleDegree < 360; angleDegree += 0.1) { + Bearing angle = Bearing.fromDegrees(angleDegree); //This is the true bearing of the boat, if it went at the angle against the wind. //For angle < 90 OR angle > 270, it means that the boat is going into the wind (tacking). //For angle > 90 AND angle < 270, it means that the boat is actually going with the wind (gybing). - double trueBoatBearing = trueWindAngle + angle + 180d; - //We put trueBoatBearing into the interval [0, 360). - while (trueBoatBearing >= 360) { - trueBoatBearing -= 360; - } + double trueBoatBearingDegrees = trueWindAngle.degrees() + angle.degrees() + 180d; + Bearing trueBoatBearing = Bearing.fromDegrees(trueBoatBearingDegrees); //Check that the boat's bearing would actually be acceptable. //We continue (skip to next iteration) if it is outside of the interval. if (flippedInterval) { - //Bearing must be inside [lower, upper), where lower > upper. So, bearing must be >= lower, or bearing < upper. We use inverted logic since we are skipping if it is true. - if ((trueBoatBearing < bearingLowerBound) & (trueBoatBearing >= bearingUpperBound)) { + //Bearing must be inside [lower, upper], where lower > upper. So, bearing must be >= lower, or bearing < upper. We use inverted logic since we are skipping if it is true. + if ((trueBoatBearing.degrees() < bearingLowerBound.degrees()) & (trueBoatBearing.degrees() > bearingUpperBound.degrees())) { continue; } } else { - //Bearing must be inside [lower, upper). - if ((trueBoatBearing < bearingLowerBound) || (trueBoatBearing >= bearingUpperBound)) { + //Bearing must be inside [lower, upper]. + if ((trueBoatBearing.degrees() < bearingLowerBound.degrees()) || (trueBoatBearing.degrees() > bearingUpperBound.degrees())) { continue; } @@ -209,14 +211,16 @@ public class Polars { //Check which pair of adjacent angles the angle is between. boolean foundAdjacentAngles = false; - double lowerBound = 0; - double upperBound = 0; + Bearing lowerBound = Bearing.fromDegrees(0d); + Bearing upperBound = Bearing.fromDegrees(0d); for (int i = 0; i < polarAngles.size() - 1; i++) { + Bearing currentAngle = polarAngles.get(i); + Bearing nextAngle = polarAngles.get(i + 1); //Check that angle is in interval [lower, upper). - if ((angle >= polarAngles.get(i)) && (angle < polarAngles.get(i + 1))) { + if ((angle.degrees() >= currentAngle.degrees()) && (angle.degrees() < nextAngle.degrees())) { foundAdjacentAngles = true; - lowerBound = polarAngles.get(i); - upperBound = polarAngles.get(i + 1); + lowerBound = currentAngle; + upperBound = nextAngle; break; } } @@ -232,11 +236,11 @@ public class Polars { //This is how far between the lower and upper bounds the angle is, as a proportion (e.g., 0.5 = half-way, 0.9 = close to upper). - double interpolationScalar = calculatePeriodicLinearInterpolateScalar(lowerBound, upperBound, 360, angle); + double interpolationScalar = calculatePeriodicLinearInterpolateScalar(lowerBound.degrees(), upperBound.degrees(), 360, angle.degrees()); //Get the estimated boat speeds for the lower and upper angles. - Pair lowerKey = new Pair<>(polarWindSpeed, lowerBound); - Pair upperKey = new Pair<>(polarWindSpeed, upperBound); + Pair lowerKey = new Pair<>(polarWindSpeed, lowerBound); + Pair upperKey = new Pair<>(polarWindSpeed, upperBound); double lowerSpeed = this.polarValues.get(lowerKey); double upperSpeed = this.polarValues.get(upperKey); @@ -245,10 +249,11 @@ public class Polars { //This is the delta angle between the boat's true bearing and the destination. - double angleBetweenDestAndTack = trueBoatBearing - destinationAngle; + double angleBetweenDestAndTackDegrees = trueBoatBearing.degrees() - destinationAngle.degrees(); + Bearing angleBetweenDestAndTack = Bearing.fromDegrees(angleBetweenDestAndTackDegrees); //This is the estimated velocity towards the target (e.g., angling away from the target reduces velocity). - double interpolatedVelocity = Math.cos(Math.toRadians(angleBetweenDestAndTack)) * interpolatedSpeed; + double interpolatedVelocity = Math.cos(angleBetweenDestAndTack.radians()) * interpolatedSpeed; //Check that the velocity is better, if so, update our best VMG so far, for this wind speed. @@ -294,7 +299,9 @@ public class Polars { //We then calculate the interpolated VMG speed and angle using the interpolation scalar. double interpolatedSpeed = calculateLinearInterpolation(vmg1.getSpeed(), vmg2.getSpeed(), interpolationScalar); - double interpolatedAngle = calculateLinearInterpolation(vmg1.getBearing(), vmg2.getBearing(), interpolationScalar); + double interpolatedAngleDegrees = calculateLinearInterpolation(vmg1.getBearing().degrees(), vmg2.getBearing().degrees(), interpolationScalar); + + Bearing interpolatedAngle = Bearing.fromDegrees(interpolatedAngleDegrees); //Return the interpolated VMG. @@ -384,11 +391,4 @@ public class Polars { return interpolatedValue; } - /** - * Returns the map used to store polar data. - * @return A map containing estimated boat speeds for a given (windSpeed, windAngle) pair. - */ - public Map, Double> getPolarValues() { - return polarValues; - } } diff --git a/mock/src/main/java/seng302/Model/Race.java b/mock/src/main/java/seng302/Model/Race.java index 63ef3537..92b51144 100644 --- a/mock/src/main/java/seng302/Model/Race.java +++ b/mock/src/main/java/seng302/Model/Race.java @@ -3,7 +3,6 @@ package seng302.Model; import javafx.animation.AnimationTimer; import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import org.geotools.referencing.GeodeticCalculator; import seng302.Constants; import seng302.DataInput.RaceDataSource; @@ -11,39 +10,94 @@ import seng302.MockOutput; import seng302.Networking.Messages.BoatLocation; import seng302.Networking.Messages.BoatStatus; import seng302.Networking.Messages.Enums.BoatStatusEnum; +import seng302.Networking.Messages.Enums.RaceStatusEnum; +import seng302.Networking.Messages.Enums.RaceTypeEnum; import seng302.Networking.Messages.RaceStatus; -import java.awt.geom.Point2D; + +import java.io.*; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import java.util.Random; -import static java.lang.Math.cos; -import static java.lang.Math.max; -import static java.lang.Math.min; /** - * Parent class for races - * Created by fwy13 on 3/03/17. + * Represents a yacht race. + * Has a course, boats, boundaries, etc... + * Is responsible for simulating the race, and sending messages to a MockOutput instance. */ public class Race implements Runnable { - protected ObservableList startingBoats; - protected ObservableList compoundMarks; - protected List legs; - protected int boatsFinished = 0; - protected long totalTimeElapsed; - protected int scaleFactor = 15; + /** + * An observable list of boats in the race. + */ + private ObservableList boats; + + /** + * An observable list of compound marks in the race. + */ + private ObservableList compoundMarks; + + /** + * A list of legs in the race. + */ + private List legs; + + /** + * A list of coordinates describing the boundary of the course. + */ + private List boundary; + + /** + * The elapsed time, in milliseconds, of the race. + */ + private long totalTimeElapsed; + + /** + * The starting timestamp, in milliseconds, of the race. + */ private long startTime; + + /** + * The scale factor of the race. + * Frame periods are multiplied by this to get the amount of time a single frame represents. + * E.g., frame period = 20ms, scale = 5, frame represents 20 * 5 = 100ms, and so boats are simulated for 100ms, even though only 20ms actually occurred. + */ + private int scaleFactor = 25; + + /** + * The race ID of the course. + */ private int raceId; - private int dnfChance = 0; //percentage chance a boat fails at each checkpoint + + /** + * The current status of the race. + */ + private RaceStatusEnum raceStatusEnum; + + /** + * The type of race this is. + */ + private RaceTypeEnum raceType; + + /** + * The percent chance that a boat fails the race, and enters a DNF state, at each checkpoint. + * 0 = 0%, 100 = 100%. + */ + private int dnfChance = 0; + + + /** + * The mockOutput to send messages to. + */ private MockOutput mockOutput; - private List boundary; + /** * Wind direction bearing. */ - private double windDirection; + private Bearing windDirection; /** * Wind speed (knots). @@ -51,18 +105,33 @@ public class Race implements Runnable { */ private double windSpeed; + + + /** + * Constructs a race object with a given RaceDataSource and sends events to the given mockOutput. + * @param raceData Data source for race related data (boats, legs, etc...). + * @param mockOutput The mockOutput to send events to. + */ public Race(RaceDataSource raceData, MockOutput mockOutput) { - this.startingBoats = FXCollections.observableArrayList(raceData.getBoats()); - this.legs = raceData.getLegs(); + + this.mockOutput = mockOutput; + + this.boats = FXCollections.observableArrayList(raceData.getBoats()); this.compoundMarks = FXCollections.observableArrayList(raceData.getCompoundMarks()); + this.boundary = raceData.getBoundary(); + this.legs = raceData.getLegs(); this.legs.add(new Leg("Finish", this.legs.size())); + this.raceId = raceData.getRaceId(); - this.mockOutput = mockOutput; - this.boundary = raceData.getBoundary(); - this.startTime = System.currentTimeMillis() + (Constants.PRE_RACE_WAIT_TIME / this.scaleFactor); - this.windSpeed = 12;//TODO could use input parameters for these. And should fluctuate during race. - this.windDirection = 180; + //The start time is current time + 4 minutes, scaled. prestart is 3 minutes, and we add another. + this.startTime = System.currentTimeMillis() + ((Constants.RacePreStartTime + (1 * 1000)) / this.scaleFactor); + + this.setRaceStatusEnum(RaceStatusEnum.NOT_ACTIVE); + this.raceType = RaceTypeEnum.FLEET_RACE; + + this.windSpeed = 12; + this.windDirection = Bearing.fromDegrees(180); } @@ -76,171 +145,348 @@ public class Race implements Runnable { } /** - * Parse the marker boats through mock output + * Parse the compound marker boats through mock output. */ - public void parseMarks() { - for (CompoundMark mark : compoundMarks){ - mockOutput.parseBoatLocation(mark.getMark1Source().getSourceID(), mark.getMark1().getLatitude(), mark.getMark1().getLongitude(),0,0); - if (mark.getMark2Source()!=null){ - mockOutput.parseBoatLocation(mark.getMark2Source().getSourceID(), mark.getMark2().getLatitude(), mark.getMark2().getLongitude(),0,0); + private void parseMarks() { + for (CompoundMark compoundMark : this.compoundMarks) { + + //Get the individual marks from the compound mark. + Mark mark1 = compoundMark.getMark1(); + Mark mark2 = compoundMark.getMark2(); + + //If they aren't null, parse them (some compound marks only have one mark). + if (mark1 != null) { + this.parseIndividualMark(mark1); } + + if (mark2 != null) { + this.parseIndividualMark(mark2); + } + } } + /** + * Parses an individual marker boat, and sends it to mockOutput. + * @param mark The marker boat to parse. + */ + private void parseIndividualMark(Mark mark) { + + this.mockOutput.parseBoatLocation(mark.getSourceID(), mark.getPosition().getLatitude(), mark.getPosition().getLongitude(),0,0); + + } /** - * Countdown timer until race starts. + * Parse the boats in the race, and send it to mockOutput. + */ + private void parseBoatLocations() { + + //Parse each boat. + for (Boat boat : this.boats) { + + this.parseIndividualBoatLocation(boat); + + } + + } + + /** + * Parses an individual boat, and sends it to mockOutput. + * @param boat The boat to parse. + */ + private void parseIndividualBoatLocation(Boat boat) { + + this.mockOutput.parseBoatLocation( + boat.getSourceID(), + boat.getCurrentPosition().getLatitude(), + boat.getCurrentPosition().getLongitude(), + boat.getBearing().degrees(), + boat.getCurrentSpeed() + ); + + } + + + /** + * Updates the race status enumeration based on the current time, in milliseconds. + * @param currentTime The current time, in milliseconds. + */ + private void updateRaceStatusEnum(long currentTime) { + + //The amount of milliseconds until the race starts. + long timeToStart = this.startTime - currentTime; + + //Scale the time to start based on the scale factor. + long timeToStartScaled = timeToStart / this.scaleFactor; + + + if (timeToStartScaled > Constants.RacePreStartTime) { + //Time > 3 minutes is the prestart period. + this.setRaceStatusEnum(RaceStatusEnum.PRESTART); + + } else if ((timeToStartScaled <= Constants.RacePreStartTime) && (timeToStartScaled >= Constants.RacePreparatoryTime)) { + //Time between [1, 3] minutes is the warning period. + this.setRaceStatusEnum(RaceStatusEnum.WARNING); + + } else if ((timeToStartScaled <= Constants.RacePreparatoryTime) && (timeToStartScaled > 0)) { + //Time between (0, 1] minutes is the preparatory period. + this.setRaceStatusEnum(RaceStatusEnum.PREPARATORY); + + } else { + //Otherwise, the race has started! + this.setRaceStatusEnum(RaceStatusEnum.STARTED); + + } + + + } + + /** + * Parses the race status, and sends it to mockOutput. + */ + private void parseRaceStatus() { + + //A race status message contains a list of boat statuses. + List boatStatuses = new ArrayList<>(); + + //Add each boat status to the status list. + for (Boat boat : boats) { + + BoatStatus boatStatus = new BoatStatus(boat.getSourceID(), boat.getStatus(), boat.getCurrentLeg().getLegNumber()); + + boatStatuses.add(boatStatus); + } + + //TODO REFACTOR for consistency, could send parameters to mockOutput instead of the whole racestatus. This will also fix the sequence number issue. + + //Convert wind direction and speed to ints. //TODO this conversion should be done inside the racestatus class. + int windDirectionInt = BoatLocation.convertHeadingDoubleToInt(this.windDirection.degrees()); + int windSpeedInt = (int) (windSpeed * Constants.KnotsToMMPerSecond); + + //Create race status object, and send it. + RaceStatus raceStatus = new RaceStatus(System.currentTimeMillis(), this.raceId, this.getRaceStatusEnum().getValue(), this.startTime, windDirectionInt, windSpeedInt, this.getRaceType().getValue(), boatStatuses); + + mockOutput.parseRaceStatus(raceStatus); + + + } + + + /** + * Sets the status of all boats in the race to RACING. */ + private void setBoatsStatusToRacing() { + + for (Boat boat : this.boats) { + boat.setStatus(BoatStatusEnum.RACING); + } + } + + /** + * Countdown timer until race starts. + */ protected AnimationTimer countdownTimer = new AnimationTimer() { + + long currentTime = System.currentTimeMillis(); - long timeLeft; + @Override public void handle(long arg0) { - timeLeft = startTime - currentTime; - if (timeLeft <= 0) { + + //Update the race status based on the current time. + updateRaceStatusEnum(this.currentTime); + + //Parse the boat locations. + parseBoatLocations(); + + //Parse the marks. + parseMarks(); + + //Parse the race status. + parseRaceStatus(); + + + if (getRaceStatusEnum() == RaceStatusEnum.STARTED) { System.setProperty("javafx.animation.fullspeed", "true"); + setBoatsStatusToRacing(); raceTimer.start(); - stop(); + this.stop(); } - ArrayList boatStatuses = new ArrayList<>(); - for (Boat boat : startingBoats) { - mockOutput.parseBoatLocation(boat.getSourceID(), boat.getCurrentPosition().getLatitude(), - boat.getCurrentPosition().getLongitude(), boat.getHeading(), 0); - boatStatuses.add(new BoatStatus(boat.getSourceID(), BoatStatusEnum.PRESTART, 0)); - } - parseMarks(); - - int raceStatusNumber = timeLeft <= 60000 / scaleFactor && timeLeft > 0? 2 : 1; - RaceStatus raceStatus = new RaceStatus(System.currentTimeMillis(), raceId, raceStatusNumber, startTime, 0, 2300, 1, boatStatuses); - mockOutput.parseRaceStatus(raceStatus); + //Update the animations timer's time. currentTime = System.currentTimeMillis(); } }; + /** + * Timer that runs for the duration of the race, until all boats finish. + */ private AnimationTimer raceTimer = new AnimationTimer() { - //Start time of loop. + + /** + * Start time of loop, in milliseconds. + */ long timeRaceStarted = System.currentTimeMillis(); - int boatOffset = 0; + + /** + * The time of the previous frame, in milliseconds. + */ + long lastFrameTime = timeRaceStarted; @Override public void handle(long arg0) { - if (boatsFinished < startingBoats.size()) { - //Get the current time. - long currentTime = System.currentTimeMillis(); - //Update the total elapsed time. - totalTimeElapsed = currentTime - timeRaceStarted; - ArrayList boatStatuses = new ArrayList<>(); + //Get the current time. + long currentTime = System.currentTimeMillis(); + + //Update the total elapsed time. + totalTimeElapsed = currentTime - this.timeRaceStarted; + + //As long as there is at least one boat racing, we still simulate the race. + if (getNumberOfActiveBoats() != 0) { + + //Get the time period of this frame. + long framePeriod = currentTime - lastFrameTime; + //We actually simulate 20ms istead of the amount of time that has occurred, as that ensure that we don't end up with large frame periods on slow computers, causing position issues. + framePeriod = 20; + + //For each boat, we update its position, and generate a BoatLocationMessage. - for (int i = 0; i < startingBoats.size(); i++) { - Boat boat = startingBoats.get((i + boatOffset) % startingBoats.size()); - if (boat != null) { - //Update position. - if (boat.getTimeFinished() < 0) { - updatePosition(boat, 15); - checkPosition(boat, totalTimeElapsed); - } - if (boat.getTimeFinished() > 0) { - mockOutput.parseBoatLocation(boat.getSourceID(), boat.getCurrentPosition().getLatitude(), boat.getCurrentPosition().getLongitude(), boat.getHeading(), boat.getCurrentSpeed()); - boatStatuses.add(new BoatStatus(boat.getSourceID(), BoatStatusEnum.FINISHED, boat.getCurrentLeg().getLegNumber())); - } else { - mockOutput.parseBoatLocation(boat.getSourceID(), boat.getCurrentPosition().getLatitude(), boat.getCurrentPosition().getLongitude(), boat.getHeading(), boat.getCurrentSpeed()); - boatStatuses.add(new BoatStatus(boat.getSourceID(), - boat.getCurrentLeg().getLegNumber() >= 0 ? BoatStatusEnum.RACING : BoatStatusEnum.DNF, boat.getCurrentLeg().getLegNumber())); - } - RaceStatus raceStatus = new RaceStatus(System.currentTimeMillis(), raceId, 4, startTime, BoatLocation.convertHeadingDoubleToInt(windDirection), (int) (windSpeed * Constants.KnotsToMMPerSecond), 2, boatStatuses);//TODO FIX replace magic values. - } else { - stop(); + for (Boat boat : boats) { + + //If it is still racing, update its position. + if (boat.getStatus() == BoatStatusEnum.RACING) { + + updatePosition(boat, framePeriod, totalTimeElapsed); + } + } - parseMarks(); - boatOffset = (boatOffset + 1) % (startingBoats.size()); - RaceStatus raceStatus = new RaceStatus(System.currentTimeMillis(), raceId, 3, startTime, BoatLocation.convertHeadingDoubleToInt(windDirection), (int) (windSpeed * Constants.KnotsToMMPerSecond), 2, boatStatuses);//TODO FIX replace magic values. - mockOutput.parseRaceStatus(raceStatus); + + } else { + //Otherwise, the race is over! + + setRaceStatusEnum(RaceStatusEnum.FINISHED); + this.stop(); } + + //Parse the boat locations. + parseBoatLocations(); + + //Parse the marks. + parseMarks(); + + //Parse the race status. + parseRaceStatus(); + + + //Update the last frame time. + this.lastFrameTime = currentTime; } }; + + /** + * Initialise the boats in the race. + * This sets their starting positions and current legs. + */ public void initialiseBoats() { - Leg officialStart = legs.get(0); - String name = officialStart.getName(); - Marker endMark = officialStart.getEndCompoundMark(); - ArrayList startingPositions = getSpreadStartingPositions(); - - for (int i = 0; i < startingBoats.size(); i++) { - Boat boat = startingBoats.get(i); - if (boat != null) { - Leg newLeg = new Leg(name, new Marker(startingPositions.get(i)), endMark, 0); - boat.setCurrentLeg(newLeg); - boat.setCurrentSpeed(Constants.TEST_VELOCITIES[i]);//TODO we should get rid of TEST_VELOCITIES since speed is based off of wind speed/angle. - boat.setCurrentPosition(startingPositions.get(i)); - boat.setHeading(boat.calculateHeading()); - boat.setTimeSinceTackChange(999999);//We set a large time since tack change so that it calculates a new VMG when the simulation starts. - } + + //Gets the starting positions of the boats. + List startingPositions = getSpreadStartingPositions(); + + //Get iterators for our boat and position lists. + Iterator boatIt = this.boats.iterator(); + Iterator startPositionIt = startingPositions.iterator(); + + //Iterate over the pair of lists. + while (boatIt.hasNext() && startPositionIt.hasNext()) { + + //Get the next boat and position. + Boat boat = boatIt.next(); + GPSCoordinate startPosition = startPositionIt.next(); + + + //The boat starts on the first leg of the race. + boat.setCurrentLeg(this.legs.get(0)); + + //Boats start with 0 knots speed. + boat.setCurrentSpeed(0d); + + //Place the boat at its starting position. + boat.setCurrentPosition(startPosition); + + //Boats start facing their next marker. + boat.setBearing(boat.calculateBearingToNextMarker()); + + //Sets the boats status to prestart - it changes to racing when the race starts. + boat.setStatus(BoatStatusEnum.PRESTART); + + //We set a large time since tack change so that it calculates a new VMG when the simulation starts. + boat.setTimeSinceTackChange(999999); + } + } + + /** - * Creates a list of starting positions for the different boats, so they do not appear cramped at the start line + * Creates a list of starting positions for the different boats, so they do not appear cramped at the start line. * - * @return list of starting positions + * @return A list of starting positions. */ - public ArrayList getSpreadStartingPositions() { + public List getSpreadStartingPositions() { + + //The first compound marker of the race - the starting gate. + CompoundMark compoundMark = this.legs.get(0).getStartCompoundMark(); - int nBoats = startingBoats.size(); - Marker compoundMark = legs.get(0).getStartCompoundMark(); + //The position of the two markers from the compound marker. + GPSCoordinate mark1Position = compoundMark.getMark1Position(); + GPSCoordinate mark2Position = compoundMark.getMark2Position(); - GeodeticCalculator initialCalc = new GeodeticCalculator(); - initialCalc.setStartingGeographicPoint(compoundMark.getMark1().getLongitude(), compoundMark.getMark1().getLatitude()); - initialCalc.setDestinationGeographicPoint(compoundMark.getMark2().getLongitude(), compoundMark.getMark2().getLatitude()); - double azimuth = initialCalc.getAzimuth(); - double distanceBetweenMarkers = initialCalc.getOrthodromicDistance(); - double distanceBetweenBoats = distanceBetweenMarkers / (nBoats + 1); + //Calculates the azimuth between the two points. + Azimuth azimuth = GPSCoordinate.calculateAzimuth(mark1Position, mark2Position); - GeodeticCalculator positionCalc = new GeodeticCalculator(); - positionCalc.setStartingGeographicPoint(compoundMark.getMark1().getLongitude(), compoundMark.getMark1().getLatitude()); - ArrayList positions = new ArrayList<>(); + //Calculates the distance between the two points. + double distanceMeters = GPSCoordinate.calculateDistanceMeters(mark1Position, mark2Position); - for (int i = 0; i < nBoats; i++) { - positionCalc.setDirection(azimuth, distanceBetweenBoats); - Point2D position = positionCalc.getDestinationGeographicPoint(); - positions.add(new GPSCoordinate(position.getY(), position.getX())); + //The number of boats in the race. + int numberOfBoats = this.boats.size(); + //Calculates the distance between each boat. We divide by numberOfBoats + 1 to ensure that no boat is placed on one of the starting gate's marks. + double distanceBetweenBoatsMeters = distanceMeters / (numberOfBoats + 1); + + + //List to store coordinates in. + List positions = new ArrayList<>(); + + //We start spacing boats out from mark 1. + GPSCoordinate position = mark1Position; + + //For each boat, displace position, and store it. + for (int i = 0; i < numberOfBoats; i++) { + + position = GPSCoordinate.calculateNewPosition(position, distanceBetweenBoatsMeters, azimuth); + + positions.add(position); - positionCalc = new GeodeticCalculator(); - positionCalc.setStartingGeographicPoint(position); } + return positions; } + /** - * Calculates the boats next GPS position based on its distance travelled and heading - * - * @param oldCoordinates GPS coordinates of the boat's starting position - * @param distanceTravelled distance in nautical miles - * @param azimuth boat's current direction. Value between -180 and 180 - * @return The boat's new coordinate - */ - public static GPSCoordinate calculatePosition(GPSCoordinate oldCoordinates, double distanceTravelled, double azimuth) { - - //Find new coordinate using current heading and distance - GeodeticCalculator geodeticCalculator = new GeodeticCalculator(); - //Load start point into calculator - Point2D startPoint = new Point2D.Double(oldCoordinates.getLongitude(), oldCoordinates.getLatitude()); - geodeticCalculator.setStartingGeographicPoint(startPoint); - //load direction and distance travelled into calculator - geodeticCalculator.setDirection(azimuth, distanceTravelled * Constants.NMToMetersConversion); - //get new point - Point2D endPoint = geodeticCalculator.getDestinationGeographicPoint(); - - return new GPSCoordinate(endPoint.getY(), endPoint.getX()); - } + * Calculates a boat's VMG. + * @param boat The boat to calculate VMG for. + * @return VMG for the specified boat. + */ + private VMG calculateVMG(Boat boat) { - private VMG calculateHeading(Boat boat) { //How fast a boat can turn, in degrees per millisecond. double turnRate = 0.03; @@ -248,110 +494,188 @@ public class Race implements Runnable { double turnAngle = turnRate * boat.getTimeSinceTackChange(); //Find the bounds on what angle the boat is allowed to travel at. The bounds cap out at [0, 360). - double bound1 = Math.max(boat.getHeading() - turnAngle, 0); - double bound2 = Math.min(boat.getHeading() + turnAngle, 360); + double bound1Degrees = Math.max(boat.getBearing().degrees() - turnAngle, 0); + double bound2Degrees = Math.min(boat.getBearing().degrees() + turnAngle, 360); + + Bearing bound1 = Bearing.fromDegrees(bound1Degrees); + Bearing bound2 = Bearing.fromDegrees(bound2Degrees); - return boat.getPolars().calculateVMG(this.windDirection, this.windSpeed, boat.calculateBearingToDestination(), bound1, bound2); + return boat.getPolars().calculateVMG(this.windDirection, this.windSpeed, boat.calculateBearingToNextMarker(), bound1, bound2); } - private boolean improvesVelocity(Boat boat, VMG newHeading) { - double angleBetweenDestAndHeading = boat.getHeading() - boat.calculateBearingToDestination(); - double angleBetweenDestAndNewVMG = newHeading.getBearing() - boat.calculateBearingToDestination(); - double currentVelocity = cos(Math.toRadians(angleBetweenDestAndHeading)) * boat.getVelocity(); - double vmgVelocity = cos(Math.toRadians(angleBetweenDestAndNewVMG)) * newHeading.getSpeed(); + + /** + * Determines whether or not a given VMG improves the velocity of a boat. + * @param boat The boat to test. + * @param vmg The new VMG to test. + * @return True if the new VMG is improves velocity, false otherwise. + */ + private boolean improvesVelocity(Boat boat, VMG vmg) { + + //Calculates the angle between the boat and its destination. + Angle angleBetweenDestAndHeading = Angle.fromDegrees(boat.getBearing().degrees() - boat.calculateBearingToNextMarker().degrees()); + + //Calculates the angle between the new VMG and the boat's destination. + Angle angleBetweenDestAndNewVMG = Angle.fromDegrees(vmg.getBearing().degrees() - boat.calculateBearingToNextMarker().degrees()); + + + //Calculate the boat's current velocity. + double currentVelocity = Math.cos(angleBetweenDestAndHeading.radians()) * boat.getCurrentSpeed(); + + //Calculate the potential velocity with the new VMG. + double vmgVelocity = Math.cos(angleBetweenDestAndNewVMG.radians()) * vmg.getSpeed(); + + //Return whether or not the new VMG gives better velocity. return vmgVelocity > currentVelocity; + } + /** * Calculates the distance a boat has travelled and updates its current position according to this value. * - * @param boat to be updated - * @param millisecondsElapsed since last update + * @param boat The boat to be updated. + * @param updatePeriodMilliseconds The time, in milliseconds, since the last update. + * @param totalElapsedMilliseconds The total number of milliseconds that have elapsed since the start of the race. */ - protected void updatePosition(Boat boat, int millisecondsElapsed) { + protected void updatePosition(Boat boat, long updatePeriodMilliseconds, long totalElapsedMilliseconds) { - //distanceTravelled = velocity (nm p hr) * time taken to update loop - double distanceTravelled = (boat.getCurrentSpeed() * this.scaleFactor * millisecondsElapsed) / 3600000; - double totalDistanceTravelled; + //Checks if the current boat has finished the race or not. + boolean finish = this.isLastLeg(boat.getCurrentLeg()); - boolean finish = boat.getCurrentLeg().getName().equals("Finish"); if (!finish) { - double totalDistanceTravelledInTack = distanceTravelled;//TODO FIX// + boat.getDistanceTravelledInTack(); - boat.setTimeSinceTackChange(boat.getTimeSinceTackChange() + this.scaleFactor * millisecondsElapsed); + //Calculates the distance travelled, in meters, in the current timeslice. + double distanceTravelledMeters = boat.calculateMetersTravelled(updatePeriodMilliseconds); + + //Scale it. + distanceTravelledMeters = distanceTravelledMeters * this.scaleFactor; + + + //Move the boat forwards that many meters, and advances its time counters by enough milliseconds. + boat.moveForwards(distanceTravelledMeters, updatePeriodMilliseconds * this.scaleFactor); + - VMG newHeading = calculateHeading(boat); //Calculate the new VMG. + VMG newVMG = this.calculateVMG(boat); - if (improvesVelocity(boat, newHeading)) { - boat.setHeading(newHeading.getBearing()); - boat.setCurrentSpeed(newHeading.getSpeed()); - boat.setTimeSinceTackChange(0); + //If the new vmg improves velocity, use it. + if (improvesVelocity(boat, newVMG)) { + boat.setVMG(newVMG); } - double azimuth = boat.getHeading(); - if (azimuth > 180) { - azimuth = azimuth - 360; - } - //tests to see if a point in front of the boat is out of bounds, if so mirror heading in the wind - GPSCoordinate test = calculatePosition(boat.getCurrentPosition(), (100.0 / Constants.NMToMetersConversion), azimuth); - if (!GPSCoordinate.isInsideBoundary(test, boundary)) { - double tempHeading = (boat.getHeading() - this.windDirection + 90) % 360; - boat.setHeading(tempHeading); - } - //calc the distance travelled in a straight line to windward - //double angleBetweenDestAndHeading = boat.getHeading() - boat.calculateBearingToDestination(); - totalDistanceTravelled = cos(Math.toRadians(boat.getHeading() - boat.calculateBearingToDestination()))*totalDistanceTravelledInTack; - boat.setDistanceTravelledInLeg(totalDistanceTravelled); + //Ensure that the boat doesn't leave the course bounds. + this.forceBoatBearingInBounds(boat); + + + //Check the boats position (update leg and stuff). + checkPosition(boat, totalTimeElapsed); + + } + + } + + + /** + * Checks if the boat's current bearing would put it out of course bounds, and adjusts it if it does. + * @param boat The boat to check. + */ + private void forceBoatBearingInBounds(Boat boat) { + + //Get the boat's azimuth. + Azimuth azimuth = Azimuth.fromBearing(boat.getBearing()); + //Tests to see if a point in front of the boat is out of bounds, if so mirror heading in the wind. + double epsilonMeters = 100d; + GPSCoordinate testCoord = GPSCoordinate.calculateNewPosition(boat.getCurrentPosition(), epsilonMeters, azimuth); - //Calculate boat's new position by adding the distance travelled onto the start point of the leg - azimuth = boat.getHeading(); - azimuth = azimuth > 180? azimuth - 360 : azimuth; - boat.setCurrentPosition(calculatePosition(boat.getCurrentPosition(), totalDistanceTravelledInTack, azimuth)); + //If it isn't inside the boundary, calculate new bearing. + if (!GPSCoordinate.isInsideBoundary(testCoord, this.boundary)) { + Bearing tempBearing = Bearing.fromDegrees(boat.getBearing().degrees() - this.windDirection.degrees() + 90); + boat.setBearing(tempBearing); } + } + + /** + * Checks if a boat has finished any legs, or has pulled out of race (DNF). + * @param boat The boat to check. + * @param timeElapsed The total time, in milliseconds, that has elapsed since the race started. + */ protected void checkPosition(Boat boat, long timeElapsed) { - //System.out.println(boat.getDistanceTravelledInLeg()); - //System.out.println(boat.getCurrentLeg().getDistance()); - //System.out.println(" "); - //if (boat.getDistanceTravelledInLeg() > boat.getCurrentLeg().getDistance()) { - //The distance (in nautical miles) within which the boat needs to get in order to consider that it has reached the marker. - double epsilon = 100.0 / Constants.NMToMetersConversion; //100 meters. TODO should be more like 5-10. - if (boat.calculateDistanceToNextMarker() < epsilon) { - //boat has passed onto new leg - - if (boat.getCurrentLeg().getName().equals("Finish")) { - //boat has finished - boatsFinished++; - boat.setTimeFinished(timeElapsed); + + //The distance, in nautical miles, within which the boat needs to get in order to consider that it has reached the marker. + double epsilonNauticalMiles = 100.0 / Constants.NMToMetersConversion; //100 meters. TODO should be more like 5-10. + + if (boat.calculateDistanceToNextMarker() < epsilonNauticalMiles) { + //Boat has reached its target marker, and has moved on to a new leg. + + + + //Calculate how much the boat overshot the marker by. + double overshootMeters = boat.calculateDistanceToNextMarker(); + + + //Move boat on to next leg. + Leg nextLeg = this.legs.get(boat.getCurrentLeg().getLegNumber() + 1); + boat.setCurrentLeg(nextLeg); + + //Add overshoot distance into the distance travelled for the next leg. + boat.setDistanceTravelledInLeg(overshootMeters); + + //Setting a high value for this allows the boat to immediately do a large turn, as it needs to in order to get to the next mark. + boat.setTimeSinceTackChange(999999); + + + //Check if the boat has finished or stopped racing. + + if (this.isLastLeg(boat.getCurrentLeg())) { + //Boat has finished. boat.setTimeFinished(timeElapsed); boat.setCurrentSpeed(0); + boat.setStatus(BoatStatusEnum.FINISHED); + } else if (doNotFinish()) { - boatsFinished++; + //Boat has pulled out of race. boat.setTimeFinished(timeElapsed); boat.setCurrentLeg(new Leg("DNF", -1)); boat.setCurrentSpeed(0); - } else { - //Calculate how much the boat overshot the marker by - boat.setDistanceTravelledInLeg(boat.getDistanceTravelledInLeg() - boat.getCurrentLeg().getDistance()); - //Move boat on to next leg - Leg nextLeg = legs.get(boat.getCurrentLeg().getLegNumber() + 1); - boat.setCurrentLeg(nextLeg); - //Add overshoot distance into the distance travelled for the next leg - boat.setDistanceTravelledInLeg(boat.getDistanceTravelledInLeg()); - - //Setting a high value for this allows the boat to immediately do a large turn, as it has needs to in order to get to the next mark. - boat.setTimeSinceTackChange(999999); + boat.setStatus(BoatStatusEnum.DNF); + } + } + + } + + + /** + * Determines whether or not a specific leg is the last leg in the race. + * @param leg The leg to check. + * @return Returns true if it is the last, false otherwse. + */ + private boolean isLastLeg(Leg leg) { + + //Get the last leg. + Leg lastLeg = this.legs.get(this.legs.size() - 1); + + //Check its ID. + int lastLegID = lastLeg.getLegNumber(); + + //Get the specified leg's ID. + int legID = leg.getLegNumber(); + + + //Check if they are the same. + return legID == lastLegID; } + /** * Sets the chance each boat has of failing at a gate or marker * @@ -363,9 +687,69 @@ public class Race implements Runnable { } } + /** + * Decides if a boat should received a DNF status. + * @return True means it should DNF, false means it shouldn't. + */ protected boolean doNotFinish() { Random rand = new Random(); return rand.nextInt(100) < dnfChance; } + + /** + * Returns the current race status. + * @return The current race status. + */ + public RaceStatusEnum getRaceStatusEnum() { + return raceStatusEnum; + } + + /** + * Sets the current race status. + * @param raceStatusEnum The new status of the race. + */ + private void setRaceStatusEnum(RaceStatusEnum raceStatusEnum) { + this.raceStatusEnum = raceStatusEnum; + } + + + /** + * Returns the type of race this is. + * @return The type of race this is. + */ + public RaceTypeEnum getRaceType() { + return raceType; + } + + + /** + * Returns the number of boats that are still active in the race. + * They become inactive by either finishing or withdrawing. + * @return The number of boats still active in the race. + */ + protected int getNumberOfActiveBoats() { + + int numberofActiveBoats = 0; + + for (Boat boat : this.boats) { + + //If the boat is currently racing, count it. + if (boat.getStatus() == BoatStatusEnum.RACING) { + numberofActiveBoats++; + } + + } + + return numberofActiveBoats; + } + + + /** + * Returns an observable list of boats in the race. + * @return List of boats in the race. + */ + public ObservableList getBoats() { + return boats; + } } diff --git a/mock/src/main/java/seng302/Model/VMG.java b/mock/src/main/java/seng302/Model/VMG.java index dbc2b89a..67bc5297 100644 --- a/mock/src/main/java/seng302/Model/VMG.java +++ b/mock/src/main/java/seng302/Model/VMG.java @@ -10,14 +10,14 @@ package seng302.Model; public class VMG { /** - * Speed component of the VMG. + * Speed component of the VMG, in knots. */ private double speed; /** * Bearing component of the VMG. */ - private double bearing; + private Bearing bearing; /** @@ -25,7 +25,7 @@ public class VMG { * @param speed Speed component of the VMG. * @param bearing Bearing component of the VMG. */ - public VMG(double speed, double bearing) { + public VMG(double speed, Bearing bearing) { this.speed = speed; this.bearing = bearing; } @@ -43,11 +43,8 @@ public class VMG { * Returns the bearing component of this VMG object. * @return Bearing component of this VMG object. */ - public double getBearing() { + public Bearing getBearing() { return bearing; } - public void setBearing(double bearing) { - this.bearing = bearing; - } } diff --git a/mock/src/test/java/seng302/Model/BoatTest.java b/mock/src/test/java/seng302/Model/BoatTest.java index 64e78d27..10c898c9 100644 --- a/mock/src/test/java/seng302/Model/BoatTest.java +++ b/mock/src/test/java/seng302/Model/BoatTest.java @@ -1,10 +1,10 @@ package seng302.Model; +import org.junit.Before; import org.junit.Test; - -import static junit.framework.TestCase.*; +import static org.junit.Assert.assertEquals; /** * Created by esa46 on 22/03/17. @@ -12,85 +12,92 @@ import static junit.framework.TestCase.*; public class BoatTest { - private GPSCoordinate ORIGIN_COORDS = new GPSCoordinate(0, 0); - private Boat TEST_BOAT = new Boat(1, "Test", "tt", new Polars()); + private GPSCoordinate ORIGIN_COORDS; + private Boat TEST_BOAT; + + @Before + public void setUp() { + ORIGIN_COORDS = new GPSCoordinate(0, 0); + TEST_BOAT = new Boat(1, "Test", "tt", new Polars()); + TEST_BOAT.setCurrentPosition(ORIGIN_COORDS); + } @Test public void calculateDueNorthAzimuthReturns0() { - Marker startMarker = new Marker(ORIGIN_COORDS); - Marker endMarker = new Marker(new GPSCoordinate(50, 0)); + CompoundMark startMarker = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORDS)); + CompoundMark endMarker = new CompoundMark(new Mark(2, "test mark 2", new GPSCoordinate(50, 0))); Leg start = new Leg("Start", startMarker, endMarker, 0); TEST_BOAT.setCurrentLeg(start); - assertEquals(GPSCoordinate.calculateAzimuth(startMarker.getAverageGPSCoordinate(), endMarker.getAverageGPSCoordinate()), 0, 1e-8); + assertEquals(GPSCoordinate.calculateAzimuth(startMarker.getAverageGPSCoordinate(), endMarker.getAverageGPSCoordinate()).degrees(), 0, 1e-8); } @Test public void calculateDueSouthAzimuthReturns180() { - Marker startMarker = new Marker(ORIGIN_COORDS); - Marker endMarker = new Marker(new GPSCoordinate(-50, 0)); + CompoundMark startMarker = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORDS)); + CompoundMark endMarker = new CompoundMark(new Mark(2, "test mark 2", new GPSCoordinate(-50, 0))); Leg start = new Leg("Start", startMarker, endMarker, 0); TEST_BOAT.setCurrentLeg(start); - assertEquals(GPSCoordinate.calculateAzimuth(startMarker.getAverageGPSCoordinate(), endMarker.getAverageGPSCoordinate()), 180, 1e-8); + assertEquals(GPSCoordinate.calculateAzimuth(startMarker.getAverageGPSCoordinate(), endMarker.getAverageGPSCoordinate()).degrees(), -180, 1e-8); } @Test public void calculateDueEastAzimuthReturns90() { - Marker startMarker = new Marker(ORIGIN_COORDS); - Marker endMarker = new Marker(new GPSCoordinate(0, 50)); + CompoundMark startMarker = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORDS)); + CompoundMark endMarker = new CompoundMark(new Mark(2, "test mark 2", new GPSCoordinate(0, 50))); Leg start = new Leg("Start", startMarker, endMarker, 0); TEST_BOAT.setCurrentLeg(start); - assertEquals(GPSCoordinate.calculateAzimuth(startMarker.getAverageGPSCoordinate(), endMarker.getAverageGPSCoordinate()), 90, 1e-8); + assertEquals(GPSCoordinate.calculateAzimuth(startMarker.getAverageGPSCoordinate(), endMarker.getAverageGPSCoordinate()).degrees(), 90, 1e-8); } @Test public void calculateDueWestAzimuthReturnsNegative90() { - Marker startMarker = new Marker(ORIGIN_COORDS); - Marker endMarker = new Marker(new GPSCoordinate(0, -50)); + CompoundMark startMarker = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORDS)); + CompoundMark endMarker = new CompoundMark(new Mark(2, "test mark 2", new GPSCoordinate(0, -50))); Leg start = new Leg("Start", startMarker, endMarker, 0); TEST_BOAT.setCurrentLeg(start); - assertEquals(GPSCoordinate.calculateAzimuth(startMarker.getAverageGPSCoordinate(), endMarker.getAverageGPSCoordinate()), -90, 1e-8); + assertEquals(GPSCoordinate.calculateAzimuth(startMarker.getAverageGPSCoordinate(), endMarker.getAverageGPSCoordinate()).degrees(), -90, 1e-8); } @Test public void calculateDueNorthHeadingReturns0() { - Marker startMarker = new Marker(ORIGIN_COORDS); - Marker endMarker = new Marker(new GPSCoordinate(50, 0)); + CompoundMark startMarker = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORDS)); + CompoundMark endMarker = new CompoundMark(new Mark(2, "test mark 2", new GPSCoordinate(50, 0))); Leg start = new Leg("Start", startMarker, endMarker, 0); TEST_BOAT.setCurrentLeg(start); - assertEquals(TEST_BOAT.calculateHeading(), 0, 1e-8); + assertEquals(TEST_BOAT.calculateBearingToNextMarker().degrees(), 0, 1e-8); } @Test public void calculateDueEastHeadingReturns90() { - Marker startMarker = new Marker(ORIGIN_COORDS); - Marker endMarker = new Marker(new GPSCoordinate(0, 50)); + CompoundMark startMarker = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORDS)); + CompoundMark endMarker = new CompoundMark(new Mark(2, "test mark 2", new GPSCoordinate(0, 50))); Leg start = new Leg("Start", startMarker, endMarker, 0); TEST_BOAT.setCurrentLeg(start); - assertEquals(TEST_BOAT.calculateHeading(), 90, 1e-8); + assertEquals(TEST_BOAT.calculateBearingToNextMarker().degrees(), 90, 1e-8); } @Test public void calculateDueSouthHeadingReturns180() { - Marker startMarker = new Marker(ORIGIN_COORDS); - Marker endMarker = new Marker(new GPSCoordinate(-50, 0)); + CompoundMark startMarker = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORDS)); + CompoundMark endMarker = new CompoundMark(new Mark(2, "test mark 2", new GPSCoordinate(-50, 0))); Leg start = new Leg("Start", startMarker, endMarker, 0); TEST_BOAT.setCurrentLeg(start); - assertEquals(TEST_BOAT.calculateHeading(), 180, 1e-8); + assertEquals(TEST_BOAT.calculateBearingToNextMarker().degrees(), 180, 1e-8); } @Test public void calculateDueWestHeadingReturns270() { - Marker startMarker = new Marker(ORIGIN_COORDS); - Marker endMarker = new Marker(new GPSCoordinate(0, -50)); + CompoundMark startMarker = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORDS)); + CompoundMark endMarker = new CompoundMark(new Mark(2, "test mark 2", new GPSCoordinate(0, -50))); Leg start = new Leg("Start", startMarker, endMarker, 0); TEST_BOAT.setCurrentLeg(start); - assertEquals(TEST_BOAT.calculateHeading(), 270, 1e-8); + assertEquals(TEST_BOAT.calculateBearingToNextMarker().degrees(), 270, 1e-8); } } diff --git a/mock/src/test/java/seng302/Model/CompoundMarkTest.java b/mock/src/test/java/seng302/Model/CompoundMarkTest.java index 00035995..ca8da8cd 100644 --- a/mock/src/test/java/seng302/Model/CompoundMarkTest.java +++ b/mock/src/test/java/seng302/Model/CompoundMarkTest.java @@ -16,7 +16,7 @@ public class CompoundMarkTest { @Test public void averageOfSingleMarkAtOriginIsSingleMark() { - Marker testMark = new Marker(ORIGIN_COORD); + CompoundMark testMark = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORD)); assertTrue(testMark.getAverageGPSCoordinate().equals(ORIGIN_COORD)); } @@ -25,7 +25,7 @@ public class CompoundMarkTest { public void averageOfSingleMarkIsSingleMark() { GPSCoordinate testCoord = new GPSCoordinate(20, 25); - Marker testMark = new Marker(testCoord); + CompoundMark testMark = new CompoundMark(new Mark(1, "test origin 1", testCoord)); assertTrue(testMark.getAverageGPSCoordinate().equals(testCoord)); } @@ -34,15 +34,16 @@ public class CompoundMarkTest { public void averageLatOfTwoMarksIsAccurate() { GPSCoordinate testCoord = new GPSCoordinate(0.001, 0); - Marker testMark = new Marker(ORIGIN_COORD, testCoord); + CompoundMark testMark = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORD), new Mark(2, "test origin 2", testCoord)); assertEquals(testMark.getAverageGPSCoordinate(), new GPSCoordinate(0.0005, 0)); + } @Test public void averageLongOfTwoMarksIsAccurate() { GPSCoordinate testCoord = new GPSCoordinate(0, 10); - Marker testMark = new Marker(ORIGIN_COORD, testCoord); + CompoundMark testMark = new CompoundMark(new Mark(1, "test origin 1", ORIGIN_COORD), new Mark(2, "test origin 2", testCoord)); assertTrue(testMark.getAverageGPSCoordinate().equals(new GPSCoordinate(0, 5))); } @@ -52,7 +53,9 @@ public class CompoundMarkTest { GPSCoordinate testCoord1 = new GPSCoordinate(0.0, 30); GPSCoordinate testCoord2 = new GPSCoordinate(0.001, 60); - Marker testMark = new Marker(testCoord1, testCoord2); + + CompoundMark testMark = new CompoundMark(new Mark(1, "test origin 1", testCoord1), new Mark(2, "test origin 2", testCoord2)); + assertEquals(testMark.getAverageGPSCoordinate().getLatitude(), 0.00051776, 1e-8); assertEquals(testMark.getAverageGPSCoordinate().getLongitude(), 45.000000, 1e-8); } diff --git a/mock/src/test/java/seng302/Model/LegTest.java b/mock/src/test/java/seng302/Model/LegTest.java index cae7b203..06ac325b 100644 --- a/mock/src/test/java/seng302/Model/LegTest.java +++ b/mock/src/test/java/seng302/Model/LegTest.java @@ -14,7 +14,7 @@ import static junit.framework.TestCase.assertEquals; */ public class LegTest { - private Marker ORIGIN_Compound_MARKER = new Marker(new GPSCoordinate(0, 0)); + private CompoundMark ORIGIN_Compound_MARKER = new CompoundMark(new Mark(1, "test mark1", new GPSCoordinate(0, 0))); @Test public void calculateDistanceHandles5nmNorth() { @@ -22,9 +22,9 @@ public class LegTest { calc.setStartingGeographicPoint(0, 0); calc.setDirection(0, 5 * Constants.NMToMetersConversion); - Marker endMarker = getEndMarker(calc.getDestinationGeographicPoint()); + CompoundMark endMarker = getEndMarker(calc.getDestinationGeographicPoint()); Leg test = new Leg("Test", ORIGIN_Compound_MARKER, endMarker, 0); - assertEquals(test.getDistance(), 5, 1e-8); + assertEquals(test.getDistanceNauticalMiles(), 5, 1e-8); } @Test @@ -33,9 +33,9 @@ public class LegTest { calc.setStartingGeographicPoint(0, 0); calc.setDirection(90, 12 * Constants.NMToMetersConversion); - Marker endMarker = getEndMarker(calc.getDestinationGeographicPoint()); + CompoundMark endMarker = getEndMarker(calc.getDestinationGeographicPoint()); Leg test = new Leg("Test", ORIGIN_Compound_MARKER, endMarker, 0); - assertEquals(test.getDistance(), 12, 1e-8); + assertEquals(test.getDistanceNauticalMiles(), 12, 1e-8); } @Test @@ -44,9 +44,9 @@ public class LegTest { calc.setStartingGeographicPoint(0, 0); calc.setDirection(180, 0.5 * Constants.NMToMetersConversion); - Marker endMarker = getEndMarker(calc.getDestinationGeographicPoint()); + CompoundMark endMarker = getEndMarker(calc.getDestinationGeographicPoint()); Leg test = new Leg("Test", ORIGIN_Compound_MARKER, endMarker, 0); - assertEquals(test.getDistance(), 0.5, 1e-8); + assertEquals(test.getDistanceNauticalMiles(), 0.5, 1e-8); } @Test @@ -55,23 +55,23 @@ public class LegTest { calc.setStartingGeographicPoint(0, 0); calc.setDirection(-90, 0.1 * Constants.NMToMetersConversion); - Marker endMarker = getEndMarker(calc.getDestinationGeographicPoint()); + CompoundMark endMarker = getEndMarker(calc.getDestinationGeographicPoint()); Leg test = new Leg("Test", ORIGIN_Compound_MARKER, endMarker, 0); - assertEquals(test.getDistance(), 0.1, 1e-8); + assertEquals(test.getDistanceNauticalMiles(), 0.1, 1e-8); } @Test public void calculateDistanceHandlesZeroDifference() { Leg test = new Leg("Test", ORIGIN_Compound_MARKER, ORIGIN_Compound_MARKER, 0); - assertEquals(test.getDistance(), 0, 1e-8); + assertEquals(test.getDistanceNauticalMiles(), 0, 1e-8); } - private Marker getEndMarker(Point2D point) { + private CompoundMark getEndMarker(Point2D point) { GPSCoordinate coords = new GPSCoordinate(point.getY(), point.getX()); - return new Marker(coords); + return new CompoundMark(new Mark(3, "test mark3", coords)); } } diff --git a/mock/src/test/java/seng302/Model/PolarsTest.java b/mock/src/test/java/seng302/Model/PolarsTest.java index d3e61d5d..fbdcae2d 100644 --- a/mock/src/test/java/seng302/Model/PolarsTest.java +++ b/mock/src/test/java/seng302/Model/PolarsTest.java @@ -16,10 +16,11 @@ public class PolarsTest { private double angleEpsilon = 2; private double speedEpsilon = 0.5; - @Before + /** * Creates the Polars object for the tests. */ + @Before public void setUp() { //Read data. try { @@ -31,216 +32,226 @@ public class PolarsTest { } } - @Test + /** * Tests if we can calculate VMG for a variety of values. */ + @Test public void testVMG1() { //Test 1. //This test has a wind speed that is between two values from the table (12kn, 16kn, this is 15.9kn). - double windAngle1 = 31.5; - double destAngle1 = 65.32; + Bearing windAngle1 = Bearing.fromDegrees(31.5); + Bearing destAngle1 = Bearing.fromDegrees(65.32); double windSpeed1 = 15.9;//knots - double vmgAngle1 = 72.4; + Bearing vmgAngle1 = Bearing.fromDegrees(72.4); double vmgSpeed1 = 30.4; - VMG calcVMG1 = polars.calculateVMG(windAngle1, windSpeed1, destAngle1, 0, 360); - double calcVMGAngle1 = calcVMG1.getBearing(); + VMG calcVMG1 = polars.calculateVMG(windAngle1, windSpeed1, destAngle1, Bearing.fromDegrees(0), Bearing.fromDegrees(359.9)); + Bearing calcVMGAngle1 = calcVMG1.getBearing(); double calcVMGSpeed1 = calcVMG1.getSpeed(); - assertEquals(calcVMGAngle1, vmgAngle1, angleEpsilon); + assertEquals(calcVMGAngle1.degrees(), vmgAngle1.degrees(), angleEpsilon); assertEquals(calcVMGSpeed1, vmgSpeed1, speedEpsilon); } - @Test + /** * Tests if we can calculate VMG for a variety of values. */ + @Test public void testVMG2() { //Test 2. //This test has a wind speed much larger than any in the table (max from table is 30kn, this is 40kn). - double windAngle2 = 200; - double destAngle2 = 35; + Bearing windAngle2 = Bearing.fromDegrees(200); + Bearing destAngle2 = Bearing.fromDegrees(35); double windSpeed2 = 40;//knots - double vmgAngle2 = 69; + Bearing vmgAngle2 = Bearing.fromDegrees(69); double vmgSpeed2 = 32.8; - VMG calcVMG2 = polars.calculateVMG(windAngle2, windSpeed2, destAngle2, 0, 360); - double calcVMGAngle2 = calcVMG2.getBearing(); + VMG calcVMG2 = polars.calculateVMG(windAngle2, windSpeed2, destAngle2, Bearing.fromDegrees(0), Bearing.fromDegrees(359.9)); + Bearing calcVMGAngle2 = calcVMG2.getBearing(); double calcVMGSpeed2 = calcVMG2.getSpeed(); - assertEquals(calcVMGAngle2, vmgAngle2, angleEpsilon); + assertEquals(calcVMGAngle2.degrees(), vmgAngle2.degrees(), angleEpsilon); assertEquals(calcVMGSpeed2, vmgSpeed2, speedEpsilon); } - @Test + /** * Tests if we can calculate VMG for a variety of values. */ + @Test public void testVMG3() { //Test 3. //This test has a wind speed lower than any non-zero values from the table (table has 0kn, 4kn, this is 2kn). - double windAngle3 = 345; - double destAngle3 = 199; + Bearing windAngle3 = Bearing.fromDegrees(345); + Bearing destAngle3 = Bearing.fromDegrees(199); double windSpeed3 = 2;//knots - double vmgAngle3 = 222; + Bearing vmgAngle3 = Bearing.fromDegrees(222); double vmgSpeed3 = 4.4; - VMG calcVMG3 = polars.calculateVMG(windAngle3, windSpeed3, destAngle3, 0, 360); - double calcVMGAngle3 = calcVMG3.getBearing(); + VMG calcVMG3 = polars.calculateVMG(windAngle3, windSpeed3, destAngle3, Bearing.fromDegrees(0), Bearing.fromDegrees(359.9)); + Bearing calcVMGAngle3 = calcVMG3.getBearing(); double calcVMGSpeed3 = calcVMG3.getSpeed(); - assertEquals(calcVMGAngle3, vmgAngle3, angleEpsilon); + assertEquals(calcVMGAngle3.degrees(), vmgAngle3.degrees(), angleEpsilon); assertEquals(calcVMGSpeed3, vmgSpeed3, speedEpsilon); } - @Test + /** * Tests if we can calculate VMG for a variety of values. */ + @Test public void testVMG4() { //Test 4. //This test has a wind speed of 0. - double windAngle4 = 5; - double destAngle4 = 100; + Bearing windAngle4 = Bearing.fromDegrees(5); + Bearing destAngle4 = Bearing.fromDegrees(100); double windSpeed4 = 0;//knots - double vmgAngle4 = 100; + Bearing vmgAngle4 = Bearing.fromDegrees(100); double vmgSpeed4 = 0; - VMG calcVMG4 = polars.calculateVMG(windAngle4, windSpeed4, destAngle4, 0, 360); - double calcVMGAngle4 = calcVMG4.getBearing(); + VMG calcVMG4 = polars.calculateVMG(windAngle4, windSpeed4, destAngle4, Bearing.fromDegrees(0), Bearing.fromDegrees(359.9)); + Bearing calcVMGAngle4 = calcVMG4.getBearing(); double calcVMGSpeed4 = calcVMG4.getSpeed(); - assertEquals(calcVMGAngle4, vmgAngle4, angleEpsilon); + assertEquals(calcVMGAngle4.degrees(), vmgAngle4.degrees(), angleEpsilon); assertEquals(calcVMGSpeed4, vmgSpeed4, speedEpsilon); } - @Test + /** * Tests if we can calculate VMG for a variety of values. */ + @Test public void testVMG5() { //Test 5. //This test has a bearing bound of [55, 70), which only contains a suboptimal VMG. - double windAngle5 = 5; - double destAngle5 = 100; + Bearing windAngle5 = Bearing.fromDegrees(5); + Bearing destAngle5 = Bearing.fromDegrees(100); double windSpeed5 = 9;//knots - double vmgAngle5 = 70; + Bearing vmgAngle5 = Bearing.fromDegrees(70); double vmgSpeed5 = 15; - double bearingUpperBound5 = 70; - double bearingLowerBound5 = 55; + Bearing bearingUpperBound5 = Bearing.fromDegrees(70); + Bearing bearingLowerBound5 = Bearing.fromDegrees(55); VMG calcVMG5 = polars.calculateVMG(windAngle5, windSpeed5, destAngle5, bearingLowerBound5, bearingUpperBound5); - double calcVMGAngle5 = calcVMG5.getBearing(); + Bearing calcVMGAngle5 = calcVMG5.getBearing(); double calcVMGSpeed5 = calcVMG5.getSpeed(); - assertEquals(calcVMGAngle5, vmgAngle5, angleEpsilon); + assertEquals(calcVMGAngle5.degrees(), vmgAngle5.degrees(), angleEpsilon); assertEquals(calcVMGSpeed5, vmgSpeed5, speedEpsilon); - assertTrue(calcVMGAngle5 >= bearingLowerBound5); - assertTrue(calcVMGAngle5 < bearingUpperBound5); + assertTrue(calcVMGAngle5.degrees() >= bearingLowerBound5.degrees()); + assertTrue(calcVMGAngle5.degrees() <= bearingUpperBound5.degrees()); } - @Test + /** * Tests if we can calculate VMG for a variety of values. */ + @Test public void testVMG6() { //Test 6. //This test has a bearing bound of [70, 55), which has a lower bound > upper bound, which is complementary to [55, 70). - double windAngle6 = 5; - double destAngle6 = 100; + Bearing windAngle6 = Bearing.fromDegrees(5); + Bearing destAngle6 = Bearing.fromDegrees(100); double windSpeed6 = 11;//knots - double vmgAngle6 = 92.85; + Bearing vmgAngle6 = Bearing.fromDegrees(92.85); double vmgSpeed6 = 20.086; - double bearingUpperBound6 = 55; - double bearingLowerBound6 = 70; + Bearing bearingUpperBound6 = Bearing.fromDegrees(55); + Bearing bearingLowerBound6 = Bearing.fromDegrees(70); VMG calcVMG6 = polars.calculateVMG(windAngle6, windSpeed6, destAngle6, bearingLowerBound6, bearingUpperBound6); - double calcVMGAngle6 = calcVMG6.getBearing(); + Bearing calcVMGAngle6 = calcVMG6.getBearing(); double calcVMGSpeed6 = calcVMG6.getSpeed(); - assertEquals(calcVMGAngle6, vmgAngle6, angleEpsilon); + assertEquals(calcVMGAngle6.degrees(), vmgAngle6.degrees(), angleEpsilon); assertEquals(calcVMGSpeed6, vmgSpeed6, speedEpsilon); - if (bearingLowerBound6 > bearingUpperBound6) { - assertTrue((calcVMGAngle6 >= bearingLowerBound6) || (calcVMGAngle6 <= bearingUpperBound6)); + if (bearingLowerBound6.degrees() > bearingUpperBound6.degrees()) { + assertTrue((calcVMGAngle6.degrees() >= bearingLowerBound6.degrees()) || (calcVMGAngle6.degrees() <= bearingUpperBound6.degrees())); } else { - assertTrue(calcVMGAngle6 >= bearingLowerBound6); - assertTrue(calcVMGAngle6 < bearingUpperBound6); + assertTrue(calcVMGAngle6.degrees() >= bearingLowerBound6.degrees()); + assertTrue(calcVMGAngle6.degrees() <= bearingUpperBound6.degrees()); } } - @Test + /** * Tests if we can calculate VMG for a variety of values. */ + @Test public void testVMG7() { //Test 7. //This test has a bearing bound of [340, 5), which has a lower bound > upper bound, which is complementary to [5, 340). - double windAngle7 = 340; - double destAngle7 = 30; + Bearing windAngle7 = Bearing.fromDegrees(340); + Bearing destAngle7 = Bearing.fromDegrees(30); double windSpeed7 = 7;//knots - double vmgAngle7 = 5; + Bearing vmgAngle7 = Bearing.fromDegrees(5); double vmgSpeed7 = 11; - double bearingUpperBound7 = 5; - double bearingLowerBound7 = 340; + Bearing bearingUpperBound7 = Bearing.fromDegrees(5); + Bearing bearingLowerBound7 = Bearing.fromDegrees(340); VMG calcVMG7 = polars.calculateVMG(windAngle7, windSpeed7, destAngle7, bearingLowerBound7, bearingUpperBound7); - double calcVMGAngle7 = calcVMG7.getBearing(); + Bearing calcVMGAngle7 = calcVMG7.getBearing(); double calcVMGSpeed7 = calcVMG7.getSpeed(); - assertEquals(calcVMGAngle7, vmgAngle7, angleEpsilon); + assertEquals(calcVMGAngle7.degrees(), vmgAngle7.degrees(), angleEpsilon); assertEquals(calcVMGSpeed7, vmgSpeed7, speedEpsilon); - if (bearingLowerBound7 > bearingUpperBound7) { - assertTrue((calcVMGAngle7 >= bearingLowerBound7) || (calcVMGAngle7 <= bearingUpperBound7)); + if (bearingLowerBound7.degrees() > bearingUpperBound7.degrees()) { + assertTrue((calcVMGAngle7.degrees() >= bearingLowerBound7.degrees()) || (calcVMGAngle7.degrees() <= bearingUpperBound7.degrees())); + } else { - assertTrue(calcVMGAngle7 >= bearingLowerBound7); - assertTrue(calcVMGAngle7 < bearingUpperBound7); + assertTrue(calcVMGAngle7.degrees() >= bearingLowerBound7.degrees()); + assertTrue(calcVMGAngle7.degrees() <= bearingUpperBound7.degrees()); + } } - @Test + /** * Tests if we can calculate VMG for a variety of values. */ + @Test public void testVMG8() { //Test 8. //This test has a bearing bound of [340, 5), which has a lower bound > upper bound, which is complementary to [5, 340). Due to the wind, dest angles, and bearing bounds, it cannot actually find a VMG > 0 (valid VMGs will actually be in the angle interval [10, 190]), so it will return the VMG(angle=0, speed=0). - double windAngle8 = 5; - double destAngle8 = 100; + Bearing windAngle8 = Bearing.fromDegrees(5); + Bearing destAngle8 = Bearing.fromDegrees(100); double windSpeed8 = 7;//knots - double vmgAngle8 = 0; + Bearing vmgAngle8 = Bearing.fromDegrees(0); double vmgSpeed8 = 0; - double bearingUpperBound8 = 5; - double bearingLowerBound8 = 340; + Bearing bearingUpperBound8 = Bearing.fromDegrees(5); + Bearing bearingLowerBound8 = Bearing.fromDegrees(340); VMG calcVMG8 = polars.calculateVMG(windAngle8, windSpeed8, destAngle8, bearingLowerBound8, bearingUpperBound8); - double calcVMGAngle8 = calcVMG8.getBearing(); + Bearing calcVMGAngle8 = calcVMG8.getBearing(); double calcVMGSpeed8 = calcVMG8.getSpeed(); - assertEquals(calcVMGAngle8, vmgAngle8, 0); + assertEquals(calcVMGAngle8.degrees(), vmgAngle8.degrees(), 0); assertEquals(calcVMGSpeed8, vmgSpeed8, 0); } diff --git a/mock/src/test/java/seng302/Model/RaceTest.java b/mock/src/test/java/seng302/Model/RaceTest.java index e86473fd..abfa5a8a 100644 --- a/mock/src/test/java/seng302/Model/RaceTest.java +++ b/mock/src/test/java/seng302/Model/RaceTest.java @@ -29,9 +29,9 @@ import static org.mockito.Mockito.*; public class RaceTest{ - public static final Marker ORIGIN = new Marker(new GPSCoordinate(0, 0)); - public static final Marker THREE_NM_FROM_ORIGIN = new Marker(new GPSCoordinate(0.050246769, 0)); - public static final Marker FIFTEEN_NM_FROM_ORIGIN = new Marker(new GPSCoordinate(0.251233845, 0)); + public static final CompoundMark ORIGIN = new CompoundMark(new Mark(1, "test origin 1", new GPSCoordinate(0, 0))); + public static final CompoundMark THREE_NM_FROM_ORIGIN = new CompoundMark(new Mark(2, "test mark 2", new GPSCoordinate(0.050246769, 0))); + public static final CompoundMark FIFTEEN_NM_FROM_ORIGIN = new CompoundMark(new Mark(3, "test mark 3", new GPSCoordinate(0.251233845, 0))); public static ArrayList TEST_LEGS = new ArrayList<>(); public static final int START_LEG_DISTANCE = 3; public static final int MIDDLE_LEG_DISTANCE = 12; @@ -92,12 +92,12 @@ public class RaceTest{ RaceDataSource dataSource = new RaceXMLReader("mockXML/raceTest.xml", new BoatXMLReader("mockXML/boatTest.xml", new Polars())); Race testRace = new Race(dataSource, mockOutput); testRace.initialiseBoats(); - Boat testBoat = testRace.startingBoats.get(0); + Boat testBoat = testRace.getBoats().get(0); testBoat.setCurrentLeg(FINISH_LEG); testBoat.setDistanceTravelledInLeg(1); testRace.checkPosition(testBoat, 1); - assertEquals(testRace.boatsFinished, 1); + assertEquals(testRace.getNumberOfActiveBoats(), 0); } catch (ParserConfigurationException | IOException | SAXException | ParseException | StreamedCourseXMLException e) { e.printStackTrace(); @@ -114,7 +114,7 @@ public class RaceTest{ RaceDataSource dataSource = new RaceXMLReader("mockXML/raceTest.xml", new BoatXMLReader("mockXML/boatTest.xml", new Polars())); Race testRace = new Race(dataSource, mockOutput); testRace.initialiseBoats(); - Boat testBoat = testRace.startingBoats.get(0); + Boat testBoat = testRace.getBoats().get(0); testBoat.setCurrentLeg(FINISH_LEG); testBoat.setDistanceTravelledInLeg(1); testRace.checkPosition(testBoat, 1); @@ -136,7 +136,7 @@ public class RaceTest{ RaceDataSource dataSource = new RaceXMLReader("mockXML/raceTest.xml", new BoatXMLReader("mockXML/boatTest.xml", new Polars())); Race testRace = new Race(dataSource, mockOutput); testRace.initialiseBoats(); - Boat testBoat = testRace.startingBoats.get(0); + Boat testBoat = testRace.getBoats().get(0); testBoat.setCurrentLeg(FINISH_LEG); testBoat.setDistanceTravelledInLeg(1); testRace.checkPosition(testBoat, 1); @@ -158,12 +158,12 @@ public class RaceTest{ RaceDataSource dataSource = new RaceXMLReader("mockXML/raceTest.xml", new BoatXMLReader("mockXML/boatTest.xml", new Polars())); Race testRace = new Race(dataSource, mockOutput); testRace.initialiseBoats(); - Boat testBoat = testRace.startingBoats.get(0); + Boat testBoat = testRace.getBoats().get(0); testBoat.setCurrentLeg(START_LEG); testBoat.setDistanceTravelledInLeg(START_LEG_DISTANCE); testRace.checkPosition(testBoat, 1); - assertEquals(testRace.boatsFinished, 0); + assertEquals(testRace.getNumberOfActiveBoats(), 1); } catch (ParserConfigurationException | IOException | SAXException | ParseException | StreamedCourseXMLException e) { e.printStackTrace(); @@ -181,7 +181,7 @@ public class RaceTest{ RaceDataSource dataSource = new RaceXMLReader("mockXML/raceTest.xml", new BoatXMLReader("mockXML/boatTest.xml", new Polars())); Race testRace = new Race(dataSource, mockOutput); testRace.initialiseBoats(); - Boat testBoat = testRace.startingBoats.get(0); + Boat testBoat = testRace.getBoats().get(0); testBoat.setCurrentLeg(START_LEG); testBoat.setDistanceTravelledInLeg(START_LEG_DISTANCE + 1); testRace.checkPosition(testBoat, 0); @@ -241,7 +241,7 @@ public class RaceTest{ RaceDataSource raceDataSource = new RaceXMLReader("mockXML/raceTest.xml", boatDataSource); Race testRace = new Race(raceDataSource, mockOutput); testRace.setDnfChance(100); - Boat testBoat = testRace.startingBoats.get(0); + Boat testBoat = testRace.getBoats().get(0); testBoat.setCurrentLeg(START_LEG); testBoat.setDistanceTravelledInLeg(START_LEG_DISTANCE + 1); testRace.checkPosition(testBoat, 1); @@ -262,10 +262,10 @@ public class RaceTest{ BoatDataSource boatDataSource = new BoatXMLReader("mockXML/boatTest.xml", new Polars()); RaceDataSource raceDataSource = new RaceXMLReader("mockXML/raceTest.xml", boatDataSource); Race testRace = new Race(raceDataSource, mockOutput); - Boat testBoat = testRace.startingBoats.get(0); + Boat testBoat = testRace.getBoats().get(0); testBoat.setCurrentLeg(FINISH_LEG); testBoat.setCurrentPosition(ORIGIN.getAverageGPSCoordinate()); - testRace.updatePosition(testBoat, 1); + testRace.updatePosition(testBoat, 1, 1); assertEquals(testBoat.getCurrentPosition(), ORIGIN.getAverageGPSCoordinate()); } catch (ParserConfigurationException | IOException | SAXException | ParseException | StreamedCourseXMLException e) { @@ -283,11 +283,11 @@ public class RaceTest{ RaceDataSource raceDataSource = new RaceXMLReader("mockXML/raceTest.xml", boatDataSource); Race testRace = new Race(raceDataSource, mockOutput); testRace.initialiseBoats(); - Boat testBoat = testRace.startingBoats.get(0); + Boat testBoat = testRace.getBoats().get(0); testBoat.setCurrentLeg(START_LEG); testBoat.setDistanceTravelledInLeg(START_LEG_DISTANCE - 1); testBoat.setCurrentPosition(ORIGIN.getAverageGPSCoordinate()); - testRace.updatePosition(testBoat, 100); + testRace.updatePosition(testBoat, 100, 100); assertFalse(testBoat.getCurrentPosition() == ORIGIN.getAverageGPSCoordinate()); } catch (ParserConfigurationException | IOException | SAXException | ParseException | StreamedCourseXMLException e) { diff --git a/network/src/main/java/seng302/Networking/MessageEncoders/RaceVisionByteEncoder.java b/network/src/main/java/seng302/Networking/MessageEncoders/RaceVisionByteEncoder.java index 4f9efa6f..cc7a4ae6 100644 --- a/network/src/main/java/seng302/Networking/MessageEncoders/RaceVisionByteEncoder.java +++ b/network/src/main/java/seng302/Networking/MessageEncoders/RaceVisionByteEncoder.java @@ -5,6 +5,7 @@ import seng302.Networking.Messages.*; import java.nio.ByteBuffer; import java.util.ArrayList; +import java.util.List; import static seng302.Networking.Utils.ByteConverter.*; @@ -32,7 +33,7 @@ public class RaceVisionByteEncoder { */ public static byte[] raceStatus(RaceStatus raceStatus){ - ArrayList boatStatuses = raceStatus.getBoatStatuses(); + List boatStatuses = raceStatus.getBoatStatuses(); ByteBuffer raceStatusMessage = ByteBuffer.allocate(24 + 20* boatStatuses.size()); //Version Number 1 bytes diff --git a/network/src/main/java/seng302/Networking/Messages/BoatStatus.java b/network/src/main/java/seng302/Networking/Messages/BoatStatus.java index ab625b95..dacb5d5e 100644 --- a/network/src/main/java/seng302/Networking/Messages/BoatStatus.java +++ b/network/src/main/java/seng302/Networking/Messages/BoatStatus.java @@ -31,10 +31,10 @@ public class BoatStatus { this.sourceID = sourceID; this.boatStatus = boatStatusEnum.getValue(); this.legNumber = ByteConverter.intToBytes(legNum)[0]; - numPenaltiesAwarded = 0; - numPenaltiesServed = 0; - estTimeAtFinish = 0; - estTimeAtNextMark = 0; + this.numPenaltiesAwarded = 0; + this.numPenaltiesServed = 0; + this.estTimeAtFinish = 0; + this.estTimeAtNextMark = 0; } diff --git a/network/src/main/java/seng302/Networking/Messages/Enums/RaceStatusEnum.java b/network/src/main/java/seng302/Networking/Messages/Enums/RaceStatusEnum.java new file mode 100644 index 00000000..2563545d --- /dev/null +++ b/network/src/main/java/seng302/Networking/Messages/Enums/RaceStatusEnum.java @@ -0,0 +1,108 @@ +package seng302.Networking.Messages.Enums; + + +import java.util.HashMap; +import java.util.Map; + +/** + * Enumeration that encapsulates the various statuses a race can have. See AC35 streaming spec, 4.2. + */ +public enum RaceStatusEnum { + + NOT_ACTIVE(0), + + /** + * Between 3:00 and 1:00 minutes before start. + */ + WARNING(1), + + /** + * Less than 1:00 minutes before start. + */ + PREPARATORY(2), + STARTED(3), + + /** + * Obsolete. + */ + FINISHED(4), + + /** + * Obsolete. + */ + RETIRED(5), + ABANDONED(6), + POSTPONED(7), + TERMINATED(8), + RACE_START_TIME_NOT_SET(9), + + /** + * More than 3:00 minutes until start. + */ + PRESTART(10), + + /** + * Used to indicate that a given byte value is invalid. + */ + NOT_A_STATUS(-1); + + + /** + * Primitive value of the enum. + */ + private byte value; + + + /** + * Ctor. Creates a RaceStatusEnum from a given primitive integer value, cast to a byte. + * @param value Integer, which is cast to byte, to construct from. + */ + private RaceStatusEnum(int value) { + this.value = (byte) value; + } + + /** + * Returns the primitive value of the enum. + * @return Primitive value of the enum. + */ + public byte getValue() { + return value; + } + + + /** + * Stores a mapping between Byte values and RaceStatusEnum values. + */ + private static final Map byteToStatusMap = new HashMap<>(); + + + /** + * Static initialization block. Initializes the byteToStatusMap. + */ + static { + for (RaceStatusEnum type : RaceStatusEnum.values()) { + RaceStatusEnum.byteToStatusMap.put(type.value, type); + } + } + + + /** + * Returns the enumeration value which corresponds to a given byte value. + * @param raceStatusByte Byte value to convert to a RaceStatusEnum value. + * @return The RaceStatusEnum value which corresponds to the given byte value. + */ + public static RaceStatusEnum fromByte(byte raceStatusByte) { + //Gets the corresponding MessageType from the map. + RaceStatusEnum type = RaceStatusEnum.byteToStatusMap.get(raceStatusByte); + + if (type == null) { + //If the byte value wasn't found, return the NOT_A_STATUS RaceStatusEnum. + return RaceStatusEnum.NOT_A_STATUS; + } else { + //Otherwise, return the RaceStatusEnum. + return type; + } + + } + +} diff --git a/network/src/main/java/seng302/Networking/Messages/Enums/RaceTypeEnum.java b/network/src/main/java/seng302/Networking/Messages/Enums/RaceTypeEnum.java new file mode 100644 index 00000000..01c1539e --- /dev/null +++ b/network/src/main/java/seng302/Networking/Messages/Enums/RaceTypeEnum.java @@ -0,0 +1,87 @@ +package seng302.Networking.Messages.Enums; + +import java.util.HashMap; +import java.util.Map; + +/** + * Enumeration that encapsulates the various types of races. See AC35 streaming spec, 4.2. + */ +public enum RaceTypeEnum { + + + /** + * A race between two boats. + */ + MATCH_RACE(1), + + /** + * A race between a fleet of boats. + */ + FLEET_RACE(2), + + /** + * Used to indicate that a given byte value is invalid. + */ + NOT_A_STATUS(-1); + + + /** + * Primitive value of the enum. + */ + private byte value; + + + /** + * Ctor. Creates a RaceTypeEnum from a given primitive integer value, cast to a byte. + * @param value Integer, which is cast to byte, to construct from. + */ + private RaceTypeEnum(int value) { + this.value = (byte) value; + } + + /** + * Returns the primitive value of the enum. + * @return Primitive value of the enum. + */ + public byte getValue() { + return value; + } + + + /** + * Stores a mapping between Byte values and RaceStatusEnum values. + */ + private static final Map byteToStatusMap = new HashMap<>(); + + + /** + * Static initialization block. Initializes the byteToStatusMap. + */ + static { + for (RaceTypeEnum type : RaceTypeEnum.values()) { + RaceTypeEnum.byteToStatusMap.put(type.value, type); + } + } + + + /** + * Returns the enumeration value which corresponds to a given byte value. + * @param raceTypeEnum Byte value to convert to a RaceTypeEnum value. + * @return The RaceTypeEnum value which corresponds to the given byte value. + */ + public static RaceTypeEnum fromByte(byte raceTypeEnum) { + //Gets the corresponding MessageType from the map. + RaceTypeEnum type = RaceTypeEnum.byteToStatusMap.get(raceTypeEnum); + + if (type == null) { + //If the byte value wasn't found, return the NOT_A_STATUS RaceTypeEnum. + return RaceTypeEnum.NOT_A_STATUS; + } else { + //Otherwise, return the RaceTypeEnum. + return type; + } + + } + + +} diff --git a/network/src/main/java/seng302/Networking/Messages/RaceStatus.java b/network/src/main/java/seng302/Networking/Messages/RaceStatus.java index 87ea6342..89c7b90c 100644 --- a/network/src/main/java/seng302/Networking/Messages/RaceStatus.java +++ b/network/src/main/java/seng302/Networking/Messages/RaceStatus.java @@ -3,6 +3,7 @@ package seng302.Networking.Messages; import seng302.Networking.Messages.Enums.MessageType; import java.util.ArrayList; +import java.util.List; /** * Created by fwy13 on 25/04/17. @@ -16,10 +17,10 @@ public class RaceStatus extends AC35Data { private int windDirection; private int windSpeed; private int raceType; - private ArrayList boatStatuses; + private List boatStatuses; private static final double windDirectionScalar = 360.0 / 32768.0; // 0x8000 / 360 - public RaceStatus(long currentTime, int raceID, int raceStatus, long expectedStartTime, int windDirection, int windSpeed, int raceType, ArrayList boatStatuses){ + public RaceStatus(long currentTime, int raceID, int raceStatus, long expectedStartTime, int windDirection, int windSpeed, int raceType, List boatStatuses){ super(MessageType.RACESTATUS); this.currentTime = currentTime; this.raceID = raceID; @@ -74,7 +75,7 @@ public class RaceStatus extends AC35Data { return raceType; } - public ArrayList getBoatStatuses() + public List getBoatStatuses() { return boatStatuses; } diff --git a/visualiser/src/main/java/seng302/Mock/StreamedRace.java b/visualiser/src/main/java/seng302/Mock/StreamedRace.java index 2ca0fd5c..afcd7d5b 100644 --- a/visualiser/src/main/java/seng302/Mock/StreamedRace.java +++ b/visualiser/src/main/java/seng302/Mock/StreamedRace.java @@ -83,6 +83,7 @@ public class StreamedRace implements Runnable { int legNumber = boatStatusMessage.getLegNumber(); + if (legNumber >= 1 && legNumber < legs.size()) { boat.setCurrentLeg(legs.get(legNumber)); } @@ -95,9 +96,9 @@ public class StreamedRace implements Runnable { boatsFinished++; boat.setTimeFinished(timeElapsed); boat.setFinished(true); - //System.out.println("Boat finished"); } } + //Update the boat display table in the GUI to reflect the leg change updatePositions(); }