source: proiecte/ptvs/src/vnsim/core/Engine2.java @ 135

Last change on this file since 135 was 135, checked in by (none), 14 years ago
File size: 68.3 KB
Line 
1//pentru 8 procesoare.
2package vnsim.core;
3
4
5import java.io.BufferedWriter;
6import java.io.DataInputStream;
7import java.io.DataOutputStream;
8import java.io.File;
9import java.io.FileInputStream;
10import java.io.FileOutputStream;
11import java.io.FileWriter;
12import java.io.IOException;
13import java.io.PrintWriter;
14import java.util.ArrayList;
15import java.util.Collections;
16import java.util.Iterator;
17import java.util.ListIterator;
18import java.util.Random;
19import java.util.Vector;
20import java.util.concurrent.ExecutorService;
21import java.util.concurrent.Executors;
22
23import vnsim.applications.adaptiveTL.IntersectionCarRecord;
24import vnsim.applications.adaptiveTL.WirelessTrafficLight;
25import vnsim.applications.emissions.EmissionsTrafficLight;
26import vnsim.applications.ezcab.EzcabCar;
27import vnsim.applications.ezcab.EzcabClient;
28import vnsim.applications.trafficview.SimulatedCarInfo;
29import vnsim.core.events.CleanupEvent;
30import vnsim.core.events.Event;
31import vnsim.core.events.GPSEvent;
32import vnsim.core.events.ReceiveEvent;
33import vnsim.core.events.SendEvent;
34import vnsim.core.events.UnicastSendEvent;
35import vnsim.map.object.Globals;
36import vnsim.map.object.Map;
37import vnsim.map.object.PeanoKey;
38import vnsim.map.object.Point;
39import vnsim.map.object.Road;
40import vnsim.map.utils.GPSutil;
41import vnsim.network.RadioDev;
42import vnsim.network.dsrc.Application;
43import vnsim.network.dsrc.CarRunningDSRC;
44import vnsim.network.dsrc.DSRCStatisticComponent;
45import vnsim.network.dsrc.DSRCStatistics;
46import vnsim.network.dsrc.EmergencyRequest;
47import vnsim.network.dsrc.MAC80211;
48import vnsim.network.dsrc.WirelessPhy;
49import vnsim.network.propagation.Ricean;
50import vnsim.network.scft.CarRunningSCFT;
51import vnsim.vehicular.emissions.EmissionsResults;
52import vnsim.vehicular.generator.EntryFlowVariation;
53import vnsim.vehicular.generator.Mobility;
54import vnsim.vehicular.generator.NewCarEvent;
55import vnsim.vehicular.routePlan.RoutingConstants;
56import vnsim.vehicular.routePlan.cityRouting.CarToIntersectionComm;
57import vnsim.vehicular.routePlan.cityRouting.CityTrafficLight;
58import vnsim.vehicular.routePlan.cityRouting.IntersectionNode;
59import vnsim.vehicular.routePlan.cityRouting.RoadSegmentCost;
60import vnsim.vehicular.routePlan.cityRouting.Server;
61import vnsim.vehicular.routePlan.infrastructureRouted.DelayRecord;
62import vnsim.vehicular.routePlan.infrastructureRouted.GuidanceRequest;
63import vnsim.vehicular.routePlan.infrastructureRouted.InfrastructureNode;
64import vnsim.vehicular.routePlan.selfRouted.QueryGeneration;
65import vnsim.vehicular.scenarios.EntryExitScenario;
66import vnsim.vehicular.scenarios.EntryScenario;
67import vnsim.vehicular.scenarios.Route;
68import vnsim.vehicular.simulator.AggresivePersonality;
69import vnsim.vehicular.simulator.CalmPersonality;
70import vnsim.vehicular.simulator.CarInstance;
71import vnsim.vehicular.simulator.Personality;
72import vnsim.vehicular.simulator.RegularPersonality;
73import vnsim.vehicular.simulator.SortedCarVector;
74import vnsim.vehicular.simulator.intersections.Intersection;
75import vnsim.vehicular.simulator.intersections.IntersectionWithTrafficLights;
76
77
78
79/**
80 *
81 * The Engine class is the main class that controlls the simulation. It manages
82 * the list of entities (cars, trafficlights) and the list of events and passes the
83 * control to the mobility layer or communication layer when needed.
84 *
85 * @author Victor Gradinescu
86 *
87 */
88
89public class Engine {
90       
91       
92        /**
93         * PTVS Project
94         */
95        public ExecutorService executor[];/////////////////////////////////////// thread pool with Executors ////////////////////
96       
97        public void start(Event e, int i) throws IOException {
98           
99              executor[i].submit(new EventProcessingThread(this,e));
100          }
101       
102        int dimens;
103       
104        public static int numThreads;
105        ///////////////////////end PTVS Project/////////////////////////////////////////////////////
106       
107       
108        /* EZCab - file informations about the client */
109        public static BufferedWriter bwClient, bwCab;
110       
111        public static double WIRELESS_RANGE = 0.1;
112        public static double EXTENDED_WIRELESS_RANGE = 1.0;
113
114//      Petroaca - simulation protocol type ( 802.11 or DSRC )
115        public static int simulationProtocol=Globals.PROTOCOL_80211;
116       
117        //Petroaca - propagation type ( tworay or shadowing )
118        public static int propagationModel=Globals.TWO_RAY_GROUND;
119       
120        //Petroaca - the Ricean propagation module
121        public static Ricean riceanModule;
122       
123        DataInputStream dis = null;
124
125        public int fps;
126
127        static Vector<Event> eventQueue = null;
128        static int nrEvThreads = 0;
129       
130        //Petroaca - the DSRC emergency channel
131        ArrayList<Event> eventQueueEmergency = null;
132       
133        public boolean pauseFlag = true;
134
135
136        boolean doneFlag = false,doneFlagEmergency=false;
137
138        public ArrayList<SimulatedCarInfo> cars = null;
139
140        public int crtTime = 0;
141
142        public long t0 = 0L;
143
144        public boolean withGUI, startedWithGUI;
145
146        boolean runtimeMobility;
147
148        public boolean disableComm = false;
149
150        File fText = null, fBin = null;
151
152        PrintWriter pwText = null;
153
154        DataOutputStream outBin = null;
155
156        long prevRealSec = 0; 
157        double lastSimSecond = 0.0;
158       
159        int eventsTime = 0, mobilityTime = 0, cleanupTime = 0, netTime = 0, codeTime = 0;
160
161
162        int schedTime = 0,  moveTime = 0, semTime = 0;
163
164
165        public double maxControlDelay = 0;
166       
167        public int mycnt = 0;
168        public long fincars;
169        public long crossedCars;
170        public double totalkm, totalControlDelay;
171        public EmissionsResults totalEM = new EmissionsResults();
172        private long totalTime;
173       
174        public static int created = 0;
175
176        // Routing
177        public static int simulationType = 0;
178        public static int applicationType = 0;
179        int jammed;
180
181        public ArrayList<SimulatedCarInfo> infrastructure = null;
182       
183        Object event;
184
185        //City Routing
186        private Server server= new Server(); 
187       
188        /**
189         *
190         *
191         * @param withGUI If the simulator is run at the same time with GUI, the code
192         * will have to be synchronized
193         * @param runtimeMobility
194         */
195        public Engine(boolean withGUI, boolean runtimeMobility) 
196        {
197                try {
198                        FileWriter fwClient = new FileWriter("client_request.txt");
199                        bwClient = new BufferedWriter(fwClient);
200                        FileWriter fwCab        = new FileWriter("client_answers.txt");
201                        bwCab    = new BufferedWriter(fwCab); 
202                } catch (IOException e1) {
203                        e1.printStackTrace();
204                }
205                this.withGUI = withGUI;
206                this.startedWithGUI = withGUI;
207                this.runtimeMobility = runtimeMobility;
208                // init();
209                prevRealSec = t0 = System.currentTimeMillis();
210       
211        }
212
213        /*
214         * Load the map, initialize eventqueue, init
215         */
216        public void init() {
217
218                Map map = Globals.map;
219               
220                //System.out.println("roads.size: "+map.roads.size()+" : "+map.roads.get(0).getName());
221               
222                //Road road = (Road)map.roads.get(0);
223               
224                //System.out.println("road.points: "+road.points);
225               
226                //System.out.println("strada:"+road.getName()+":"+" road.crosses.size(): "+road.crosses.size());
227               
228                       
229               
230               
231               
232                /**
233                 * PTVS project
234                 */
235                ArrayList<Intersection> intersectii = map.allIntersections;
236                //numThreads=intersectii.size();
237                numThreads = Globals.NO_FEP_PROC - 1;
238                               
239                executor=new ExecutorService[numThreads];
240               
241                for(int i=0; i < numThreads; i++){
242                        executor[i] = Executors.newFixedThreadPool(1); // un singur thread e mereu refolosit pt fiecare intersectie.. ar putea fi mai multe
243                }
244                ///////////////////////end PTVS Project/////////////////////////////////////////////////////
245               
246               
247                for(int q=0;q<intersectii.size();q++){
248                        System.out.println("intersectia "+q+": "+" nume: "+intersectii.get(q).toString()+" "+intersectii.get(q).getMapPoint());
249                }
250               
251                System.out.println(".........................aici4.........");
252               
253                //***************************************************************
254               
255                if (map.roads.get(0).getName().startsWith("Iuliu") || map.roads.get(0).getName().startsWith("Dr"))
256                {
257                       
258                        Globals.monitorWTL = (WirelessTrafficLight)map.allIntersections.get(1);
259                }
260                pauseFlag = false;
261                doneFlag = false;
262
263                // the positions of the cars may be updated by a mobility module by
264                // recomputing positions at each step or can be updated by reading a
265                // traces file
266                if (!runtimeMobility) 
267                {
268                        try 
269                        {
270                                if (dis != null) {
271                                        dis.close();
272                                }
273                                dis = new DataInputStream(new FileInputStream(Globals.inFile));
274                        } 
275                        catch (IOException e) 
276                        {
277                                System.err.println("Error reading scenario; file error"+ Globals.inFile);
278                                e.printStackTrace();
279                                System.exit(0);
280                        }
281                        try 
282                        {
283                                fps = dis.readInt();
284                        } 
285                        catch (IOException e)
286                        {
287                                System.err.println("Error reading file " + Globals.inFile);
288                                e.printStackTrace();
289                        }
290                }
291                else 
292                {
293                        fps = Globals.executionFPS;
294
295                        Globals.WIRELESS_TRANSMISSION_FRAMES = (int) Math
296                                        .ceil((double) Globals.WIRELESS_TRANSMISSION_TIME
297                                                        / (1000 / Globals.executionFPS));
298
299                }
300
301                // init cars and events
302                eventQueue = new Vector<Event>();
303               
304               
305                cars = new ArrayList<SimulatedCarInfo>();
306               
307       
308
309                //Petroaca - if DSRC simulation then initialize the emergency event queue
310                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
311                        eventQueueEmergency = new ArrayList<Event>();
312               
313                crtTime = 0;
314
315                if (!runtimeMobility) {
316                        readScenarioPhase();
317                } else {
318                        // Mobility.initCarsTest(this);
319                        // Mobility.initCarsAutostrada(this);
320//                      Mobility.initCars(this);
321                }
322
323                synchronized (eventQueue) {
324                       
325                                eventQueue.add(new GPSEvent(0));
326                                                               
327                                eventQueue.add(new CleanupEvent(1));
328                               
329                                Iterator<SimulatedCarInfo> it = cars.iterator();
330                                while (it.hasNext()) 
331                                {
332                                        System.out.println("nu ai cum sa intri pe aici!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! cars este vida");
333                                        SimulatedCarInfo r = it.next();
334                               
335                                schedEvent(new SendEvent(4, r,
336                                                SimulatedCarInfo.STANDARD_MESSAGE_ID));
337                                }
338                               
339                                // cod comentat deaorece vroiam sa vad daca se calculeaza cum trebuie intersectia cea mai apropiata
340                                // si partea asta face ca semafoarele din toate intersectiile sa genereze evenimente
341                               
342                                /* Szekeres A. START_MODIFY - add broadcast event for each traffic light*/
343                        for(int i=0;i<Globals.map.allIntersections.size();i++) {
344                                Intersection sender = Globals.map.allIntersections.get(i);
345                                if (sender instanceof EmissionsTrafficLight)
346                                {
347                                        ((EmissionsTrafficLight)sender).init();
348                                        schedEvent(new SendEvent(4, (EmissionsTrafficLight)sender, (int)Globals.PROT_TL_FEEDBACK));
349                                }
350                        }                       
351                                /* Szekeres A. STOP_MODIFY */
352                }
353               
354               
355                try 
356                {
357                        if (runtimeMobility && outputToFile) 
358                        {
359
360                                fText = new File(Globals.inFile + ".txt");
361                                fBin = new File(Globals.inFile);
362                                fText.createNewFile();
363                                fBin.createNewFile();
364                                pwText = new PrintWriter(new FileOutputStream(fText));
365                                outBin = new DataOutputStream(new FileOutputStream(fBin));
366
367                                pwText.println("" + Globals.FPS);
368                                outBin.writeInt(Globals.FPS);
369                        }
370                }
371                catch (IOException e) 
372                {
373                        System.err.println("Error reading scenario; file error"
374                                        + Globals.inFile);
375                        e.printStackTrace();
376                        System.exit(0);
377                }
378
379                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
380                        DelayRecord.initDelays();
381                        this.infrastructure=new ArrayList<SimulatedCarInfo>();
382                        //create a fixed node for every intersection
383                        InfrastructureNode.createInfrastructureNodes();
384                }
385
386                //Petroaca - instantiate the ricean propagation module
387                try
388                {
389                  if(Engine.propagationModel==Globals.RICEAN)
390                        Engine.riceanModule=new Ricean(Globals.RICEAN_FILE_NAME,true);
391                }
392                catch(IOException ioe){System.out.println("Ricean file io error:"+ioe.getMessage());System.exit(1);}
393               
394                System.out.println(">>> Engine initialized - "+eventQueue.size()+" events in the queue");
395                System.out.println("CARS:"+cars);
396                System.out.println("Events:"+eventQueue);
397                 
398               
399                System.out.println();
400               
401                /*Road r = Globals.map.roads.get(1);
402                System.out.print("road:"+r.getName());
403                System.out.println("  r.points.size():"+r.points.size());
404               
405                Point p1 = r.points.get(r.points.size()-1);
406                System.out.println(p1);
407                Point p2 = r.points.get(r.points.size()-2);
408                System.out.println(p2);
409               
410                System.out.println("distanta: " +(p1.getDistance() - p2.getDistance()));
411                System.out.println("distanta: " +GPSutil.distance(p1, p2));*/
412                System.out.println("__________________end init____________________________\n");
413                               
414
415        }
416
417        /**
418         * Reset simulation
419         */
420        public void reset()
421        {
422                eventQueue = new Vector<Event>();
423                cars = new ArrayList<SimulatedCarInfo>();
424
425                //Petroaca - if DSRC simulation also reset the emergency channel
426                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
427                        eventQueueEmergency = new ArrayList<Event>();
428               
429                crtTime = 0;
430
431        }
432       
433        /**
434         * Turn on communication by scheduling transmission events for each car.
435         *
436         */
437        public void restartCommunication() {
438                disableComm = false;
439                synchronized (eventQueue) {
440                        // eventQueue.add(new CleanupEvent(crtTime+1));
441
442                        schedEvent(new CleanupEvent(crtTime + 1));
443
444                        synchronized (cars) 
445                        {
446                                Iterator<SimulatedCarInfo> it = cars.iterator();
447                                while (it.hasNext()) {
448                                        SimulatedCarInfo r = it.next();
449                                        schedEvent(new SendEvent(crtTime + 2, r, SimulatedCarInfo.STANDARD_MESSAGE_ID));
450                                }
451                        }
452                }
453               
454//              Petroaca - if DSRC simulation also reset the emergency channel
455                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
456                        eventQueueEmergency = new ArrayList<Event>();
457        }
458
459        /**
460         * Start simulation, execute events from queue continously
461         *
462         */
463        public void play() {
464                // supposed to be in the init()
465                // between init and play() Globals.map.allIntersections is changing
466                // need to find a fix
467               
468                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
469                        CityTrafficLight.upgradeToCityTL();
470                        RoadSegmentCost.initRoadSegmentsCost();
471                        this.infrastructure=new ArrayList<SimulatedCarInfo>();
472                        //create a fixed node for every intersection
473                        IntersectionNode.createIntersectionNodes(server);
474                        server.init();
475                }
476               
477                prevRealSec = t0 = System.currentTimeMillis();
478                pauseFlag = false;
479                while (!pauseFlag && !doneFlag) {
480                        step();                 
481                }
482        }
483
484        /**
485         * Execute all the events for the following <seconds> s
486         *
487         */
488        public void play(int seconds) {
489                int frames = seconds * fps;
490                pauseFlag = false;
491                for (int i = 0; i < frames && !pauseFlag && !doneFlag; i++) {
492                        step();
493                }
494        }
495
496        /**
497         * Request the interruption of the continous execution of events
498         *
499         */
500        public void pause() {
501                pauseFlag = true;
502        }
503
504        /**
505         * Execute all the events for the current moment of time (virtual time)
506         *
507         */
508        double dec1(double x){
509                return (double)((int)(x * 10)) / 10;
510        }
511       
512       
513        long lastTime = -1;
514       
515       
516
517       
518        ////////////////////////////////////// step ///////////////////////////////////////////////////////////
519        /**
520         * Process the events for the current step of the simulation
521         *
522         */
523       
524       
525        /**
526         * PTVS
527         */
528       
529       
530        public void step() {
531               
532                int cnt = 0;
533               
534                if(Globals.SOCIALNETWORK == 1){
535                        double sec = vnsim.socialNet.GlobalNetwork.nextReconfigurationTime*Globals.SECOND;
536                }
537                       
538                if (crtTime >  3.5 * Globals.HOUR){     //nu rulez mai mult de 3 ore juma
539                        doneFlag = true;
540                        System.exit(0);
541                        return;
542                }
543                if (withGUI) {
544                        synchronized (Globals.mutex) {
545                                if (Globals.flag == 1) {
546                                        try {
547                                                Globals.mutex.wait();
548                                        } catch (Exception e) {
549                                               
550                                        }
551                                }
552                                Globals.flag = 0;
553                        }
554                }
555
556                long t1 = System.currentTimeMillis();
557                if (crtTime % Globals.SECOND == 0)
558                {
559                        lastSimSecond = (double)(t1-prevRealSec)/1000;
560                        prevRealSec = t1;
561                        if (lastSimSecond < 1)
562                                try{
563                                        Thread.sleep(100);//(int)((1.0 - lastSimSecond)*1000));
564                                }catch(Exception e){
565                                       
566                                }
567                }       
568               
569                if (crtTime % Globals.MINUTE == 0){
570
571                        Globals.packets = 0;
572                        Globals.collided = 0;
573                        Globals.lost = 0;
574                       
575                        System.out.println((crtTime / Globals.MINUTE) + " sim min;\t" +
576                                        "simulation time: "+ (System.currentTimeMillis() - t0) +"\t" +
577                                        " cars: "+cars.size() + " created " + created);
578
579                        Globals.volume = 0;
580                        Globals.demand = 0;
581                       
582                        //Petroaca
583                        if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
584                        {
585                                DSRCStatistics.addStatistic(new DSRCStatisticComponent(0,Globals.DSRC_PACKETS_LOST_WEAK,Globals.DSRC_PACKETS_TOTAL,Globals.DSRC_PACKETS_LOST_CORRUPTED,Globals.DSRC_PACKETS_LOST_COLLISION,Globals.DSRC_PACKETS_LOST_TX,Globals.DSRC_PACKETS_LOST_RX,Globals.DSRC_PACKETS_LOST_PER,Globals.DSRC_PACKETS_RECEIVED_OK
586                                                ,0,0,Globals.CUMMULATIVE_PACKETS_FV,Globals.CUMMULATIVE_PACKETS_NFV,Globals.CUMMULATIVE_PACKETS_LAV,Globals.CUMMULATIVE_PACKETS_RAV,Globals.IRT_FV,Globals.IRT_NFV,Globals.IRT_LAV,Globals.IRT_RAV,0,0,0,0,cars.size(),Globals.EMERGENCY_RECEIVED,Globals.EMERGENCY_SENT));
587                               
588                               
589                                Globals.DSRC_PACKETS_LOST_WEAK=0;
590                                Globals.DSRC_PACKETS_LOST_COLLISION=0;
591                                Globals.DSRC_PACKETS_LOST_TX=0;
592                                Globals.DSRC_PACKETS_LOST_RX=0;
593                                Globals.DSRC_PACKETS_LOST_PER=0;
594                                Globals.DSRC_PACKETS_LOST_CORRUPTED=0;
595                                Globals.DSRC_PACKETS_RECEIVED_OK=0;
596                                Globals.DSRC_PACKETS_TOTAL=0;
597                                Globals.DSRC_PACKETS_SEND_FALIURE_RX=0;
598                                Globals.DSRC_PACKETS_SEND_FALIURE_NOISE=0;
599                                Globals.DSRC_SEND=0;
600                               
601                                //System.out.println((crtTime / Globals.MINUTE)+ " min\t"+"FV:"+Globals.CUMMULATIVE_PACKETS_FV+" NFV:"+Globals.CUMMULATIVE_PACKETS_NFV+" LAV:"+Globals.CUMMULATIVE_PACKETS_LAV+" RAV:"+Globals.CUMMULATIVE_PACKETS_RAV+" EMERGENCY_RECV:"+Globals.EMERGENCY_RECEIVED+" EMERGENCY_SENT:"+Globals.EMERGENCY_SENT);
602                               
603                                Globals.CUMMULATIVE_PACKETS_RAV=0;
604                                Globals.CUMMULATIVE_PACKETS_LAV=0;
605                                Globals.CUMMULATIVE_PACKETS_FV=0;
606                                Globals.CUMMULATIVE_PACKETS_NFV=0;
607                                Globals.IRT_FV=0;
608                                Globals.IRT_NFV=0;
609                                Globals.IRT_LAV=0;
610                                Globals.IRT_RAV=0;
611                                Globals.EMERGENCY_RECEIVED=0;
612                                Globals.EMERGENCY_SENT=0;
613                               
614                                /*System.out.println("END DSRC DATA------------------------------");*/
615                        }       
616                }               
617                if (crtTime % (5 * Globals.MINUTE) == 0){
618                        if (lastTime == -1)
619                                lastTime = t0;
620                        long realTime = t1 - lastTime;
621                        lastTime = t1;
622
623                        eventsTime = 0;
624                        codeTime = 0;
625                        cleanupTime = 0;
626                        mobilityTime = 0;
627                       
628                        Globals.pw.flush();
629                       
630                        Globals.demo.st.clearInfo();
631                        Globals.demo.st.addInfo("Avg Delay "+ dec1(totalControlDelay/(fincars*60))+" min");
632                        Globals.demo.st.addInfo("Max Delay "+dec1(maxControlDelay / 60)+" min");
633                        Globals.demo.st.addInfo("Fuel: " + dec1( ( totalEM.fc * 100) / (1000 * totalkm)) + " L/100 km");
634                        Globals.demo.st.addInfo("CO2: " + dec1((totalEM.co2 * 20 )/ 1000)+" kg/h");
635                        Globals.demo.st.addInfo("CO: " + dec1((totalEM.co * 20 )/ 1000)+" kg/h");
636                        Globals.demo.st.addInfo("HC: " + dec1((totalEM.hc * 20 )/ 1000)+" kg/h");
637                        Globals.demo.st.addInfo("NOx: " + dec1((totalEM.nox * 20 )/ 1000)+" kg/h");
638                       
639
640                        if (fincars>0) {
641                                Globals.pwxc.println( "min " + (crtTime / Globals.MINUTE) +
642                                                "  cars: " + fincars + 
643                                                "  total time: " + totalTime +
644                                                "  total km: " + totalkm +
645                                                "  time/car: " + totalTime / fincars +
646                                                "  L/100: "+ ( (totalEM.fc * 100) / ( 1000 * totalkm)) +
647                                                "  fc: " + (totalEM.fc / fincars) +
648                                                "  co2: " + (totalEM.co2 / fincars) +
649                                                "  co: " + (totalEM.co / fincars) +
650                                                "  hc: " + (totalEM.hc / fincars) +
651                                                "  nox: " + (totalEM.nox / fincars)
652                                                );
653                                Globals.pwxc.flush();
654                        }
655                }               
656               
657               
658                if (startedWithGUI) {
659                        Globals.demo.st.setCount(crtTime);
660                        Globals.demo.st.setCurrentTime(System.currentTimeMillis() - t0);
661                        Globals.demo.st.setSimulationTime((float) ((crtTime * 1000) / fps));
662                        //Globals.demo.st.setSemTime(mycnt);
663                        Globals.demo.st.setNrEvents(eventQueue.size() + nrEvThreads);
664                        Globals.demo.st.setCarsNo(cars.size());                 
665                }
666               
667                long t2 = System.currentTimeMillis();
668               
669//              Petroaca - if DSRC simualtion play the events in emergency channel as well
670               
671                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC && Globals.MULTI_CHANNEL)
672                {
673                        while (true) {
674                                if (eventQueueEmergency.size() == 0) {
675                                        doneFlagEmergency = true;
676                                        break;
677                                }
678                               
679                                Event e = (Event) eventQueueEmergency.get(0);
680                                if (e.getTime() == crtTime) {
681                                        playEventEmergency();
682                                        //cnt++;
683                                } else
684                                        break;
685                        }
686                }
687               
688                /*while (true) {
689                        if (eventQueue.size() == 0) {
690                                doneFlag = true;
691                                return;
692                        }
693                       
694                        Event e = (Event) eventQueue.get(0);
695                        if (e.getTime() == crtTime) {
696                                playEvent(null);
697                                cnt++;
698                        } else
699                                break;
700                }*/
701
702               
703                /**
704                 * PTVS Project
705                 * we know how many intersections i have, to start as many threads as intersections i have
706                 */
707                Map map = Globals.map;
708                ArrayList<Intersection> intersectii = map.allIntersections;
709                numThreads=intersectii.size();
710                numThreads = Globals.NO_FEP_PROC - 1;
711               
712                while (true) {
713                       
714                        if (eventQueue.size() == 0) {
715                                doneFlag = true;
716                                System.out.println("\ndoneFlag = true ");
717                                return;
718                        }
719                       
720                        // extrag un eveniment din coada !!!!! acum doar il extrag.. cand intru in playEvent il si scot cu remove(0)
721                        Event e = (Event) eventQueue.get(0);
722                        if (e == null) continue;
723                       
724                        if (e.getTime() == crtTime) {
725                                //System.out.println("------------->> e.getTime() == crtTime== "+crtTime);
726                               
727                        }
728                       
729                        if(dimens!=eventQueue.size()){
730                               
731                                System.out.println("\n----------- number of events in the queue:" +eventQueue.size());
732                                dimens = eventQueue.size();
733                        }
734                       
735                       
736                        /**
737                         * PTVS Project
738                         *
739                         * we have an array of threads for processing events based on location (intersection)
740                         * i process only receive and send messages
741                         */
742                       
743               
744                        if((e instanceof SendEvent) || (e instanceof ReceiveEvent)){
745                               
746                                synchronized (eventQueue) {
747                                        e = eventQueue.remove(0);
748                                        nrEvThreads++;
749                                        //System.out.println("remove from eventQueue");
750                                }
751                               
752                                /**
753                                 * PTVS Project
754                                 * i should know the location of the event
755                                 */                     
756                                Road r = null;
757                                Point p = null;
758                                if(e instanceof SendEvent){
759                                        SendEvent se=(SendEvent)e;
760                                        r = (Road) Globals.map.roads.get(se.sender.getRoadIdx());       //aflu strada pe care se afla senderul
761                                        p = (Point) r.points.get(se.sender.getPointIdx());                      //aflu punctul unde se afla senderul
762                                }
763                                if(e instanceof ReceiveEvent){
764                                        ReceiveEvent re=(ReceiveEvent)e;
765                                        r = (Road) Globals.map.roads.get(re.sender.getRoadIdx());
766                                        p = (Point) r.points.get(re.sender.getPointIdx());
767                                }
768                               
769                                //System.out.println("p:"+p);
770                               
771                                /**
772                                 * PTVS Project
773                                 * from intersections array, i find the closest one
774                                 */
775                                double MIN_DIST=Double.MAX_VALUE;
776                                int indexClosestIntersection=0;
777                                double distanta;
778                                for(int i=0;i<intersectii.size();i++){ 
779                                        Intersection intersectie = intersectii.get(i);
780                                        if(r.getPoints().contains(intersectie.getMapPoint())){ //iau in calcul doar intersectiile aflate pe strada pe care sunt
781                                                distanta=GPSutil.distance(p, intersectie.getMapPoint());
782                                                if (distanta < MIN_DIST){
783                                                        MIN_DIST=distanta;
784                                                        indexClosestIntersection=i;                                             
785                                                }
786                                        }
787                                               
788                                }
789                               
790                                /**
791                                 * PTVS Project
792                                 * i will assign a thread for the event
793                                 */
794                               
795                               
796                                if (e.getTime() == crtTime) {
797                               
798                                        if(e instanceof SendEvent){             
799                                               
800                                                        System.out.print("SendEvent: ");
801                                                        //processingThreads[indexClosestIntersection] = new SendEventProcessingThread(e,this);
802                                                }
803                                        else {                                 
804                                                        System.out.print("ReceiveEvent: ");
805                                                        //processingThreads[indexClosestIntersection] = new ReceiveEventProcessingThread(e,this);
806                                                }
807                                       
808                                        System.out.println("Processing thread "+indexClosestIntersection+" from intersection "+intersectii.get(indexClosestIntersection));
809                                       
810                                        try {
811                                                int indexThread = indexClosestIntersection % (Globals.NO_FEP_PROC - 1);
812                                                start(e, indexThread);
813                                                cnt++;
814                                               
815                                        } catch (IOException e1) {
816                                                System.out.println("exception on assigning event for thread");
817                                                e1.printStackTrace();
818                                        }
819                                       
820                                        //new Thread(processingThreads[indexClosestIntersection]).start();
821                                       
822                                }
823                                else
824                                        break;
825                        }
826                       
827                        else if (e.getTime() == crtTime) {
828                                System.out.println("OtherEvent ");
829                                playEvent(null);
830                                cnt++;
831                               
832                        } else
833                                break;
834                       
835                       
836                }
837               
838                ///////////////////////end PTVS Project/////////////////////////////////////////////////////
839               
840                //increment simulation time
841                crtTime++;
842                //System.out.println("Increment crtTime!  crtTime:"+crtTime);
843               
844                long t3 = System.currentTimeMillis();
845                if (crtTime % (Globals.executionFPS / Globals.FPS) == 0)
846                        if (!runtimeMobility)
847                                readScenarioPhase();
848                        else
849                                generateScenarioPhase();
850               
851                checkCreateNewCars();
852               
853                long t4 = System.currentTimeMillis();
854                eventsTime += t3 - t2;
855                mobilityTime += t4 - t3;
856
857                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
858                        if (crtTime % 100 == 0) {
859                                for (int i = 0; i < this.infrastructure.size(); i++) {
860                                       
861                                        ((InfrastructureNode) this.infrastructure.get(i)).updateDelays();
862                                }
863                        }
864                }
865                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
866                        for (int i = 0; i < this.infrastructure.size(); i++) {
867                                ((IntersectionNode) infrastructure.get(i)).step(crtTime);
868                        }
869                        server.step(crtTime);
870                }
871        }
872        //////////////////////////////////////////////end metoda step////////////////////////////////////
873
874        static Random random = new Random();
875
876        public static int lastCarID = 0;
877
878        /**
879         * Insert new cars at the map entry points according to the scheduled flow.
880         *
881         */
882        private void checkCreateNewCars(){
883
884                int percent;
885//              should create some new cars?
886                NewCarEvent first=Mobility.events.first();
887                while(first!=null && first.timestamp==crtTime) {
888                        //create this one
889                        EntryScenario es=Mobility.entryScenarios.get(first.index);
890
891                        int roadIndexSrc=es.entry.roadIdx;
892                        int pointIndexSrc=es.entry.ptIdx;
893
894                        int ID=lastCarID;
895                        lastCarID++;
896
897                        //which exit is the car going towards?
898                        double rand;
899                        rand=(random.nextDouble())*100;
900                        int i=0;
901                        int sum=0;
902                        while(i<es.entryExits.size()) {
903                                sum+=es.entryExits.elementAt(i).percentOfFlow;
904                                if(rand<sum) {
905                                        //this is the chosen exit
906                                        break;
907                                }
908                                i++;
909                        }
910                        EntryExitScenario ees=null;
911                        if(i==es.entryExits.size()) {
912                                //last exit chosen
913                                ees=es.entryExits.lastElement();
914                        } else 
915                                ees=es.entryExits.elementAt(i);
916
917                        int roadIndexDst=ees.exit.roadIdx;
918                        int pointIndexDst=ees.exit.ptIdx;
919
920                        //which route is the car choosing?
921                        rand=(random.nextDouble())*100;
922                        i=0;
923                        sum=0;
924                        while(i<ees.percentsEachRoute.size()) {
925                                sum+=ees.percentsEachRoute.elementAt(i);
926                                if(rand<sum) {
927                                        //this is the chosen route
928                                        break;
929                                }
930                                i++;
931                        }
932                        Route r=null;
933                        if(i==ees.percentsEachRoute.size()) {
934                                //last route chosen
935                                r=ees.routes.lastElement();
936                        } else 
937                                r=ees.routes.elementAt(i);
938
939                        for(i=0;i<Globals.map.roads.get(roadIndexSrc).laneNo;i++) {
940                                //one vehicle on each lane
941
942                                Personality personality;
943                                rand=(random.nextDouble())*100;
944                                if(rand<es.percentsDriverTypes.elementAt(0)) 
945                                {
946                                        personality=new CalmPersonality();
947                                } else if(rand<es.percentsDriverTypes.elementAt(0)+es.percentsDriverTypes.elementAt(1)) {
948                                        personality=new RegularPersonality();
949                                } else {
950                                        personality=new AggresivePersonality();
951                                }
952                               
953                                CarInstance car = null;
954                                if (simulationType == RoutingConstants.INITIALLY_PROVIDED_ROUTE || simulationType == RoutingConstants.ROUTING_SCFT) {
955                                       
956                                        car = Mobility.createNewCar(roadIndexSrc,
957                                                        pointIndexSrc, 0, i + 1, 0.0, personality, /*personality.getWantedSpeed(roadIndexSrc)*/ 0.0, ID,
958                                                        roadIndexDst, pointIndexDst, r.route);
959                                       
960                                        System.out.println("Finished creating new car "+car);
961                                       
962                                        double d =0;
963                                        if(car!=null)
964                                                d = car.getDistanceToCarInFront();
965                                        if (d < 10 && d!=0) {
966                                                // closer than 5 meters --> do not create
967                                                // System.out.println("Skipping creation...");
968                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad.remove(car.ID);
969                                                continue;
970                                        }
971                                }
972
973                                if (Engine.simulationType == RoutingConstants.DYNAMIC_SELF_ROUTE) {
974                                        System.out.println("Dynamic; we are here");
975                                        percent = random.nextInt(100);
976                                        percent = (int) Math.abs((double) percent);
977                                        if (percent <= Globals.routePlanConstants.percentBestRoute) {
978                                                percent = 1;
979                                        } else {
980                                                percent = 0;
981                                        }
982                                        car = Mobility.createNewCar(roadIndexSrc, pointIndexSrc, 0,
983                                                        i + 1, 0.0, personality, 0.0, ID, roadIndexDst,
984                                                        pointIndexDst, r.route, percent);
985                                        if (car == null) {
986                                       
987                                                continue;
988                                        }
989                                        double d = car.getDistanceToCarInFront();
990                                        if (d < 10) {
991                                                // closer than 10 meters --> do not create
992                                               
993                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad.remove(car.ID);                                         
994                                                continue;
995                                        }
996
997                                }
998                                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
999
1000                                        car = Mobility.createNewCarCommunicatingWithInfrastucture(
1001                                                        roadIndexSrc, pointIndexSrc, 0, i + 1, 0.0,
1002                                                        personality, 0.0, ID, roadIndexDst, pointIndexDst,
1003                                                        r.route);
1004                                        if (car == null) {
1005                                               
1006                                                continue;
1007                                        }
1008                                        double d = car.getDistanceToCarInFront();
1009                                        if (d < 10) {
1010                                                // closer than 10 meters --> do not create                                             
1011                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
1012                                                                .remove(car.ID);
1013                                               
1014
1015                                                continue;
1016                                        }
1017
1018                                }
1019                               
1020                                //create new ezcab client (entity)
1021                               
1022                                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
1023
1024                                        car = Mobility.createNewCityCarCommunicatingWithInfrastucture(
1025                                                        roadIndexSrc, pointIndexSrc, 0, i + 1, 0.0,
1026                                                        personality, 0.0, ID, roadIndexDst, pointIndexDst,
1027                                                        r.route);
1028                                        if (car == null) {                                     
1029                                                continue;
1030                                        }
1031                                        double d = car.getDistanceToCarInFront();
1032                                        if (d < 10) {
1033                                                // closer than 10 meters --> do not create                                             
1034                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
1035                                                                .remove(car.ID);
1036                                               
1037
1038                                                continue;
1039                                        }
1040
1041                                }
1042
1043                                ID = lastCarID;
1044                                lastCarID++;
1045                                this.addCar(car);
1046                        }
1047                        Mobility.events.removeFirst();
1048                       
1049                        try {
1050                                EntryFlowVariation efv=Mobility.entryFlowVariations.get(first.index);
1051                               
1052                                if(efv.getFirstMom()<crtTime && efv.getFirstMom()!=-1) {
1053                                        int newFlow=efv.getFirstValue();
1054                                        int old=first.period;
1055                                        first.period=(int)((double)(3600 * Globals.SECOND) / newFlow);
1056                                        System.out.print("TIME="+crtTime+"; CHANGING PERIOD FOR ENTRY="+first.index+" FROM: "+old+" TO: "+first.period);
1057                                        efv.removeFirst();
1058                                }
1059                        } catch (Exception ex) {
1060                               
1061                        }
1062                        if(Globals.SOCIALNETWORK == 0 )
1063                                Mobility.events.addEvent(new NewCarEvent(first.timestamp
1064                                                + first.period, first.index, first.period));
1065                        first = Mobility.events.first();
1066                }
1067        }
1068
1069////////////////////////////////////////// playEvent ////////////////////////////////////////////////////////////////   
1070
1071        long messagesSize = 0;
1072        long carInfosSize = 0;
1073        /**
1074         * Execute the following event in the eventQueue
1075         *
1076         */
1077        public void playEvent(Event ev) {
1078        //public void playEvent() {
1079               
1080                //System.out.println(">> Thread:"+Thread.currentThread().getName());
1081               
1082                if (eventQueue.size() == 0) {
1083                        doneFlag = true;
1084                        return;
1085                }
1086
1087                Event e = null;
1088                if (ev == null) {
1089                        synchronized (eventQueue) {
1090                                e = eventQueue.remove(0);
1091                                //System.out.println("remove from eventQueue");
1092                        }
1093                } else {
1094                        e = ev;
1095                        synchronized (eventQueue) { nrEvThreads--; }
1096                }
1097                //System.out.print(e.toString()+", ");
1098                //System.out.flush();
1099                               
1100                if (e instanceof GPSEvent) {    //////////// eveniment GPS
1101                       
1102                        Iterator<SimulatedCarInfo> it = cars.iterator();
1103                        while (it.hasNext()) {
1104                                SimulatedCarInfo r = it.next();
1105                                r.update();
1106                        }
1107                        GPSEvent newEvent = new GPSEvent(crtTime + fps);
1108                        schedEvent(newEvent);
1109                }
1110                if (e instanceof CleanupEvent) {        //////////// eveniment CLEANUP
1111
1112                        long t1 = System.currentTimeMillis();
1113                        long deleted = 0;
1114                        Iterator<SimulatedCarInfo> it = cars.iterator();
1115                        while (it.hasNext()) {
1116                                SimulatedCarInfo r = it.next();
1117synchronized (r.trafficDB) {
1118                                Iterator<CarInfo> j = r.trafficDB.iterator();
1119                                while (j.hasNext()) {
1120                                        CarInfo neighbor = j.next();
1121                                        if ( (crtTime - neighbor.getTimestamp() > Globals.NEIGHBOR_EXPIRES && neighbor.state != 3) ||
1122                                                        (neighbor.state == 3 && crtTime - neighbor.getTimestamp() > Globals.PROMISCUOUS_NEIGHBOR_EXPIRES)){
1123                                                j.remove();
1124                                        }
1125                                }
1126}
1127                                carInfosSize += r.trafficDB.size();
1128                        }
1129                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
1130                                WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
1131                                                .get(Globals.map.lightsIndices.get(j));
1132                               
1133                                synchronized(wtl.trafficDB){
1134                                        Iterator<IntersectionCarRecord> wtlit = wtl.trafficDB.iterator();
1135                                        while (wtlit.hasNext()) {
1136                                                IntersectionCarRecord icr = wtlit.next();
1137                                                if (!icr.isPassed() && crtTime - icr.getCar().getTimestamp() > Globals.HOUR 
1138                                                                && icr.getCar().state != 3){
1139                                                        icr.segment.cars.remove(icr);
1140                                                        wtlit.remove();
1141                                                        deleted++;
1142                                                }
1143                                                if (icr.isPassed() && crtTime - icr.getCar().getTimestamp() > Globals.TRAFFICLIGHT_NEIGHBOR_EXPIRES){
1144                                                        icr.segment.cars.remove(icr);
1145                                                        wtlit.remove();
1146                                                }
1147                                        }
1148                                }
1149                        }
1150                        long t2 = System.currentTimeMillis();
1151                        cleanupTime += t2 - t1;
1152                        if (!disableComm) {
1153                                CleanupEvent newCleanupEvent = new CleanupEvent(crtTime + fps);
1154                                schedEvent(newCleanupEvent);
1155                        }
1156                        messagesSize = 0;
1157                }
1158               
1159                if (e instanceof SendEvent) {   /////////////////////////////// eveniment SEND
1160                       
1161                        SendEvent se = (SendEvent) e;
1162                        Communicator sender = se.getSender();
1163                       
1164                        long t1 = System.currentTimeMillis();   
1165                       
1166                        // senderul e un SimulatedCarInfo
1167                       
1168                        if (se.getMessage() == null){
1169                                byte[] message = sender.prepareMessage(se.getMessageType());
1170                                se.setMessage(message);
1171                                if (se.getMessage() == null){
1172                                        if (sender.isPromiscuousMode() && sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1173                                                int eventPeriod = sender.getPeriod(se.getMessageType());
1174                                                if (eventPeriod != -1)
1175                                                        schedEvent(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1176                                        }
1177                                        return;
1178                                }
1179                                messagesSize += message.length;
1180                                long t2 = System.currentTimeMillis();
1181                                codeTime += t2 - t1;
1182
1183                                if (sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1184                                        int eventPeriod = sender.getPeriod(se.getMessageType());
1185                                        if (eventPeriod != -1)
1186                                                schedEvent(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1187                                }
1188                        }
1189                       
1190                        //Petroaca - the DSRC impl
1191                        if(Engine.simulationProtocol==Globals.PROTOCOL_80211)
1192                        {
1193                               
1194                                if (!sender.mediumAvailable(crtTime)) {
1195                                        e.setTime(crtTime + 1);
1196                                        schedEvent(e);
1197                                       
1198                                        return;
1199                                }
1200                               
1201                                sender.getRadio().setRadioTxMode();
1202                                simulateCommunication(se);
1203                       
1204                        }
1205                        else
1206                        {
1207                                if(sender instanceof CarRunningDSRC)
1208                                {
1209                                        MAC80211 macs=((CarRunningDSRC)sender).getMac();
1210                                        WirelessPhy phys=((CarRunningDSRC)sender).getPhysical();
1211                                       
1212                                        macs.refreshFrameTime(crtTime);
1213                                        phys.refreshFrameTime(crtTime);
1214                                       
1215                                        if(macs.sendToPhysical(se.getMessage(),crtTime)!=null)
1216                                        {
1217                                                phys.sendToChannel(se.getMessage(),crtTime);
1218                                                macs.setChannelState(Globals.CCA_BUSY);
1219                                                simulateCommunication(se);
1220                                        }
1221                                        else
1222                                        {
1223                                       
1224                                                e.setTime(crtTime+1);
1225                                                schedEvent(e);
1226                                               
1227                                        }
1228                                        return;
1229                                } 
1230                                else
1231                                {
1232                                        if (!sender.mediumAvailable(crtTime)) {
1233                                                e.setTime(crtTime + 1);
1234                                                schedEvent(e);
1235                                               
1236                                                return;
1237                                        }
1238                                       
1239                                        sender.getRadio().setRadioTxMode();
1240                                        simulateCommunication(se);
1241                                }
1242                        }
1243                }
1244               
1245                if (e instanceof ReceiveEvent) {        //////////////////////// eveniment RECEIVE
1246                        ReceiveEvent re = (ReceiveEvent) e;
1247
1248                                long t1 = System.currentTimeMillis();
1249                               
1250                                //Petroaca - the DSRC impl
1251                                if(Engine.simulationProtocol==Globals.PROTOCOL_80211){
1252                                        RadioDev rxradio = re.receiver.getRadio();
1253                                        ReceiveEvent goodSignal = rxradio.receive(re.signals);
1254                                        re.receiver.removeReceiveEventForTime(re.getTime());
1255                               
1256                                        if (goodSignal != null){
1257                                                        re.receiver.onReceive(goodSignal.getMessage(), goodSignal.getMessageObject(), goodSignal.sender);
1258                                                }
1259                                }
1260                                else
1261                                {
1262                                        if(re.receiver instanceof CarRunningDSRC)
1263                                        {
1264                                                MAC80211 macr=((CarRunningDSRC)re.receiver).getMac();
1265                                                WirelessPhy phyr=((CarRunningDSRC)re.receiver).getPhysical();
1266                                                Application appr=((CarRunningDSRC)re.receiver).getAppLayer();
1267                                               
1268                                                if(Globals.DIFFERENTIAL_CW)
1269                                                        macr.recalculateCW(phyr.getTotalReceivedPackets(),crtTime);
1270                                               
1271                                                macr.refreshFrameTime(crtTime);
1272                                                phyr.refreshFrameTime(crtTime);
1273                                                appr.refreshApplication(crtTime);
1274                                               
1275                                                ReceiveEvent best=phyr.recvFromChannel(re.signals,crtTime);
1276                                                re.receiver.removeReceiveEventForTime(re.getTime());
1277                                               
1278                                                double sinr=phyr.getSINR();
1279                                                if(best!=null)
1280                                                {
1281                                                        macr.setChannelState(Globals.CCA_BUSY); 
1282                                                       
1283                                                        if(macr.recvFromPhysical(best,sinr,crtTime)!=null)
1284                                                        {
1285                                                                appr.ForwardCollisionWarning(best.getMessage(),((CarInfo)re.receiver));
1286                                                                //appr.LaneChangeAssistance(best.getMessage(),((CarInfo)re.receiver));
1287                                                                re.receiver.onReceive(best.getMessage(), best.getMessageObject(), best.sender);
1288                                                        }
1289                                                }
1290                                        }
1291                                        else
1292                                        {
1293                                                RadioDev rxradio = re.receiver.getRadio();
1294                                                ReceiveEvent goodSignal = rxradio.receive(re.signals);
1295                                                re.receiver.removeReceiveEventForTime(re.getTime());
1296                                       
1297                                                if (goodSignal != null){
1298                                                                re.receiver.onReceive(goodSignal.getMessage(), goodSignal.getMessageObject(), goodSignal.sender);
1299                                                        }
1300                                        }
1301                                }       
1302                               
1303                                long t2 = System.currentTimeMillis();
1304                                codeTime += t2 - t1;
1305                        }
1306        }
1307
1308
1309        public void playEventEmergency()
1310        {
1311                if (eventQueueEmergency.size() == 0) {
1312                        doneFlagEmergency = true;
1313                        return;
1314                }
1315
1316                Event e = null;
1317                synchronized (eventQueueEmergency) {
1318                        e = eventQueueEmergency.remove(0);
1319                }
1320               
1321                if (e instanceof SendEvent) {
1322                        SendEvent se = (SendEvent) e;
1323                        Communicator sender = se.getSender();
1324                       
1325                        long t1 = System.currentTimeMillis();   
1326                       
1327                       
1328                        if (se.getMessage() == null){
1329                                byte[] message = sender.prepareMessage(se.getMessageType());
1330                                se.setMessage(message);
1331                                if (se.getMessage() == null){
1332        //                              System.out.println("null message"+se.sender + " "+se.sender.getClass());
1333                                        if (sender.isPromiscuousMode() && sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1334                                                int eventPeriod = sender.getPeriod(se.getMessageType());
1335                                                if (eventPeriod != -1)
1336                                                        schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1337                                        }
1338                                        return;
1339                                }
1340                                messagesSize += message.length;
1341                                long t2 = System.currentTimeMillis();
1342                                codeTime += t2 - t1;
1343
1344                                if (sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1345                                        int eventPeriod = sender.getPeriod(se.getMessageType());
1346                                        if (eventPeriod != -1)
1347                                                schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1348                                }
1349                        }
1350                       
1351                        //Petroaca - the DSRC impl
1352                                if(sender instanceof CarRunningDSRC)
1353                                {
1354                                        MAC80211 macs=((CarRunningDSRC)sender).getMac();
1355                                        WirelessPhy phys=((CarRunningDSRC)sender).getPhysical();
1356                                       
1357                                        macs.refreshFrameTime(crtTime);
1358                                        phys.refreshFrameTime(crtTime);
1359                                       
1360                                        if(macs.sendToPhysical(se.getMessage(),crtTime)!=null)
1361                                        {
1362                                                phys.sendToChannel(se.getMessage(),crtTime);
1363                                                macs.setChannelState(Globals.CCA_BUSY);
1364                                                simulateCommunicationEmergency(se);
1365                                        }
1366                                        else
1367                                        {
1368                                       
1369                                                e.setTime(crtTime+1);
1370                                                schedEventEmergency(e);
1371                                               
1372                                        }
1373                                        return;
1374                                }
1375                               
1376                                if(sender instanceof CarRunningDSRC)
1377                                {
1378                                        return;
1379                                }
1380                                else
1381                                {
1382                                        return;
1383                                }
1384                        }
1385                       
1386                if (e instanceof ReceiveEvent) {
1387                        ReceiveEvent re = (ReceiveEvent) e;
1388                       
1389                        long t1 = System.currentTimeMillis();
1390                       
1391                        //Petroaca - the DSRC impl
1392                               
1393                                        if(re.receiver instanceof CarRunningDSRC)
1394                                        {
1395                                                MAC80211 macr=((CarRunningDSRC)re.receiver).getMac();
1396                                                WirelessPhy phyr=((CarRunningDSRC)re.receiver).getPhysical();
1397                                                Application appr=((CarRunningDSRC)re.receiver).getAppLayer();
1398                                                appr.refreshApplication(crtTime);
1399                                               
1400                                                if(Globals.DIFFERENTIAL_CW)
1401                                                        macr.recalculateCW(phyr.getTotalReceivedPackets(),crtTime);
1402                                               
1403                                                macr.refreshFrameTime(crtTime);
1404                                                phyr.refreshFrameTime(crtTime);
1405                                               
1406                                                ReceiveEvent best=phyr.recvFromChannel(re.signals,crtTime);
1407                                                ((SimulatedCarInfo)re.receiver).removeReceiveEventEmergencyForTime(re.getTime());
1408                                               
1409                                                double sinr=phyr.getSINR();
1410                                                if(best!=null)
1411                                                {
1412                                                        macr.setChannelState(Globals.CCA_BUSY); 
1413                                                       
1414                                                        if(macr.recvFromPhysical(best,sinr,crtTime)!=null)
1415                                                        {
1416                                                                //appr.ForwardCollisionWarning(best.getMessage(),((CarInfo)re.receiver));
1417                                                                //appr.LaneChangeAssistance(best.getMessage(),((CarInfo)re.receiver));
1418                                                                re.receiver.onReceive(best.getMessage(), best.getMessageObject(), best.sender);
1419                                                        }
1420                                                }
1421                                        }
1422                                        long t2 = System.currentTimeMillis();
1423                                        codeTime += t2 - t1;
1424                                }       
1425        }
1426       
1427        /**
1428         * Applications may schedule dynamically communication events using this method
1429         * to insert new events in the queue.
1430         *
1431         * @param e Event to schedule
1432         */
1433        public void schedEvent(Event e) {
1434
1435                long t1 = System.currentTimeMillis();
1436
1437                if (e instanceof ReceiveEvent) {
1438                        ReceiveEvent re = (ReceiveEvent) e;
1439                        ReceiveEvent existing = re.receiver.getReceiveEventForTime(e.getTime());
1440                        //getReceiveEventForTime returneaza evenimentele receive petrecute la momentul e.getTime()
1441                       
1442                        if (existing == null){
1443                                re.receiver.addReceiveEventForTime(re);
1444                        }else{
1445                                existing.signals.add(re);
1446                                return;
1447                        }
1448                }
1449               
1450                // cauta evenimetul in coada, ii gaseste pozitia corecta in lista de evenimente si il adauga
1451                // ce face de fapt? de ce cauta un eveniment si il readauga tot pe el in lista???
1452                int idx = Collections.binarySearch(eventQueue, e);
1453                synchronized (eventQueue) {
1454                        if (idx >= 0) {
1455                                // advance till the end of the sequence of equal events
1456                                if (eventQueue.get(idx).equals(e))
1457                                        idx++;
1458                                eventQueue.add(idx, e);
1459                                //System.out.println("add in eventQueue..");
1460                        } else {
1461                                eventQueue.add(-(idx + 1), e);
1462                                //System.out.println("add in eventQueue....");
1463                        }
1464                }
1465                long t2 = System.currentTimeMillis();
1466                schedTime += t2 - t1;
1467        }
1468
1469        //Petroaca - the message scheduler for the emergency channel
1470        public void schedEventEmergency(Event e)
1471        {
1472                long t1 = System.currentTimeMillis();
1473
1474                if (e instanceof ReceiveEvent) {
1475                        ReceiveEvent re = (ReceiveEvent) e;
1476                        ReceiveEvent existing = ((SimulatedCarInfo)re.receiver).getReceiveEventEmergencyForTime(e.getTime());
1477                        if (existing == null){
1478                                ((SimulatedCarInfo)re.receiver).addReceiveEventEmergencyForTime(re);
1479                        }else{
1480                                existing.signals.add(re);
1481                                return;
1482                        }
1483                }
1484               
1485                int idx = Collections.binarySearch(eventQueueEmergency, e);
1486                synchronized (eventQueueEmergency) {
1487                        if (idx >= 0) {
1488                                // advance till the end of the sequence of equal events
1489                                if (eventQueueEmergency.get(idx).equals(e))
1490                                        idx++;
1491                                eventQueueEmergency.add(idx, e);
1492                        } else {
1493                                eventQueueEmergency.add(-(idx + 1), e);
1494                        }
1495                }
1496                long t2 = System.currentTimeMillis();
1497                schedTime += t2 - t1;
1498        }
1499       
1500        /**
1501         * Generate the receive events corresponding to one send event, for the cars
1502         * in the wireless range of the sending car.
1503         *
1504         */
1505        public void simulateCommunication(SendEvent e) {
1506               
1507                Road r1 = null;
1508                Point p1 = null;
1509                r1 = (Road) Globals.map.roads.get(e.sender.getRoadIdx());
1510                p1 = (Point) r1.points.get(e.sender.getPointIdx());
1511               
1512                if (e instanceof UnicastSendEvent) {
1513                        long t1 = System.currentTimeMillis();
1514                        Iterator<SimulatedCarInfo> it = cars.iterator();
1515                        ReceiveEvent re = null;
1516                        while (it.hasNext()) {
1517                                SimulatedCarInfo r = it.next();
1518                                if (r.vehicleId == ((UnicastSendEvent) e).getReceiverId()) {
1519                                        Road r2 = (Road) Globals.map.roads.get(r.getRealPos().getRoadIdx());
1520                                        Point p2 = (Point) r2.points.get(r.getRealPos().getPointIdx());
1521
1522                                        // MODIFIED BY CRISTI!!!
1523                                        // ReceiveEvent er = new ReceiveEvent(e.getTime() + 1, r, e.getMessage());
1524
1525                                        re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1526                                        re.setUnicast(true);
1527
1528                                        schedEvent(re);
1529                                        if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
1530                                        } else {
1531                                                System.out.println("EROARE! DISTANCE="+ GPSutil.distance(p1, p2));
1532                                        }
1533                                        // END MODIFIED!!!
1534                                        return;
1535                                }
1536                        }
1537                       
1538                       
1539                        re.setSender(e.getSender());
1540                       
1541                        schedEvent(re);
1542
1543                        long t2 = System.currentTimeMillis();
1544                        netTime += t2 - t1;
1545
1546                } else {
1547                       
1548                        long tmp = 0;
1549                        long t3 = System.currentTimeMillis();
1550                        long t4;
1551
1552//                      re = new ReceiveEvent(e.getTime() + 1, e.getSender(), e.getMessage());
1553                       
1554
1555                        int cnt3 = 0;
1556                        int pkcnt = 0;
1557                        PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
1558
1559                        ListIterator<PeanoKey> pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1560                        PeanoKey maxpk = null;
1561                       
1562                        double wifirange;
1563                        if (e.sender instanceof WirelessTrafficLight){
1564                                maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
1565                                wifirange = EXTENDED_WIRELESS_RANGE;
1566                        }else{
1567                                wifirange = WIRELESS_RANGE;
1568                                maxpk = pk.getMaxpk();
1569                        }
1570                       
1571                        PeanoKey pkx = null;
1572                        for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
1573                                pkcnt++;
1574                                // long tc1 = System.currentTimeMillis();
1575                                if (pkx.compareTo(maxpk) > 0)
1576                                        break;
1577                                // long tc2 = System.currentTimeMillis();
1578                                // comp += (tc2-tc1);
1579
1580                                if (pkx.getCars() != null) {
1581                                        Road r2 = (Road) Globals.map.roads.get(pkx.getRoadIndex());
1582                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1583                                        if (GPSutil.distance(p1, p2) < 5 * wifirange) {
1584                                                cnt3 += pkx.getCars().size();
1585                                                Iterator<SimulatedCarInfo> it = pkx.getCars().iterator();
1586                                                while (it.hasNext()) {
1587                                                        SimulatedCarInfo r = it.next();
1588                                                        if (e.sender instanceof SimulatedCarInfo)
1589                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender).getVehicleId())
1590                                                                        continue;
1591                                                        r.setLastMediumTransmition(crtTime);
1592                                                       
1593                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1594                                                        re.setSender(e.getSender());
1595                                                        schedEvent(re);
1596                                                }
1597                                        }
1598                                }
1599                        }
1600                        PeanoKey minpk = null;
1601                        if (e.sender instanceof WirelessTrafficLight)
1602                                minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
1603                        else
1604                                minpk = pk.getMinpk();
1605                       
1606                        pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1607
1608                        if (pkit.hasPrevious()){
1609                                pkx = pkit.previous();
1610                        }
1611                        for (; pkit.hasPrevious(); pkx = pkit.previous()) {
1612                                pkcnt++;
1613                                // long tc1 = System.currentTimeMillis();
1614                                if (pkx.compareTo(minpk) < 0) {
1615                                        break;
1616                                }
1617                                // long tc2 = System.currentTimeMillis();
1618                                // comp += (tc2-tc1);
1619
1620                                if (pkx.getCars() != null) {
1621                                        Road r2 = (Road) Globals.map.roads.get(pkx.getRoadIndex());
1622                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1623                                        double distance = GPSutil.distance(p1, p2);
1624                                        if (distance < 5 * wifirange) {
1625                                                Iterator<SimulatedCarInfo> it = pkx.getCars().iterator();
1626                                                cnt3 += pkx.getCars().size();
1627                                                while (it.hasNext()) {
1628                                                        SimulatedCarInfo r = it.next();
1629                                                       
1630                                                        r.setLastMediumTransmition(crtTime);
1631                                               
1632                                                        if (e.sender instanceof SimulatedCarInfo)
1633                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender).getVehicleId())
1634                                                                        continue;
1635                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1636                                                        re.setSender(e.getSender());
1637                                                        schedEvent(re);
1638                                                }
1639                                        }
1640                                }
1641                        }
1642                       
1643                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
1644                                WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
1645                                                .get(Globals.map.lightsIndices.get(j));
1646                                long t1sem = System.currentTimeMillis();
1647
1648                                if (GPSutil.distance(p1, wtl.getMapPoint()) < 5 * WIRELESS_RANGE) {
1649                                        wtl.setLastMediumTransmition(crtTime);
1650                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, wtl, e.getMessage(), e.getMessageObject(), e.getMessageType());
1651                                        re.setSender(e.getSender());
1652                                        schedEvent(re);
1653                                }
1654                                long t2sem = System.currentTimeMillis();
1655                                semTime += (t2sem - t1sem);
1656                        }
1657                       
1658                        t4 = System.currentTimeMillis();
1659                        tmp += t4 - t3;
1660                        netTime += tmp;
1661                }
1662        }
1663
1664        //Petroaca - the communication simulation for the emergency channel
1665        public void simulateCommunicationEmergency(SendEvent e) {
1666
1667                Road r1 = null;
1668                Point p1 = null;
1669                r1 = (Road) Globals.map.roads.get(e.sender.getRoadIdx());
1670                p1 = (Point) r1.points.get(e.sender.getPointIdx());
1671               
1672                if (e instanceof UnicastSendEvent) {
1673                        long t1 = System.currentTimeMillis();
1674                        Iterator<SimulatedCarInfo> it = cars.iterator();
1675                        ReceiveEvent re = null;
1676                        while (it.hasNext()) {
1677                                SimulatedCarInfo r = it.next();
1678                                if (r.vehicleId == ((UnicastSendEvent) e).getReceiverId()) {
1679                                        Road r2 = (Road) Globals.map.roads.get(r.getRealPos()
1680                                                        .getRoadIdx());
1681                                        Point p2 = (Point) r2.points.get(r.getRealPos()
1682                                                        .getPointIdx());
1683
1684                                        // MODIFIED BY CRISTI!!!
1685                                        // ReceiveEvent er = new ReceiveEvent(e.getTime() + 1, r,
1686                                        // e.getMessage());
1687
1688                                        re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1689                                        re.setUnicast(true);
1690
1691                                        schedEventEmergency(re);
1692                                        if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
1693                                        } else {
1694                                                System.out.println("EROARE! DISTANCE="
1695                                                                + GPSutil.distance(p1, p2));
1696                                        }
1697                                        // END MODIFIED!!!
1698                                        return;
1699                                }
1700                        }
1701                       
1702                        re.setSender(e.getSender());
1703                        schedEventEmergency(re);
1704
1705                        long t2 = System.currentTimeMillis();
1706                        netTime += t2 - t1;
1707
1708                } else {
1709                       
1710                        long tmp = 0;
1711                        long t3 = System.currentTimeMillis();
1712                        long t4;
1713
1714//                      re = new ReceiveEvent(e.getTime() + 1, e.getSender(), e
1715//                                      .getMessage());
1716                       
1717
1718                        int cnt3 = 0;
1719                        int pkcnt = 0;
1720                        PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
1721
1722                        ListIterator<PeanoKey> pkit = Globals.map.peanoKeys
1723                                        .listIterator(p1.getPeanoKeyIdx());
1724                        PeanoKey maxpk = null;
1725                       
1726                        double wifirange;
1727                        if (e.sender instanceof WirelessTrafficLight){
1728                                maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
1729                                wifirange = EXTENDED_WIRELESS_RANGE;
1730                        }else{
1731                                wifirange = WIRELESS_RANGE;
1732                                maxpk = pk.getMaxpk();
1733                        }
1734                        PeanoKey pkx = null;
1735                        for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
1736                                pkcnt++;
1737                                // long tc1 = System.currentTimeMillis();
1738                                if (pkx.compareTo(maxpk) > 0)
1739                                        break;
1740                                // long tc2 = System.currentTimeMillis();
1741                                // comp += (tc2-tc1);
1742
1743                                if (pkx.getCars() != null) {
1744                                        Road r2 = (Road) Globals.map.roads.get(pkx
1745                                                        .getRoadIndex());
1746                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1747                                        if (GPSutil.distance(p1, p2) < 5 * wifirange) {
1748                                                cnt3 += pkx.getCars().size();
1749                                                Iterator<SimulatedCarInfo> it = pkx.getCars()
1750                                                                .iterator();
1751                                                while (it.hasNext()) {
1752                                                        SimulatedCarInfo r = it.next();
1753                                                        if (e.sender instanceof SimulatedCarInfo)
1754                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender)
1755                                                                        .getVehicleId())
1756                                                                        continue;
1757                                                        r.setLastMediumTransmition(crtTime);
1758                                                       
1759                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1760                                                        re.setSender(e.getSender());
1761                                                        schedEventEmergency(re);
1762                                                }
1763                                        }
1764                                }
1765                        }
1766                        PeanoKey minpk = null;
1767                        if (e.sender instanceof WirelessTrafficLight)
1768                                minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
1769                        else
1770                                minpk = pk.getMinpk();
1771                       
1772                        pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1773
1774                        if (pkit.hasPrevious()){
1775                                pkx = pkit.previous();
1776                        }
1777                        for (; pkit.hasPrevious(); pkx = pkit
1778                                        .previous()) {
1779                                pkcnt++;
1780                                // long tc1 = System.currentTimeMillis();
1781                                if (pkx.compareTo(minpk) < 0) {
1782                                        break;
1783                                }
1784                                // long tc2 = System.currentTimeMillis();
1785                                // comp += (tc2-tc1);
1786
1787                                if (pkx.getCars() != null) {
1788                                        Road r2 = (Road) Globals.map.roads.get(pkx
1789                                                        .getRoadIndex());
1790                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1791                                        double distance = GPSutil.distance(p1, p2);
1792                                        if (distance < 5 * wifirange) {
1793                                                Iterator<SimulatedCarInfo> it = pkx.getCars()
1794                                                                .iterator();
1795                                                cnt3 += pkx.getCars().size();
1796                                                while (it.hasNext()) {
1797                                                        SimulatedCarInfo r = it.next();
1798                                                        r.setLastMediumTransmition(crtTime);
1799                                               
1800                                                        if (e.sender instanceof SimulatedCarInfo)
1801                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender)
1802                                                                        .getVehicleId())
1803                                                                        continue;
1804                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1805                                                        re.setSender(e.getSender());
1806                                                        schedEventEmergency(re);
1807                                                }
1808                                        }
1809                                }
1810                        }
1811                       
1812                        t4 = System.currentTimeMillis();
1813                        tmp += t4 - t3;
1814                        netTime += tmp;
1815                }
1816        }
1817       
1818        /**
1819         * Adds a new car to the simulation.
1820         *
1821         * @param car The object that stores the physical behaviour of the vehicle to add
1822         */
1823        public void addCar(CarInstance car) 
1824        {
1825                if (car == null)
1826                        return;
1827               
1828                car.timestamp = crtTime;
1829                created ++;
1830                synchronized (cars) 
1831                {
1832                        SimulatedCarInfo dc = null;
1833                        if (crtTime == 0) {
1834//                              dc = new SimulatedCarInfo(car.ID, car.getLane(),
1835//                                              car.getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1836//                                              car.getDirection(), car.getOffset());
1837                                /*
1838                                dc = new CarRunningVITP(car.ID, car.getLane(), car.getSpeed(),
1839                                                car.getRoadIdx(), car.getPointIdx(),
1840                                                car.getDirection(), car.getOffset());
1841                                */
1842                                //EZcab car
1843                                if (applicationType == Globals.PROT_EZCAB){
1844                                        dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1845                                                        car.getRoadIdx(), car.getPointIdx(),
1846                                                        car.getDirection(), car.getOffset());
1847                                        System.out.println("new ezcab car created");
1848                                }
1849                                else if (simulationType == RoutingConstants.ROUTING_SCFT) 
1850                                        dc=new CarRunningSCFT(car.ID, car.getLane(), car.getSpeed(),
1851                                                        car.getRoadIdx(), car.getPointIdx(),
1852                                                        car.getDirection(), car.getOffset());
1853                                else
1854                                        dc=new CarRunningDSRC(car.ID, car.getLane(), car.getSpeed(),
1855                                                car.getRoadIdx(), car.getPointIdx(),
1856                                                car.getDirection(), car.getOffset());
1857                               
1858                                dc.setTimestamp(crtTime);
1859                                dc.setRealPos(car);
1860                                cars.add(dc);
1861                                dc.init();
1862                        } 
1863                        else 
1864                        {
1865                                int poz = cars.indexOf(new SimulatedCarInfo(car.ID));
1866                                if (poz == -1) 
1867                                {
1868                                        /*     
1869                                        dc = new CarRunningVITP(car.ID, car.getLane(), car
1870                                                        .getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1871                                                        car.getDirection(), car.getOffset());
1872                                                        */
1873                                        //Ezcab
1874                                        if (applicationType == Globals.PROT_EZCAB){
1875                                                if(System.currentTimeMillis() % 2 == 0){
1876                                                        dc = new EzcabClient(car.ID, car.getLane(), 1.0, //a minimum speed
1877                                                                        car.getRoadIdx(), car.getPointIdx(),
1878                                                                        car.getDirection(), car.getOffset());
1879                                                       
1880//                                                      dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1881//                                                                      car.getRoadIdx(), car.getPointIdx(),
1882//                                                                      car.getDirection(), car.getOffset());
1883                                                        //System.out.println("new client created");
1884                                                }
1885                                                else {
1886                                                        dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1887                                                                        car.getRoadIdx(), car.getPointIdx(),
1888                                                                        car.getDirection(), car.getOffset());
1889                                                       
1890//                                                      dc = new EzcabClient(car.ID, car.getLane(), 1.0, //a minimum speed
1891//                                                                      car.getRoadIdx(), car.getPointIdx(),
1892//                                                                      car.getDirection(), car.getOffset());
1893                                                        //System.out.println("new ezcab car created");
1894                                                }
1895                                        }
1896                                        else if (simulationType == RoutingConstants.ROUTING_SCFT) 
1897                                                dc=new CarRunningSCFT(car.ID, car.getLane(), car.getSpeed(),
1898                                                                car.getRoadIdx(), car.getPointIdx(),
1899                                                                car.getDirection(), car.getOffset());
1900                                        else
1901                                                dc=new CarRunningDSRC(car.ID, car.getLane(), car.getSpeed(),
1902                                                        car.getRoadIdx(), car.getPointIdx(),
1903                                                        car.getDirection(), car.getOffset());
1904//                                      dc = new SimulatedCarInfo(car.ID, car.getLane(), car
1905//                                                      .getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1906//                                                      car.getDirection(), car.getOffset());
1907                                       
1908                                        dc.setTimestamp(crtTime);
1909                                        dc.setRealPos(car);
1910                                        int t = 1 + random.nextInt(fps / 2 - 5);
1911                                        schedEvent(new SendEvent(crtTime + t, dc,SimulatedCarInfo.STANDARD_MESSAGE_ID));
1912                                        cars.add(dc);
1913                                        dc.init();                                     
1914                                } 
1915                                else 
1916                                {
1917                                        ((SimulatedCarInfo) cars.get(poz)).setRealPos(car);
1918                                }
1919                        }
1920                }
1921        }
1922
1923        /*
1924         * Read a scenario phase from a traces file. Update the vehicle's position
1925         * for the current step.
1926         *
1927         */
1928        public void readScenarioPhase() {
1929                int nrCars = 0;
1930                try {
1931                        int vehId, rdIdx, ptIdx;
1932                        byte dir, lane, speed;
1933                        double offset;
1934                        nrCars = dis.readInt();
1935                        // System.out.println(nrCars+" masini");
1936
1937                        synchronized (cars) 
1938                        {
1939                                for (int i = 0; i < nrCars; i++) 
1940                                {
1941                                        vehId   = dis.readInt();
1942                                        rdIdx   = dis.readInt();
1943                                        ptIdx   = dis.readInt();
1944                                        offset  = dis.readDouble();
1945                                        dir             = (byte) dis.readInt();
1946                                        lane    = (byte) dis.readInt();
1947                                        speed   = (byte) dis.readDouble();
1948
1949                                        SimulatedCarInfo dc = null;
1950                                        if (crtTime == 0) {
1951                                                /*     
1952                                                dc = new CarRunningVITP(vehId, lane, speed,
1953                                                                (short) rdIdx, (short) ptIdx, dir, offset);
1954                                                */
1955                                                //create ezcab car
1956                                                if (applicationType == Globals.PROT_EZCAB){
1957                                                        dc = new EzcabCar(vehId, lane, speed,
1958                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1959                                                        System.out.println("new ezcab car");
1960                                                }
1961                                                else if (simulationType == RoutingConstants.ROUTING_SCFT)
1962                                                        dc = new CarRunningSCFT(vehId, lane, speed,
1963                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1964                                                else
1965                                                        dc = new CarRunningDSRC(vehId, lane, speed,
1966                                                                (short) rdIdx, (short) ptIdx, dir, offset);
1967                                                // dc = new SimulatedCarInfo(vehId, lane, speed,
1968                                                // (short)rdIdx, (short)ptIdx, dir, offset);
1969                                                dc.setTimestamp(crtTime);
1970                                                dc.setRealPos(new CarInstance((CarInfo) dc));
1971                                                cars.add(dc);
1972                                                dc.init();
1973                                        } else {
1974                                                int poz = cars.indexOf(new SimulatedCarInfo(vehId));
1975                                                if (poz == -1) {
1976                                                        /*     
1977                                                        dc = new CarRunningVITP(vehId, lane, speed,
1978                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1979                                                        */
1980                                                        //create new ezcab car or client
1981                                                        if (applicationType == Globals.PROT_EZCAB){
1982                                                                if(System.currentTimeMillis() % 2 == 0){
1983                                                                        dc = new EzcabClient(vehId, lane, 1.0, //minimum allowed speed
1984                                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1985//                                                                      dc = new EzcabCar(vehId, lane, speed,
1986//                                                                                      (short) rdIdx, (short) ptIdx, dir, offset);
1987                                                                        //System.out.println("new ezcab client created");
1988                                                                }
1989                                                                else{
1990                                                                        dc = new EzcabCar(vehId, lane, speed,
1991                                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1992//                                                                      dc = new EzcabClient(vehId, lane, 1.0, //minimum allowed speed
1993//                                                                                      (short) rdIdx, (short) ptIdx, dir, offset);
1994                                                                        //System.out.println("new ezcab car created");
1995                                                                }
1996                                                        }
1997                                                        else if (simulationType == RoutingConstants.ROUTING_SCFT)
1998                                                                dc = new CarRunningSCFT(vehId, lane, speed,
1999                                                                                (short) rdIdx, (short) ptIdx, dir, offset);
2000                                                        else
2001                                                                dc = new CarRunningDSRC(vehId, lane, speed,
2002                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
2003                                                        // dc = new SimulatedCarInfo(vehId, lane, speed,
2004                                                        // (short)rdIdx, (short)ptIdx, dir, offset);
2005                                                        dc.setTimestamp(crtTime);
2006                                                        dc.setRealPos(new CarInstance((CarInfo) dc));
2007                                                        cars.add(dc);
2008                                                        dc.init();
2009                                                } else {
2010                                                        CarInstance ci = ((SimulatedCarInfo) cars.get(poz))
2011                                                                        .getRealPos();
2012                                                        ci.deleteCarToPointMapping();
2013                                                        ci.setSpeed((byte) speed);
2014                                                        ci.setRoadIdx((short) rdIdx);
2015                                                        ci.setPointIdx((short) ptIdx);
2016                                                        ci.setLane(lane);
2017                                                        ci.setDirection((byte) dir);
2018                                                        ci.setOffset(offset);
2019                                                        ci.setTimestamp(crtTime);
2020                                                        ci.updateCarToPointMapping();
2021                                                }
2022                                        }
2023                                }
2024                        }
2025                } catch (Exception e) {
2026                        System.err.println("Error reading scenario file");
2027                        e.printStackTrace();
2028                }
2029        }
2030
2031        public static boolean outputToFile = false;
2032
2033        public void generateScenarioPhase() {
2034               
2035                long t1sem = System.currentTimeMillis();
2036                if (crtTime % Globals.SECOND == 0){
2037                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
2038                                IntersectionWithTrafficLights iwtl = (IntersectionWithTrafficLights) Globals.map.allIntersections
2039                                .get(Globals.map.lightsIndices.get(j));
2040                                iwtl.step(crtTime);
2041                        }
2042                }
2043                long t2sem = System.currentTimeMillis();
2044                semTime += (t2sem - t1sem);
2045
2046                int NCARS = 0;
2047
2048                for (int j = 0; j < Globals.map.roads.size(); j++) {
2049
2050                        //Petroaca - random car on road to send emergency message
2051                        Random r;
2052                        int randId=0;
2053                        if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
2054                        {
2055                                r=new Random();
2056                                randId=r.nextInt(Globals.map.roads.get(j).carsOnThisRoad.size()+1);
2057                               
2058                        }
2059                       
2060                        SortedCarVector newVector = new SortedCarVector();
2061                        for (int k = Globals.map.roads.get(j).carsOnThisRoad.size() - 1; k >= 0; k--) {
2062                                CarInstance car = Globals.map.roads.get(j).carsOnThisRoad
2063                                                .get(k);
2064                                if (car.finished) {
2065                                       
2066                                        totalControlDelay += car.totalControlDelay;
2067                                        fincars ++;
2068                                        if (maxControlDelay < car.totalControlDelay)
2069                                                maxControlDelay = car.totalControlDelay;
2070
2071                                        synchronized (cars) {
2072                                                if (car.startMonitor) {
2073                                                        crossedCars++;
2074                                                        totalEM.addEmissionsResults(car.em, 1);
2075                                                        totalkm += car.totalDistance - car.startMonitorDistance;
2076                                                        totalTime += (crtTime - car.startTime)/Globals.SECOND;
2077                                                }
2078                                                Globals.monitoredCars.remove(car.getSimulatedCarInfo());
2079                                                car.finish();
2080                                                car.deleteCarToPointMapping();
2081                                                cars.remove(car.getSimulatedCarInfo());
2082                                        }
2083                                        continue;
2084                                }
2085                                try {
2086                                        long t1 = System.currentTimeMillis();
2087
2088                                        synchronized (cars) {
2089                                                car.deleteCarToPointMapping();
2090                                                car.move();
2091
2092                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_SELF_ROUTE) {
2093                                                        QueryGeneration.generateQueryForCar(car);
2094                                                }
2095
2096                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
2097                                                        GuidanceRequest.generateRequestToInfrastructure(car);
2098                                                }
2099                                               
2100                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
2101                                                        CarToIntersectionComm.updateMetrics(car);
2102                                                }
2103                                               
2104//                                              Petroaca - emergency messages schedule
2105                                               
2106                                                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC && car.ID==randId && crtTime%50==0)
2107                                                {
2108                                                        EmergencyRequest.generateEmergencyMessage(car);
2109                                                }
2110                                               
2111                                                car.setTimestamp(crtTime);
2112                                       
2113                                               
2114                                               
2115                                                if (car.endMonitor){
2116                                                        crossedCars ++;
2117                                                        totalEM.addEmissionsResults(car.em, 1);
2118                                                        totalkm += car.totalDistance - car.startMonitorDistance;
2119        //                                              System.out.println("Fuel: " + car.em.fc / 1000 +" "+ car.totalDistance + " "+car.em.fc * 100.0/ (10000 * car.totalDistance) + " "+(car.totalDistance * 3600.0)  / (double)(car.travelTime / Globals.SECOND));
2120                                                        car.endMonitor = false;
2121                                                        car.startMonitor = false;
2122                                                }
2123
2124                                                car.updateCarToPointMapping();
2125                                                 
2126                                        }
2127
2128                                        long t2 = System.currentTimeMillis();
2129                                        moveTime += t2 - t1;
2130                                } catch (Exception ex) {
2131                                        ex.printStackTrace();
2132                                }
2133                                // if it has changed road, place it in the vector of its new
2134                                // road
2135                                if (car.getRoadIdx() != j) {
2136                                        if (car.getRoadIdx() > j)
2137                                                NCARS--; // it will be moved again when that road
2138                                                                        // will be processed
2139                                        Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
2140                                                        .addCarInstance(car);
2141                                } else {
2142                                        // it's still on the same road
2143                                        newVector.addCarInstance(Globals.map.roads.get(j).carsOnThisRoad.get(k));
2144                                }
2145                                NCARS++;
2146                        }
2147
2148                        // loop through the new vector and set the indices
2149                        for (int k = 0; k < newVector.size(); k++) {
2150                                newVector.get(k).index = k;
2151                        }
2152                        Globals.map.roads.get(j).carsOnThisRoad = newVector;
2153                }
2154       
2155               
2156                if (!outputToFile)
2157                        return;
2158                // output text
2159                try {
2160                        pwText.print(NCARS + " ");
2161                        outBin.writeInt(NCARS);
2162                        for (int j = 0; j < Globals.map.roads.size(); j++) {
2163                                for (int k = 0; k < Globals.map.roads.get(j).carsOnThisRoad
2164                                                .size(); k++) {
2165                                        CarInstance ci = Globals.map.roads.get(j).carsOnThisRoad
2166                                                        .get(k);
2167                                        pwText.print(ci.ID + " " + ci.getRoadIdx() + " "
2168                                                        + ci.getPointIdx() + " " + ci.getOffset() + " "
2169                                                        + ci.getDirection() + " " + ci.getLane() + "   ");
2170                                        outBin.writeInt(ci.ID);
2171                                        outBin.writeInt(ci.getRoadIdx());
2172                                        outBin.writeInt(ci.getPointIdx());
2173                                        outBin.writeDouble(ci.getOffset());
2174                                        outBin.writeInt(ci.getDirection());
2175                                        outBin.writeInt(ci.getLane());
2176                                        outBin.writeDouble(ci.getSpeed());
2177                                }
2178                        }
2179                        pwText.println();
2180                } catch (IOException e) {
2181                        System.err.println("Error writing traces");
2182                        e.printStackTrace();
2183                        System.exit(0);
2184                }
2185        }
2186       
2187        public int getCrtTime(){
2188                return crtTime;
2189        }
2190       
2191       
2192       
2193       
2194        public SimulatedCarInfo getCarIdx(int rdIdx, int ptIdx) 
2195        {
2196                synchronized (cars) 
2197                {
2198                        Iterator<SimulatedCarInfo> it = cars.iterator();
2199                        while (it.hasNext()) {
2200                                SimulatedCarInfo r = it.next();
2201                                if (r.getRoadIdx() == rdIdx && r.getPointIdx() == ptIdx)
2202                                        return r;
2203                        }
2204                }
2205                return null;
2206        }
2207
2208        public SimulatedCarInfo getCarIdx(int idx) 
2209        {
2210                synchronized (cars) 
2211                {
2212                        Iterator<SimulatedCarInfo> it = cars.iterator();
2213                        while (it.hasNext()) {
2214                                SimulatedCarInfo r = it.next();
2215                                if (r.vehicleId == idx)
2216                                        return r;
2217                        }
2218                }
2219                return null;
2220        }
2221
2222        public static void main(String args[]) {
2223               
2224                // Globals.map = new Map("Intersectie.RT1","Intersectie.RT2");
2225
2226                int tests = 1;
2227                for (int i = 0; i < tests; i++){
2228                        try{
2229                                switch (i){
2230                                        case 0: Globals.pw.println("Adaptive xc  = 1, variations2");
2231                                                break;
2232                                        case 1:Globals.pw.println("Adaptive xc  = 0.95, variations2");
2233                                                break;
2234                                        case 2:break;
2235                                }
2236                               
2237//                              ObjectInputStream ois=new ObjectInputStream(new FileInputStream(".\\maps\\fsc\\Apaca.fsc"));
2238//                              Scenario sc=(Scenario)ois.readObject();
2239//                              Mobility.loadScenario(sc);
2240                       
2241                                Engine e = Globals.engine = new Engine(false, true);
2242                                e.init();
2243//                                              public void run(){
2244//                                                      Globals.demo = new Display();
2245//                                                      Globals.demo.setVisible(true);
2246//                                              }
2247//                                      });
2248//                              t.start();
2249//                              e.play();
2250                                switch (i){
2251                                        case 0:
2252                                                Globals.Xc = 0.95;
2253                                                break;
2254                                        case 1:break;
2255                                        case 2:break;
2256                                }
2257                               
2258                                if (i != tests - 1){
2259                                        Globals.pw.close();
2260                                        String pwname = "rezultate"+System.currentTimeMillis()+".txt";
2261                                        Globals.pw = new PrintWriter(new FileWriter(pwname));
2262                                }
2263                        } catch (Exception ex) {
2264                                ex.printStackTrace();
2265                                System.exit(0);
2266                        }               
2267               
2268                       
2269                }
2270               
2271/*              long t1 = System.currentTimeMillis();
2272                e.play(60);
2273                long t2 = System.currentTimeMillis();
2274
2275                System.out.println("SimTime: " + (t2 - t1));
2276                System.out.println("events: " + (double) (100 * e.eventsTime)
2277                                / (t2 - t1));
2278                System.out.println("mobility: " + (double) (100 * e.mobilityTime)
2279                                / (t2 - t1));
2280                System.out.println("move: " + (double) (100 * e.moveTime) / (t2 - t1));
2281                System.out.println("code: " + (double) (100 * e.codeTime) / (t2 - t1));
2282                System.out.println("net: " + (double) (100 * e.netTime) / (t2 - t1));
2283                System.out.println("cleanup: " + (double) (100 * e.cleanupTime)
2284                                / (t2 - t1));
2285                System.out
2286                                .println("sched: " + (double) (100 * e.schedTime) / (t2 - t1));
2287
2288//              System.out.println("pkavg " + pkavg + "\npkmax" + pkmax
2289//                              + "\ncomp time " + avgTime);
2290                //              e.play();
2291                //              e.step();
2292                //              e.step();
2293                //              e.step();
2294                //              e.step();
2295                //              e.step();
2296                System.exit(0);*/
2297        }
2298
2299       
2300/*      public void createDummyCars() {
2301                Road r = Globals.map.roads.get(1);
2302               
2303                //Stopping a car on a road
2304                int ID = lastCarID;
2305                lastCarID++;
2306                CarInstance car = Mobility.createNewCar(1, 46, 0, 1, 0.0,
2307                                new NotMovingPersonality(), 0.0, ID, 2, 64, null, 1);
2308                if (car == null) {
2309                        lastCarID--;
2310                        System.out.println("Could not create the first stopped car");
2311                } else {
2312                        System.out.println("Jammed car id=" + ID);
2313                        jammed = ID;
2314                }
2315
2316                this.addCar(car);
2317        }
2318*/
2319       
2320
2321}
Note: See TracBrowser for help on using the repository browser.