Merge remote-tracking branch 'remotes/origin/master' into Game_Controller

This commit is contained in:
hba56
2017-07-24 11:58:01 +12:00
218 changed files with 8957 additions and 6977 deletions
@@ -0,0 +1,97 @@
package visualiser.Controllers;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import visualiser.model.RaceConnection;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import java.util.ResourceBundle;
/**
* Controls the connection that the VIsualiser can connect to.
*/
public class ConnectionController extends Controller {
@FXML
private AnchorPane connectionWrapper;
@FXML
private TableView<RaceConnection> connectionTable;
@FXML
private TableColumn<RaceConnection, String> hostnameColumn;
@FXML
private TableColumn<RaceConnection, String> statusColumn;
@FXML
private Button connectButton;
@FXML
private TextField urlField;
@FXML
private TextField portField;
private ObservableList<RaceConnection> connections;
@Override
public void initialize(URL location, ResourceBundle resources) {
// TODO - replace with config file
connections = FXCollections.observableArrayList();
connections.add(new RaceConnection("livedata.americascup.com", 4941));
connections.add(new RaceConnection("localhost", 4942));
connectionTable.setItems(connections);
hostnameColumn.setCellValueFactory(cellData -> cellData.getValue().hostnameProperty());
statusColumn.setCellValueFactory(cellData -> cellData.getValue().statusProperty());
connectionTable.getSelectionModel().selectedItemProperty().addListener((obs, prev, curr) -> {
if (curr != null && ((RaceConnection)curr).check()) connectButton.setDisable(false);
else connectButton.setDisable(true);
});
connectButton.setDisable(true);
}
/**
* Sets current status of all connections.
*/
public void checkConnections() {
for(RaceConnection connection: connections) {
connection.check();
}
}
public AnchorPane startWrapper(){
return connectionWrapper;
}
/**
* Connects to host currently selected in table. Button enabled only if host is ready.
*/
public void connectSocket() {
try{
RaceConnection connection = connectionTable.getSelectionModel().getSelectedItem();
Socket socket = new Socket(connection.getHostname(), connection.getPort());
connectionWrapper.setVisible(false);
parent.enterLobby(socket);
} catch (IOException e) { /* Never reached */ }
}
/**
* adds a new connection
*/
public void addConnection(){
String hostName = urlField.getText();
String portString = portField.getText();
try{
int port = Integer.parseInt(portString);
connections.add(new RaceConnection(hostName, port));
}catch(NumberFormatException e){
System.err.println("Port number entered is not a number");
}
}
}
@@ -0,0 +1,32 @@
package visualiser.Controllers;
import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;
/**
* Controller parent for app controllers.
* Created by fwy13 on 15/03/2017.
*/
public abstract class Controller implements Initializable {
protected MainController parent;
/**
* Sets the parent of the application
*
* @param parent controller
*/
public void setParent(MainController parent) {
this.parent = parent;
}
/**
* Initialisation class that is run on start up.
*
* @param location resources location
* @param resources resources bundle
*/
@Override
public abstract void initialize(URL location, ResourceBundle resources);
}
@@ -0,0 +1,90 @@
package visualiser.Controllers;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
import visualiser.model.VisualiserBoat;
import java.net.URL;
import java.util.ResourceBundle;
/**
* Finish Screen for when the race finishes.
*/
public class FinishController extends Controller {
@FXML
AnchorPane finishWrapper;
@FXML
TableView<VisualiserBoat> boatInfoTable;
@FXML
TableColumn<VisualiserBoat, String> boatRankColumn;
@FXML
TableColumn<VisualiserBoat, String> boatNameColumn;
@FXML
Label raceWinnerLabel;
/**
* The boats to display on the table.
*/
private ObservableList<VisualiserBoat> boats;
/**
* Ctor.
*/
public FinishController() {
}
@Override
public void initialize(URL location, ResourceBundle resources){
}
/**
* Sets up the finish table
* @param boats Boats to display
*/
private void setFinishTable(ObservableList<VisualiserBoat> boats) {
this.boats = boats;
//Set contents.
boatInfoTable.setItems(boats);
//Name.
boatNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
//Rank/position.
boatRankColumn.setCellValueFactory(cellData -> cellData.getValue().positionProperty());
//Winner label.
raceWinnerLabel.setText("Winner: "+ boatNameColumn.getCellObservableValue(0).getValue());
raceWinnerLabel.setWrapText(true);
}
/**
* Display the table
* @param boats boats to display on the table.
*/
public void enterFinish(ObservableList<VisualiserBoat> boats){
finishWrapper.setVisible(true);
setFinishTable(boats);
}
}
@@ -0,0 +1,88 @@
package visualiser.Controllers;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.layout.AnchorPane;
import visualiser.app.VisualiserInput;
import visualiser.model.VisualiserBoat;
import visualiser.model.VisualiserRace;
import java.net.Socket;
import java.net.URL;
import java.util.ResourceBundle;
/**
* Controller that everything is overlayed onto. This makes it so that changing scenes does not resize your stage.
*/
public class MainController extends Controller {
@FXML private StartController startController;
@FXML private RaceController raceController;
@FXML private ConnectionController connectionController;
@FXML private FinishController finishController;
/**
* Ctor.
*/
public MainController() {
}
/**
* Transitions from the StartController screen (displays pre-race information) to the RaceController (displays the actual race).
* @param visualiserInput The object used to read packets from the race server.
* @param visualiserRace The object modelling the race.
*/
public void beginRace(VisualiserInput visualiserInput, VisualiserRace visualiserRace) {
raceController.startRace(visualiserInput, visualiserRace);
}
/**
* Transitions from the server selection screen to the pre-race lobby for a given server.
* @param socket The server to read data from.
*/
public void enterLobby(Socket socket) {
startController.enterLobby(socket);
}
/**
* Transitions from the {@link RaceController} screen to the {@link FinishController} screen.
* @param boats The boats to display on the finish screen.
*/
public void enterFinish(ObservableList<VisualiserBoat> boats) {
finishController.enterFinish(boats);
}
/**
* Main Controller for the applications will house the menu and the displayed pane.
*
* @param location of resources
* @param resources bundle
*/
@Override
public void initialize(URL location, ResourceBundle resources) {
startController.setParent(this);
raceController.setParent(this);
connectionController.setParent(this);
finishController.setParent(this);
AnchorPane.setTopAnchor(startController.startWrapper(), 0.0);
AnchorPane.setBottomAnchor(startController.startWrapper(), 0.0);
AnchorPane.setLeftAnchor(startController.startWrapper(), 0.0);
AnchorPane.setRightAnchor(startController.startWrapper(), 0.0);
AnchorPane.setTopAnchor(connectionController.startWrapper(), 0.0);
AnchorPane.setBottomAnchor(connectionController.startWrapper(), 0.0);
AnchorPane.setLeftAnchor(connectionController.startWrapper(), 0.0);
AnchorPane.setRightAnchor(connectionController.startWrapper(), 0.0);
AnchorPane.setTopAnchor(finishController.finishWrapper, 0.0);
AnchorPane.setBottomAnchor(finishController.finishWrapper, 0.0);
AnchorPane.setLeftAnchor(finishController.finishWrapper, 0.0);
AnchorPane.setRightAnchor(finishController.finishWrapper, 0.0);
}
}
@@ -0,0 +1,383 @@
package visualiser.Controllers;
import javafx.animation.AnimationTimer;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.chart.LineChart;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.util.Callback;
import network.Messages.Enums.RaceStatusEnum;
import shared.model.Leg;
import visualiser.app.VisualiserInput;
import visualiser.model.*;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ResourceBundle;
/**
* Controller used to display a running race.
*/
public class RaceController extends Controller {
/**
* The object used to read packets from the connected server.
*/
private VisualiserInput visualiserInput;
/**
* The race object which describes the currently occurring race.
*/
private VisualiserRace visualiserRace;
/**
* An additional observable list of boats. This is used by the table view, to allow it to sort boats without effecting the race's own list of boats.
*/
private ObservableList<VisualiserBoat> tableBoatList;
/**
* The canvas that draws the race.
*/
private ResizableRaceCanvas raceCanvas;
/**
* The sparkline graph.
*/
private Sparkline sparkline;
@FXML private GridPane canvasBase;
@FXML private Pane arrow;
@FXML private SplitPane race;
@FXML private StackPane arrowPane;
@FXML private Label timer;
@FXML private Label FPS;
@FXML private Label timeZone;
@FXML private CheckBox showFPS;
@FXML private TableView<VisualiserBoat> boatInfoTable;
@FXML private TableColumn<VisualiserBoat, String> boatPlacingColumn;
@FXML private TableColumn<VisualiserBoat, String> boatTeamColumn;
@FXML private TableColumn<VisualiserBoat, Leg> boatMarkColumn;
@FXML private TableColumn<VisualiserBoat, Number> boatSpeedColumn;
@FXML private LineChart<Number, Number> sparklineChart;
@FXML private AnchorPane annotationPane;
/**
* Ctor.
*/
public RaceController() {
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
/**
* Initialises the various UI components to listen to the {@link #visualiserRace}.
*/
private void initialiseRace() {
//Fps display.
initialiseFps(this.visualiserRace);
//Need to add the included arrow pane to the arrowPane container.
initialiseArrow();
//Information table.
initialiseInfoTable(this.visualiserRace);
//Sparkline.
initialiseSparkline(this.visualiserRace);
//Race canvas.
initialiseRaceCanvas(this.visualiserRace);
//Race timezone label.
initialiseRaceTimezoneLabel(this.visualiserRace);
//Race clock.
initialiseRaceClock(this.visualiserRace);
//Start the race animation timer.
raceTimer();
}
/**
* Initialises the frame rate functionality. This allows for toggling the frame rate, and connect the fps label to the race's fps property.
* @param visualiserRace The race to connect the fps label to.
*/
private void initialiseFps(VisualiserRace visualiserRace) {
//On/off toggle.
initialiseFpsToggle();
//Label value.
initialiseFpsLabel(visualiserRace);
}
/**
* Initialises a listener for the fps toggle.
*/
private void initialiseFpsToggle() {
showFPS.selectedProperty().addListener((ov, old_val, new_val) -> {
if (showFPS.isSelected()) {
FPS.setVisible(true);
} else {
FPS.setVisible(false);
}
});
}
/**
* Initialises the fps label to update when the race fps changes.
* @param visualiserRace The race to monitor the frame rate of.
*/
private void initialiseFpsLabel(VisualiserRace visualiserRace) {
visualiserRace.fpsProperty().addListener((observable, oldValue, newValue) -> {
Platform.runLater(() -> this.FPS.setText("FPS: " + newValue.toString()));
});
}
/**
* Initialises the information table view to listen to a given race.
* @param race Race to listen to.
*/
public void initialiseInfoTable(VisualiserRace race) {
//Copy list of boats.
this.tableBoatList = FXCollections.observableArrayList(race.getBoats());
//Set up table.
boatInfoTable.setItems(this.tableBoatList);
//Set up each column.
//Name.
boatTeamColumn.setCellValueFactory(
cellData -> cellData.getValue().nameProperty() );
//Speed.
boatSpeedColumn.setCellValueFactory(
cellData -> cellData.getValue().currentSpeedProperty() );
//Kind of ugly, but allows for formatting an observed speed.
boatSpeedColumn.setCellFactory(
//Callback object.
new Callback<TableColumn<VisualiserBoat, Number>, TableCell<VisualiserBoat, Number>>() {
//Callback function.
@Override
public TableCell<VisualiserBoat, Number> call(TableColumn<VisualiserBoat, Number> param) {
//We return a table cell that populates itself with a Number, and formats it.
return new TableCell<VisualiserBoat, Number>(){
//Function to update the cell text.
@Override
protected void updateItem(Number item, boolean empty) {
if (item != null) {
super.updateItem(item, empty);
setText(String.format("%.2fkn", item.doubleValue()));
}
}
};
}
} );
//Last mark.
boatMarkColumn.setCellValueFactory(
cellData -> cellData.getValue().legProperty() );
//Kind of ugly, but allows for turning an observed Leg into a string.
boatMarkColumn.setCellFactory(
//Callback object.
new Callback<TableColumn<VisualiserBoat, Leg>, TableCell<VisualiserBoat, Leg>>() {
//Callback function.
@Override
public TableCell<VisualiserBoat, Leg> call(TableColumn<VisualiserBoat, Leg> param) {
//We return a table cell that populates itself with a Leg's name.
return new TableCell<VisualiserBoat, Leg>(){
//Function to update the cell text.
@Override
protected void updateItem(Leg item, boolean empty) {
if (item != null) {
super.updateItem(item, empty);
setText(item.getName());
}
}
};
}
} );
//Current place within race.
boatPlacingColumn.setCellValueFactory(
cellData -> cellData.getValue().positionProperty() );
}
/**
* Initialises the {@link Sparkline}, and listens to a specified {@link VisualiserRace}.
* @param race The race to listen to.
*/
private void initialiseSparkline(VisualiserRace race) {
//The race.getBoats() we are passing in is sorted by position in race inside the race class.
this.sparkline = new Sparkline(this.visualiserRace, this.sparklineChart);
}
/**
* Initialises the {@link ResizableRaceCanvas}, provides the race to read data from.
* @param race Race to read data from.
*/
private void initialiseRaceCanvas(VisualiserRace race) {
//Create canvas.
raceCanvas = new ResizableRaceCanvas(race, arrow.getChildren().get(0));
//Set properties.
raceCanvas.setMouseTransparent(true);
raceCanvas.widthProperty().bind(canvasBase.widthProperty());
raceCanvas.heightProperty().bind(canvasBase.heightProperty());
//Draw it and show it.
raceCanvas.draw();
raceCanvas.setVisible(true);
//Add to scene.
canvasBase.getChildren().add(0, raceCanvas);
}
/**
* Intialises the race time zone label with the race's time zone.
* @param race The race to get time zone from.
*/
private void initialiseRaceTimezoneLabel(VisualiserRace race) {
timeZone.setText(race.getRaceClock().getTimeZone());
}
/**
* Initialises the race clock to listen to the specified race.
* @param race The race to listen to.
*/
private void initialiseRaceClock(VisualiserRace race) {
//RaceClock.duration isn't necessarily being changed in the javaFX thread, so we need to runlater the update.
race.getRaceClock().durationProperty().addListener((observable, oldValue, newValue) -> {
Platform.runLater(() -> {
timer.setText(newValue);
});
});
}
/**
* Displays a specified race.
* @param visualiserInput Object used to read packets from server.
* @param visualiserRace Object modelling the race.
*/
public void startRace(VisualiserInput visualiserInput, VisualiserRace visualiserRace) {
this.visualiserInput = visualiserInput;
this.visualiserRace = visualiserRace;
initialiseRace();
//Display this controller.
race.setVisible(true);
// set up annotation displays
new Annotations(annotationPane, raceCanvas);
}
/**
* Transition from the race view to the finish view.
* @param boats boats there are in the race.
*/
public void finishRace(ObservableList<VisualiserBoat> boats){
race.setVisible(false);
parent.enterFinish(boats);
}
/**
* Adds the included arrow pane (see arrow.fxml) to the arrowPane (see race.fxml).
*/
private void initialiseArrow() {
arrowPane.getChildren().add(arrow);
}
/**
* Timer which monitors the race.
*/
private void raceTimer() {
new AnimationTimer() {
@Override
public void handle(long arg0) {
//Get the current race status.
RaceStatusEnum raceStatus = visualiserRace.getRaceStatusEnum();
//If the race has finished, go to finish view.
if (raceStatus == RaceStatusEnum.FINISHED) {
//Stop this timer.
stop();
//Hide this, and display the finish controller.
finishRace(visualiserRace.getBoats());
} else {
//Otherwise, render the canvas.
raceCanvas.drawRace();
//Sort the tableview. Doesn't automatically work for all columns.
boatInfoTable.sort();
}
}
}.start();
}
}
@@ -0,0 +1,321 @@
package visualiser.Controllers;
import javafx.animation.AnimationTimer;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import network.Messages.Enums.RaceStatusEnum;
import network.Messages.LatestMessages;
import shared.dataInput.*;
import shared.enums.XMLFileType;
import shared.exceptions.InvalidBoatDataException;
import shared.exceptions.InvalidRaceDataException;
import shared.exceptions.InvalidRegattaDataException;
import shared.exceptions.XMLReaderException;
import visualiser.app.VisualiserInput;
import visualiser.model.VisualiserBoat;
import visualiser.model.VisualiserRace;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import java.util.*;
/**
* Controller to for waiting for the race to start.
*/
public class StartController extends Controller implements Observer {
@FXML private GridPane start;
@FXML private AnchorPane startWrapper;
/**
* The name of the race/regatta.
*/
@FXML private Label raceTitleLabel;
/**
* The time the race starts at.
*/
@FXML private Label raceStartLabel;
/**
* The current time at the race location.
*/
@FXML private Label timeZoneTime;
/**
* Time until the race starts.
*/
@FXML private Label timer;
@FXML private TableView<VisualiserBoat> boatNameTable;
@FXML private TableColumn<VisualiserBoat, String> boatNameColumn;
@FXML private TableColumn<VisualiserBoat, String> boatCodeColumn;
/**
* The status of the race.
*/
@FXML private Label raceStatusLabel;
/**
* The object used to read packets from the connected server.
*/
private VisualiserInput visualiserInput;
/**
* The race object which describes the currently occurring race.
*/
private VisualiserRace visualiserRace;
/**
* An array of colors used to assign colors to each boat - passed in to the VisualiserRace constructor.
*/
List<Color> colors = new ArrayList<>(Arrays.asList(
Color.BLUEVIOLET,
Color.BLACK,
Color.RED,
Color.ORANGE,
Color.DARKOLIVEGREEN,
Color.LIMEGREEN,
Color.PURPLE,
Color.DARKGRAY,
Color.YELLOW
));
/**
* Ctor.
*/
public StartController() {
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
/**
* Starts the race.
* Called once we have received all XML files from the server.
* @param latestMessages The set of latest race messages to use for race.
* @throws XMLReaderException Thrown if XML file cannot be parsed.
* @throws InvalidRaceDataException Thrown if XML file cannot be parsed.
* @throws InvalidBoatDataException Thrown if XML file cannot be parsed.
* @throws InvalidRegattaDataException Thrown if XML file cannot be parsed.
*/
private void startRace(LatestMessages latestMessages) throws XMLReaderException, InvalidRaceDataException, InvalidBoatDataException, InvalidRegattaDataException {
//Create data sources from latest messages for the race.
RaceDataSource raceDataSource = new RaceXMLReader(latestMessages.getRaceXMLMessage().getXmlMessage(), XMLFileType.Contents);
BoatDataSource boatDataSource = new BoatXMLReader(latestMessages.getBoatXMLMessage().getXmlMessage(), XMLFileType.Contents);
RegattaDataSource regattaDataSource = new RegattaXMLReader(latestMessages.getRegattaXMLMessage().getXmlMessage(), XMLFileType.Contents);
//Create race.
this.visualiserRace = new VisualiserRace(boatDataSource, raceDataSource, regattaDataSource, latestMessages, this.colors);
new Thread(this.visualiserRace).start();
//Initialise the boat table.
initialiseBoatTable(this.visualiserRace);
//Initialise the race name.
initialiseRaceName(this.visualiserRace);
//Initialises the race clock.
initialiseRaceClock(this.visualiserRace);
//Starts the race countdown timer.
countdownTimer();
}
public AnchorPane startWrapper(){
return startWrapper;
}
/**
* Initialises the boat table that is to be shown on the pane.
* @param visualiserRace The race to get data from.
*/
private void initialiseBoatTable(VisualiserRace visualiserRace) {
//Get the boats.
ObservableList<VisualiserBoat> boats = visualiserRace.getBoats();
//Populate table.
boatNameTable.setItems(boats);
boatNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
boatCodeColumn.setCellValueFactory(cellData -> cellData.getValue().countryProperty());
}
/**
* Initialises the race name which is shown on the pane.
* @param visualiserRace The race to get data from.
*/
private void initialiseRaceName(VisualiserRace visualiserRace) {
raceTitleLabel.setText(visualiserRace.getRegattaName());
}
/**
* Initialises the race clock/timer labels for the start time, current time, and remaining time.
* @param visualiserRace The race to get data from.
*/
private void initialiseRaceClock(VisualiserRace visualiserRace) {
//Start time.
initialiseRaceClockStartTime(visualiserRace);
//Current time.
initialiseRaceClockCurrentTime(visualiserRace);
//Remaining time.
initialiseRaceClockDuration(visualiserRace);
}
/**
* Initialises the race current time label.
* @param visualiserRace The race to get data from.
*/
private void initialiseRaceClockStartTime(VisualiserRace visualiserRace) {
raceStartLabel.setText(visualiserRace.getRaceClock().getStartingTimeString());
visualiserRace.getRaceClock().startingTimeProperty().addListener((observable, oldValue, newValue) -> {
Platform.runLater(() -> {
raceStartLabel.setText(newValue);
});
});
}
/**
* Initialises the race current time label.
* @param visualiserRace The race to get data from.
*/
private void initialiseRaceClockCurrentTime(VisualiserRace visualiserRace) {
visualiserRace.getRaceClock().currentTimeProperty().addListener((observable, oldValue, newValue) -> {
Platform.runLater(() -> {
timeZoneTime.setText(newValue);
});
});
}
/**
* Initialises the race duration label.
* @param visualiserRace The race to get data from.
*/
private void initialiseRaceClockDuration(VisualiserRace visualiserRace) {
visualiserRace.getRaceClock().durationProperty().addListener((observable, oldValue, newValue) -> {
Platform.runLater(() -> {
timer.setText(newValue);
});
});
}
/**
* Countdown timer until race starts.
*/
private void countdownTimer() {
new AnimationTimer() {
@Override
public void handle(long arg0) {
//TODO instead of having an AnimationTimer checking the race status, we could provide a Property<RaceStatusEnum>, and connect a listener to that.
//Get the current race status.
RaceStatusEnum raceStatus = visualiserRace.getRaceStatusEnum();
//Display it.
raceStatusLabel.setText("Race Status: " + raceStatus.name());
//If the race has reached the preparatory phase, or has started...
if (raceStatus == RaceStatusEnum.PREPARATORY || raceStatus == RaceStatusEnum.STARTED) {
//Stop this timer.
stop();
//Hide this, and display the race controller.
startWrapper.setVisible(false);
start.setVisible(false);
parent.beginRace(visualiserInput, visualiserRace);
}
}
}.start();
}
/**
* Function to handle changes in objects we observe.
* We observe LatestMessages.
* @param o The observed object.
* @param arg The {@link Observable#notifyObservers(Object)} parameter.
*/
@Override
public void update(Observable o, Object arg) {
//Check that we actually have LatestMessages.
if (o instanceof LatestMessages) {
LatestMessages latestMessages = (LatestMessages) o;
//If we've received all of the xml files, start the race. Only start it if it hasn't already been created.
if (latestMessages.hasAllXMLMessages() && this.visualiserRace == null) {
//Need to handle it in the javafx thread.
Platform.runLater(() -> {
try {
this.startRace(latestMessages);
} catch (XMLReaderException | InvalidBoatDataException | InvalidRaceDataException | InvalidRegattaDataException e) {
//We currently don't handle this in meaningful way, as it should never occur.
//If we reach this point it means that malformed XML files were sent.
e.printStackTrace();
}
});
}
}
}
/**
* Show starting information for a race given a socket.
* @param socket network source of information
*/
public void enterLobby(Socket socket) {
startWrapper.setVisible(true);
try {
//Begin reading packets from the socket/server.
this.visualiserInput = new VisualiserInput(socket);
//Store a reference to latestMessages so that we can observe it.
LatestMessages latestMessages = this.visualiserInput.getLatestMessages();
latestMessages.addObserver(this);
new Thread(this.visualiserInput).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,40 @@
package visualiser.app;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import seng302.gameController.InputChecker;
public class App extends Application {
/**
* Entry point for running the programme
*
* @param args for starting the programme
*/
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) throws Exception {
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
Platform.exit();
System.exit(0);
}
});
FXMLLoader loader = new FXMLLoader(getClass().getResource("/visualiser/scenes/main.fxml"));
Parent root = loader.load();
Scene scene = new Scene(root, 1200, 800);
stage.setScene(scene);
stage.setTitle("RaceVision - Team 7");
stage.show();
}
}
@@ -0,0 +1,377 @@
package visualiser.app;
import javafx.application.Platform;
import network.BinaryMessageDecoder;
import network.Exceptions.InvalidMessageException;
import network.Messages.*;
import org.xml.sax.SAXException;
import shared.dataInput.BoatXMLReader;
import shared.dataInput.RaceXMLReader;
import shared.dataInput.RegattaXMLReader;
import shared.exceptions.InvalidBoatDataException;
import shared.exceptions.InvalidRaceDataException;
import shared.exceptions.InvalidRegattaDataException;
import shared.exceptions.XMLReaderException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static network.Utils.ByteConverter.bytesToShort;
/**
* TCP client which receives packets/messages from a race data source
* (e.g., mock source, official source), and exposes them to any observers.
*/
public class VisualiserInput implements Runnable {
/**
* Timestamp of the last heartbeat.
*/
private long lastHeartbeatTime = -1;
/**
* Sequence number of the last heartbeat.
*/
private long lastHeartbeatSequenceNum = -1;
/**
* The socket that we have connected to.
*/
private Socket connectionSocket;
/**
* InputStream (from the socket).
*/
private DataInputStream inStream;
/**
* An object containing the set of latest messages to write to.
* Every server frame, VisualiserInput reads messages from its inputStream, and write them to this.
*/
private LatestMessages latestMessages;
/**
* Ctor.
* @param socket Socket from which we will receive race data.
* @throws IOException If there is something wrong with the socket's input stream.
*/
public VisualiserInput(Socket socket) throws IOException {
this.connectionSocket = socket;
//We wrap a DataInputStream around the socket's InputStream because it has the stream.readFully(buffer) function, which is a blocking read until the buffer has been filled.
this.inStream = new DataInputStream(connectionSocket.getInputStream());
this.latestMessages = new LatestMessages();
this.lastHeartbeatTime = System.currentTimeMillis();
}
/**
* Returns the LatestMessages object, which can be queried for any received race related messages.
* @return The LatestMessages object.
*/
public LatestMessages getLatestMessages() {
return latestMessages;
}
/**
* Calculates the time since last heartbeat, in milliseconds.
* @return Time since last heartbeat, in milliseconds..
*/
private double timeSinceHeartbeat() {
long now = System.currentTimeMillis();
return (now - lastHeartbeatTime);
}
/**
* Reads and returns the next message as an array of bytes from the socket. Use getNextMessage() to get the actual message object instead.
* @return Encoded binary message bytes.
* @throws IOException Thrown when an error occurs while reading from the socket.
*/
private byte[] getNextMessageBytes() throws IOException {
inStream.mark(0);
short CRCLength = 4;
short headerLength = 15;
//Read the header of the next message.
byte[] headerBytes = new byte[headerLength];
inStream.readFully(headerBytes);
//Read the message body length.
byte[] messageBodyLengthBytes = Arrays.copyOfRange(headerBytes, headerLength - 2, headerLength);
short messageBodyLength = bytesToShort(messageBodyLengthBytes);
//Read the message body.
byte[] messageBodyBytes = new byte[messageBodyLength];
inStream.readFully(messageBodyBytes);
//Read the message CRC.
byte[] messageCRCBytes = new byte[CRCLength];
inStream.readFully(messageCRCBytes);
//Put the head + body + crc into one large array.
ByteBuffer messageBytes = ByteBuffer.allocate(headerBytes.length + messageBodyBytes.length + messageCRCBytes.length);
messageBytes.put(headerBytes);
messageBytes.put(messageBodyBytes);
messageBytes.put(messageCRCBytes);
return messageBytes.array();
}
/**
* Reads and returns the next message object from the socket.
* @return The message object. Use instanceof for concrete type.
* @throws IOException Thrown when an error occurs while reading from the socket.
* @throws InvalidMessageException Thrown when the message is invalid in some way.
*/
private AC35Data getNextMessage() throws IOException, InvalidMessageException
{
//Get the next message from the socket as a block of bytes.
byte[] messageBytes = this.getNextMessageBytes();
//Decode the binary message into an appropriate message object.
BinaryMessageDecoder decoder = new BinaryMessageDecoder(messageBytes);
return decoder.decode();
}
/**
* Main loop which reads messages from the socket, and exposes them.
*/
public void run(){
boolean receiverLoop = true;
//receiver loop that gets the input
while (receiverLoop) {
//If no heartbeat has been received in more the heartbeat period
//then the connection will need to be restarted.
//System.out.println("time since last heartbeat: " + timeSinceHeartbeat());//TEMP REMOVE
long heartBeatPeriod = 10 * 1000;
if (timeSinceHeartbeat() > heartBeatPeriod) {
System.out.println("Connection has stopped, trying to reconnect.");
//Attempt to reconnect the socket.
try {//This attempt doesn't really work. Under what circumstances would
this.connectionSocket = new Socket(this.connectionSocket.getInetAddress(), this.connectionSocket.getPort());
//this.connectionSocket.connect(this.connectionSocket.getRemoteSocketAddress());
//Reset the heartbeat timer.
this.lastHeartbeatTime = System.currentTimeMillis();
}
catch (IOException e) {
System.err.println("Unable to reconnect.");
//Wait 500ms. Ugly hack, should refactor.
long waitPeriod = 500;
long waitTimeStart = System.currentTimeMillis() + waitPeriod;
while (System.currentTimeMillis() < waitTimeStart){
//Nothing. Busyloop.
}
//Swallow the exception.
continue;
}
}
//Reads the next message.
AC35Data message;
try {
message = this.getNextMessage();
}
catch (InvalidMessageException | IOException e) {
//Prints exception to stderr, and iterate loop (that is, read the next message).
System.err.println("Unable to read message: " + e.getMessage());
try {
inStream.reset();
} catch (IOException e1) {
e1.printStackTrace();
}
//Continue to the next loop iteration/message.
continue;
}
//Checks which message is being received and does what is needed for that message.
switch (message.getType()) {
//Heartbeat.
case HEARTBEAT: {
Heartbeat heartbeat = (Heartbeat) message;
//Check that the heartbeat number is greater than the previous value, and then set the last heartbeat time.
if (heartbeat.getSequenceNumber() > this.lastHeartbeatSequenceNum) {
lastHeartbeatTime = System.currentTimeMillis();
lastHeartbeatSequenceNum = heartbeat.getSequenceNumber();
//System.out.println("HeartBeat Message! " + lastHeartbeatSequenceNum);
}
break;
}
//RaceStatus.
case RACESTATUS: {
RaceStatus raceStatus = (RaceStatus) message;
//System.out.println("Race Status Message");
this.latestMessages.setRaceStatus(raceStatus);
for (BoatStatus boatStatus : raceStatus.getBoatStatuses()) {
this.latestMessages.setBoatStatus(boatStatus);
}
break;
}
//DisplayTextMessage.
case DISPLAYTEXTMESSAGE: {
//System.out.println("Display Text Message");
//No decoder for this.
break;
}
//XMLMessage.
case XMLMESSAGE: {
XMLMessage xmlMessage = (XMLMessage) message;
//System.out.println("XML Message!");
this.latestMessages.setXMLMessage(xmlMessage);
break;
}
//RaceStartStatus.
case RACESTARTSTATUS: {
//System.out.println("Race Start Status Message");
break;
}
//YachtEventCode.
case YACHTEVENTCODE: {
//YachtEventCode yachtEventCode = (YachtEventCode) message;
//System.out.println("Yacht Event Code!");
//No decoder for this.
break;
}
//YachtActionCode.
case YACHTACTIONCODE: {
//YachtActionCode yachtActionCode = (YachtActionCode) message;
//System.out.println("Yacht Action Code!");
// No decoder for this.
break;
}
//ChatterText.
case CHATTERTEXT: {
//ChatterText chatterText = (ChatterText) message;
//System.out.println("Chatter Text Message!");
//No decoder for this.
break;
}
//BoatLocation.
case BOATLOCATION: {
BoatLocation boatLocation = (BoatLocation) message;
//System.out.println("Boat Location!");
BoatLocation existingBoatLocation = this.latestMessages.getBoatLocationMap().get(boatLocation.getSourceID());
if (existingBoatLocation != null) {
//If our boatlocation map already contains a boat location message for this boat, check that the new message is actually for a later timestamp (i.e., newer).
if (boatLocation.getTime() > existingBoatLocation.getTime()) {
//If it is, replace the old message.
this.latestMessages.setBoatLocation(boatLocation);
}
} else {
//If the map _doesn't_ already contain a message for this boat, insert the message.
this.latestMessages.setBoatLocation(boatLocation);
}
break;
}
//MarkRounding.
case MARKROUNDING: {
MarkRounding markRounding = (MarkRounding) message;
//System.out.println("Mark Rounding Message!");
MarkRounding existingMarkRounding = this.latestMessages.getMarkRoundingMap().get(markRounding.getSourceID());
if (existingMarkRounding != null) {
//If our markRoundingMap already contains a mark rounding message for this boat, check that the new message is actually for a later timestamp (i.e., newer).
if (markRounding.getTime() > existingMarkRounding.getTime()) {
//If it is, replace the old message.
this.latestMessages.setMarkRounding(markRounding);
}
} else {
//If the map _doesn't_ already contain a message for this boat, insert the message.
this.latestMessages.setMarkRounding(markRounding);
}
break;
}
//CourseWinds.
case COURSEWIND: {
//System.out.println("Course Wind Message!");
CourseWinds courseWinds = (CourseWinds) message;
this.latestMessages.setCourseWinds(courseWinds);
break;
}
//AverageWind.
case AVGWIND: {
//System.out.println("Average Wind Message!");
AverageWind averageWind = (AverageWind) message;
this.latestMessages.setAverageWind(averageWind);
break;
}
//Unrecognised message.
default: {
System.out.println("Broken Message!");
break;
}
}
}
}
}
@@ -0,0 +1,285 @@
package visualiser.model;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.scene.layout.AnchorPane;
import java.util.HashMap;
import java.util.Map;
/**
* Class that processes user selected annotation visibility options to
* display the requested information on the
* {@link ResizableRaceCanvas}. These are displayed
* via the {@link visualiser.Controllers.RaceController}. <br>
* Annotation options for a {@link VisualiserBoat} include: its name,
* abbreviation, speed, the time since it passed the last
* {@link shared.model.Mark}, estimated time to the next marker,
* and a path it has travelled made up of
* {@link TrackPoint}s.
*/
public class Annotations {
private ResizableRaceCanvas raceMap;
// checkable objects in the anchor pane
private Map<String, CheckBox> checkBoxes = new HashMap<>();
private Map<String, Toggle> annoToggles = new HashMap<>();
// maps of selected and saved annotations
private Map<String, Boolean> importantAnno = new HashMap<>();
private Map<String, Boolean> annoShownBeforeHide = new HashMap<>();
// string values match the fx:id value of check boxes
private static String nameCheckAnno = "showName";
private static String abbrevCheckAnno = "showAbbrev";
private static String speedCheckAnno = "showSpeed";
private static String pathCheckAnno = "showBoatPath";
private static String timeCheckAnno = "showTime";
private static String estTimeCheckAnno = "showEstTime";
// string values match the fx:id value of radio buttons
private static String noBtn = "noBtn";
private static String hideBtn = "hideAnnoRBtn";
private static String showBtn = "showAnnoRBtn";
private static String partialBtn = "partialAnnoRBtn";
private static String importantBtn = "importantAnnoRBtn";
private Boolean selectShow = false;
private String buttonChecked;
private String prevBtnChecked;
@FXML Button saveAnnoBtn;
/**
* Constructor to set up and display initial annotations
* @param annotationPane javaFX pane containing annotation options
* @param raceMap the canvas to update annotation displays
*/
public Annotations(AnchorPane annotationPane, ResizableRaceCanvas raceMap){
this.raceMap = raceMap;
for (Node child : annotationPane.getChildren()) {
// collect all check boxes into a map
if (child.getClass()==CheckBox.class){
checkBoxes.put(child.getId(), (CheckBox)child);
}
// collect annotation toggle radio buttons into a map
else if (child.getClass()== RadioButton.class){
//annotationGroup.getToggles().add((RadioButton)child);
annoToggles.put(child.getId(), (RadioButton)child);
}
else if (child.getClass() == Button.class){
saveAnnoBtn = (Button)child;
}
}
initializeAnnotations();
}
/**
* Set up initial boat annotations and shows all data.
* Defines partial annotations.
* Creates listeners for when the user selects a different annotation
* visibility.
*/
public void initializeAnnotations() {
for (Map.Entry<String, CheckBox> checkBox : checkBoxes.entrySet())
{ annoShownBeforeHide.put(checkBox.getKey(), true); }
addCheckBoxListeners();
addSaveAnnoListener();
addAnnoToggleListeners();
annoToggles.get(showBtn).setSelected(true);
}
/**
* Creates listeners for each checkbox so the annotation display is
* updated when a user selects a different level of annotation visibility.
*/
private void addCheckBoxListeners(){
//listener for show name in annotation
checkBoxes.get(nameCheckAnno).selectedProperty()
.addListener((ov, old_val, new_val) -> {
if (old_val != new_val) {
raceMap.toggleAnnoName();
storeCurrentAnnotationState(nameCheckAnno, new_val);
raceMap.draw();
}
});
//listener for show abbreviation for annotation
checkBoxes.get(abbrevCheckAnno).selectedProperty()
.addListener((ov, old_val, new_val) -> {
if (old_val != new_val) {
raceMap.toggleAnnoAbbrev();
storeCurrentAnnotationState(abbrevCheckAnno, new_val);
raceMap.draw();
}
});
//listener for show boat path for annotation
checkBoxes.get(pathCheckAnno).selectedProperty()
.addListener((ov, old_val, new_val) -> {
if (old_val != new_val) {
raceMap.toggleBoatPath();
storeCurrentAnnotationState(pathCheckAnno, new_val);
raceMap.draw();
}
});
//listener to show speed for annotation
checkBoxes.get(speedCheckAnno).selectedProperty()
.addListener((ov, old_val, new_val) -> {
if (old_val != new_val) {
raceMap.toggleAnnoSpeed();
storeCurrentAnnotationState(speedCheckAnno, new_val);
raceMap.draw();
}
});
//listener to show time for annotation
checkBoxes.get(timeCheckAnno).selectedProperty()
.addListener((ov, old_val, new_val) -> {
if (old_val != new_val) {
raceMap.toggleAnnoTime();
storeCurrentAnnotationState(timeCheckAnno, new_val);
raceMap.draw();
}
});
//listener to show estimated time for annotation
checkBoxes.get(estTimeCheckAnno).selectedProperty()
.addListener((ov, old_val, new_val) -> {
if (old_val != new_val) {
raceMap.toggleAnnoEstTime();
storeCurrentAnnotationState(estTimeCheckAnno, new_val);
raceMap.draw();
}
});
}
/**
* Creates a listener so the system knows when to save a users currently
* selected annotation options as important for future use.
*/
private void addSaveAnnoListener(){
//listener to save currently selected annotations as important
saveAnnoBtn.setOnAction(event -> {
importantAnno.clear();
for (Map.Entry<String, CheckBox> checkBox : checkBoxes.entrySet()){
importantAnno.put(checkBox.getKey(),
checkBox.getValue().isSelected());
}
});
}
/**
* Creates listeners for each visibility option so that the annotation
* display is updated when a user selects a different level of annotation
* visibility.
*/
private void addAnnoToggleListeners(){
//listener for hiding all annotations
RadioButton hideAnnoRBtn = (RadioButton)annoToggles.get(hideBtn);
hideAnnoRBtn.setOnAction((e)->{
buttonChecked = hideBtn;
selectShow = false;
for (Map.Entry<String, CheckBox> checkBox : checkBoxes.entrySet()){
checkBox.getValue().setSelected(false);
}
raceMap.draw();
buttonChecked = noBtn;
prevBtnChecked = hideBtn;
selectShow = true;
});
//listener for showing previously visible annotations
RadioButton showAnnoRBTN = (RadioButton)annoToggles.get(showBtn);
showAnnoRBTN.setOnAction((e)->{
if (selectShow) {
buttonChecked = showBtn;
for (Map.Entry<String, CheckBox> checkBox : checkBoxes.entrySet()){
checkBox.getValue().setSelected(
annoShownBeforeHide.get(checkBox.getKey()));
}
raceMap.draw();
buttonChecked = noBtn;
prevBtnChecked = showBtn;
}
selectShow = true;
});
//listener for showing a predetermined subset of annotations
RadioButton partialAnnoRBTN = (RadioButton)annoToggles.get(partialBtn);
partialAnnoRBTN.setOnAction((e)->{
selectShow = false;
buttonChecked = partialBtn;
for (Map.Entry<String, CheckBox> checkBox : checkBoxes.entrySet()){
// the checkbox defaults for partial annotations
if (checkBox.getKey().equals(abbrevCheckAnno)
|| checkBox.getKey().equals(speedCheckAnno)){
checkBox.getValue().setSelected(true);
}
else { checkBox.getValue().setSelected(false); }
}
raceMap.draw();
buttonChecked = noBtn;
prevBtnChecked = partialBtn;
selectShow = true;
});
//listener for showing all saved important annotations
RadioButton importantAnnoRBTN = (RadioButton)annoToggles.get(importantBtn);
importantAnnoRBTN.setOnAction((e) ->{
selectShow = false;
buttonChecked = importantBtn;
if (importantAnno.size()>0){
for (Map.Entry<String, CheckBox> checkBox : checkBoxes.entrySet()){
checkBox.getValue().setSelected
(importantAnno.get(checkBox.getKey()));
}
}
raceMap.draw();
buttonChecked = noBtn;
prevBtnChecked = importantBtn;
selectShow = true;
});
}
/**
* Updates the current state of an annotation so that when a user
* deselects the hidden visibility option, the previous annotations will
* be displayed again.
* @param dictionaryAnnotationKey annotation checkbox
* @param selected boolean value representing the state of the checkbox
*/
private void storeCurrentAnnotationState(String dictionaryAnnotationKey, boolean selected){
if (buttonChecked != hideBtn) {
//if we are checking the box straight out of hide instead of using the radio buttons
annoShownBeforeHide.put(dictionaryAnnotationKey, selected);
if (prevBtnChecked == hideBtn && buttonChecked == noBtn){
storeCurrentAnnotationDictionary();
}
if (buttonChecked == noBtn) {
selectShow = false;
annoToggles.get(showBtn).setSelected(true);
}
}
}
/**
* Stores all current annotation states so that when a user
* deselects the hidden visibility option, the previous annotations will
* be displayed again.
*/
private void storeCurrentAnnotationDictionary(){
for (Map.Entry<String, CheckBox> checkBox : checkBoxes.entrySet()){
annoShownBeforeHide.put(checkBox.getKey(),
checkBox.getValue().isSelected());
}
}
}
@@ -0,0 +1,49 @@
package visualiser.model;
/**
* It is a coordinate representing a location
* resizable race canvas
*/
public class GraphCoordinate {
/**
* X (horizontal) coordinate.
*/
private final int x;
/**
* Y (vertical) coordinate.
*/
private final int y;
/**
* Constructor method.
*
* @param x X coordinate.
* @param y Y coordinate.
*/
public GraphCoordinate(int x, int y) {
this.x = x;
this.y = y;
}
/**
* Returns the X coordinate.
*
* @return x axis Coordinate.
*/
public int getX() {
return x;
}
/**
* Returns the Y coordinate.
*
* @return y axis Coordinate.
*/
public int getY() {
return y;
}
}
@@ -0,0 +1,58 @@
package visualiser.model;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* Created by cbt24 on 3/05/17.
*/
public class RaceConnection {
private final StringProperty hostname;
private final int port;
private final StringProperty status;
public RaceConnection(String hostname, int port) {
this.hostname = new SimpleStringProperty(hostname);
this.port = port;
this.status = new SimpleStringProperty("");
check();
}
/**
* Tries to create a socket to hostname and port, indicates status after test.
* @return true if socket can connect
*/
@SuppressWarnings("unused")
public boolean check() {
//TODO the connection needs to be moved to its own thread, so it doesn't block fx thread.
InetSocketAddress i = new InetSocketAddress(hostname.get(), port);
try (Socket s = new Socket()){
s.connect(i, 750);//TODO this should be at least a second or two, once moved to its own thread
status.set("Ready");
return true;
} catch (IOException e) {}
status.set("Offline");
return false;
}
public String getHostname() {
return hostname.get();
}
public StringProperty hostnameProperty() {
return hostname;
}
public int getPort() {
return port;
}
public StringProperty statusProperty() {
return status;
}
}
@@ -0,0 +1,146 @@
package visualiser.model;
import shared.model.GPSCoordinate;
/**
* The base size of the map to be used for the
* resizable race map
*/
public class RaceMap {
/**
* The longitude of the left side of the map.
*/
private final double longLeft;
/**
* The longitude of the right side of the map.
*/
private final double longRight;
/**
* The latitude of the top side of the map.
*/
private final double latTop;
/**
* The latitude of the bottom side of the map.
*/
private final double latBottom;
/**
* The width, in pixels, of the map.
*/
private int width;
/**
* The height, in pixels, of the map.
*/
private int height;
/**
* Constructor Method.
*
* @param latTop Latitude of the top left point.
* @param longLeft Longitude of the top left point.
* @param latBottom Latitude of the top right point.
* @param longRight Longitude of the top right point.
* @param width width that the Canvas the race is to be drawn on is.
* @param height height that the Canvas the race is to be drawn on is.
*/
public RaceMap(double latTop, double longLeft, double latBottom, double longRight, int width, int height) {
//Long/lat edges.
this.longLeft = longLeft;
this.longRight = longRight;
this.latTop = latTop;
this.latBottom = latBottom;
//Pixel sizes.
this.width = width;
this.height = height;
}
/**
* Converts GPS coordinates to coordinates for container.
* It is assumed that the provided GPSCoordinate will always be within the GPSCoordinate boundaries of the RaceMap.
*
* @param lat GPS latitude
* @param lon GPS longitude
* @return GraphCoordinate (pair of doubles)
* @see GraphCoordinate
*/
private GraphCoordinate convertGPS(double lat, double lon) {
//Calculate the width/height, in gps coordinates, of the map.
double longWidth = longRight - longLeft;
double latHeight = latBottom - latTop;
//Calculate the distance between the specified coordinate and the edge of the map.
double longDelta = lon - longLeft;
double latDelta = lat - latTop;
//Calculate the proportion along horizontally, from the left, the coordinate should be.
double longProportion = longDelta / longWidth;
//Calculate the proportion along vertically, from the top, the coordinate should be.
double latProportion = latDelta / latHeight;
//Check which pixel dimension of our map is smaller. We use this to ensure that any rendered stuff retains its correct aspect ratio, and that everything is visible on screen.
int smallerDimension = Math.min(width, height);
//Calculate the x and y pixel coordinates.
//We take the complement of latProportion to flip it.
int x = (int) (longProportion * smallerDimension);
int y = (int) ((1 - latProportion) * smallerDimension);
//Because we try to maintain the correct aspect ratio, we will end up with "spare" pixels along the larger dimension (e.g., width 800, height 600, 200 extra pixels along width).
int extraPixels = Math.abs(width - height);
//We therefore "center" the coordinates along this larger dimension, by adding half of the extra pixels.
if (width > height) {
x += extraPixels / 2;
} else {
y += extraPixels / 2;
}
//Finally, create the GraphCoordinate.
GraphCoordinate graphCoordinate = new GraphCoordinate(x, y);
return graphCoordinate;
}
/**
* Converts the GPS Coordinate to GraphCoordinate.
* It is assumed that the provided GPSCoordinate will always be within the GPSCoordinate boundaries of the RaceMap.
*
* @param coordinate GPSCoordinate representation of Latitude and Longitude.
* @return GraphCoordinate that the GPS is coordinates are to be displayed on the map.
* @see GraphCoordinate
* @see GPSCoordinate
*/
public GraphCoordinate convertGPS(GPSCoordinate coordinate) {
return convertGPS(coordinate.getLatitude(), coordinate.getLongitude());
}
/**
* Sets the width, in pixels, of our RaceMap.
* @param width The new width, in pixels, of the RaceMap.
*/
public void setWidth(int width) {
this.width = width;
}
/**
* Sets the height, in pixels, of our RaceMap.
* @param height The new height, in pixels, of the RaceMap.
*/
public void setHeight(int height) {
this.height = height;
}
}
@@ -0,0 +1,53 @@
package visualiser.model;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
/**
* The abstract class for the resizable race canvases.
*/
public abstract class ResizableCanvas extends Canvas {
/**
* The {@link GraphicsContext} to draw to.
*/
protected final GraphicsContext gc;
/**
* Ctor.
*/
public ResizableCanvas(){
this.gc = this.getGraphicsContext2D();
// Redraw canvas when size changes.
widthProperty().addListener(evt -> draw());
heightProperty().addListener(evt -> draw());
}
/**
* Draws desired contents onto the canvas.
* Subclasses implement this to decide what to draw.
*/
public abstract void draw();
@Override
public boolean isResizable() {
return true;
}
@Override
public double prefWidth(double width) {
return getWidth();
}
@Override
public double prefHeight(double height) {
return getHeight();
}
}
@@ -0,0 +1,560 @@
package visualiser.model;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.transform.Rotate;
import network.Messages.Enums.BoatStatusEnum;
import shared.dataInput.RaceDataSource;
import shared.model.GPSCoordinate;
import shared.model.Mark;
import shared.model.RaceClock;
import java.time.Duration;
import java.util.List;
/**
* This JavaFX Canvas is used to update and display details for a
* {@link RaceMap} via the
* {@link visualiser.Controllers.RaceController}.<br>
* It fills it's parent and cannot be downsized. <br>
* Details displayed include:
* {@link VisualiserBoat}s (and their
* {@link TrackPoint}s),
* {@link shared.model.Mark}s, a
* {@link RaceClock}, a wind direction arrow and
* various user selected {@link Annotations}.
*/
public class ResizableRaceCanvas extends ResizableCanvas {
/**
* The RaceMap used for converting GPSCoordinates to GraphCoordinates.
*/
private RaceMap map;
/**
* The race we read data from and draw.
*/
private VisualiserRace visualiserRace;
/**
* The background of the race.
* We render the background whenever the race boundary changes, or the screen size changes.
*/
private Image background;
private boolean annoName = true;
private boolean annoAbbrev = true;
private boolean annoSpeed = true;
private boolean annoPath = true;
private boolean annoEstTime = true;
private boolean annoTimeSinceLastMark = true;
/**
* The wind arrow node.
*/
private Node arrow;
/**
* Constructs a {@link ResizableRaceCanvas} using a given {@link VisualiserRace}.
* @param visualiserRace The race that data is read from in order to be drawn.
* @param arrow The wind arrow's node.
*/
public ResizableRaceCanvas(VisualiserRace visualiserRace, Node arrow) {
super();
this.visualiserRace = visualiserRace;
this.arrow = arrow;
RaceDataSource raceData = visualiserRace.getRaceDataSource();
double lat1 = raceData.getMapTopLeft().getLatitude();
double long1 = raceData.getMapTopLeft().getLongitude();
double lat2 = raceData.getMapBottomRight().getLatitude();
double long2 = raceData.getMapBottomRight().getLongitude();
this.map = new RaceMap(
lat1, long1, lat2, long2,
(int) getWidth(), (int) getHeight() );
}
/**
* Toggle name display in annotation
*/
public void toggleAnnoName() {
annoName = !annoName;
}
/**
* Toggle boat path display in annotation
*/
public void toggleBoatPath() {
annoPath = !annoPath;
}
public void toggleAnnoEstTime() {
annoEstTime = !annoEstTime;
}
/**
* Toggle boat time display in annotation
*/
public void toggleAnnoTime() {
annoTimeSinceLastMark = !annoTimeSinceLastMark;
}
/**
* Toggle abbreviation display in annotation
*/
public void toggleAnnoAbbrev() {
annoAbbrev = !annoAbbrev;
}
/**
* Toggle speed display in annotation
*/
public void toggleAnnoSpeed() {
annoSpeed = !annoSpeed;
}
/**
* Rotates things on the canvas Note: this must be called in between gc.save() and gc.restore() else they will rotate everything
*
* @param degrees Bearing degrees to rotate.
* @param px Pivot point x of rotation.
* @param py Pivot point y of rotation.
*/
private void rotate(double degrees, double px, double py) {
Rotate r = new Rotate(degrees, px, py);
gc.setTransform(r.getMxx(), r.getMyx(), r.getMxy(), r.getMyy(), r.getTx(), r.getTy());
}
/**
* Draws a circle with a given diameter, centred on a given graph coordinate.
* @param center The center coordinate of the circle.
* @param diameter The diameter of the circle.
*/
private void drawCircle(GraphCoordinate center, double diameter) {
//The graphCoordinates are for the center of the point, so we offset them to get the corner coordinate.
gc.fillOval(
center.getX() - (diameter / 2),
center.getY() - (diameter / 2),
diameter, diameter );
}
/**
* Displays a line on the map with rectangles on the starting and ending point of the line.
*
* @param graphCoordinateA Starting Point of the line in GraphCoordinate.
* @param graphCoordinateB End Point of the line in GraphCoordinate.
* @param paint Colour the line is to coloured.
*/
private void drawLine(GraphCoordinate graphCoordinateA, GraphCoordinate graphCoordinateB, Paint paint) {
gc.setStroke(paint);
gc.setFill(paint);
double endPointDiameter = 6;
//Draw first end-point.
drawCircle(graphCoordinateA, endPointDiameter);
//Draw second end-point.
drawCircle(graphCoordinateB, endPointDiameter);
//Draw line between them.
gc.strokeLine(
graphCoordinateA.getX(),
graphCoordinateA.getY(),
graphCoordinateB.getX(),
graphCoordinateB.getY() );
}
/**
* Display a point on the Canvas. It has a diameter of 10 pixels.
*
* @param graphCoordinate Coordinate that the point is to be displayed at.
* @param paint Paint to use for the point.
*/
private void drawPoint(GraphCoordinate graphCoordinate, Paint paint) {
//Set paint.
gc.setFill(paint);
double pointDiameter = 10;
//Draw the point.
drawCircle(graphCoordinate, pointDiameter);
}
/**
* Display given name and speed of boat at a graph coordinate
*
* @param name name of the boat
* @param abbrev abbreviation of the boat name
* @param speed speed of the boat
* @param coordinate coordinate the text appears
* @param timeToNextMark The time until the boat reaches the next mark.
* @param timeSinceLastMark The time since the boat passed the last mark.
*/
private void drawText(String name, String abbrev, double speed, GraphCoordinate coordinate, String timeToNextMark, String timeSinceLastMark) {
//The text to draw. Built during the function.
String text = "";
//Draw name if annotation is enabled.
if (annoName) {
text += String.format("%s ", name);
}
//Draw abbreviation/country if annotation is enabled.
if (annoAbbrev) {
text += String.format("%s ", abbrev);
}
//Draw speed if annotation is enabled.
if (annoSpeed){
text += String.format("%.2fkn ", speed);
}
//Draw time to reach next mark if annotation is enabled.
if (annoEstTime) {
text += timeToNextMark;
}
//Draw time since last mark if annotation is enabled.
if(annoTimeSinceLastMark) {
text += timeSinceLastMark;
}
//Offset by 20 pixels horizontally.
long xCoord = coordinate.getX() + 20;
long yCoord = coordinate.getY();
//If the text would extend out of the canvas (to the right), move it left.
if (xCoord + (text.length() * 7) >= getWidth()) {
xCoord -= text.length() * 7;
}
if (yCoord - (text.length() * 2) <= 0) {
yCoord += 30;
}
//Draw text.
gc.fillText(text, xCoord, yCoord);
}
/**
* Draws the label for a given boat. Includes name, abbreviation, speed, time since mark, and time to next mark.
* @param boat The boat to draw text for.
*/
private void drawBoatText(VisualiserBoat boat) {
drawText(
boat.getName(),
boat.getCountry(),
boat.getCurrentSpeed(),
this.map.convertGPS(boat.getCurrentPosition()),
boat.getTimeToNextMarkFormatted(this.visualiserRace.getRaceClock().getCurrentTime()),
boat.getTimeSinceLastMarkFormatted(this.visualiserRace.getRaceClock().getCurrentTime()) );
}
/**
* Draws all of the boats on the canvas.
*/
private void drawBoats() {
for (VisualiserBoat boat : visualiserRace.getBoats()) {
//Draw the boat.
drawBoat(boat);
//Only draw wake if they are currently racing.
if (boat.getStatus() == BoatStatusEnum.RACING) {
drawWake(boat);
}
//If the race hasn't started, we set the time since last mark to the current time, to ensure we don't start counting until the race actually starts.
if ((boat.getStatus() != BoatStatusEnum.RACING) && (boat.getStatus() == BoatStatusEnum.FINISHED)) {
boat.setTimeAtLastMark(visualiserRace.getRaceClock().getCurrentTime());
}
//Draw boat label.
drawBoatText(boat);
//Draw track.
drawTrack(boat);
}
}
/**
* Draws a given boat on the canvas.
* @param boat The boat to draw.
*/
private void drawBoat(VisualiserBoat boat) {
//The position may be null if we haven't received any BoatLocation messages yet.
if (boat.getCurrentPosition() != null) {
//Convert position to graph coordinate.
GraphCoordinate pos = this.map.convertGPS(boat.getCurrentPosition());
//The x coordinates of each vertex of the boat.
double[] x = {
pos.getX() - 6,
pos.getX(),
pos.getX() + 6 };
//The y coordinates of each vertex of the boat.
double[] y = {
pos.getY() + 12,
pos.getY() - 12,
pos.getY() + 12 };
//The above shape is essentially a triangle 12px wide, and 24px long.
//Draw the boat.
gc.setFill(boat.getColor());
gc.save();
rotate(boat.getBearing().degrees(), pos.getX(), pos.getY());
gc.fillPolygon(x, y, 3);
gc.restore();
}
}
/**
* Draws the wake for a given boat.
* @param boat Boat to draw wake for.
*/
private void drawWake(VisualiserBoat boat) {
//Calculate either end of wake line.
GraphCoordinate wakeFrom = this.map.convertGPS(boat.getCurrentPosition());
GraphCoordinate wakeTo = this.map.convertGPS(boat.getWake());
//Draw.
drawLine(wakeFrom, wakeTo, boat.getColor());
}
/**
* Displays an arrow representing wind direction on the Canvas.
* This function accepts a wind-to bearing, but displays a wind-from bearing.
*
* @param angle Angle that the arrow is to be facing in degrees 0 degrees = North (Up).
* @see GraphCoordinate
*/
private void displayWindArrow(double angle) {
//We need to display wind-from, so add 180 degrees.
angle += 180d;
//Get it within [0, 360).
while (angle >= 360d) {
angle -= 360d;
}
//Rotate the wind arrow.
if (arrow != null && arrow.getRotate() != angle) {
arrow.setRotate(angle);
}
}
/**
* Draws all of the {@link Mark}s on the canvas.
*/
private void drawMarks() {
for (Mark mark : this.visualiserRace.getMarks()) {
drawMark(mark);
}
}
/**
* Draws a given mark on the canvas.
* @param mark The mark to draw.
*/
private void drawMark(Mark mark) {
//Calculate screen position.
GraphCoordinate mark1 = this.map.convertGPS(mark.getPosition());
//Draw.
drawPoint(mark1, Color.LIMEGREEN);
}
/**
* Draws the Race Map.
* Called when the canvas is resized.
*/
public void draw() {
//Clear canvas.
clear();
//Update our RaceMap using new canvas size.
this.map.setWidth((int) getWidth());
this.map.setHeight((int) getHeight());
//Redraw the boundary.
redrawBoundaryImage();
//Draw the race.
drawRace();
}
/**
* Clears the canvas.
*/
private void clear() {
gc.clearRect(0, 0, getWidth(), getHeight());
}
/**
* Draws the race boundary, and saves the image to {@link #background}.
* You should call {@link #clear()} before calling this.
*/
private void redrawBoundaryImage() {
//Prepare to draw.
gc.setLineWidth(1);
gc.setFill(Color.AQUA);
//Calculate the screen coordinates of the boundary.
List<GPSCoordinate> boundary = this.visualiserRace.getBoundary();
double[] xpoints = new double[boundary.size()];
double[] ypoints = new double[boundary.size()];
//For each boundary coordinate.
for (int i = 0; i < boundary.size(); i++) {
//Convert.
GraphCoordinate coord = map.convertGPS(boundary.get(i));
//Use.
xpoints[i] = coord.getX();
ypoints[i] = coord.getY();
}
//Draw the boundary.
gc.fillPolygon(xpoints, ypoints, xpoints.length);
//Render boundary to image.
this.background = snapshot(null, null);
}
/**
* Draws the race.
* Called once per frame, and on canvas resize.
*/
public void drawRace() {
gc.setLineWidth(2);
clear();
//Race boundary.
drawBoundary();
//Boats.
drawBoats();
//Marks.
drawMarks();
//Wind arrow. This rotates the wind arrow node.
displayWindArrow(this.visualiserRace.getWindDirection().degrees());
}
/**
* Draws the race boundary image onto the canvas.
* See {@link #background}.
*/
private void drawBoundary() {
gc.drawImage(this.background, 0, 0);
}
/**
* Draws all track points for a given boat. Colour is set by boat, opacity by track point.
* This checks if {@link #annoPath} is enabled.
* @param boat The boat to draw tracks for.
* @see TrackPoint
*/
private void drawTrack(VisualiserBoat boat) {
//Check that track points are enabled.
if (this.annoPath) {
//Apply the boat color.
gc.setFill(boat.getColor());
//Draw each TrackPoint.
for (TrackPoint point : boat.getTrack()) {
//Convert the GPSCoordinate to a screen coordinate.
GraphCoordinate scaledCoordinate = this.map.convertGPS(point.getCoordinate());
//Draw a circle for the trackpoint.
gc.fillOval(scaledCoordinate.getX(), scaledCoordinate.getY(), point.getDiameter(), point.getDiameter());
}
}
}
}
@@ -0,0 +1,185 @@
package visualiser.model;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.paint.Color;
import java.util.List;
/**
* Class to process and modify a sparkline display. This display keeps visual
* track of {@link VisualiserBoat}s in a race and their current
* placing position as they complete each {@link shared.model.Leg} by
* passing a course {@link shared.model.Mark}. <br>
* This sparkline is displayed using the
* {@link visualiser.Controllers.RaceController}.
*/
public class Sparkline {
/**
* The race to observe.
*/
private VisualiserRace race;
/**
* The boats to observe.
*/
private ObservableList<VisualiserBoat> boats;
/**
* The number of legs in the race.
* Used to correctly scale the linechart.
*/
private Integer legNum;
/**
* The linchart to plot sparklines on.
*/
private LineChart<Number, Number> sparklineChart;
/**
* The x axis of the sparkline chart.
*/
private NumberAxis xAxis;
/**
* The y axis of the sparkline chart.
*/
private NumberAxis yAxis;
/**
* Constructor to set up initial sparkline (LineChart) object
* @param race The race to listen to.
* @param sparklineChart JavaFX LineChart for the sparkline.
*/
public Sparkline(VisualiserRace race, LineChart<Number,Number> sparklineChart) {
this.race = race;
this.boats = race.getBoats();
this.legNum = race.getLegCount();
this.sparklineChart = sparklineChart;
this.yAxis = (NumberAxis) sparklineChart.getYAxis();
this.xAxis = (NumberAxis) sparklineChart.getXAxis();
createSparkline();
}
/**
* Creates and sets initial display for Sparkline for race positions.
* A data series for each boat in the race is added.
* Position numbers are displayed.
*/
private void createSparkline() {
// NOTE: Y axis is in negatives to display correct positions
//For each boat...
for (VisualiserBoat boat : this.boats) {
//Create data series for each boat.
XYChart.Series<Number, Number> series = new XYChart.Series<>();
//All boats start in "last" place.
series.getData().add(new XYChart.Data<>(0, boats.size()));
//Listen for changes in the boat's leg - we only update the graph when it changes leg.
boat.legProperty().addListener(
(observable, oldValue, newValue) -> {
//Get the data to plot.
List<VisualiserBoat> boatOrder = race.getLegCompletionOrder().get(oldValue);
//Find boat position in list.
int boatPosition = boatOrder.indexOf(boat) + 1;
//Get leg number.
int legNumber = oldValue.getLegNumber() + 1;
//Create new data point for boat's position at the new leg.
XYChart.Data<Number, Number> dataPoint = new XYChart.Data<>(legNumber, boatPosition);
//Add to series.
Platform.runLater(() -> series.getData().add(dataPoint));
});
//Add to chart.
sparklineChart.getData().add(series);
//Color using boat's color. We need to do this after adding the series to a chart, otherwise we get null pointer exceptions.
series.getNode().setStyle("-fx-stroke: " + colourToHex(boat.getColor()) + ";");
}
sparklineChart.setCreateSymbols(false);
//Set x axis details
xAxis.setAutoRanging(false);
xAxis.setTickMarkVisible(false);
xAxis.setTickLabelsVisible(false);
xAxis.setMinorTickVisible(false);
xAxis.setLowerBound(0);
xAxis.setUpperBound(legNum + 2);
xAxis.setTickUnit(1);
//Set y axis details
yAxis.setLowerBound(boats.size() + 1);
yAxis.setUpperBound(0);
yAxis.setAutoRanging(false);
yAxis.setLabel("Position in Race");
yAxis.setTickUnit(-1);//Negative tick reverses the y axis.
yAxis.setTickMarkVisible(true);
yAxis.setTickLabelsVisible(true);
yAxis.setTickMarkVisible(true);
yAxis.setMinorTickVisible(true);
/* TODO FIX currently this doesn't work - I broke it :(
TODO only 0 and 7 get passed in to it for some reason
//Hide minus number from displaying on y axis.
yAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(yAxis) {
@Override
public String toString(Number value) {
//We only label the values between [1,boats.size()].
System.out.print("y axis: " + value.doubleValue());//TEMP remove
if ((value.doubleValue() >= 1)
&& (value.doubleValue() <= boats.size())) {
System.out.println(" is good");//TEMP
return String.format("%7.0f", value.doubleValue());
} else {
System.out.println(" is bad");//TEMP
return "";
}
}
});
*/
}
/**
* Converts a color to a hex string, starting with a {@literal #} symbol.
* @param color The color to convert.
* @return Hex string of the color (e.g., {@literal "#11AB4C"}).
*/
private static String colourToHex(Color color) {
return String.format( "#%02X%02X%02X",
(int)( color.getRed() * 255 ),
(int)( color.getGreen() * 255 ),
(int)( color.getBlue() * 255 ) );
}
}
@@ -0,0 +1,108 @@
package visualiser.model;
import shared.model.GPSCoordinate;
/**
* A TrackPoint is a point plotted to display the track a
* {@link VisualiserBoat Boat} has travelled in a race. <br>
* TrackPoints are displayed on a
* {@link ResizableRaceCanvas}, via the
* {@link visualiser.Controllers.RaceController}. <br>
* Track points can be made visible or hidden via the RaceController's
* {@link Annotations}.
*/
public class TrackPoint {
/**
* The {@link GPSCoordinate} this {@link TrackPoint} corresponds to.
*/
private final GPSCoordinate coordinate;
/**
* The time the track point was created at, in milliseconds since unix epoch.
*/
private final long timeAdded;
/**
* The period of time, in milliseconds, over which the track point's alpha should diminish to a floor value of {@link #minAlpha}.
*/
private final long expiry;
/**
* The minimum alpha to draw the track point with.
*/
private final double minAlpha;
/**
* The diameter to draw the track point with.
*/
private final double diameter;
/**
* Creates a new track point with fixed GPS coordinates and time, to reach minimum opacity on expiry.
*
* @param coordinate position of point on physical race map
* @param timeAdded system clock at time of addition
* @param expiry time to minimum opacity after added
*/
public TrackPoint(GPSCoordinate coordinate, long timeAdded, long expiry) {
this.coordinate = coordinate;
this.timeAdded = timeAdded;
this.expiry = expiry;
this.minAlpha = 0.1;
this.diameter = 5d;
}
/**
* Gets the position of the point on physical race map.
*
* @return GPS coordinate of point
*/
public GPSCoordinate getCoordinate() {
return coordinate;
}
/**
* Gets opacity of point scaled by age in proportion to expiry, between 1 and minimum opacity inclusive.
*
* @return Greater of minimum opacity and scaled opacity.
*/
public double getAlpha() {
//Calculate how much the alpha should be attenuated by elapsed time.
//Elapsed time.
long elapsedTime = System.currentTimeMillis() - this.timeAdded;
//Proportion of expiry period that has elapsed. (E.g., 2.5 means that 5 times the period has elapsed.)
double elapsedProportion = ((double) elapsedTime) / this.expiry;
//As the alpha diminishes from 1 down to a floor, we take the complement of this value. This may be negative.
double calculatedAlpha = 1.0 - elapsedProportion;
//We then take the max of the minAlpha and calculatedAlpha so that it doesn't go past our floor value.
return Double.max(this.minAlpha, calculatedAlpha);
}
/**
* Gets time point was added to track.
*
* @return system clock at time of addition
*/
public long getTimeAdded() {
return timeAdded;
}
/**
* Returns the diameter to draw the track point with.
* @return The diameter to draw the track point with.
*/
public double getDiameter() {
return diameter;
}
}
@@ -0,0 +1,217 @@
package visualiser.model;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.paint.Color;
import network.Messages.Enums.BoatStatusEnum;
import shared.model.Azimuth;
import shared.model.Boat;
import shared.model.Constants;
import shared.model.GPSCoordinate;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a Boat on the visualiser side of a race.
* This adds visualiser specific functionality to a boat.
* This class is used to represent and store information about a boat which may
* travel around in a race. It is displayed on the
* {@link ResizableRaceCanvas ResizableRaceCanvas} via the
* {@link visualiser.Controllers.RaceController RaceController}.
*/
public class VisualiserBoat extends Boat {
/**
* The collection of trackpoints generated for the boat.
*/
private final List<TrackPoint> track = new ArrayList<>();
/**
* The next time, in milliseconds since unix epoch, at which we may create a new track point.
*/
private long nextValidTime = 0;
/**
* The minimum period of time, in milliseconds, between the creation of each track point.
*/
private static final long trackPointTimeInterval = 5000;
/**
* The number of track points that should be created before fully diminishing the alpha of a given track point.
*/
private static final int trackPointLimit = 10;
/**
* The boat's color.
*/
private Color color;
/**
* Scalar used to scale the boat's wake.
*/
private static final double wakeScale = 5;
/**
* Constructs a boat object from a given boat and color.
*
* @param boat The boat to convert into a MockBoat.
* @param color The color of the boat.
*/
public VisualiserBoat(Boat boat, Color color) {
super(boat.getSourceID(), boat.getName(), boat.getCountry());
this.color = color;
}
/**
* Returns the position of the end of the boat's wake, which is 180 degrees
* from the boat's heading, and whose length is proportional to the boat's
* speed.
*
* @return GPSCoordinate of wake endpoint.
*/
public GPSCoordinate getWake() {
//Calculate the reverse bearing of the boat, and convert it to an azimuth.
Azimuth reverseAzimuth = Azimuth.fromDegrees(getBearing().degrees() - 180d);
//Calculate the distance, in meters, of the wake.
//We currently use boat's speed, in meters per second, to calculate the wake length. Could maybe move the knot -> m/s calculation somewhere else.
double speedKnots = getCurrentSpeed();
double speedMetersPerHour = speedKnots * Constants.NMToMetersConversion;
double speedMetersPerSecond = speedMetersPerHour / Constants.OneHourSeconds;
double wakeDistanceMeters = speedMetersPerSecond * this.wakeScale;
//Calculate the new coordinate.
GPSCoordinate wakeCoordinate = GPSCoordinate.calculateNewPosition(getCurrentPosition(), wakeDistanceMeters, reverseAzimuth);
return wakeCoordinate;
}
/**
* Attempts to add a new point to boat's track.
* It only adds a new point if the boat is still racing (see {@link #getStatus()} and {@link BoatStatusEnum#RACING}), and if at least {@link #trackPointTimeInterval} milliseconds have occurred, using race time.
* @param coordinate The {@link GPSCoordinate} of the trackpoint.
* @param currentTime The current race time.
* @see TrackPoint
*/
public void addTrackPoint(GPSCoordinate coordinate, ZonedDateTime currentTime) {
//Get current time.
long currentTimeMilli = currentTime.toInstant().toEpochMilli();
//Check if enough time has passed to create a new track point.
Boolean canBeAdded = currentTimeMilli >= nextValidTime;
//If it has, and if we are still racing, create the point.
if (canBeAdded && (getStatus() == BoatStatusEnum.RACING)) {
//Calculate the period of time that it should take the track point to diminish over. We essentially allow for trackPointLimit number of track points to be created before it should fade out.
long expiryPeriod = trackPointTimeInterval * trackPointLimit;
//Create and add point.
TrackPoint trackPoint = new TrackPoint(coordinate, currentTimeMilli, expiryPeriod);
track.add(trackPoint);
//Update the nextValidTime for the next track point.
nextValidTime = currentTimeMilli + trackPointTimeInterval;
}
}
/**
* Returns the boat's sampled track between start of race and current time.
* @return The list of track points.
* @see TrackPoint
*/
public List<TrackPoint> getTrack() {
return track;
}
/**
* Returns the color of the boat.
* @return The color of the boat.
*/
public Color getColor() {
return color;
}
/**
* Print method prints the name of the boat
*
* @return Name of the boat.
*/
public String toString() {
return getName();
}
/**
* Returns the time until the boat will reach the next mark, as a string.
* @param currentTime The current race time.
* @return The time delta until the boat reaches the next mark.
*/
public String getTimeToNextMarkFormatted(ZonedDateTime currentTime) {
//Calculate time delta.
Duration timeUntil = Duration.between(currentTime, getEstimatedTimeAtNextMark());
//Convert to seconds.
long secondsUntil = timeUntil.getSeconds();
//This means the estimated time is in the past, or not racing.
if ((secondsUntil < 0) || (getStatus() != BoatStatusEnum.RACING)) {
return " -";
}
if (secondsUntil <= 60) {
//If less than 1 minute, display seconds only.
return " " + secondsUntil + "s";
} else {
//Otherwise display minutes and seconds.
long seconds = secondsUntil % 60;
long minutes = (secondsUntil - seconds) / 60;
return String.format(" %dm %ds", minutes, seconds);
}
}
/**
* Returns the time since the boat passed the previous mark, as a string.
* @param currentTime The current race time.
* @return The time delta since the boat passed the previous mark.
*/
public String getTimeSinceLastMarkFormatted(ZonedDateTime currentTime) {
if (getTimeAtLastMark() != null) {
//Calculate time delta.
Duration timeSince = Duration.between(getTimeAtLastMark(), currentTime);
//Format it.
return String.format(" %ds ", timeSince.getSeconds());
} else {
return " -";
}
}
}
@@ -0,0 +1,471 @@
package visualiser.model;
import javafx.animation.AnimationTimer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.paint.Color;
import network.Messages.BoatLocation;
import network.Messages.BoatStatus;
import network.Messages.Enums.BoatStatusEnum;
import network.Messages.Enums.RaceStatusEnum;
import network.Messages.LatestMessages;
import network.Messages.RaceStatus;
import shared.dataInput.BoatDataSource;
import shared.dataInput.RaceDataSource;
import shared.dataInput.RegattaDataSource;
import shared.model.*;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The Class used to view the race streamed.
* Has a course, boats, boundaries, etc...
* Observes LatestMessages and updates its state based on new messages.
*/
public class VisualiserRace extends Race {
/**
* An observable list of boats in the race.
*/
private final ObservableList<VisualiserBoat> boats;
/**
* An observable list of marker boats in the race.
*/
private ObservableList<Mark> boatMarkers;
/**
* Maps between a Leg to a list of boats, in the order that they finished the leg.
* Used by the Sparkline to ensure it has correct information.
*/
private Map<Leg, List<VisualiserBoat>> legCompletionOrder = new HashMap<>();
/**
* Constructs a race object with a given RaceDataSource, BoatDataSource, and RegattaDataSource and receives events from LatestMessages.
* @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 colors A collection of colors used to assign a color to each boat.
*/
public VisualiserRace(BoatDataSource boatDataSource, RaceDataSource raceDataSource, RegattaDataSource regattaDataSource, LatestMessages latestMessages, List<Color> colors) {
super(boatDataSource, raceDataSource, regattaDataSource, latestMessages);
this.boats = FXCollections.observableArrayList(this.generateVisualiserBoats(boatDataSource.getBoats(), raceDataSource.getParticipants(), colors));
this.boatMarkers = FXCollections.observableArrayList(boatDataSource.getMarkerBoats().values());
//Initialise the leg completion order map.
for (Leg leg : this.legs) {
this.legCompletionOrder.put(leg, new ArrayList<>(this.boats.size()));
}
}
/**
* Sets the race data source for this race to a new RaceDataSource.
* Uses the boundary and legs specified by the new RaceDataSource.
* @param raceDataSource The new RaceDataSource to use.
*/
public void setRaceDataSource(RaceDataSource raceDataSource) {
this.raceDataSource = raceDataSource;
this.boundary = raceDataSource.getBoundary();
this.useLegsList(raceDataSource.getLegs());
}
/**
* Sets the boat data source for this race to a new BoatDataSource.
* Uses the marker boats specified by the new BoatDataSource.
* @param boatDataSource The new BoatDataSource to use.
*/
public void setBoatDataSource(BoatDataSource boatDataSource) {
this.boatDataSource = boatDataSource;
this.boatMarkers = FXCollections.observableArrayList(boatDataSource.getMarkerBoats().values());
}
/**
* Sets the regatta data source for this race to a new RegattaDataSource.
* @param regattaDataSource The new RegattaDataSource to use.
*/
public void setRegattaDataSource(RegattaDataSource regattaDataSource) {
this.regattaDataSource = regattaDataSource;
}
/**
* Returns a list of {@link Mark} boats.
* @return List of mark boats.
*/
public ObservableList<Mark> getMarks() {
return boatMarkers;
}
/**
* Generates a list of VisualiserBoats given a list of Boats, and a list of participating boats.
* @param boats The map of Boats describing boats that are potentially in the race. Maps boat sourceID to boat.
* @param sourceIDs The list of boat sourceIDs describing which specific boats are actually participating.
* @param colors The list of colors to be used for the boats.
* @return A list of MockBoats that are participating in the race.
*/
private List<VisualiserBoat> generateVisualiserBoats(Map<Integer, Boat> boats, List<Integer> sourceIDs, List<Color> colors) {
List<VisualiserBoat> visualiserBoats = new ArrayList<>(sourceIDs.size());
//For each sourceID participating...
int colorIndex = 0;
for (int sourceID : sourceIDs) {
//Get the boat associated with the sourceID.
Boat boat = boats.get(sourceID);
//Get a color for the boat.
Color color = colors.get(colorIndex);
//Construct a VisualiserBoat using the Boat and Polars.
VisualiserBoat visualiserBoat = new VisualiserBoat(boat, color);
visualiserBoats.add(visualiserBoat);
//Next color.
colorIndex++;
}
return visualiserBoats;
}
/**
* Initialise the boats in the race.
* This sets their current leg.
*/
@Override
protected void initialiseBoats() {
Leg startingLeg = legs.get(0);
for (VisualiserBoat boat : boats) {
boat.setCurrentLeg(startingLeg);
boat.setTimeAtLastMark(this.raceClock.getCurrentTime());
}
}
/**
* Updates all of the racing boats based on messages received.
* @param boats The list of racing boats.
* @param boatLocationMap A map between boat sourceIDs and BoatLocation messages.
* @param boatStatusMap A map between boat sourceIDs and BoatStatus messages.
*/
private void updateBoats(ObservableList<VisualiserBoat> boats, Map<Integer, BoatLocation> boatLocationMap, Map<Integer, BoatStatus> boatStatusMap) {
for (VisualiserBoat boat : boats) {
BoatLocation boatLocation = boatLocationMap.get(boat.getSourceID());
BoatStatus boatStatus = boatStatusMap.get(boat.getSourceID());
updateBoat(boat, boatLocation, boatStatus);
}
}
/**
* Updates an individual racing boat based on messages received.
* @param boat The boat to update.
* @param boatLocation The BoatLocation message to use.
* @param boatStatus The BoatStatus message to use.
*/
private void updateBoat(VisualiserBoat boat, BoatLocation boatLocation, BoatStatus boatStatus) {
if (boatLocation != null && boatStatus != null) {
//Get the new position.
double latitude = boatLocation.getLatitudeDouble();
double longitude = boatLocation.getLongitudeDouble();
GPSCoordinate gpsCoordinate = new GPSCoordinate(latitude, longitude);
boat.setCurrentPosition(gpsCoordinate);
//Bearing.
boat.setBearing(Bearing.fromDegrees(boatLocation.getHeadingDegrees()));
//Time until next mark.
boat.setEstimatedTimeAtNextMark(raceClock.getLocalTime(boatStatus.getEstTimeAtNextMark()));
//Speed.
boat.setCurrentSpeed(boatLocation.getBoatSOG() / Constants.KnotsToMMPerSecond);
//Boat status.
BoatStatusEnum newBoatStatusEnum = BoatStatusEnum.fromByte(boatStatus.getBoatStatus());
//If we are changing from non-racing to racing, we need to initialise boat with their time at last mark.
if ((boat.getStatus() != BoatStatusEnum.RACING) && (newBoatStatusEnum == BoatStatusEnum.RACING)) {
boat.setTimeAtLastMark(this.raceClock.getCurrentTime());
}
boat.setStatus(newBoatStatusEnum);
//Leg.
int legNumber = boatStatus.getLegNumber();
if (legNumber >= 1 && legNumber < legs.size()) {
if (boat.getCurrentLeg() != legs.get(legNumber)) {
boatFinishedLeg(boat, legs.get(legNumber));
}
}
//Attempt to add a track point.
if (newBoatStatusEnum == BoatStatusEnum.RACING) {
boat.addTrackPoint(boat.getCurrentPosition(), raceClock.getCurrentTime());
}
//Set finish time if boat finished.
if (newBoatStatusEnum == BoatStatusEnum.FINISHED || legNumber == this.legs.size()) {
boat.setTimeFinished(boatLocation.getTime());
boat.setStatus(BoatStatusEnum.FINISHED);
}
}
}
/**
* Updates a boat's leg to a specified leg. Also records the order in which the boat passed the leg.
* @param boat The boat to update.
* @param leg The leg to use.
*/
private void boatFinishedLeg(VisualiserBoat boat, Leg leg) {
//Record order in which boat finished leg.
this.legCompletionOrder.get(boat.getCurrentLeg()).add(boat);
//Update boat.
boat.setCurrentLeg(leg);
boat.setTimeAtLastMark(this.raceClock.getCurrentTime());
}
/**
* Updates all of the marker boats based on messages received.
* @param boatMarkers The list of marker boats.
* @param boatLocationMap A map between boat sourceIDs and BoatLocation messages.
* @param boatStatusMap A map between boat sourceIDs and BoatStatus messages.
*/
private void updateMarkers(ObservableList<Mark> boatMarkers, Map<Integer, BoatLocation> boatLocationMap, Map<Integer, BoatStatus> boatStatusMap) {
for (Mark mark : boatMarkers) {
BoatLocation boatLocation = boatLocationMap.get(mark.getSourceID());
updateMark(mark, boatLocation);
}
}
/**
* Updates an individual marker boat based on messages received.
* @param mark The marker boat to be updated.
* @param boatLocation The message describing the boat's new location.
*/
private void updateMark(Mark mark, BoatLocation boatLocation) {
if (boatLocation != null) {
//We only update the boat's position.
double latitude = boatLocation.getLatitudeDouble();
double longitude = boatLocation.getLongitudeDouble();
GPSCoordinate gpsCoordinate = new GPSCoordinate(latitude, longitude);
mark.setPosition(gpsCoordinate);
}
}
/**
* Updates the race status (RaceStatusEnum, wind bearing, wind speed) based on received messages.
* @param raceStatus The RaceStatus message received.
*/
private void updateRaceStatus(RaceStatus raceStatus) {
//Race status enum.
this.raceStatusEnum = RaceStatusEnum.fromByte(raceStatus.getRaceStatus());
//Wind bearing.
this.windDirection.setDegrees(raceStatus.getScaledWindDirection());
//Wind speed.
this.windSpeed = raceStatus.getWindSpeedKnots();
//Current race time.
this.raceClock.setUTCTime(raceStatus.getCurrentTime());
}
/**
* Runnable for the thread.
*/
public void run() {
initialiseBoats();
startRaceStream();
}
/**
* Starts the race.
* This updates the race based on {@link #latestMessages}.
*/
private void startRaceStream() {
new AnimationTimer() {
long lastFrameTime = System.currentTimeMillis();
@Override
public void handle(long arg0) {
//Calculate the frame period.
long currentFrameTime = System.currentTimeMillis();
long framePeriod = currentFrameTime - lastFrameTime;
//Update race status.
updateRaceStatus(latestMessages.getRaceStatus());
//Update racing boats.
updateBoats(boats, latestMessages.getBoatLocationMap(), latestMessages.getBoatStatusMap());
//And their positions (e.g., 5th).
updateBoatPositions(boats);
//Update marker boats.
updateMarkers(boatMarkers, latestMessages.getBoatLocationMap(), latestMessages.getBoatStatusMap());
if (getRaceStatusEnum() == RaceStatusEnum.FINISHED) {
stop();
}
lastFrameTime = currentFrameTime;
//Increment fps.
incrementFps(framePeriod);
}
}.start();
}
/**
* Update position of boats in race (e.g, 5th), no position if on starting leg or DNF.
* @param boats The list of boats to update.
*/
private void updateBoatPositions(ObservableList<VisualiserBoat> boats) {
//Sort boats.
sortBoatsByPosition(boats);
//Assign new positions.
for (int i = 0; i < boats.size(); i++) {
VisualiserBoat boat = boats.get(i);
if ((boat.getStatus() == BoatStatusEnum.DNF) || (boat.getStatus() == BoatStatusEnum.PRESTART) || (boat.getCurrentLeg().getLegNumber() < 0)) {
boat.setPosition("-");
} else {
boat.setPosition(Integer.toString(i + 1));
}
}
}
/**
* Sorts the list of boats by their position within the race.
* @param boats The list of boats in the race.
*/
private void sortBoatsByPosition(ObservableList<VisualiserBoat> boats) {
FXCollections.sort(boats, (a, b) -> {
//Get the difference in leg numbers.
int legNumberDelta = b.getCurrentLeg().getLegNumber() - a.getCurrentLeg().getLegNumber();
//If they're on the same leg, we need to compare time to finish leg.
if (legNumberDelta == 0) {
return (int) Duration.between(b.getEstimatedTimeAtNextMark(), a.getEstimatedTimeAtNextMark()).toMillis();
} else {
return legNumberDelta;
}
});
}
/**
* Returns the boats participating in the race.
* @return ObservableList of boats participating in the race.
*/
public ObservableList<VisualiserBoat> getBoats() {
return boats;
}
/**
* Returns the order in which boats completed each leg. Maps the leg to a list of boats, ordered by the order in which they finished the leg.
* @return Leg completion order for each leg.
*/
public Map<Leg, List<VisualiserBoat>> getLegCompletionOrder() {
return legCompletionOrder;
}
/**
* Takes an estimated time an event will occur, and converts it to the
* number of seconds before the event will occur.
*
* @param estTimeMillis The estimated time, in milliseconds.
* @param currentTime The current time, in milliseconds.
* @return int difference between time the race started and the estimated time
*/
private int convertEstTime(long estTimeMillis, long currentTime) {
//Calculate millisecond delta.
long estElapsedMillis = estTimeMillis - currentTime;
//Convert milliseconds to seconds.
int estElapsedSecs = Math.round(estElapsedMillis / 1000);
return estElapsedSecs;
}
}