source: proiecte/ptvs/src/vnsim/core/Engine.java @ 111

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