View Javadoc

1   /*
2    * @(#)Game.java Jun 8, 2004
3    * 
4    * Copyright (c) 2003-2005 Delft University of Technology, Jaffalaan 5, 2628 BX
5    * Delft, the Netherlands. All rights reserved.
6    * 
7    * See for project information <a href="http://www.simulation.tudelft.nl/">
8    * www.simulation.tudelft.nl </a>.
9    * 
10   * The source code and binary code of this software is proprietary information
11   * of Delft University of Technology.
12   */
13  
14  package org.gscg.game;
15  
16  import java.io.IOException;
17  import java.io.ObjectOutputStream;
18  import java.net.URL;
19  import java.rmi.RemoteException;
20  
21  import javax.vecmath.Point3d;
22  
23  import nl.tudelft.simulation.dsol.ModelInterface;
24  import nl.tudelft.simulation.dsol.experiment.Experiment;
25  import nl.tudelft.simulation.dsol.simulators.AnimatorInterface;
26  import nl.tudelft.simulation.dsol.simulators.DEVSSimulator;
27  import nl.tudelft.simulation.dsol.simulators.DEVSSimulatorInterface;
28  import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
29  import nl.tudelft.simulation.language.d3.DirectedPoint;
30  import nl.tudelft.simulation.language.io.URLResource;
31  import nl.tudelft.simulation.logger.Logger;
32  import nl.tudelft.simulation.supplychain.banking.Bank;
33  import nl.tudelft.simulation.xml.dsol.ExperimentParser;
34  
35  import org.gscg.common.interactionlayer.ThreadedEventProducer;
36  import org.gscg.common.interactionlayer.dataobjects.LocationAndNameData;
37  import org.gscg.common.interactionlayer.messaging.ScenarioText;
38  import org.gscg.common.interactionlayer.timecontrol.GlobalProgressDateAndTime;
39  import org.gscg.common.interactionlayer.timecontrol.GlobalRowOrColumnNumber;
40  import org.gscg.experiment.DistributorParser;
41  import org.gscg.experiment.Distributors;
42  import org.gscg.experiment.ManufacturerParser;
43  import org.gscg.experiment.Manufacturers;
44  import org.gscg.experiment.MarketParser;
45  import org.gscg.experiment.Markets;
46  import org.gscg.experiment.ProductParser;
47  import org.gscg.experiment.Products;
48  import org.gscg.experiment.SupplierParser;
49  import org.gscg.experiment.Suppliers;
50  import org.gscg.experiment.scenario.ScenarioManager;
51  import org.gscg.experiment.scenario.ScenarioParser;
52  import org.gscg.gameactors.statistics.DistributorStatistics;
53  import org.gscg.gameactors.statistics.ManufacturerStatistics;
54  import org.gscg.gameleader.animation2D.GisLegendRenderable;
55  import org.gscg.gameleader.animation2D.GisRenderable2D;
56  import org.gscg.singleuser.interactionlayer.DistributorSingleUserInteractionLayer;
57  import org.gscg.singleuser.interactionlayer.ManufacturerSingleUserInteractionLayer;
58  
59  /***
60   * The Game is the object which initializes the game. <br>
61   * <p>
62   * Copyright (c) 2003-2005 Delft University of Technology, Jaffalaan 5, 2628 BX
63   * Delft, the Netherlands. All rights reserved.
64   * 
65   * See for project information <a href="http://www.simulation.tudelft.nl/">
66   * www.simulation.tudelft.nl </a>.
67   * 
68   * The source code and binary code of this software is proprietary information
69   * of Delft University of Technology.
70   * 
71   * @author <a
72   *         href="http://www.tbm.tudelft.nl/webstaf/alexandv/index.htm">Alexander
73   *         Verbraeck </a>
74   * @author <a
75   *         href="http://www.tbm.tudelft.nl/webstaf/stijnh/index.htm">Stijn-Pieter
76   *         van Houten </a>
77   * @version $Revision: 1.2 $ $Date: 2005/08/09 15:43:42 $
78   * @since 1.0.0
79   */
80  
81  public class Game implements ModelInterface
82  {
83  	/*** the serial version uid */
84  	private static final long serialVersionUID = 12L;
85  
86  	/*** the simulator */
87  	private DEVSSimulatorInterface simulator = null;
88  
89  	/*** the global supply chain game data */
90  	private GameGlobalData gameGlobalData = null;
91  
92  	/*** the scenario manager to use */
93  	private ScenarioManager scenarioManager = null;
94  
95  	/*** the scenario text */
96  	private ScenarioText scenarioText = null;
97  
98  	/*** the name of the context to use for serialization */
99  	private String contextName = null;
100 
101 	/*** the progress management; reference made for persistency reasons */
102 	private GlobalProgressDateAndTime staticProgressDateAndTime = null;
103 
104 	/*** the row or column number; reference made for persistency reasons */
105 	private GlobalRowOrColumnNumber staticGlobalRowOrColumnNumber = null;
106 
107 	/*** the manufacturer statistics; reference made for persistency reasons */
108 	protected ManufacturerStatistics manufacturerStatistics = null;
109 
110 	/*** the distributor statistics; reference made for persistency reasons */
111 	protected DistributorStatistics distributorStatistics = null;
112 
113 	/*** the bank */
114 	private static Bank bank;
115 
116 	/***
117 	 * constructs a new Game
118 	 */
119 	public Game()
120 	{
121 		super();
122 	}
123 
124 	/***
125 	 * @see nl.tudelft.simulation.dsol.ModelInterface#constructModel(nl.tudelft.simulation.dsol.simulators.SimulatorInterface)
126 	 */
127 	public void constructModel(final SimulatorInterface simulator)
128 			throws RemoteException
129 	{
130 
131 		// Logger.setDefaultHandler(FileHandler.class);
132 
133 		// initialize the model
134 		DEVSSimulatorInterface devsSimulator = (DEVSSimulatorInterface) simulator;
135 		this.simulator = devsSimulator;
136 		if (devsSimulator instanceof AnimatorInterface)
137 		{
138 			((AnimatorInterface) simulator).setTimeStep(0.002);
139 			((AnimatorInterface) simulator).setAnimationDelay(120);
140 
141 			// we construct the world
142 			// TODO provide less hard-coded implementation (e.g. store in
143 			// experiment file)
144 			new GisRenderable2D(simulator, URLResource
145 					.getResource("/world.map.xml"), null);
146 
147 			// we construct our legenda
148 			new GisLegendRenderable(new DirectedPoint(0.0, 0.0, 0.0),
149 					simulator, null);
150 			// and we save the context name for serialization purposes
151 			this.contextName = simulator.getReplication().getRunControl()
152 					.getTreatment().getExperiment().getRun()
153 					+ "/treatment("
154 					+ simulator.getReplication().getRunControl().getTreatment()
155 							.getNumber()
156 					+ ")/replication("
157 					+ simulator.getReplication().getNumber() + ")";
158 		}
159 
160 		// init the global progress date and time
161 		this.staticProgressDateAndTime = new GlobalProgressDateAndTime(
162 				this.simulator);
163 
164 		// init the global row or column number
165 		this.staticGlobalRowOrColumnNumber = new GlobalRowOrColumnNumber(
166 				this.simulator);
167 
168 		// init the scenario text
169 		this.scenarioText = new ScenarioText(this.simulator);
170 
171 		// make the global supply chain data object
172 		this.gameGlobalData = new GameGlobalData(this.simulator);
173 
174 		try
175 		{
176 			// create the bank
177 			Game.bank = new Bank("ING", this.simulator, new Point3d(0.0, 0.0,
178 					0.0));
179 
180 			//
181 			// create the products
182 			//
183 			String xsdProducts = URLResource.getResource("/product.xsd")
184 					.toExternalForm();
185 			ProductParser.parseProducts(xsdProducts, URLResource
186 					.getResource("/products.xml"));
187 
188 			for (int i = 0; i < Products.getProductsArray().length; i++)
189 			{
190 				this.gameGlobalData.addProduct(Products.getProductsArray()[i]);
191 				Logger.fine(this, "constructModel", "Generated product: "
192 						+ Products.getProductsArray()[i].getName()
193 						+ " with initial unit price: "
194 						+ Products.getProductsArray()[i].getUnitMarketPrice());
195 			}
196 
197 			//
198 			// create the suppliers
199 			//
200 			String xsdSuppliers = URLResource.getResource("/supplier.xsd")
201 					.toExternalForm();
202 			SupplierParser.parseSuppliers(xsdSuppliers, URLResource
203 					.getResource("/suppliers.xml"), this.simulator);
204 
205 			for (int i = 0; i < Suppliers.getSuppliersArray().length; i++)
206 			{
207 				Logger.fine(this, "constructModel", "Generated Supplier: "
208 						+ Suppliers.getSuppliersArray()[i].getName());
209 				this.gameGlobalData.addSupplyChainActor(Suppliers
210 						.getSuppliersArray()[i],
211 						LocationAndNameData.ACTORTYPE_SUPPLIER, false);
212 			}
213 
214 			//
215 			// create the manufacturers
216 			//
217 			String xsdManufacturers = URLResource.getResource(
218 					"/manufacturer.xsd").toExternalForm();
219 			ManufacturerParser.parseManufacturers(xsdManufacturers, URLResource
220 					.getResource("/manufacturers.xml"), this.gameGlobalData,
221 					this.simulator);
222 			// the statistics for the manufacturers divided per region
223 			this.manufacturerStatistics = new ManufacturerStatistics();
224 
225 			for (int i = 0; i < Manufacturers.getManufacturersArray().length; i++)
226 			{
227 				Logger.fine(this, "constructModel", "Generated Manufacturer: "
228 						+ Manufacturers.getManufacturersArray()[i].getName());
229 				this.gameGlobalData.addSupplyChainActor(Manufacturers
230 						.getManufacturersArray()[i],
231 						LocationAndNameData.ACTORTYPE_MANUFACTURER, false);
232 				ManufacturerStatistics.addManufacturer(Manufacturers
233 						.getManufacturersArray()[i]);
234 
235 				// create interaction layer
236 				this.scenarioText
237 						.addInteractionLayer(new ManufacturerSingleUserInteractionLayer(
238 								this.simulator, Manufacturers
239 										.getManufacturersArray()[i].getName(),
240 								Manufacturers.getManufacturersArray()[i],
241 								this.gameGlobalData));
242 			}
243 
244 			//
245 			// create the distributors
246 			//
247 			String xsdDistributor = URLResource.getResource("/distributor.xsd")
248 					.toExternalForm();
249 			DistributorParser.parseDistributors(xsdDistributor, URLResource
250 					.getResource("/distributors.xml"), this.gameGlobalData,
251 					this.simulator);
252 
253 			// the statistics for the distributors divided per region
254 			this.distributorStatistics = new DistributorStatistics();
255 
256 			for (int i = 0; i < Distributors.getDistributorsArray().length; i++)
257 			{
258 				Logger.fine(this, "constructModel", "Generated Distributor: "
259 						+ Distributors.getDistributorsArray()[i].getName());
260 				this.gameGlobalData.addSupplyChainActor(Distributors
261 						.getDistributorsArray()[i],
262 						LocationAndNameData.ACTORTYPE_RETAILER, true);
263 				DistributorStatistics.addDistributor(Distributors
264 						.getDistributorsArray()[i]);
265 
266 				// create interaction layer
267 				this.scenarioText
268 						.addInteractionLayer(new DistributorSingleUserInteractionLayer(
269 								this.simulator, Distributors
270 										.getDistributorsArray()[i].getName(),
271 								Distributors.getDistributorsArray()[i],
272 								this.gameGlobalData));
273 			}
274 
275 			// get the total number of distributors and manufacturers and set
276 			// the value for the DijkstraSemaphore, add 1 for the
277 			// GameAdministrator
278 			ThreadedEventProducer.DIJKSTRASEMAPHORE
279 					.setMaximumCount(Distributors.getDistributorsArray().length
280 							+ Manufacturers.getManufacturersArray().length + 1);
281 
282 			//
283 			// create the markets
284 			//
285 			String xsdMarkets = URLResource.getResource("/market.xsd")
286 					.toExternalForm();
287 			MarketParser.parseMarkets(xsdMarkets, URLResource
288 					.getResource("/markets.xml"), this.simulator);
289 
290 			for (int i = 0; i < Markets.getMarketsArray().length; i++)
291 			{
292 				Logger.fine(this, "constructModel", "Generated Market: "
293 						+ Markets.getMarketsArray()[i].getName());
294 				this.gameGlobalData.addSupplyChainActor(Markets
295 						.getMarketsArray()[i],
296 						LocationAndNameData.ACTORTYPE_MARKET, false);
297 			}
298 
299 			// after all actors have been created, we check
300 			// the scenario, and schedule all the events
301 			this.loadScenario();
302 			this.scenarioManager.scheduleObjects();
303 		} catch (Exception exception)
304 		{
305 			Logger.severe(this, "constructModel", exception);
306 		}
307 	}
308 
309 	/***
310 	 * @return Returns the staticGlobalRowOrColumnNumber instance
311 	 */
312 	protected GlobalRowOrColumnNumber getStaticGlobalRowOrColumnNumber()
313 	{
314 		return this.staticGlobalRowOrColumnNumber;
315 	}
316 
317 	/***
318 	 * @return Returns the staticProgressDateAndTime instance
319 	 */
320 	protected GlobalProgressDateAndTime getStaticProgressDateAndTime()
321 	{
322 		return this.staticProgressDateAndTime;
323 	}
324 
325 	//
326 	// private methods
327 	//	
328 
329 	/***
330 	 * Method loadScenario.
331 	 */
332 	private void loadScenario()
333 	{
334 		// Let's find the XSD file
335 		String xsd = URLResource.getResource("/scenario.xsd").toExternalForm();
336 		URL input = URLResource.getResource("/scenario.xml");
337 
338 		try
339 		{
340 			this.scenarioManager = new ScenarioManager(ScenarioParser
341 					.parseScenario(xsd, input), this.simulator);
342 		} catch (IOException ioException)
343 		{
344 			Logger.severe(this, "loadScenario", ioException);
345 		}
346 	}
347 
348 	/***
349 	 * writes a serializable method to stream
350 	 * 
351 	 * @param out the outputstream
352 	 * @throws IOException on IOException
353 	 */
354 	private synchronized void writeObject(final ObjectOutputStream out)
355 			throws IOException
356 	{
357 		out.writeObject(Game.bank);
358 		out.defaultWriteObject();
359 	}
360 
361 	/***
362 	 * @return Returns the bank
363 	 */
364 	public static Bank getBank()
365 	{
366 		return Game.bank;
367 	}
368 
369 	/***
370 	 * reads a serializable method from stream
371 	 * 
372 	 * @param in the inputstream
373 	 */
374 	private synchronized void readObject(final java.io.ObjectInputStream in)
375 	{
376 		try
377 		{
378 			Game.bank = (Bank) in.readObject();
379 			in.defaultReadObject();
380 			// custom deserialize methods
381 			String name = this.contextName + "/animation/2D";
382 			new GisLegendRenderable(new DirectedPoint(0.0, 0.0, 0.0),
383 					this.simulator, name);
384 			new GisRenderable2D(this.simulator, URLResource
385 					.getResource("/world.map.xml"), name);
386 		} catch (Exception exception)
387 		{
388 			Logger.severe(this, "readObject", exception);
389 		}
390 	}
391 
392 	/***
393 	 * executes SingeUserGame
394 	 * 
395 	 * @param args the commandline arguments
396 	 */
397 	public static void main(final String[] args)
398 	{
399 		if (args.length != 0)
400 		{
401 			System.out.println("Usage: java org.gscg.game.Game");
402 			System.exit(0);
403 		}
404 		try
405 		{
406 			// We parse the experiment
407 			Experiment experiment = ExperimentParser.parseExperiment(Game.class
408 					.getResource("/experiment.xml"));
409 			// We make sure the experiment is reset
410 			DEVSSimulatorInterface simulator = new DEVSSimulator();
411 			experiment.setSimulator(simulator);
412 			experiment.setModel(new Game());
413 			experiment.start();
414 		} catch (Exception exception)
415 		{
416 			exception.printStackTrace();
417 		}
418 	}
419 }