Merge branch 'master' into MapWindRotation

# Conflicts:
#	racevisionGame/src/main/java/mock/app/Event.java
#	racevisionGame/src/main/java/mock/model/MockRace.java
#	racevisionGame/src/main/java/mock/model/commandFactory/CommandFactory.java
#	racevisionGame/src/main/java/shared/dataInput/RaceXMLReader.java
#	racevisionGame/src/main/java/shared/model/CompoundMark.java
#	racevisionGame/src/main/java/shared/model/Mark.java
#	racevisionGame/src/main/java/visualiser/Controllers/ConnectionController.java
#	racevisionGame/src/main/java/visualiser/Controllers/HostController.java
#	racevisionGame/src/main/java/visualiser/app/VisualiserInput.java
#	racevisionGame/src/main/java/visualiser/gameController/ControllerServer.java
#	racevisionGame/src/main/java/visualiser/model/VisualiserRace.java
This commit is contained in:
Joseph Gardner
2017-08-17 11:46:09 +12:00
115 changed files with 7745 additions and 2288 deletions
@@ -1,18 +1,26 @@
package mock.app;
import mock.model.RaceLogic;
import mock.model.ClientConnection;
import mock.model.SourceIdAllocator;
import mock.model.commandFactory.CompositeCommand;
import network.Messages.Enums.XMLMessageType;
import network.Messages.LatestMessages;
import network.Messages.XMLMessage;
import visualiser.gameController.ControllerServer;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Connection acceptor for multiple clients
@@ -28,10 +36,31 @@ public class ConnectionAcceptor implements Runnable {
* Socket used to listen for clients on.
*/
private ServerSocket serverSocket;
//mock outputs
private ArrayBlockingQueue<MockOutput> mockOutputList = new ArrayBlockingQueue<>(16, true);
//latest messages
/**
* List of client connections.
*/
private BlockingQueue<ClientConnection> clientConnections = new ArrayBlockingQueue<>(16, true);
/**
* Snapshot of the race.
*/
private LatestMessages latestMessages;
/**
* Collection of commands from clients for race to execute.
*/
private CompositeCommand compositeCommand;
/**
* Used to allocate source IDs to clients.
*/
private SourceIdAllocator sourceIdAllocator;
//Acknowledgement number for packets
private int ackNumber = 0;
//race xml sequence number
@@ -40,22 +69,28 @@ public class ConnectionAcceptor implements Runnable {
private short boatXMLSequenceNumber;
//regatta xml sequence number
private short regattaXMLSequenceNumber;
//controller server
private ControllerServer controllerServer;
//
private RaceLogic rl = null;
private RaceLogic raceLogic = null;
/**
* Connection Acceptor Constructor
* @param latestMessages Latest messages to be sent
* @param compositeCommand Collection of commands for race to execute.
* @param sourceIdAllocator Object used to allocate source IDs for clients.
* @param raceLogic The race the client will connect to.
* @throws IOException if a server socket cannot be instantiated.
*/
public ConnectionAcceptor(LatestMessages latestMessages) throws IOException {
public ConnectionAcceptor(LatestMessages latestMessages, CompositeCommand compositeCommand, SourceIdAllocator sourceIdAllocator, RaceLogic raceLogic) throws IOException {
this.latestMessages = latestMessages;
this.compositeCommand = compositeCommand;
this.sourceIdAllocator = sourceIdAllocator;
this.raceLogic = raceLogic;
this.serverSocket = new ServerSocket(serverPort);
CheckClientConnection checkClientConnection = new CheckClientConnection(mockOutputList);
CheckClientConnection checkClientConnection = new CheckClientConnection(clientConnections);
new Thread(checkClientConnection, "ConnectionAcceptor()->CheckClientConnection thread").start();
}
public String getAddress() throws UnknownHostException {
@@ -67,9 +102,6 @@ public class ConnectionAcceptor implements Runnable {
}
public void setRace(RaceLogic rl){
this.rl = rl;
}
/**
* Run the Acceptor
@@ -77,28 +109,28 @@ public class ConnectionAcceptor implements Runnable {
@Override
public void run() {
while(mockOutputList.remainingCapacity() > 0) {
while(clientConnections.remainingCapacity() > 0) {
try {
System.out.println("Waiting for a connection...");//TEMP DEBUG REMOVE
Socket mockSocket = serverSocket.accept();
//TODO at this point we need to assign the connection a boat source ID, if they requested to participate.
DataOutputStream outToVisualiser = new DataOutputStream(mockSocket.getOutputStream());
MockOutput mockOutput = new MockOutput(latestMessages, outToVisualiser);
ControllerServer controllerServer = new ControllerServer(mockSocket, this.rl); //TODO probably pass assigned boat source ID into ControllerServer.
Logger.getGlobal().log(Level.INFO, String.format("Client connected. client ip/port = %s. Local ip/port = %s.", mockSocket.getRemoteSocketAddress(), mockSocket.getLocalSocketAddress()));
new Thread(mockOutput, "ConnectionAcceptor.run()->MockOutput thread" + mockOutput).start();
new Thread(controllerServer, "ConnectionAcceptor.run()->ControllerServer thread" + controllerServer).start();
mockOutputList.add(mockOutput);
ClientConnection clientConnection = new ClientConnection(mockSocket, sourceIdAllocator, latestMessages, compositeCommand, raceLogic);
System.out.println(String.format("%d number of Visualisers Connected.", mockOutputList.size()));//TEMP
clientConnections.add(clientConnection);
new Thread(clientConnection, "ConnectionAcceptor.run()->ClientConnection thread " + clientConnection).start();
Logger.getGlobal().log(Level.INFO, String.format("%d number of Visualisers Connected.", clientConnections.size()));
} catch (IOException e) {
e.printStackTrace();//TODO handle this properly
Logger.getGlobal().log(Level.WARNING, "Got an IOException while a client was attempting to connect.", e);
}
@@ -110,14 +142,14 @@ public class ConnectionAcceptor implements Runnable {
*/
class CheckClientConnection implements Runnable{
private ArrayBlockingQueue<MockOutput> mocks;
private BlockingQueue<ClientConnection> connections;
/**
* Constructor
* @param mocks Mocks "connected"
* @param connections Clients "connected"
*/
public CheckClientConnection(ArrayBlockingQueue<MockOutput> mocks){
this.mocks = mocks;
public CheckClientConnection(BlockingQueue<ClientConnection> connections){
this.connections = connections;
}
/**
@@ -125,21 +157,44 @@ public class ConnectionAcceptor implements Runnable {
*/
@Override
public void run() {
double timeSinceLastHeartBeat = System.currentTimeMillis();
while(true) {
//System.out.println(mocks.size());//used to see current amount of visualisers connected.
ArrayBlockingQueue<MockOutput> m = new ArrayBlockingQueue<>(16, true, mocks);
for (MockOutput mo : m) {
try {
mo.sendHeartBeat();
} catch (IOException e) {
mocks.remove(mo);
//We track the number of times each connection fails the !isAlive() test.
//This is to give a bit of lee-way in case the connection checker checks a connection before its thread has actually started.
Map<ClientConnection, Integer> connectionDeadCount = new HashMap<>();
while(!Thread.interrupted()) {
//Make copy of connections.
List<ClientConnection> clientConnections = new ArrayList<>(connections);
for (ClientConnection client : clientConnections) {
connectionDeadCount.put(client, connectionDeadCount.getOrDefault(client, 0));
if (!client.isAlive()) {
//Add one to fail count.
connectionDeadCount.put(client, connectionDeadCount.get(client) + 1);
}
//We only remove them if they fail 5 times.
if (connectionDeadCount.get(client) > 5) {
connections.remove(client);
connectionDeadCount.remove(client);
client.terminate();
Logger.getGlobal().log(Level.WARNING, "CheckClientConnection is removing the dead connection: " + client);
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
Logger.getGlobal().log(Level.WARNING, "CheckClientConnection was interrupted while sleeping.", e);
Thread.currentThread().interrupt();
return;
}
}
}
+134 -36
View File
@@ -1,10 +1,15 @@
package mock.app;
import mock.dataInput.PolarParser;
import mock.exceptions.EventConstructionException;
import mock.model.*;
import mock.model.commandFactory.CompositeCommand;
import mock.model.MockRace;
import mock.model.Polars;
import mock.xml.RaceXMLCreator;
import mock.model.RaceLogic;
import mock.model.SourceIdAllocator;
import mock.model.commandFactory.CompositeCommand;
import network.Messages.LatestMessages;
import org.xml.sax.SAXException;
import shared.dataInput.*;
@@ -13,6 +18,7 @@ import shared.exceptions.InvalidBoatDataException;
import shared.exceptions.InvalidRaceDataException;
import shared.exceptions.InvalidRegattaDataException;
import shared.exceptions.XMLReaderException;
import shared.model.Bearing;
import shared.model.Constants;
import shared.xml.Race.XMLRace;
import shared.xml.XMLUtilities;
@@ -23,14 +29,22 @@ import javax.xml.transform.TransformerException;
import java.io.*;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A Race Event, this holds all of the race's information as well as handling the connection to its clients.
*/
public class Event {
private static Event theEvent = new Event();
/**
* Contents of the various xml files.
*/
private String raceXML;
private String regattaXML;
private String boatXML;
@@ -39,41 +53,60 @@ public class Event {
private Polars boatPolars;
/**
* Data sources containing data from the xml files.
*/
RaceDataSource raceDataSource;
BoatDataSource boatDataSource;
RegattaDataSource regattaDataSource;
private ConnectionAcceptor connectionAcceptor;
private LatestMessages latestMessages;
private CompositeCommand compositeCommand;
/**
* This is used to allocate source IDs.
*/
private SourceIdAllocator sourceIdAllocator;
/**
* Constructs an event, using various XML files.
* @param singlePlayer Whether or not to create a single player event.
* @throws EventConstructionException Thrown if we cannot create an Event for any reason.
*/
private Event() {
public Event(boolean singlePlayer) throws EventConstructionException {
String raceXMLFile = "mock/mockXML/raceTest.xml";
String boatsXMLFile = "mock/mockXML/boatTest.xml";
String regattaXMLFile = "mock/mockXML/regattaTest.xml";
if (singlePlayer) {
raceXMLFile = "mock/mockXML/raceSinglePlayer.xml";
boatsXMLFile = "mock/mockXML/boatsSinglePlayer.xml";
}
//Read XML files.
try {
try {
this.raceXML = RaceXMLCreator.alterRaceToWind("mock/mockXML/raceSchemaTest.xml", 90);
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
this.boatXML = XMLReader.readXMLFileToString("mock/mockXML/boatsSinglePlayer.xml", StandardCharsets.UTF_8);
this.regattaXML = XMLReader.readXMLFileToString("mock/mockXML/regattaTest.xml", StandardCharsets.UTF_8);
this.xmlFileType = XMLFileType.Contents;
this.raceXML = RaceXMLCreator.alterRaceToWind("mock/mockXML/raceSchemaTest.xml", 90);
this.boatXML = XMLReader.readXMLFileToString(boatsXMLFile, StandardCharsets.UTF_8);
this.regattaXML = XMLReader.readXMLFileToString(regattaXMLFile, StandardCharsets.UTF_8);
this.boatPolars = PolarParser.parse("mock/polars/acc_polars.csv");
this.latestMessages = new LatestMessages();
this.connectionAcceptor = new ConnectionAcceptor(latestMessages);
}
catch (IOException e) {
e.printStackTrace();
} catch (XMLReaderException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (InvalidRaceDataException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
throw new EventConstructionException("Could not read XML files.", e);
}
this.xmlFileType = XMLFileType.Contents;
this.boatPolars = PolarParser.parse("mock/polars/acc_polars.csv");
this.latestMessages = new LatestMessages();
this.connectionAcceptor = new ConnectionAcceptor(latestMessages);
}
public static Event getEvent() {
@@ -104,21 +137,71 @@ public class Event {
sendXMLs();
//Parse the XML files into data sources.
RaceDataSource raceDataSource = new RaceXMLReader(this.raceXML, this.xmlFileType);
//more work here
XMLRace race = (XMLRace) XMLUtilities.xmlToClass(raceXML,
RaceXMLCreator.class.getClassLoader().getResource("mock/mockXML/schema/raceSchema.xsd"),
XMLRace.class);
BoatDataSource boatDataSource = new BoatXMLReader(this.boatXML, this.xmlFileType);
RegattaDataSource regattaDataSource = new RegattaXMLReader(this.regattaXML, this.xmlFileType);
try {
this.raceDataSource = new RaceXMLReader(this.raceXML, this.xmlFileType);
XMLRace race = (XMLRace) XMLUtilities.xmlToClass(raceXML,
RaceXMLCreator.class.getClassLoader().getResource("mock/mockXML/schema/raceSchema.xsd"),
XMLRace.class);
this.boatDataSource = new BoatXMLReader(this.boatXML, this.xmlFileType);
this.regattaDataSource = new RegattaXMLReader(this.regattaXML, this.xmlFileType);
} catch (XMLReaderException | InvalidRaceDataException | InvalidRegattaDataException | InvalidBoatDataException e) {
throw new EventConstructionException("Could not parse XML files.", e);
}
this.sourceIdAllocator = new SourceIdAllocator(raceDataSource.getParticipants());
this.compositeCommand = new CompositeCommand();
this.latestMessages = new LatestMessages();
//Create and start race.
RaceLogic newRace = new RaceLogic(new MockRace(boatDataSource, raceDataSource, regattaDataSource, this.latestMessages, this.boatPolars, Constants.RaceTimeScale), this.latestMessages);
WindGenerator windGenerator = new RandomWindGenerator(
Bearing.fromDegrees(225),
Bearing.fromDegrees(215),
Bearing.fromDegrees(235),
12d,
8d,
16d );
RaceLogic newRace = new RaceLogic(
new MockRace(
boatDataSource,
raceDataSource,
regattaDataSource,
this.boatPolars,
Constants.RaceTimeScale,
windGenerator ),
this.latestMessages,
this.compositeCommand);
connectionAcceptor.setRace(newRace);
new Thread(newRace, "Event.Start()->RaceLogic thread").start();
//Create connection acceptor.
try {
this.connectionAcceptor = new ConnectionAcceptor(latestMessages, compositeCommand, sourceIdAllocator, newRace);
} catch (IOException e) {
throw new EventConstructionException("Could not create ConnectionAcceptor.", e);
}
new Thread(connectionAcceptor, "Event.Start()->ConnectionAcceptor thread").start();
sendXMLs();
}
/**
* Sends the initial race data and then begins race simulation.
*/
public void start() {
}
/**
@@ -134,4 +217,19 @@ public class Event {
}
//The start time is current time + 4 minutes. prestart is 3 minutes, and we add another minute.
long millisecondsToAdd = Constants.RacePreStartTime + Duration.ofMinutes(1).toMillis();
long secondsToAdd = millisecondsToAdd / 1000;
//Scale the time using our time scalar.
secondsToAdd = secondsToAdd / Constants.RaceTimeScale;
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
ZonedDateTime creationTime = ZonedDateTime.now();
raceXML = raceXML.replace("CREATION_TIME", dateFormat.format(creationTime));
raceXML = raceXML.replace("START_TIME", dateFormat.format(creationTime.plusSeconds(secondsToAdd)));
return raceXML;
}
}
@@ -2,37 +2,25 @@ package mock.app;
import network.BinaryMessageEncoder;
import network.Exceptions.InvalidMessageException;
import network.MessageEncoders.RaceVisionByteEncoder;
import network.Messages.*;
import network.Messages.Enums.MessageType;
import shared.model.RunnableWithFramePeriod;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* TCP server to send race information to connected clients.
*/
public class MockOutput implements Runnable
{
/**
* Timestamp of the last sent heartbeat message.
*/
private long lastHeartbeatTime;
public class MockOutput implements RunnableWithFramePeriod {
/**
* Period for the heartbeat - that is, how often we send it.
* A queue to send messages to client.
*/
private double heartbeatPeriod = 5.0;
/**
* Output stream which wraps around mockSocket outstream.
*/
private DataOutputStream outToVisualiser;
private BlockingQueue<AC35Data> outgoingMessages;
/**
@@ -43,186 +31,20 @@ public class MockOutput implements Runnable
/**
* Ack numbers used in messages.
*/
private int ackNumber = 1;
/**
* Sequence number for heartbeat messages.
*/
private int heartbeatSequenceNum = 1;
/**
* Ctor.
* @param latestMessages Latests Messages that the Mock is to send out
* @param outToVisualiser DataStream to output to Visualisers
* @throws IOException if server socket cannot be opened.
* @param latestMessages Latest Messages that the Mock is to send out
* @param outgoingMessages A queue to place outgoing messages on.
*/
public MockOutput(LatestMessages latestMessages, DataOutputStream outToVisualiser) throws IOException {
this.outToVisualiser = outToVisualiser;
this.lastHeartbeatTime = System.currentTimeMillis();
public MockOutput(LatestMessages latestMessages, BlockingQueue<AC35Data> outgoingMessages) {
this.outgoingMessages = outgoingMessages;
this.latestMessages = latestMessages;
}
/**
* Increments the ackNumber value, and returns it.
* @return Incremented ackNumber.
*/
private int getNextAckNumber(){
this.ackNumber++;
return this.ackNumber;
}
/**
* Calculates the time since last heartbeat message, in seconds.
* @return Time since last heartbeat message, in seconds.
*/
private double timeSinceHeartbeat() {
long now = System.currentTimeMillis();
return (now - lastHeartbeatTime) / 1000.0;
}
/**
* Generates the next heartbeat message and returns it. Increments the heartbeat sequence number.
* @return The next heartbeat message.
*/
private HeartBeat createHeartbeatMessage() {
//Create the heartbeat message.
HeartBeat heartBeat = new HeartBeat(this.heartbeatSequenceNum);
heartbeatSequenceNum++;
return heartBeat;
}
/**
* Serializes a heartbeat message into a packet to be sent, and returns the byte array.
* @param heartBeat The heartbeat message to serialize.
* @return Byte array containing the next heartbeat message.
* @throws InvalidMessageException Thrown if the message cannot be encoded.
*/
private byte[] parseHeartbeat(HeartBeat heartBeat) throws InvalidMessageException {
//Serializes the heartbeat message.
byte[] heartbeatMessage = RaceVisionByteEncoder.encode(heartBeat);
//Places the serialized message in a packet.
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
MessageType.HEARTBEAT,
System.currentTimeMillis(),
getNextAckNumber(),
(short) heartbeatMessage.length,
heartbeatMessage );
return binaryMessageEncoder.getFullMessage();
}
/**
* Encodes/serialises a XMLMessage message, and returns it.
* @param xmlMessage The XMLMessage message to serialise.
* @return The XMLMessage message in a serialised form.
* @throws InvalidMessageException Thrown if the message cannot be encoded.
*/
private synchronized byte[] parseXMLMessage(XMLMessage xmlMessage) throws InvalidMessageException {
//Serialize the xml message.
byte[] encodedXML = RaceVisionByteEncoder.encode(xmlMessage);
//Place the message in a packet.
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
MessageType.XMLMESSAGE,
System.currentTimeMillis(),
xmlMessage.getAckNumber(), //We use the ack number from the xml message.
(short) encodedXML.length,
encodedXML );
return binaryMessageEncoder.getFullMessage();
}
/**
* Encodes/serialises a BoatLocation message, and returns it.
* @param boatLocation The BoatLocation message to serialise.
* @return The BoatLocation message in a serialised form.
* @throws InvalidMessageException If the message cannot be encoded.
*/
private synchronized byte[] parseBoatLocation(BoatLocation boatLocation) throws InvalidMessageException {
//Encodes the message.
byte[] encodedBoatLoc = RaceVisionByteEncoder.encode(boatLocation);
//Encodes the full message with header.
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
MessageType.BOATLOCATION,
System.currentTimeMillis(),
getNextAckNumber(),
(short) encodedBoatLoc.length,
encodedBoatLoc );
return binaryMessageEncoder.getFullMessage();
}
/**
* Encodes/serialises a RaceStatus message, and returns it.
* @param raceStatus The RaceStatus message to serialise.
* @return The RaceStatus message in a serialised form.
* @throws InvalidMessageException Thrown if the message cannot be encoded.
*/
private synchronized byte[] parseRaceStatus(RaceStatus raceStatus) throws InvalidMessageException {
//Encodes the messages.
byte[] encodedRaceStatus = RaceVisionByteEncoder.encode(raceStatus);
//Encodes the full message with header.
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
MessageType.RACESTATUS,
System.currentTimeMillis(),
getNextAckNumber(),
(short) encodedRaceStatus.length,
encodedRaceStatus );
return binaryMessageEncoder.getFullMessage();
}
/**
* Sends a heartbeat
* @throws IOException if the socket is no longer open at both ends the heartbeat returns an error.
*/
public void sendHeartBeat() throws IOException {
//Sends a heartbeat every so often.
if (timeSinceHeartbeat() >= heartbeatPeriod) {
HeartBeat heartBeat = createHeartbeatMessage();
try {
outToVisualiser.write(parseHeartbeat(heartBeat));
} catch (InvalidMessageException e) {
Logger.getGlobal().log(Level.WARNING, "Could not encode HeartBeat: " + heartBeat, e);
}
lastHeartbeatTime = System.currentTimeMillis();
}
}
/**
* Sending loop of the Server
@@ -251,107 +73,40 @@ public class MockOutput implements Runnable
long previousFrameTime = System.currentTimeMillis();
boolean sentXMLs = false;
try {
while (!Thread.interrupted()) {
try {
long currentFrameTime = System.currentTimeMillis();
//This is the time elapsed, in milliseconds, since the last server "frame".
long framePeriod = currentFrameTime - previousFrameTime;
//We only attempt to send packets every X milliseconds.
long minimumFramePeriod = 16;
if (framePeriod >= minimumFramePeriod) {
//Send XML messages.
if (!sentXMLs) {
//Serialise them.
try {
byte[] raceXMLBlob = parseXMLMessage(latestMessages.getRaceXMLMessage());
byte[] regattaXMLBlob = parseXMLMessage(latestMessages.getRegattaXMLMessage());
byte[] boatsXMLBlob = parseXMLMessage(latestMessages.getBoatXMLMessage());
//Send them.
outToVisualiser.write(raceXMLBlob);
outToVisualiser.write(regattaXMLBlob);
outToVisualiser.write(boatsXMLBlob);
sentXMLs = true;
} catch (InvalidMessageException e) {
Logger.getGlobal().log(Level.WARNING, "Could not encode XMLMessage: " + latestMessages.getRaceXMLMessage(), e);
continue; //Go to next iteration.
}
}
//Sends the RaceStatus message.
if (this.latestMessages.getRaceStatus() != null) {
try {
byte[] raceStatusBlob = this.parseRaceStatus(this.latestMessages.getRaceStatus());
this.outToVisualiser.write(raceStatusBlob);
} catch (InvalidMessageException e) {
Logger.getGlobal().log(Level.WARNING, "Could not encode RaceStatus: " + latestMessages.getRaceStatus(), e);
}
}
//Send all of the BoatLocation messages.
for (int sourceID : this.latestMessages.getBoatLocationMap().keySet()) {
//Get the message.
BoatLocation boatLocation = this.latestMessages.getBoatLocation(sourceID);
if (boatLocation != null) {
try {
//Encode.
byte[] boatLocationBlob = this.parseBoatLocation(boatLocation);
while (!Thread.interrupted()) {
//Write it.
this.outToVisualiser.write(boatLocationBlob);
try {
} catch (InvalidMessageException e) {
Logger.getGlobal().log(Level.WARNING, "Could not encode BoatLocation: " + boatLocation, e);
}
long currentFrameTime = System.currentTimeMillis();
waitForFramePeriod(previousFrameTime, currentFrameTime, 16);
previousFrameTime = currentFrameTime;
//Send XML messages.
if (!sentXMLs) {
}
}
outgoingMessages.put(latestMessages.getRaceXMLMessage());
outgoingMessages.put(latestMessages.getRegattaXMLMessage());
outgoingMessages.put(latestMessages.getBoatXMLMessage());
previousFrameTime = currentFrameTime;
} else {
//Wait until the frame period will be large enough.
long timeToWait = minimumFramePeriod - framePeriod;
try {
Thread.sleep(timeToWait);
} catch (InterruptedException e) {
//If we get interrupted, exit the function.
Logger.getGlobal().log(Level.WARNING, "MockOutput.run().sleep(framePeriod) was interrupted on thread: " + Thread.currentThread(), e);
//Re-set the interrupt flag.
Thread.currentThread().interrupt();
return;
}
}
} catch (SocketException e) {
break;
sentXMLs = true;
}
List<AC35Data> snapshot = latestMessages.getSnapshot();
for (AC35Data message : snapshot) {
outgoingMessages.put(message);
}
} catch (InterruptedException e) {
Logger.getGlobal().log(Level.WARNING, "MockOutput.run() interrupted while putting message in queue.", e);
Thread.currentThread().interrupt();
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
@@ -0,0 +1,95 @@
package mock.enums;
import java.util.HashMap;
import java.util.Map;
/**
* The states in which a connection to a client may have.
*/
public enum ConnectionStateEnum {
UNKNOWN(0),
/**
* We're waiting for the client to complete the joining handshake (see {@link network.Messages.RequestToJoin}.
*/
WAITING_FOR_HANDSHAKE(1),
/**
* The server has receved a {@link network.Messages.RequestToJoin} from the client.
*/
REQUEST_RECEIVED(2),
/**
* The client has completed the handshake, and is connected.
* That is, the client sent a {@link network.Messages.RequestToJoin}, which was successful, and the server responded with a {@link network.Messages.JoinAcceptance}.
*/
CONNECTED(3),
/**
* The client has timed out.
*/
TIMED_OUT(4),
/**
* The client's connection has been declined.
*/
DECLINED(5);
private byte value;
/**
* Ctor. Creates a ConnectionStateEnum from a given primitive integer value, cast to a byte.
* @param value Integer, which is cast to byte, to construct from.
*/
private ConnectionStateEnum(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 ConnectionStateEnum values.
*/
private static final Map<Byte, ConnectionStateEnum> byteToStatusMap = new HashMap<>();
/*
Static initialization block. Initializes the byteToStatusMap.
*/
static {
for (ConnectionStateEnum type : ConnectionStateEnum.values()) {
ConnectionStateEnum.byteToStatusMap.put(type.value, type);
}
}
/**
* Returns the enumeration value which corresponds to a given byte value.
* @param connectionState Byte value to convert to a ConnectionStateEnum value.
* @return The ConnectionStateEnum value which corresponds to the given byte value.
*/
public static ConnectionStateEnum fromByte(byte connectionState) {
//Gets the corresponding MessageType from the map.
ConnectionStateEnum type = ConnectionStateEnum.byteToStatusMap.get(connectionState);
if (type == null) {
//If the byte value wasn't found, return the UNKNOWN connectionState.
return ConnectionStateEnum.UNKNOWN;
} else {
//Otherwise, return the connectionState.
return type;
}
}
}
@@ -0,0 +1,24 @@
package mock.exceptions;
/**
* An exception thrown when we cannot create a command for some reasn (e.g., uknown action type).
*/
public class CommandConstructionException extends Exception {
/**
* Constructs the exception with a given message.
* @param message Message to store.
*/
public CommandConstructionException(String message) {
super(message);
}
/**
* Constructs the exception with a given message and cause.
* @param message Message to store.
* @param cause Cause to store.
*/
public CommandConstructionException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,24 @@
package mock.exceptions;
/**
* An exception thrown when we cannot create an {@link mock.app.Event}.
*/
public class EventConstructionException extends Exception {
/**
* Constructs the exception with a given message.
* @param message Message to store.
*/
public EventConstructionException(String message) {
super(message);
}
/**
* Constructs the exception with a given message and cause.
* @param message Message to store.
* @param cause Cause to store.
*/
public EventConstructionException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,24 @@
package mock.exceptions;
/**
* An exception thrown when we cannot allocate a source ID.
*/
public class SourceIDAllocationException extends Exception {
/**
* Constructs the exception with a given message.
* @param message Message to store.
*/
public SourceIDAllocationException(String message) {
super(message);
}
/**
* Constructs the exception with a given message and cause.
* @param message Message to store.
* @param cause Cause to store.
*/
public SourceIDAllocationException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,288 @@
package mock.model;
import mock.app.MockOutput;
import mock.enums.ConnectionStateEnum;
import shared.exceptions.HandshakeException;
import mock.exceptions.SourceIDAllocationException;
import mock.model.commandFactory.CompositeCommand;
import network.Messages.*;
import network.Messages.Enums.JoinAcceptanceEnum;
import network.Messages.Enums.MessageType;
import network.Messages.Enums.RequestToJoinEnum;
import network.StreamRelated.MessageDeserialiser;
import network.StreamRelated.MessageSerialiser;
import visualiser.gameController.ControllerServer;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class handles the client connection handshake, and creation of MockOutput and ControllerServer.
*/
public class ClientConnection implements Runnable {
/**
* The socket for the client's connection.
*/
private Socket socket;
/**
* Periodically sends HeartBeat messages to client.
*/
private HeartBeatService heartBeatService;
/**
* The thread the {@link HeartBeatService} runs on.
*/
private Thread heartBeatThread;
/**
* Used to allocate source ID to client, if they request to participate.
*/
private SourceIdAllocator sourceIdAllocator;
/**
* Latest snapshot of the race, to send to client. Currently only used for XML messages.
*/
private LatestMessages latestMessages;
/**
* Collection of commands from client for race to execute.
*/
private CompositeCommand compositeCommand;
/**
* The race the client is connected to.
*/
private RaceLogic raceLogic;
/**
* Used to send the race snapshot to client.
*/
private MockOutput mockOutput;
/**
* The thread the {@link MockOutput} runs on.
*/
private Thread mockOutputThread;
/**
* Used to receive client input, and turn it into commands.
*/
private ControllerServer controllerServer;
/**
* The thread the {@link ControllerServer} runs on.
*/
private Thread controllerServerThread;
/**
* Used to write messages to socket.
*/
private MessageSerialiser messageSerialiser;
/**
* Stores messages to write to socket.
*/
private BlockingQueue<AC35Data> outputQueue;
/**
* Used to read messages from socket.
*/
private MessageDeserialiser messageDeserialiser;
/**
* Stores messages read from socket.
*/
private BlockingQueue<AC35Data> inputQueue;
/**
* The state of the connection to the client.
*/
private ConnectionStateEnum connectionState = ConnectionStateEnum.UNKNOWN;
/**
* Creates a client connection, using a given socket.
* @param socket The socket which connects to the client.
* @param sourceIdAllocator Used to allocate a source ID for the client.
* @param latestMessages Latest race snapshot to send to client.
* @param compositeCommand Collection of commands for race to execute.
* @param raceLogic The race the client is connected to.
* @throws IOException Thrown if there is a problem with the client socket.
*/
public ClientConnection(Socket socket, SourceIdAllocator sourceIdAllocator, LatestMessages latestMessages, CompositeCommand compositeCommand, RaceLogic raceLogic) throws IOException {
this.socket = socket;
this.sourceIdAllocator = sourceIdAllocator;
this.latestMessages = latestMessages;
this.compositeCommand = compositeCommand;
this.raceLogic = raceLogic;
this.outputQueue = new LinkedBlockingQueue<>();
this.inputQueue = new LinkedBlockingQueue<>();
this.messageSerialiser = new MessageSerialiser(socket.getOutputStream(), outputQueue);
this.messageDeserialiser = new MessageDeserialiser(socket.getInputStream(), inputQueue);
new Thread(messageSerialiser, "ClientConnection()->MessageSerialiser thread " + messageSerialiser).start();
new Thread(messageDeserialiser, "ClientConnection()->MessageDeserialiser thread " + messageDeserialiser).start();
this.heartBeatService = new HeartBeatService(outputQueue);
this.heartBeatThread = new Thread(heartBeatService, "ClientConnection()->HeartBeatService thread " + heartBeatService);
this.heartBeatThread.start();
}
@Override
public void run() {
try {
handshake();
} catch (HandshakeException | SourceIDAllocationException e) {
Logger.getGlobal().log(Level.WARNING, "Client handshake failed.", e);
Thread.currentThread().interrupt();
return;
}
}
/**
* Initiates the handshake with the client.
* @throws HandshakeException Thrown if something goes wrong with the handshake.
* @throws SourceIDAllocationException Thrown if we cannot allocate a sourceID.
*/
private void handshake() throws SourceIDAllocationException, HandshakeException {
//This function is a bit messy, and could probably be refactored a bit.
connectionState = ConnectionStateEnum.WAITING_FOR_HANDSHAKE;
RequestToJoin requestToJoin = waitForRequestToJoin();
int allocatedSourceID = 0;
//If they want to participate, give them a source ID number.
if (requestToJoin.getRequestType() == RequestToJoinEnum.PARTICIPANT) {
allocatedSourceID = sourceIdAllocator.allocateSourceID();
this.controllerServer = new ControllerServer(compositeCommand, inputQueue, allocatedSourceID, raceLogic.getRace());
this.controllerServerThread = new Thread(controllerServer, "ClientConnection.run()->ControllerServer thread" + controllerServer);
this.controllerServerThread.start();
}
sendJoinAcceptanceMessage(allocatedSourceID);
this.mockOutput = new MockOutput(latestMessages, outputQueue);
this.mockOutputThread = new Thread(mockOutput, "ClientConnection.run()->MockOutput thread" + mockOutput);
this.mockOutputThread.start();
connectionState = ConnectionStateEnum.CONNECTED;
}
/**
* Waits until the client sends a {@link RequestToJoin} message, and returns it.
* @return The {@link RequestToJoin} message.
* @throws HandshakeException Thrown if we get interrupted while waiting.
*/
private RequestToJoin waitForRequestToJoin() throws HandshakeException {
try {
while (connectionState == ConnectionStateEnum.WAITING_FOR_HANDSHAKE) {
AC35Data message = inputQueue.take();
//We need to wait until they actually send a join request.
if (message.getType() == MessageType.REQUEST_TO_JOIN) {
return (RequestToJoin) message;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new HandshakeException("Handshake failed. Thread: " + Thread.currentThread() + " was interrupted while waiting on the incoming message queue.", e);
}
throw new HandshakeException("Handshake was cancelled. Connection state is now: " + connectionState);
}
/**
* Sends the client a {@link JoinAcceptance} message, containing their assigned sourceID.
* @param sourceID The sourceID to assign to client.
* @throws HandshakeException Thrown if the thread is interrupted while placing message on the outgoing message queue.
*/
private void sendJoinAcceptanceMessage(int sourceID) throws HandshakeException {
//Send them the source ID.
JoinAcceptance joinAcceptance = new JoinAcceptance(JoinAcceptanceEnum.JOIN_SUCCESSFUL_PARTICIPANT, sourceID);
try {
outputQueue.put(joinAcceptance);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new HandshakeException("Handshake failed. Thread: " + Thread.currentThread() + " interrupted while placing JoinAcceptance message on outgoing message queue.", e);
}
}
/**
* Determines whether or not this connection is still alive.
* This is based off whether the {@link MessageSerialiser} is still alive.
* @return True if it is alive, false otherwise.
*/
public boolean isAlive() {
return messageSerialiser.isRunning();
}
/**
* Terminates this connection.
*/
public void terminate() {
if (this.heartBeatThread != null) {
this.heartBeatThread.interrupt();
}
if (this.mockOutputThread != null) {
this.mockOutputThread.interrupt();
}
if (this.controllerServerThread != null) {
this.controllerServerThread.interrupt();
}
}
}
@@ -0,0 +1,54 @@
package mock.model;
import shared.model.Bearing;
import shared.model.Wind;
import java.util.Random;
/**
* This class generates Wind objects for use in a MockRace.
* Initialised with a baseline wind speed and direction, and keeps it constant.
*/
public class ConstantWindGenerator implements WindGenerator {
/**
* The bearing the wind direction starts at.
*/
private Bearing windBaselineBearing;
/**
* The speed the wind starts at, in knots.
*/
private double windBaselineSpeed;
/**
* Creates a constant wind generator, with a baseline wind speed and direction.
* @param windBaselineBearing Baseline wind direction.
* @param windBaselineSpeed Baseline wind speed, in knots.
*/
public ConstantWindGenerator(Bearing windBaselineBearing, double windBaselineSpeed) {
this.windBaselineBearing = windBaselineBearing;
this.windBaselineSpeed = windBaselineSpeed;
}
@Override
public Wind generateBaselineWind() {
return new Wind(windBaselineBearing, windBaselineSpeed);
}
@Override
public Wind generateNextWind(Wind currentWind) {
return generateBaselineWind();
}
}
@@ -0,0 +1,110 @@
package mock.model;
import network.Messages.AC35Data;
import network.Messages.HeartBeat;
import shared.model.RunnableWithFramePeriod;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class is responsible for sending {@link HeartBeat} messages to queue.
*/
public class HeartBeatService implements RunnableWithFramePeriod {
/**
* Timestamp of the last sent heartbeat message.
*/
private long lastHeartbeatTime;
/**
* Period for the heartbeat - that is, how often we send it. Milliseconds.
*/
private long heartbeatPeriod = 2500;
/**
* The messages we're writing to the stream.
*/
private BlockingQueue<AC35Data> messagesToSend;
/**
* Sequence number for heartbeat messages.
*/
private int heartbeatSequenceNum = 1;
/**
* Constructs a new HeartBeatService to send heartBeat messages to a given outputStream.
* @param messagesToSend The queue to send heartBeat messages to.
*/
public HeartBeatService(BlockingQueue<AC35Data> messagesToSend) {
this.messagesToSend = messagesToSend;
this.lastHeartbeatTime = System.currentTimeMillis();
}
/**
* Increments the {@link #heartbeatSequenceNum} value, and returns it.
* @return Incremented heat beat number.
*/
private int getNextHeartBeatNumber(){
this.heartbeatSequenceNum++;
return this.heartbeatSequenceNum;
}
/**
* Generates the next heartbeat message and returns it. Increments the heartbeat sequence number.
* @return The next heartbeat message.
*/
private HeartBeat createHeartbeatMessage() {
HeartBeat heartBeat = new HeartBeat(getNextHeartBeatNumber());
return heartBeat;
}
/**
* Puts a HeartBeat message on the message queue.
* @throws InterruptedException Thrown if the thread is interrupted.
*/
private void sendHeartBeat() throws InterruptedException {
HeartBeat heartBeat = createHeartbeatMessage();
messagesToSend.put(heartBeat);
}
@Override
public void run() {
while (!Thread.interrupted()) {
long currentFrameTime = System.currentTimeMillis();
waitForFramePeriod(lastHeartbeatTime, currentFrameTime, heartbeatPeriod);
lastHeartbeatTime = currentFrameTime;
try {
sendHeartBeat();
} catch (InterruptedException e) {
Logger.getGlobal().log(Level.WARNING, "HeartBeatService: " + this + " sendHeartBeat() was interrupted on thread: " + Thread.currentThread(), e);
Thread.currentThread().interrupt();
return;
}
}
}
}
@@ -22,6 +22,14 @@ public class MockBoat extends Boat {
*/
private long timeSinceTackChange = 0;
/**
* This stores the boats current status of rounding a mark
* 0: not started rounding
* 1: passed only first check
* 2: passed first and second check
*/
private Integer roundingStatus = 0;
/**
* Stores whether the boat is on autoVMG or not
*/
@@ -67,10 +75,19 @@ public class MockBoat extends Boat {
//Get the start and end points.
GPSCoordinate currentPosition = this.getCurrentPosition();
GPSCoordinate nextMarkerPosition = this.getCurrentLeg().getEndCompoundMark().getAverageGPSCoordinate();
GPSCoordinate nextMarkerPosition;
// if boat is at the finish
if (this.getCurrentLeg().getEndCompoundMark() == null) {
nextMarkerPosition = currentPosition;
}
else {
nextMarkerPosition = this.getCurrentLeg().getEndCompoundMark().getAverageGPSCoordinate();
}
//Calculate bearing.
Bearing bearing = GPSCoordinate.calculateBearing(currentPosition, nextMarkerPosition);
return bearing;
}
@@ -196,11 +213,96 @@ public class MockBoat extends Boat {
return distanceTravelledMeters;
}
public boolean isAutoVMG() {
return autoVMG;
/**
* Check if a mark is on the port side of the boat
* @param mark mark to be passed
* @return true if mark is on port side
*/
public boolean isPortSide(Mark mark){
Bearing towardsMark = GPSCoordinate.calculateBearing(this.getCurrentPosition(), mark.getPosition());
if (towardsMark.degrees() > 315 || towardsMark.degrees() <= 45){
//south quadrant
return this.getBearing().degrees() <= 180;
} else if(towardsMark.degrees() > 45 && towardsMark.degrees() <= 135){
//west quadrant
return (this.getBearing().degrees() <= 270 && this.getBearing().degrees() >= 90);
}else if(towardsMark.degrees() > 135 && towardsMark.degrees() <= 225){
//north quadrant
return this.getBearing().degrees() >= 180;
}else if(towardsMark.degrees() > 225 && towardsMark.degrees() <= 315){
//east quadrant
return (this.getBearing().degrees() <= 90 || this.getBearing().degrees() >= 270);
}else{
//should not reach here
return false;
}
}
/**
* Check if a mark is on the starboard side of the boat
* @param mark mark to be passed
* @return true if mark is on starboard side
*/
public boolean isStarboardSide(Mark mark){
//if this boat is lower than the mark check which way it is facing
Bearing towardsMark = GPSCoordinate.calculateBearing(this.getCurrentPosition(), mark.getPosition());
if (towardsMark.degrees() > 315 || towardsMark.degrees() <= 45){
//south quadrant
return !(this.getBearing().degrees() <= 180);
} else if(towardsMark.degrees() > 45 && towardsMark.degrees() <= 135){
//west quadrant
return !(this.getBearing().degrees() <= 270 && this.getBearing().degrees() >= 90);
}else if(towardsMark.degrees() > 135 && towardsMark.degrees() <= 225){
//north quadrant
return !(this.getBearing().degrees() >= 180);
}else if(towardsMark.degrees() > 225 && towardsMark.degrees() <= 315){
//east quadrant
return !(this.getBearing().degrees() <= 90 || this.getBearing().degrees() >= 270);
}else{
//should not reach here
return false;
}
}
/**
* Used to check if this boat is between a gate
* @param gate the gate to be checked
* @return true if the boat is between two marks that make up a gate
*/
public boolean isBetweenGate(CompoundMark gate){
return (this.isPortSide(gate.getMark1()) && this.isStarboardSide(gate.getMark2())) ||
(this.isStarboardSide(gate.getMark1()) && this.isPortSide(gate.getMark2()));
}
/**
* Used to check if this boat is between a two marks
* @param mark1 the first mark
* @param mark2 the second mark
* @return true if the boat is between two marks
*/
public boolean isBetweenGate(Mark mark1, Mark mark2){
return (this.isPortSide(mark1) && this.isStarboardSide(mark2)) ||
(this.isStarboardSide(mark1) && this.isPortSide(mark2));
}
public Integer getRoundingStatus() {
return Integer.valueOf(roundingStatus);
}
public void increaseRoundingStatus() {
this.roundingStatus++;
}
public void resetRoundingStatus() {
this.roundingStatus = 0;
}
public void setAutoVMG(boolean autoVMG) {
this.autoVMG = autoVMG;
}
public boolean getAutoVMG(){
return autoVMG;
}
}
@@ -5,19 +5,19 @@ import mock.xml.*;
import network.Messages.BoatLocation;
import network.Messages.BoatStatus;
import network.Messages.Enums.BoatStatusEnum;
import network.Messages.Enums.RaceStatusEnum;
import network.Messages.LatestMessages;
import org.opengis.geometry.primitive.*;
import shared.dataInput.BoatDataSource;
import shared.dataInput.RaceDataSource;
import network.Messages.Enums.RaceStatusEnum;
import shared.dataInput.RegattaDataSource;
import shared.exceptions.BoatNotFoundException;
import shared.enums.RoundingType;
import shared.model.*;
import shared.model.Bearing;
import shared.model.Race;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.*;
import static java.lang.Math.cos;
@@ -59,13 +59,13 @@ public class MockRace extends Race {
* @param boatDataSource Data source for boat related data (yachts and marker boats).
* @param raceDataSource Data source for race related data (participating boats, legs, etc...).
* @param regattaDataSource Data source for race related data (course name, location, timezone, etc...).
* @param latestMessages The LatestMessages to send events to.
* @param polars The polars table to be used for boat simulation.
* @param timeScale The timeScale for the race. See {@link Constants#RaceTimeScale}.
* @param windGenerator The wind generator used for the race.
*/
public MockRace(BoatDataSource boatDataSource, RaceDataSource raceDataSource, RegattaDataSource regattaDataSource, LatestMessages latestMessages, Polars polars, int timeScale) {
public MockRace(BoatDataSource boatDataSource, RaceDataSource raceDataSource, RegattaDataSource regattaDataSource, Polars polars, int timeScale, WindGenerator windGenerator) {
super(boatDataSource, raceDataSource, regattaDataSource, latestMessages);
super(boatDataSource, raceDataSource, regattaDataSource);
this.scaleFactor = timeScale;
@@ -73,14 +73,8 @@ public class MockRace extends Race {
this.shrinkBoundary = GPSCoordinate.getShrinkBoundary(this.boundary);
//Set up wind generator. It may be tidier to create this outside the race (with the values sourced from a data file maybe?) and pass it in.
this.windGenerator = new WindGenerator(
Bearing.fromDegrees(225),
Bearing.fromDegrees(215),
Bearing.fromDegrees(235),
12d,
8d,
16d );
this.windGenerator = windGenerator;
//Wind.
this.setWind(windGenerator.generateBaselineWind());
@@ -327,6 +321,8 @@ public class MockRace extends Race {
if (!finish && totalElapsedMilliseconds >= updatePeriodMilliseconds) {
checkPosition(boat, totalElapsedMilliseconds);
if (boat.getCurrentSpeed() == 0) {
newOptimalVMG(boat);
boat.setBearing(boat.calculateBearingToNextMarker());
@@ -345,7 +341,7 @@ public class MockRace extends Race {
boat.moveForwards(distanceTravelledMeters);
boat.setTimeSinceTackChange(boat.getTimeSinceTackChange() + updatePeriodMilliseconds);
if (boat.isAutoVMG()) {
if (boat.getAutoVMG()) {
newOptimalVMG(boat);
}
@@ -355,7 +351,7 @@ public class MockRace extends Race {
}
private void newOptimalVMG(MockBoat boat) {
long tackPeriod = 15000;
long tackPeriod = 1000;
if (boat.getTimeSinceTackChange() > tackPeriod) {
//Calculate the new VMG.
@@ -379,13 +375,259 @@ public class MockRace extends Race {
this.getWindDirection(),
this.getWindSpeed(),
boat.getBearing(),
boat.getBearing(),
boat.getBearing());
Bearing.fromDegrees(boat.getBearing().degrees() - 1),
Bearing.fromDegrees(boat.getBearing().degrees() + 1));
if (vmg.getSpeed() > 0) {
boat.setCurrentSpeed(vmg.getSpeed());
}
}
/**
* Calculates the upper and lower bounds that the boat may have in order to not go outside of the course.
* @param boat The boat to check.
* @return An array of bearings. The first is the lower bound, the second is the upper bound.
*/
private Bearing[] calculateBearingBounds(MockBoat boat) {
Bearing[] bearings = new Bearing[2];
Bearing lowerBearing = Bearing.fromDegrees(0.001);
Bearing upperBearing = Bearing.fromDegrees(359.999);
double lastAngle = -1;
boolean lastAngleWasGood = false;
//Check all bearings between [0his.latestMessages = new LatestMessages();
thi, 360).
for (double angle = 0; angle < 360; angle += 1) {
//Create bearing from angle.
Bearing bearing = Bearing.fromDegrees(angle);
//Check that if it is acceptable.
boolean bearingIsGood = this.checkBearingInsideCourse(bearing, boat.getCurrentPosition());
if (lastAngle != -1) {
if (lastAngleWasGood && !bearingIsGood) {
//We have flipped over from good bearings to bad bearings. So the last good bearing is the upper bearing.
upperBearing = Bearing.fromDegrees(lastAngle);
}
if (!lastAngleWasGood && bearingIsGood) {
//We have flipped over from bad bearings to good bearings. So the current bearing is the lower bearing.
lowerBearing = Bearing.fromDegrees(angle);
}
}
lastAngle = angle;
lastAngleWasGood = bearingIsGood;
}
//TODO BUG if it can't find either upper or lower, it returns (0, 359.999). Should return (boatbearing, boatbearing+0.0001)
bearings[0] = lowerBearing;
bearings[1] = upperBearing;
return bearings;
}
/**
* Checks if a given bearing, starting at a given position, would put a boat out of the course boundaries.
* @param bearing The bearing to check.
* @param position The position to start from.
* @return True if the bearing would keep the boat in the course, false if it would take it out of the course.
*/
private boolean checkBearingInsideCourse(Bearing bearing, GPSCoordinate position) {
//Get azimuth from bearing.
Azimuth azimuth = Azimuth.fromBearing(bearing);
//Tests to see if a point in front of the boat is out of bounds.
double epsilonMeters = 50d;
GPSCoordinate testCoord = GPSCoordinate.calculateNewPosition(position, epsilonMeters, azimuth);
//If it isn't inside the boundary, calculate new bearing.
if (GPSCoordinate.isInsideBoundary(testCoord, this.shrinkBoundary)) {
return true;
} else {
return false;
}
}
/**
* Checks to be run on boats rounding marks on the port side
* @param boat the boat that is rounding a mark
* @param roundingChecks the checks to run
* @param legBearing the direction of the leg
*/
private void boatRoundingCheckPort(MockBoat boat, List<GPSCoordinate> roundingChecks, Bearing legBearing) {
//boats must pass all checks in order to round a mark
//boolean for if boat has to/needs to pass through a gate
boolean gateCheck = boat.getCurrentLeg().getEndCompoundMark().getMark2() == null || boat.isBetweenGate(boat.getCurrentLeg().getEndCompoundMark());
Mark roundingMark = boat.getCurrentLeg().getEndCompoundMark().getMarkForRounding(legBearing);
switch (boat.getRoundingStatus()) {
case 0://hasn't started rounding
if (boat.isPortSide(roundingMark) &&
GPSCoordinate.passesLine(roundingMark.getPosition(),
roundingChecks.get(0), boat.getCurrentPosition(), legBearing) &&
gateCheck && boat.isBetweenGate(roundingMark, Mark.tempMark(roundingChecks.get(0)))) {
boat.increaseRoundingStatus();
if (boat.getCurrentLeg().getLegNumber() + 2 >= legs.size()){
//boat has finished race
boat.increaseRoundingStatus();
}
}
break;
case 1://has been parallel to the mark;
if (boat.isPortSide(roundingMark) &&
GPSCoordinate.passesLine(roundingMark.getPosition(),
roundingChecks.get(1), boat.getCurrentPosition(),
Bearing.fromDegrees(legBearing.degrees() - 90)) &&//negative 90 from bearing because of port rounding
boat.isBetweenGate(roundingMark, Mark.tempMark(roundingChecks.get(1)))) {
boat.increaseRoundingStatus();
}
break;
case 2://has traveled 180 degrees around the mark
//Move boat on to next leg.
boat.resetRoundingStatus();
Leg nextLeg = this.legs.get(boat.getCurrentLeg().getLegNumber() + 1);
boat.setCurrentLeg(nextLeg);
break;
}
}
/**
* Checks to be run on boats rounding marks on the starboard side
* @param boat the boat that is rounding a mark
* @param roundingChecks the checks to run
* @param legBearing the direction of the leg
*/
private void boatRoundingCheckStarboard(MockBoat boat, List<GPSCoordinate> roundingChecks, Bearing legBearing){
//boats must pass all checks in order to round a mark
//boolean for if boat has to/needs to pass through a gate
boolean gateCheck = boat.getCurrentLeg().getEndCompoundMark().getMark2() == null || boat.isBetweenGate(boat.getCurrentLeg().getEndCompoundMark());
Mark roundingMark = boat.getCurrentLeg().getEndCompoundMark().getMarkForRounding(legBearing);
switch (boat.getRoundingStatus()) {
case 0://hasn't started rounding
if (boat.isStarboardSide(roundingMark) &&
GPSCoordinate.passesLine(roundingMark.getPosition(),
roundingChecks.get(0), boat.getCurrentPosition(), legBearing) &&
gateCheck &&
boat.isBetweenGate(roundingMark, Mark.tempMark(roundingChecks.get(0)))) {
boat.increaseRoundingStatus();
if (boat.getCurrentLeg().getLegNumber() + 2 >= legs.size()){
//boat has finished race
boat.increaseRoundingStatus();
}
}
break;
case 1://has been parallel to the mark
if (boat.isStarboardSide(roundingMark) &&
GPSCoordinate.passesLine(roundingMark.getPosition(),
roundingChecks.get(1), boat.getCurrentPosition(), Bearing.fromDegrees(legBearing.degrees() + 90)) && //positive 90 from bearing because of starboard rounding
boat.isBetweenGate(roundingMark, Mark.tempMark(roundingChecks.get(1)))) {
boat.increaseRoundingStatus();
}
break;
case 2://has traveled 180 degrees around the mark
//Move boat on to next leg.
boat.resetRoundingStatus();
Leg nextLeg = this.legs.get(boat.getCurrentLeg().getLegNumber() + 1);
boat.setCurrentLeg(nextLeg);
break;
}
}
/**
* 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(MockBoat boat, long 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 = boat.getCurrentLeg().getEndCompoundMark().getRoundingDistance(); //250 meters.
if (boat.calculateDistanceToNextMarker() < epsilonNauticalMiles) {
//Boat is within an acceptable distance from the mark.
GPSCoordinate startDirectionLinePoint = boat.getCurrentLeg().getStartCompoundMark().getMark1Position();
GPSCoordinate endDirectionLinePoint = boat.getCurrentLeg().getEndCompoundMark().getMark1Position();
Bearing bearingOfDirectionLine = GPSCoordinate.calculateBearing(startDirectionLinePoint, endDirectionLinePoint);
//use the direction line to create three invisible points that act as crossover lines a boat must cross
//to round a mark
double bearingToAdd;
if (boat.getCurrentLeg().getEndCompoundMark().getRoundingType() == RoundingType.Port ||
boat.getCurrentLeg().getEndCompoundMark().getRoundingType() == RoundingType.SP){
bearingToAdd = 90;
}else{
bearingToAdd = -90;
}
GPSCoordinate roundCheck1 = GPSCoordinate.calculateNewPosition(endDirectionLinePoint,
epsilonNauticalMiles, Azimuth.fromDegrees(bearingOfDirectionLine.degrees() + bearingToAdd));
GPSCoordinate roundCheck2;
try{
Leg nextLeg = legs.get(legs.indexOf(boat.getCurrentLeg()) + 1);
GPSCoordinate startNextDirectionLinePoint = nextLeg.getStartCompoundMark().getMark1Position();
GPSCoordinate endNextDirectionLinePoint = nextLeg.getEndCompoundMark().getMark1Position();
Bearing bearingOfNextDirectionLine = GPSCoordinate.calculateBearing(startNextDirectionLinePoint, endNextDirectionLinePoint);
roundCheck2 = GPSCoordinate.calculateNewPosition(endDirectionLinePoint,
epsilonNauticalMiles, Azimuth.fromDegrees(bearingOfNextDirectionLine.degrees() + bearingToAdd));
}catch(NullPointerException e){
//this is caused by the last leg not being having a leg after it
roundCheck2 = roundCheck1;
}
List<GPSCoordinate> roundingChecks = new ArrayList<GPSCoordinate>(Arrays.asList(roundCheck1, roundCheck2));
switch (boat.getCurrentLeg().getEndCompoundMark().getRoundingType()) {
case SP://Not yet implemented so these gates will be rounded port side
case Port:
boatRoundingCheckPort(boat, roundingChecks, bearingOfDirectionLine);
break;
case PS://not yet implemented so these gates will be rounded starboard side
case Starboard:
boatRoundingCheckStarboard(boat, roundingChecks, bearingOfDirectionLine);
break;
}
//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);
}
}
}
/**
* Returns the number of boats that are still active in the race.
* They become inactive by either finishing or withdrawing.
@@ -394,7 +636,8 @@ public class MockRace extends Race {
protected int getNumberOfActiveBoats() {
int numberOfActiveBoats = 0;
his.latestMessages = new LatestMessages();
thi
for (MockBoat boat : this.boats) {
//If the boat is currently racing, count it.
@@ -416,6 +659,25 @@ public class MockRace extends Race {
return boats;
}
/**
* Returns a boat by sourceID.
* @param sourceID The source ID the boat.
* @return The boat.
* @throws BoatNotFoundException Thrown if there is not boat with the specified sourceID.
*/
public MockBoat getBoat(int sourceID) throws BoatNotFoundException {
for (MockBoat boat : boats) {
if (boat.getSourceID() == sourceID) {
return boat;
}
}
throw new BoatNotFoundException("Boat with sourceID: " + sourceID + " was not found.");
}
/**
* Changes the wind direction randomly, while keeping it within [windLowerBound, windUpperBound].
*/
@@ -448,7 +710,6 @@ public class MockRace extends Race {
}
public List<CompoundMark> getCompoundMarks() {
return compoundMarks;
}
}
@@ -1,20 +1,16 @@
package mock.model;
import javafx.animation.AnimationTimer;
import mock.model.commandFactory.Command;
import mock.model.commandFactory.CommandFactory;
import mock.model.commandFactory.CompositeCommand;
import mock.model.commandFactory.CommandFactory;
import network.Messages.Enums.BoatActionEnum;
import network.Messages.Enums.BoatStatusEnum;
import network.Messages.Enums.RaceStatusEnum;
import network.Messages.LatestMessages;
import visualiser.gameController.ControllerServer;
import shared.model.RunnableWithFramePeriod;
import java.util.Observable;
import java.util.Observer;
import java.util.Stack;
public class RaceLogic implements Observer, Runnable {
public class RaceLogic implements RunnableWithFramePeriod {
/**
* State of current race modified by this object
*/
@@ -30,11 +26,12 @@ public class RaceLogic implements Observer, Runnable {
* Initialises race loop with state and server message queue
* @param race state of race to modify
* @param messages to send to server
* @param compositeCommand Commands from clients to execute.
*/
public RaceLogic(MockRace race, LatestMessages messages) {
public RaceLogic(MockRace race, LatestMessages messages, CompositeCommand compositeCommand) {
this.race = race;
this.server = new RaceServer(race, messages);
this.commands = new CompositeCommand();
this.commands = compositeCommand;
}
/**
@@ -43,20 +40,23 @@ public class RaceLogic implements Observer, Runnable {
@Override
public void run() {
race.initialiseBoats();
this.countdownTimer.start();
countdown();
raceLoop();
}
/**
* Countdown timer until race starts.
*/
protected AnimationTimer countdownTimer = new AnimationTimer() {
private void countdown() {
long previousFrameTime = System.currentTimeMillis();
long currentTime = System.currentTimeMillis();
while (race.getRaceStatusEnum() != RaceStatusEnum.STARTED) {
@Override
public void handle(long arg0) {
long currentTime = System.currentTimeMillis();
//Update race time.
race.updateRaceTime(currentTime);
@@ -67,58 +67,39 @@ public class RaceLogic implements Observer, Runnable {
//Provide boat's with an estimated time at next mark until the race starts.
race.setBoatsTimeNextMark(race.getRaceClock().getCurrentTime());
//Parse the boat locations.
server.parseBoatLocations();
//Parse the race snapshot.
server.parseSnapshot();
//Parse the marks.
server.parseMarks();
// Change wind direction
race.changeWindDirection();
//Parse the race status.
server.parseRaceStatus();
if (race.getRaceStatusEnum() == RaceStatusEnum.STARTED) {
race.setBoatsStatusToRacing();
raceTimer.start();
this.stop();
}
//Update the animations timer's time.
currentTime = System.currentTimeMillis();
waitForFramePeriod(previousFrameTime, currentTime, 50);
previousFrameTime = currentTime;
}
};
}
/**
* Timer that runs for the duration of the race, until all boats finish.
*/
private AnimationTimer raceTimer = new AnimationTimer() {
private void raceLoop() {
/**
* Start time of loop, in milliseconds.
*/
long timeRaceStarted = System.currentTimeMillis();
long previousFrameTime = System.currentTimeMillis();
/**
* Current time during a loop iteration.
*/
long currentTime = System.currentTimeMillis();
/**
* The time of the previous frame, in milliseconds.
*/
long lastFrameTime = timeRaceStarted;
long framePeriod = currentTime - lastFrameTime;
@Override
public void handle(long arg0) {
while (race.getRaceStatusEnum() != RaceStatusEnum.FINISHED) {
//Get the current time.
currentTime = System.currentTimeMillis();
long currentTime = System.currentTimeMillis();
//Execute commands from clients.
commands.execute();
//Update race time.
race.updateRaceTime(currentTime);
@@ -127,14 +108,13 @@ public class RaceLogic implements Observer, Runnable {
if (race.getNumberOfActiveBoats() != 0) {
//Get the time period of this frame.
framePeriod = currentTime - lastFrameTime;
long framePeriod = currentTime - previousFrameTime;
//For each boat, we update its position, and generate a BoatLocationMessage.
for (MockBoat boat : race.getBoats()) {
//If it is still racing, update its position.
if (boat.getStatus() == BoatStatusEnum.RACING) {
commands.execute();
race.updatePosition(boat, framePeriod, race.getRaceClock().getDurationMilli());
}
@@ -145,28 +125,23 @@ public class RaceLogic implements Observer, Runnable {
//Otherwise, the race is over!
raceFinished.start();
race.setRaceStatusEnum(RaceStatusEnum.FINISHED);
this.stop();
}
if (race.getNumberOfActiveBoats() != 0) {
// Change wind direction
race.changeWindDirection();
//Parse the boat locations.
server.parseBoatLocations();
//Parse the marks.
server.parseMarks();
//Parse the race status.
server.parseRaceStatus();
//Parse the race snapshot.
server.parseSnapshot();
//Update the last frame time.
this.lastFrameTime = currentTime;
previousFrameTime = currentTime;
}
waitForFramePeriod(previousFrameTime, currentTime, 50);
previousFrameTime = currentTime;
}
};
}
/**
* Broadcast that the race has finished.
@@ -176,7 +151,7 @@ public class RaceLogic implements Observer, Runnable {
@Override
public void handle(long now) {
server.parseRaceStatus();
server.parseSnapshot();
if (iters > 500) {
stop();
@@ -185,12 +160,12 @@ public class RaceLogic implements Observer, Runnable {
}
};
@Override
public void update(Observable o, Object arg) {
ControllerServer server = (ControllerServer)o;
BoatActionEnum action = server.getAction();
MockBoat boat = race.getBoats().get(0);
commands.addCommand(CommandFactory.createCommand(race, boat, action));
/**
* Returns the race state that this RaceLogic is simulating.
* @return Race state this RaceLogic is simulating.
*/
public MockRace getRace() {
return race;
}
}
@@ -1,10 +1,7 @@
package mock.model;
import network.Messages.BoatLocation;
import network.Messages.BoatStatus;
import network.Messages.*;
import network.Messages.Enums.BoatLocationDeviceEnum;
import network.Messages.LatestMessages;
import network.Messages.RaceStatus;
import network.Utils.AC35UnitConverter;
import shared.model.Bearing;
import shared.model.CompoundMark;
@@ -21,10 +18,6 @@ public class RaceServer {
private MockRace race;
private LatestMessages latestMessages;
/**
* The sequence number of the latest RaceStatus message sent or received.
*/
private int raceStatusSequenceNumber = 1;
/**
* The sequence number of the latest BoatLocation message sent or received.
@@ -39,10 +32,31 @@ public class RaceServer {
/**
* Parses an individual marker boat, and sends it to mockOutput.
* @param mark The marker boat to parse.
* Parses the race to create a snapshot, and places it in latestMessages.
*/
private void parseIndividualMark(Mark mark) {
public void parseSnapshot() {
List<AC35Data> snapshotMessages = new ArrayList<>();
//Parse the boat locations.
snapshotMessages.addAll(parseBoatLocations());
//Parse the marks.
snapshotMessages.addAll(parseMarks());
//Parse the race status.
snapshotMessages.add(parseRaceStatus());
latestMessages.setSnapshot(snapshotMessages);
}
/**
* Parses an individual marker boat, and returns it.
* @param mark The marker boat to parse.
* @return The BoatLocation message.
*/
private BoatLocation parseIndividualMark(Mark mark) {
//Create message.
BoatLocation boatLocation = new BoatLocation(
mark.getSourceID(),
@@ -57,13 +71,17 @@ public class RaceServer {
//Iterates the sequence number.
this.boatLocationSequenceNumber++;
this.latestMessages.setBoatLocation(boatLocation);
return boatLocation;
}
/**
* Parse the compound marker boats through mock output.
* Parse the compound marker boats, and returns a list of BoatLocation messages.
* @return BoatLocation messages for each mark.
*/
public void parseMarks() {
private List<BoatLocation> parseMarks() {
List<BoatLocation> markLocations = new ArrayList<>(race.getCompoundMarks().size());
for (CompoundMark compoundMark : race.getCompoundMarks()) {
//Get the individual marks from the compound mark.
@@ -72,31 +90,40 @@ public class RaceServer {
//If they aren't null, parse them (some compound marks only have one mark).
if (mark1 != null) {
this.parseIndividualMark(mark1);
markLocations.add(this.parseIndividualMark(mark1));
}
if (mark2 != null) {
this.parseIndividualMark(mark2);
markLocations.add(this.parseIndividualMark(mark2));
}
}
return markLocations;
}
/**
* Parse the boats in the race, and send it to mockOutput.
* Parse the boats in the race, and returns all of their BoatLocation messages.
* @return List of BoatLocation messages, for each boat.
*/
public void parseBoatLocations() {
private List<BoatLocation> parseBoatLocations() {
List<BoatLocation> boatLocations = new ArrayList<>(race.getBoats().size());
//Parse each boat.
for (MockBoat boat : race.getBoats()) {
this.parseIndividualBoatLocation(boat);
boatLocations.add(this.parseIndividualBoatLocation(boat));
}
return boatLocations;
}
/**
* Parses an individual boat, and sends it to mockOutput.
* Parses an individual boat, and returns it.
* @param boat The boat to parse.
* @return The BoatLocation message.
*/
private void parseIndividualBoatLocation(MockBoat boat) {
private BoatLocation parseIndividualBoatLocation(MockBoat boat) {
BoatLocation boatLocation = new BoatLocation(
boat.getSourceID(),
@@ -111,16 +138,17 @@ public class RaceServer {
//Iterates the sequence number.
this.boatLocationSequenceNumber++;
this.latestMessages.setBoatLocation(boatLocation);
return boatLocation;
}
/**
* Parses the race status, and sends it to mockOutput.
* Parses the race status, and returns it.
* @return The race status message.
*/
public void parseRaceStatus() {
private RaceStatus parseRaceStatus() {
//A race status message contains a list of boat statuses.
List<BoatStatus> boatStatuses = new ArrayList<>();
@@ -151,6 +179,6 @@ public class RaceServer {
race.getRaceType(),
boatStatuses);
this.latestMessages.setRaceStatus(raceStatus);
return raceStatus;
}
}
@@ -0,0 +1,242 @@
package mock.model;
import shared.model.Bearing;
import shared.model.Wind;
import java.util.Random;
/**
* This class generates Wind objects for use in a MockRace.
* Bounds on bearing and speed can be specified.
* Wind can be completely random, or random incremental change.
*/
public class RandomWindGenerator implements WindGenerator {
/**
* The bearing the wind direction starts at.
*/
private Bearing windBaselineBearing;
/**
* The lower bearing angle that the wind may have.
*/
private Bearing windBearingLowerBound;
/**
* The upper bearing angle that the wind may have.
*/
private Bearing windBearingUpperBound;
/**
* The speed the wind starts at, in knots.
*/
private double windBaselineSpeed;
/**
* The lower speed that the wind may have, in knots.
*/
private double windSpeedLowerBound;
/**
* The upper speed that the wind may have, in knots.
*/
private double windSpeedUpperBound;
/**
* Creates a wind generator, with a baseline, lower bound, and upper bound, for the wind speed and direction.
* @param windBaselineBearing Baseline wind direction.
* @param windBearingLowerBound Lower bound for wind direction.
* @param windBearingUpperBound Upper bound for wind direction.
* @param windBaselineSpeed Baseline wind speed, in knots.
* @param windSpeedLowerBound Lower bound for wind speed, in knots.
* @param windSpeedUpperBound Upper bound for wind speed, in knots.
*/
public RandomWindGenerator(Bearing windBaselineBearing, Bearing windBearingLowerBound, Bearing windBearingUpperBound, double windBaselineSpeed, double windSpeedLowerBound, double windSpeedUpperBound) {
this.windBaselineBearing = windBaselineBearing;
this.windBearingLowerBound = windBearingLowerBound;
this.windBearingUpperBound = windBearingUpperBound;
this.windBaselineSpeed = windBaselineSpeed;
this.windSpeedLowerBound = windSpeedLowerBound;
this.windSpeedUpperBound = windSpeedUpperBound;
}
@Override
public Wind generateBaselineWind() {
return new Wind(windBaselineBearing, windBaselineSpeed);
}
/**
* Generates a random Wind object, that is within the provided bounds.
* @return Generated wind object.
*/
public Wind generateRandomWind() {
double windSpeed = generateRandomWindSpeed();
Bearing windBearing = generateRandomWindBearing();
return new Wind(windBearing, windSpeed);
}
/**
* Generates a random wind speed within the specified bounds. In knots.
* @return Wind speed, in knots.
*/
private double generateRandomWindSpeed() {
double randomSpeedKnots = generateRandomValueInBounds(windSpeedLowerBound, windSpeedUpperBound);
return randomSpeedKnots;
}
/**
* Generates a random wind bearing within the specified bounds.
* @return Wind bearing.
*/
private Bearing generateRandomWindBearing() {
double randomBearingDegrees = generateRandomValueInBounds(windBearingLowerBound.degrees(), windBearingUpperBound.degrees());
return Bearing.fromDegrees(randomBearingDegrees);
}
/**
* Generates a random value within a specified interval.
* @param lowerBound The lower bound of the interval.
* @param upperBound The upper bound of the interval.
* @return A random value within the interval.
*/
private static double generateRandomValueInBounds(double lowerBound, double upperBound) {
float proportion = new Random().nextFloat();
double delta = upperBound - lowerBound;
double amount = delta * proportion;
double finalAmount = amount + lowerBound;
return finalAmount;
}
/**
* Generates a new value within an interval, given a start value, chance to change, and change amount.
* @param lowerBound Lower bound of interval.
* @param upperBound Upper bound of interval.
* @param currentValue The current value to change.
* @param changeAmount The amount to change by.
* @param chanceToChange The change to actually change the value.
* @return The new value.
*/
private static double generateNextValueInBounds(double lowerBound, double upperBound, double currentValue, double changeAmount, double chanceToChange) {
float chance = new Random().nextFloat();
if (chance <= chanceToChange) {
currentValue += changeAmount;
} else if (chance <= (2 * chanceToChange)) {
currentValue -= changeAmount;
}
currentValue = clamp(lowerBound, upperBound, currentValue);
return currentValue;
}
@Override
public Wind generateNextWind(Wind currentWind) {
double windSpeed = generateNextWindSpeed(currentWind.getWindSpeed());
Bearing windBearing = generateNextWindBearing(currentWind.getWindDirection());
return new Wind(windBearing, windSpeed);
}
/**
* Generates the next wind speed to use.
* @param windSpeed Current wind speed, in knots.
* @return Next wind speed, in knots.
*/
private double generateNextWindSpeed(double windSpeed) {
double chanceToChange = 0.2;
double changeAmount = 0.1;
double nextWindSpeed = generateNextValueInBounds(
windSpeedLowerBound,
windSpeedUpperBound,
windSpeed,
changeAmount,
chanceToChange);
return nextWindSpeed;
}
/**
* Generates the next wind speed to use.
* @param windBearing Current wind bearing.
* @return Next wind speed.
*/
private Bearing generateNextWindBearing(Bearing windBearing) {
double chanceToChange = 0.2;
double changeAmount = 0.5;
double nextWindBearingDegrees = generateNextValueInBounds(
windBearingLowerBound.degrees(),
windBearingUpperBound.degrees(),
windBearing.degrees(),
changeAmount,
chanceToChange);
return Bearing.fromDegrees(nextWindBearingDegrees);
}
/**
* Clamps a value to be within an interval.
* @param lower Lower bound of the interval.
* @param upper Upper bound of the interval.
* @param value Value to clamp.
* @return The clamped value.
*/
private static double clamp(double lower, double upper, double value) {
if (value > upper) {
value = upper;
} else if (value < lower) {
value = lower;
}
return value;
}
}
@@ -0,0 +1,70 @@
package mock.model;
import mock.exceptions.SourceIDAllocationException;
import java.util.ArrayList;
import java.util.List;
/**
* This class is responsible for allocating boat source IDs for use in a race, upon request.
*/
public class SourceIdAllocator {
/**
* This list contains all unallocated source IDs.
*/
List<Integer> unallocatedIDs = new ArrayList<>();
/**
* This list contains all allocated source IDs.
*/
List<Integer> allocatedIDs = new ArrayList<>();
/**
* Creates a source ID allocator, using the given list of unallocated source IDs.
* @param unallocatedIDs List of unallocated source IDs.
*/
public SourceIdAllocator(List<Integer> unallocatedIDs) {
//We need to copy the list.
this.unallocatedIDs.addAll(unallocatedIDs);
}
/**
* Allocates a source ID for a boat.
* @return The allocated source ID.
* @throws SourceIDAllocationException Thrown if we cannot allocate any more source IDs.
*/
public synchronized int allocateSourceID() throws SourceIDAllocationException {
if (!unallocatedIDs.isEmpty()) {
int sourceID = unallocatedIDs.remove(0);
allocatedIDs.add(sourceID);
return sourceID;
} else {
throw new SourceIDAllocationException("Could not allocate a source ID.");
}
}
/**
* Returns a source ID to the source ID allocator, so that it can be reused.
* @param sourceID Source ID to return.
*/
public void returnSourceID(Integer sourceID) {
//We remove an Integer, not an int, so that we remove by value not by index.
allocatedIDs.remove(sourceID);
unallocatedIDs.add(sourceID);
}
}
@@ -1,249 +1,29 @@
package mock.model;
import shared.model.Bearing;
import shared.model.Wind;
import java.util.Random;
/**
* This class generates Wind objects for use in a MockRace.
* Bounds on bearing and speed can be specified.
* Wind can be completely random, or random incremental change.
* Interface for wind generators. It allows for generating a baseline wind, and subsequent winds.
*/
public class WindGenerator {
public interface WindGenerator {
/**
* The bearing the wind direction starts at.
*/
private Bearing windBaselineBearing;
/**
* The lower bearing angle that the wind may have.
*/
private Bearing windBearingLowerBound;
/**
* The upper bearing angle that the wind may have.
*/
private Bearing windBearingUpperBound;
/**
* The speed the wind starts at, in knots.
*/
private double windBaselineSpeed;
/**
* The lower speed that the wind may have, in knots.
*/
private double windSpeedLowerBound;
/**
* The upper speed that the wind may have, in knots.
*/
private double windSpeedUpperBound;
/**
* Creates a wind generator, with a baseline, lower bound, and upper bound, for the wind speed and direction.
* @param windBaselineBearing Baseline wind direction.
* @param windBearingLowerBound Lower bound for wind direction.
* @param windBearingUpperBound Upper bound for wind direction.
* @param windBaselineSpeed Baseline wind speed, in knots.
* @param windSpeedLowerBound Lower bound for wind speed, in knots.
* @param windSpeedUpperBound Upper bound for wind speed, in knots.
*/
public WindGenerator(Bearing windBaselineBearing, Bearing windBearingLowerBound, Bearing windBearingUpperBound, double windBaselineSpeed, double windSpeedLowerBound, double windSpeedUpperBound) {
this.windBaselineBearing = windBaselineBearing;
this.windBearingLowerBound = windBearingLowerBound;
this.windBearingUpperBound = windBearingUpperBound;
this.windBaselineSpeed = windBaselineSpeed;
this.windSpeedLowerBound = windSpeedLowerBound;
this.windSpeedUpperBound = windSpeedUpperBound;
}
/**
* Generates a wind object using the baseline wind speed and bearing.
* @return Baseline wind object.
*/
public Wind generateBaselineWind() {
return new Wind(windBaselineBearing, windBaselineSpeed);
}
Wind generateBaselineWind();
/**
* Generates a random Wind object, that is within the provided bounds.
* @return Generated wind object.
*/
public Wind generateRandomWind() {
double windSpeed = generateRandomWindSpeed();
Bearing windBearing = generateRandomWindBearing();
return new Wind(windBearing, windSpeed);
}
/**
* Generates a random wind speed within the specified bounds. In knots.
* @return Wind speed, in knots.
*/
private double generateRandomWindSpeed() {
double randomSpeedKnots = generateRandomValueInBounds(windSpeedLowerBound, windSpeedUpperBound);
return randomSpeedKnots;
}
/**
* Generates a random wind bearing within the specified bounds.
* @return Wind bearing.
*/
private Bearing generateRandomWindBearing() {
double randomBearingDegrees = generateRandomValueInBounds(windBearingLowerBound.degrees(), windBearingUpperBound.degrees());
return Bearing.fromDegrees(randomBearingDegrees);
}
/**
* Generates a random value within a specified interval.
* @param lowerBound The lower bound of the interval.
* @param upperBound The upper bound of the interval.
* @return A random value within the interval.
*/
private static double generateRandomValueInBounds(double lowerBound, double upperBound) {
float proportion = new Random().nextFloat();
double delta = upperBound - lowerBound;
double amount = delta * proportion;
double finalAmount = amount + lowerBound;
return finalAmount;
}
/**
* Generates a new value within an interval, given a start value, chance to change, and change amount.
* @param lowerBound Lower bound of interval.
* @param upperBound Upper bound of interval.
* @param currentValue The current value to change.
* @param changeAmount The amount to change by.
* @param chanceToChange The change to actually change the value.
* @return The new value.
*/
private static double generateNextValueInBounds(double lowerBound, double upperBound, double currentValue, double changeAmount, double chanceToChange) {
float chance = new Random().nextFloat();
if (chance <= chanceToChange) {
currentValue += changeAmount;
} else if (chance <= (2 * chanceToChange)) {
currentValue -= changeAmount;
}
currentValue = clamp(lowerBound, upperBound, currentValue);
return currentValue;
}
/**
* Generates the next Wind object, that is within the provided bounds. This randomly increases or decreases the wind's speed and bearing.
* Generates the next Wind object, according to the implementation of the wind generator.
* @param currentWind The current wind to change. This is not modified.
* @return Generated wind object.
*/
public Wind generateNextWind(Wind currentWind) {
double windSpeed = generateNextWindSpeed(currentWind.getWindSpeed());
Bearing windBearing = generateNextWindBearing(currentWind.getWindDirection());
return new Wind(windBearing, windSpeed);
}
/**
* Generates the next wind speed to use.
* @param windSpeed Current wind speed, in knots.
* @return Next wind speed, in knots.
*/
private double generateNextWindSpeed(double windSpeed) {
double chanceToChange = 0.2;
double changeAmount = 0.1;
double nextWindSpeed = generateNextValueInBounds(
windSpeedLowerBound,
windSpeedUpperBound,
windSpeed,
changeAmount,
chanceToChange);
return nextWindSpeed;
}
/**
* Generates the next wind speed to use.
* @param windBearing Current wind bearing.
* @return Next wind speed.
*/
private Bearing generateNextWindBearing(Bearing windBearing) {
double chanceToChange = 0.2;
double changeAmount = 0.5;
double nextWindBearingDegrees = generateNextValueInBounds(
windBearingLowerBound.degrees(),
windBearingUpperBound.degrees(),
windBearing.degrees(),
changeAmount,
chanceToChange);
return Bearing.fromDegrees(nextWindBearingDegrees);
}
/**
* Clamps a value to be within an interval.
* @param lower Lower bound of the interval.
* @param upper Upper bound of the interval.
* @param value Value to clamp.
* @return The clamped value.
*/
private static double clamp(double lower, double upper, double value) {
if (value > upper) {
value = upper;
} else if (value < lower) {
value = lower;
}
return value;
}
Wind generateNextWind(Wind currentWind);
}
@@ -1,8 +1,10 @@
package mock.model.commandFactory;
import mock.exceptions.CommandConstructionException;
import mock.model.MockBoat;
import mock.model.MockRace;
import network.Messages.Enums.BoatActionEnum;
import network.Messages.BoatAction;
import shared.exceptions.BoatNotFoundException;
/**
* Factory class for Command objects
@@ -11,17 +13,28 @@ public class CommandFactory {
/**
* Generates a command on a race and boat corresponding to the protocol action number.
* @param race to receive command
* @param boat to receive command in race
* @param action number to select command
* @return returns a new command based on a Command ENUM
* @return The command to execute the given action.
* @throws CommandConstructionException Thrown if the command cannot be constructed (e.g., unknown action type).
*/
public static Command createCommand(MockRace race, MockBoat boat, BoatActionEnum action) {
switch(action) {
public static Command createCommand(MockRace race, BoatAction action) throws CommandConstructionException {
MockBoat boat = null;
try {
boat = race.getBoat(action.getSourceID());
} catch (BoatNotFoundException e) {
throw new CommandConstructionException("Could not create command for BoatAction: " + action + ". Boat with sourceID: " + action.getSourceID() + " not found.", e);
}
switch(action.getBoatAction()) {
case AUTO_PILOT: return new VMGCommand(race, boat);
case TACK_GYBE: return new TackGybeCommand(race, boat);
case UPWIND: return new WindCommand(race, boat, true);
case DOWNWIND: return new WindCommand(race, boat, false);
default: return null; // TODO - please please have discussion over what to default to
default: throw new CommandConstructionException("Could not create command for BoatAction: " + action + ". Unknown BoatAction.");
}
}
}
@@ -2,34 +2,52 @@ package mock.model.commandFactory;
import mock.model.MockBoat;
import mock.model.MockRace;
import shared.model.Bearing;
/**
* Created by David on 2/08/2017.
* Command class for tacking and gybing
*/
public class TackGybeCommand implements Command {
private MockRace race;
private MockBoat boat;
/**
* Constructor for class
* @param race mock race
* @param boat mock boat to update
*/
public TackGybeCommand(MockRace race, MockBoat boat) {
this.race = race;
this.boat = boat;
}
//The refactoring of MockRace will require changes to be made
@Override
public void execute() {
boat.setAutoVMG(false);
/*VMG newVMG = boat.getPolars().calculateVMG(
race.getWindDirection(),
race.getWindSpeed(),
boat.calculateBearingToNextMarker(),
Bearing.fromDegrees(0d),
Bearing.fromDegrees(359.99999d));
VMG boatVMG = new VMG(boat.getCurrentSpeed(), boat.getBearing());
if(race.improvesVelocity(boatVMG, newVMG, boat.calculateBearingToNextMarker())){
boat.setVMG(newVMG);
}*/
double boatAngle = boat.getBearing().degrees();
double windAngle =race.getWindDirection().degrees();
double differenceAngle = calcDistance(boatAngle, windAngle);
double angleA = windAngle + differenceAngle;
double angleB = windAngle - differenceAngle;
if(angleA % 360 == boatAngle){
boat.setBearing(Bearing.fromDegrees(angleB));
} else {
boat.setBearing(Bearing.fromDegrees(angleA));
}
}
/**
* Method to calculate smallest angle between 2 angles
* @param degreeA first angle degree
* @param degreeB second angle degree
* @return the calculated smallest angle
*/
public double calcDistance(double degreeA, double degreeB){
double phi = Math.abs(degreeB - degreeA) % 360;
return phi > 180 ? 360 - phi : phi;
}
}
@@ -4,27 +4,28 @@ import mock.model.MockBoat;
import mock.model.MockRace;
/**
* Created by David on 2/08/2017.
* Command class for autoVMG
*/
public class VMGCommand implements Command {
private MockRace race;
private MockBoat boat;
/**
* Constructor for class
* @param race mock race
* @param boat mock boat to update
*/
public VMGCommand(MockRace race, MockBoat boat) {
this.race = race;
this.boat = boat;
}
//The refactoring of MockRace will require changes to be made
@Override
public void execute() {
boat.setAutoVMG(true);
/*VMG newVMG = boat.getPolars().calculateVMG(
race.getWindDirection(),
race.getWindSpeed(),
boat.calculateBearingToNextMarker(),
Bearing.fromDegrees(0d),
Bearing.fromDegrees(359.99999d));
boat.setVMG(newVMG);*/
if (boat.getAutoVMG()){
boat.setAutoVMG(false);
} else {
boat.setAutoVMG(true);
}
}
}