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

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