diff --git a/assignments/src/MV3500Cohort2021JulySeptember/homework3/Frank/FrankAssisgmentThreeSimulation.java b/assignments/src/MV3500Cohort2021JulySeptember/homework3/Frank/FrankAssisgmentThreeSimulation.java index 538c5713e1e21bdc61be3fcc1c47c44e00dbe18a..84a7488a8e4e7c5ac75026b10c3df29fd35c8dcd 100644 --- a/assignments/src/MV3500Cohort2021JulySeptember/homework3/Frank/FrankAssisgmentThreeSimulation.java +++ b/assignments/src/MV3500Cohort2021JulySeptember/homework3/Frank/FrankAssisgmentThreeSimulation.java @@ -6,44 +6,30 @@ */ package MV3500Cohort2021JulySeptember.homework3.Frank; -import edu.nps.moves.dis7.enumerations.Country; -import edu.nps.moves.dis7.enumerations.EntityKind; -import edu.nps.moves.dis7.enumerations.MunitionDescriptorFuse; -import edu.nps.moves.dis7.enumerations.PlatformDomain; -import edu.nps.moves.dis7.enumerations.VariableRecordType; -import edu.nps.moves.dis7.pdus.CommentPdu; -import edu.nps.moves.dis7.pdus.*; -import edu.nps.moves.dis7.pdus.Domain; -import edu.nps.moves.dis7.pdus.EntityID; -import edu.nps.moves.dis7.pdus.EntityStatePdu; -import edu.nps.moves.dis7.pdus.EntityType; -import edu.nps.moves.dis7.pdus.EulerAngles; -import edu.nps.moves.dis7.pdus.FirePdu; -import edu.nps.moves.dis7.pdus.MunitionDescriptor; -import edu.nps.moves.dis7.pdus.Pdu; -import edu.nps.moves.dis7.pdus.Vector3Double; -import edu.nps.moves.dis7.utilities.CoordinateConversions; +import edu.nps.moves.dis7.enumerations.*; // match any +import edu.nps.moves.dis7.pdus.*; // match any of the PDU classes, easier than listing individually import edu.nps.moves.dis7.utilities.DisThreadedNetworkInterface; import edu.nps.moves.dis7.utilities.PduFactory; import edu.nps.moves.dis7.utilities.stream.PduRecorder; +import edu.nps.moves.disutil.CoordinateConversions; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** - * The purpose of this program is to have M1Abrams Destroy A Russian T62 Tank. + * The purpose of this program is to have M1Abrams Destroy A Russian T62 Tank. * simulation program that includes DIS-capable entities doing tasks and * reporting them to the network. Default settings include PDU recording turned * on by default. */ -public class FrankAssisgmentThreeSimulation{ +public class FrankAssisgmentThreeSimulation { private boolean verboseComments; - static final String NETWORK_ADDRESS_DEFAULT = "239.1.2.3"; - static final int NETWORK_PORT_DEFAULT = 3000; - static String networkAddress = NETWORK_ADDRESS_DEFAULT; - static int networkPort = NETWORK_PORT_DEFAULT; - String DEFAULT_OUTPUT_DIRECTORY = "./pduLog"; + static final String NETWORK_ADDRESS_DEFAULT = "239.1.2.3"; + static final int NETWORK_PORT_DEFAULT = 3000; + static String networkAddress = NETWORK_ADDRESS_DEFAULT; + static int networkPort = NETWORK_PORT_DEFAULT; + String DEFAULT_OUTPUT_DIRECTORY = "./pduLog"; private EntityID createM1Abrams() { EntityID M1AbramsID = new EntityID(); // 1.1.225.1.1.1 Platform,Ground,USA,ArmoredFightingVehicle M1 Abrams @@ -118,23 +104,24 @@ public class FrankAssisgmentThreeSimulation{ orient1.setTheta((float) 0.0); return orient1; } - - private MunitionDescriptor createM829IT(){ - - EntityType M829Type = new EntityType(); //2.2.225.2.13.1 - M829Type.setEntityKind(EntityKind.MUNITION); - M829Type.setDomain(Domain.inst(PlatformDomain.AIR)); - M829Type.setCountry(Country.UNITED_STATES_OF_AMERICA_USA); - M829Type.setCategory(2); - M829Type.setSubCategory(13); - M829Type.setSpecific(1); - MunitionDescriptor M829IT = new MunitionDescriptor(); - M829IT.setMunitionType(M829Type); - M829IT.setQuantity(3); - M829IT.setFuse(MunitionDescriptorFuse.CONTACT_GRAZE); - M829IT.setRate(200); - return M829IT; - } + + private MunitionDescriptor createM829IT() { + + EntityType M829Type = new EntityType(); //2.2.225.2.13.1 + M829Type.setEntityKind(EntityKind.MUNITION); + M829Type.setDomain(Domain.inst(PlatformDomain.AIR)); + M829Type.setCountry(Country.UNITED_STATES_OF_AMERICA_USA); + M829Type.setCategory(2); + M829Type.setSubCategory(13); + M829Type.setSpecific(1); + MunitionDescriptor M829IT = new MunitionDescriptor(); + M829IT.setMunitionType(M829Type); + M829IT.setQuantity(3); + M829IT.setFuse(MunitionDescriptorFuse.CONTACT_GRAZE); + M829IT.setRate(200); + return M829IT; + } + /** * This runSimulation() method is for you, a programmer-modifiable method * for defining and running a new simulation of interest. Welcome! Other @@ -160,7 +147,7 @@ public class FrankAssisgmentThreeSimulation{ boolean simulationComplete = false; // sentinel variable as termination condition,, are we done yet? boolean fireBool = false; boolean destBool = false; - + EntityID entityID_1 = new EntityID(); entityID_1.setSiteID(1).setApplicationID(2).setEntityID(3); // made-up example ID; // TODO someday, use enumerations; is there a unique site triplet for MOVES Institute? @@ -204,12 +191,11 @@ public class FrankAssisgmentThreeSimulation{ firePdu.setTargetEntityID(targetID); firePdu.setDescriptor(createM829IT()); // calling create M829IT Method - + EntityID M829ID = new EntityID(); M829ID.setEntityID(1); firePdu.setMunitionExpendibleID(M829ID); - CommentReliablePdu T62DestroyedComment = pduFactory.makeCommentReliablePdu("T62 DESTROYED BY M1 Abrams AFTER 2 rounds M829I-T ON TARGET"); CommentReliablePdu T62SightedComment = pduFactory.makeCommentReliablePdu("M1 Abrams Acquires Target - T62 with in firing distance"); //if(eloc1.getX()) @@ -217,7 +203,7 @@ public class FrankAssisgmentThreeSimulation{ FirePdu firePdu_1a = pduFactory.makeFirePdu(); // for entity 1 first weapon (if any) - while (simulationLoopCount < SIMULATION_MAX_LOOP_COUNT) // are we done yet? + while (simulationLoopCount < SIMULATION_MAX_LOOP_COUNT) { simulationLoopCount++; // good practice: increment loop counter as first action in that loop // Where is my entity? @@ -251,12 +237,11 @@ public class FrankAssisgmentThreeSimulation{ } } - if (simulationLoopCount > 4) // for example { simulationComplete = true; } - + entityStatePdu_1.getEntityLocation().setX(entityStatePdu_1.getEntityLocation().getX() + 1.0); // 1m per timestep narrativeMessage1 = "MV3500 FrankAssignment3Simulation"; @@ -271,167 +256,161 @@ public class FrankAssisgmentThreeSimulation{ // ============================================================================================= // * your own simulation code is finished here! * // ============================================================================================= -Thread.sleep((long)(SIMULATION_LOOP_DURATION_SECONDS * 1000)); // seconds * (1000 msec/sec) = milliseconds - System.out.println ("... [Pausing for " + SIMULATION_LOOP_DURATION_SECONDS + " seconds]"); - - // OK now send the status PDUs for this loop, and then continue - System.out.println ("sending PDUs for simulation step " + simulationLoopCount + ", monitor loopback to confirm sent"); - sendAllPdusForLoopTimestep(entityStatePdu_1, firePdu_1a, timeStepComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); - System.out.println ("... [PDUs successfully sent for this loop]"); - - // =============================== - // loop now finished, check whether to terminate if simulation complete, otherwise continue - if (simulationComplete || (simulationLoopCount > 10000)) // for example; including fail-safe condition is good - { - System.out.println ("... [Termination condition met, simulationComplete=" + simulationComplete + "]"); // ", final loopCount=" + loopCount + - break; - } - } // end of simulation loop - - narrativeMessage2 = "runSimulation() completed successfully"; // all done - sendCommentPdu(narrativeComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); - System.out.println ("... [final CommentPdu successfully sent for simulation]"); - // TODO simulation management PDUs - } - catch (InterruptedException iex) // handle any exception that your code might choose to provoke! - { - Logger.getLogger(FrankAssisgmentThreeSimulation.class.getName()).log(Level.SEVERE, null, iex); - } + Thread.sleep((long) (SIMULATION_LOOP_DURATION_SECONDS * 1000)); // seconds * (1000 msec/sec) = milliseconds + System.out.println("... [Pausing for " + SIMULATION_LOOP_DURATION_SECONDS + " seconds]"); + + // OK now send the status PDUs for this loop, and then continue + System.out.println("sending PDUs for simulation step " + simulationLoopCount + ", monitor loopback to confirm sent"); + sendAllPdusForLoopTimestep(entityStatePdu_1, firePdu_1a, timeStepComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); + System.out.println("... [PDUs successfully sent for this loop]"); + + // =============================== + // loop now finished, check whether to terminate if simulation complete, otherwise continue + if (simulationComplete || (simulationLoopCount > 10000)) // for example; including fail-safe condition is good + { + System.out.println("... [Termination condition met, simulationComplete=" + simulationComplete + "]"); // ", final loopCount=" + loopCount + + break; + } + } // end of simulation loop + + narrativeMessage2 = "runSimulation() completed successfully"; // all done + sendCommentPdu(narrativeComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); + System.out.println("... [final CommentPdu successfully sent for simulation]"); + // TODO simulation management PDUs + } catch (InterruptedException iex) // handle any exception that your code might choose to provoke! + { + Logger.getLogger(FrankAssisgmentThreeSimulation.class.getName()).log(Level.SEVERE, null, iex); + } } /* **************************** infrastructure code, modification is seldom needed ************************* */ - + String narrativeMessage1 = new String(); String narrativeMessage2 = new String(); String narrativeMessage3 = new String(); String narrativeMessage4 = new String(); - + /* VariableRecordType enumerations have potential use with CommentPdu logs */ - /* TODO contrast to EntityType */ + /* TODO contrast to EntityType */ VariableRecordType descriptionComment = VariableRecordType.DESCRIPTION; - VariableRecordType narrativeComment = VariableRecordType.COMPLETE_EVENT_REPORT; - VariableRecordType statusComment = VariableRecordType.APPLICATION_STATUS; - VariableRecordType timeStepComment = VariableRecordType.APPLICATION_TIMESTEP; - VariableRecordType otherComment = VariableRecordType.OTHER; - - /** - * Output prefix to identify this class, helps with logging - */ + VariableRecordType narrativeComment = VariableRecordType.COMPLETE_EVENT_REPORT; + VariableRecordType statusComment = VariableRecordType.APPLICATION_STATUS; + VariableRecordType timeStepComment = VariableRecordType.APPLICATION_TIMESTEP; + VariableRecordType otherComment = VariableRecordType.OTHER; + + /** + * Output prefix to identify this class, helps with logging + */ private final static String TRACE_PREFIX = "[" + FrankAssisgmentThreeSimulation.class.getName() + "] "; - + // class variables - PduFactory pduFactory = new PduFactory(); - DisThreadedNetworkInterface disNetworkInterface; + PduFactory pduFactory = new PduFactory(); + DisThreadedNetworkInterface disNetworkInterface; DisThreadedNetworkInterface.PduListener pduListener; - Pdu receivedPdu; - PduRecorder pduRecorder; - + Pdu receivedPdu; + PduRecorder pduRecorder; + /** - * Constructor design goal: additional built-in initialization conveniences can go here - * to keep student efforts focused on the runSimulation() method. + * Constructor design goal: additional built-in initialization conveniences + * can go here to keep student efforts focused on the runSimulation() + * method. */ - public FrankAssisgmentThreeSimulation() - { + public FrankAssisgmentThreeSimulation() { // Constructor is under consideration. Constructor is not currently needed. } - + /** - * Utility Constructor that allows your example simulation program to override default network address and port + * Utility Constructor that allows your example simulation program to + * override default network address and port + * * @param address network address to use * @param port corresponding network port to use */ - public FrankAssisgmentThreeSimulation(String address, int port) - { + public FrankAssisgmentThreeSimulation(String address, int port) { setNetworkAddress(address); - + setNetworkPort(port); } /** * @return the networkAddress */ - public String getNetworkAddress() - { + public String getNetworkAddress() { return networkAddress; } /** * @param newNetworkAddress the networkAddress to set */ - public final void setNetworkAddress(String newNetworkAddress) - { + public final void setNetworkAddress(String newNetworkAddress) { FrankAssisgmentThreeSimulation.networkAddress = newNetworkAddress; } /** * @return the networkPort */ - public int getNetworkPort() - { + public int getNetworkPort() { return networkPort; } /** * @param newNetworkPort the networkPort to set */ - public final void setNetworkPort(int newNetworkPort) - { + public final void setNetworkPort(int newNetworkPort) { FrankAssisgmentThreeSimulation.networkPort = newNetworkPort; } /** * Initialize network interface, choosing best available network interface */ - public void setUpNetworkInterface() - { + public void setUpNetworkInterface() { disNetworkInterface = new DisThreadedNetworkInterface(getNetworkAddress(), getNetworkPort()); - disNetworkInterface.setDescriptor ("FrankAssisgmentThreeSimulation pdu looping"); - - System.out.println("Network confirmation:" + - " address=" + disNetworkInterface.getAddress()+ // disNetworkInterface.getMulticastGroup() + - " port=" + disNetworkInterface.getPort()); // + disNetworkInterface.getDisPort()); - pduListener = new DisThreadedNetworkInterface.PduListener() - { - /** Callback handler for listener */ + disNetworkInterface.setDescriptor("FrankAssisgmentThreeSimulation pdu looping"); + + System.out.println("Network confirmation:" + + " address=" + disNetworkInterface.getAddress() + + // disNetworkInterface.getMulticastGroup() + + " port=" + disNetworkInterface.getPort()); // + disNetworkInterface.getDisPort()); + pduListener = new DisThreadedNetworkInterface.PduListener() { + /** + * Callback handler for listener + */ @Override - public void incomingPdu(Pdu newPdu) - { + public void incomingPdu(Pdu newPdu) { receivedPdu = newPdu; } }; disNetworkInterface.addListener(pduListener); - + String outputDirectory = DEFAULT_OUTPUT_DIRECTORY; //"./pduLog" System.out.println("Beginning pdu save to directory " + outputDirectory); pduRecorder = new PduRecorder(outputDirectory, getNetworkAddress(), getNetworkPort()); // assumes save - pduRecorder.setDescriptor ("FrankAssisgmentThreeSimulation pduRecorder"); + pduRecorder.setDescriptor("FrankAssisgmentThreeSimulation pduRecorder"); pduRecorder.start(); // begin running } - /** All done, release network resources */ - public void tearDownNetworkInterface() - { + /** + * All done, release network resources + */ + public void tearDownNetworkInterface() { pduRecorder.stop(); disNetworkInterface.removeListener(pduListener); - + disNetworkInterface.close(); // disNetworkInterface.kill(); // renamed as close(), deprecated // disNetworkInterface = null; // making sure no possibility of zombie process remaining... } - /** + /** * Send a single Protocol Data Unit (PDU) of any type + * * @param pdu the pdu to send */ - private void sendSinglePdu(Pdu pdu) - { - try - { + private void sendSinglePdu(Pdu pdu) { + try { disNetworkInterface.send(pdu); Thread.sleep(100); // TODO consider refactoring the wait logic and moving externally - } - catch (InterruptedException ex) - { + } catch (InterruptedException ex) { System.err.println(this.getClass().getName() + " Error sending PDU: " + ex.getLocalizedMessage()); System.exit(1); } @@ -439,82 +418,91 @@ Thread.sleep((long)(SIMULATION_LOOP_DURATION_SECONDS * 1000)); // seconds * (100 /** * Send Comment PDU - * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing Information to a Method or a Constructor</a> Arbitrary Number of Arguments - * @param commentType enumeration value describing purpose of the narrative comment - * @param comments String array of narrative comments + * + * @see + * <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing + * Information to a Method or a Constructor</a> Arbitrary Number of + * Arguments + * @param commentType enumeration value describing purpose of the narrative + * comment + * @param comments String array of narrative comments */ public void sendCommentPdu(VariableRecordType commentType, - // vararg... variable-length set of String comments can optionally follow - String... comments) - { - sendAllPdusForLoopTimestep (null, null, commentType, comments); + // vararg... variable-length set of String comments can optionally follow + String... comments) { + sendAllPdusForLoopTimestep(null, null, commentType, comments); } /** - * Send EntityState, Fire, Comment PDUs that got updated for this loop, reflecting state of current simulation timestep. - * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing Information to a Method or a Constructor</a> Arbitrary Number of Arguments + * Send EntityState, Fire, Comment PDUs that got updated for this loop, + * reflecting state of current simulation timestep. + * + * @see + * <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing + * Information to a Method or a Constructor</a> Arbitrary Number of + * Arguments * @param entityStatePdu the ESPDU to send, if any - * @param firePdu the FirePDU to send, if any - * @param commentType enumeration value describing purpose of the narrative comment - * @param comments String array of narrative comments + * @param firePdu the FirePDU to send, if any + * @param commentType enumeration value describing purpose of the narrative + * comment + * @param comments String array of narrative comments */ public void sendAllPdusForLoopTimestep(EntityStatePdu entityStatePdu, - FirePdu firePdu, - VariableRecordType commentType, - // vararg... variable-length set of String comments can optionally follow - String... comments) - { - if (entityStatePdu != null) + FirePdu firePdu, + VariableRecordType commentType, + // vararg... variable-length set of String comments can optionally follow + String... comments) { + if (entityStatePdu != null) { sendSinglePdu(entityStatePdu); - - if (firePdu != null) + } + + if (firePdu != null) { sendSinglePdu(firePdu); // bang - - if ((comments != null) && (comments.length > 0)) - { + } + if ((comments != null) && (comments.length > 0)) { ArrayList<String> newCommentsList = new ArrayList<>(); - for (String comment : comments) - { - if (!comment.isEmpty()) - { + for (String comment : comments) { + if (!comment.isEmpty()) { newCommentsList.add(comment); // OK found something to send } } - if (!newCommentsList.isEmpty()) - { - if (commentType == null) + if (!newCommentsList.isEmpty()) { + if (commentType == null) { commentType = otherComment; // fallback value otherComment - // now build the commentPdu from these string inputs, thus constructing a narrative entry + } // now build the commentPdu from these string inputs, thus constructing a narrative entry CommentPdu commentPdu = pduFactory.makeCommentPdu(commentType, newCommentsList.toArray(new String[0])); // comments); sendSinglePdu(commentPdu); - if (isVerboseComments()) + if (isVerboseComments()) { System.out.println("*** [Narrative comment sent: " + commentType.name() + "] " + newCommentsList.toString()); + } } } } - + /** * Main method is first executed when a program instance is loaded. - * @see <a href="https://docs.oracle.com/javase/tutorial/getStarted/application/index.html">Java Tutorials: A Closer Look at the "Hello World!" Application</a> - * @param args command-line arguments are an array of optional String parameters that are passed from execution environment during invocation + * + * @see + * <a href="https://docs.oracle.com/javase/tutorial/getStarted/application/index.html">Java + * Tutorials: A Closer Look at the "Hello World!" Application</a> + * @param args command-line arguments are an array of optional String + * parameters that are passed from execution environment during invocation */ - public static void main(String[] args) - { + public static void main(String[] args) { System.out.println(TRACE_PREFIX + "started..."); - + FrankAssisgmentThreeSimulation thisProgram = new FrankAssisgmentThreeSimulation(); // creates instance - + // initial execution: can handle args array of initialization arguments here - if (args.length == 2) - { - if ((args[0] != null) && !args[0].isEmpty()) + if (args.length == 2) { + if ((args[0] != null) && !args[0].isEmpty()) { thisProgram.setNetworkAddress(args[0]); - - if ((args[1] != null) && !args[1].isEmpty()) + } + + if ((args[1] != null) && !args[1].isEmpty()) { thisProgram.setNetworkPort(Integer.parseInt(args[1])); - } - else if (args.length != 0) - { + } + } else if (args.length != 0) { System.err.println("Usage: " + thisProgram.getClass().getName() + " [address port]"); System.exit(-1); } @@ -522,10 +510,10 @@ Thread.sleep((long)(SIMULATION_LOOP_DURATION_SECONDS * 1000)); // seconds * (100 thisProgram.setUpNetworkInterface(); - thisProgram.runSimulation (); // ... your simulation execution code goes in there ... - + thisProgram.runSimulation(); // ... your simulation execution code goes in there ... + thisProgram.tearDownNetworkInterface(); // make sure no processes are left lingering - + System.out.println(TRACE_PREFIX + "complete."); // report successful completion } @@ -543,5 +531,3 @@ Thread.sleep((long)(SIMULATION_LOOP_DURATION_SECONDS * 1000)); // seconds * (100 this.verboseComments = newVerboseComments; } } - - \ No newline at end of file