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

Last change on this file since 61 was 61, checked in by (none), 14 years ago

modificari 4 ianuarie

File size: 66.7 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                 * Mihaela Teler
648                 * vreau sa aflu cate intersectii am
649                 * voi avea tot atatea threaduri
650                 */
651                Map map = Globals.map;
652                ArrayList<Intersection> intersectii = map.allIntersections;
653                int numThreads=intersectii.size();
654               
655                EventProcessingThread processingThreads[] = new EventProcessingThread[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                        System.out.println("\n----------- number of events in the queue:"+eventQueue.size() );
668                       
669                        /**
670                         * Mihaela Teler
671                         * vector de threaduri pt procesare evenimente in functie de locatie
672                         * procesez folosind threaduri doar evenimentele send si receive
673                         */
674                       
675               
676                        if((e instanceof SendEvent) || (e instanceof ReceiveEvent)){
677                               
678                                /**
679                                 * Mihaela Teler
680                                 * aflu locatia evenimentului
681                                 */                     
682                                Road r = null;
683                                Point p = null;
684                                if(e instanceof SendEvent){
685                                        SendEvent se=(SendEvent)e;
686                                        r = (Road) Globals.map.roads.get(se.sender.getRoadIdx());       //aflu strada pe care se afla senderul
687                                        p = (Point) r.points.get(se.sender.getPointIdx());                      //aflu punctul unde se afla senderul
688                                }
689                                if(e instanceof ReceiveEvent){
690                                        ReceiveEvent re=(ReceiveEvent)e;
691                                        r = (Road) Globals.map.roads.get(re.sender.getRoadIdx());
692                                        p = (Point) r.points.get(re.sender.getPointIdx());
693                                }
694                               
695                                //System.out.println("p:"+p);
696                               
697                                /**
698                                 * Mihaela Teler
699                                 * parcurg toate intersectiile si o gasesc pe cea mai apropiata
700                                 */
701                                double MIN_DIST=Double.MAX_VALUE;
702                                int indexClosestIntersection=0;
703                                double distanta;
704                                for(int i=0;i<intersectii.size();i++){ 
705                                        Intersection intersectie = intersectii.get(i);
706                                        if(r.getPoints().contains(intersectie.getMapPoint())){ //iau in calcul doar intersectiile aflate pe strada pe care sunt
707                                                distanta=GPSutil.distance(p, intersectie.getMapPoint());
708                                                if (distanta < MIN_DIST){
709                                                        MIN_DIST=distanta;
710                                                        indexClosestIntersection=i;                                             
711                                                }
712                                        }
713                                               
714                                }
715                                /**
716                                 * Mihaela Teler
717                                 * acum trebuie sa asignez un thread sa proceseze
718                                 */
719                               
720                                // nu e bine cu apelul lui run pt ca practic nu se porneste un thread nou ci
721                                // se apeleaza metoda run ca orice alta metoda dintr-o clasa, executia este secventiala..
722                               
723                                if (e.getTime() == crtTime) {
724                               
725                                        if(e instanceof SendEvent){             
726                                               
727                                                        System.out.print("SendEvent: ");
728                                                        processingThreads[indexClosestIntersection] = new SendEventProcessingThread(e,crtTime);
729                                                }
730                                        else {                                 
731                                                        System.out.print("ReceiveEvent: ");
732                                                        processingThreads[indexClosestIntersection] = new ReceiveEventProcessingThread(e,crtTime);
733                                                }
734                                       
735                                        System.out.println("Processing thread "+indexClosestIntersection+" from intersection "+intersectii.get(indexClosestIntersection));
736                                        //processingThreads[indexClosestIntersection].start();// cu start nu merge ... why????
737                                        processingThreads[indexClosestIntersection].run();
738                                        cnt++;
739                                }
740                                else
741                                        break;
742                        }
743                       
744                        else if (e.getTime() == crtTime) {
745                                playEvent();
746                                cnt++;
747                        } else
748                                break;
749                       
750                       
751                }
752               
753               
754                //increment simulation time
755                crtTime++;
756               
757                long t3 = System.currentTimeMillis();
758                if (crtTime % (Globals.executionFPS / Globals.FPS) == 0)
759                        if (!runtimeMobility)
760                                readScenarioPhase();
761                        else
762                                generateScenarioPhase();
763               
764                checkCreateNewCars();
765               
766                long t4 = System.currentTimeMillis();
767                eventsTime += t3 - t2;
768                mobilityTime += t4 - t3;
769
770                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
771                        if (crtTime % 100 == 0) {
772                                for (int i = 0; i < this.infrastructure.size(); i++) {
773                                       
774                                        ((InfrastructureNode) this.infrastructure.get(i)).updateDelays();
775                                }
776                        }
777                }
778                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
779                        for (int i = 0; i < this.infrastructure.size(); i++) {
780                                ((IntersectionNode) infrastructure.get(i)).step(crtTime);
781                        }
782                        server.step(crtTime);
783                }
784        }
785        //////////////////////////////////////////////end metoda step////////////////////////////////////
786
787        static Random random = new Random();
788
789        public static int lastCarID = 0;
790
791        /**
792         * Insert new cars at the map entry points according to the scheduled flow.
793         *
794         */
795        private void checkCreateNewCars(){
796
797                int percent;
798//              should create some new cars?
799                NewCarEvent first=Mobility.events.first();
800                while(first!=null && first.timestamp==crtTime) {
801                        //create this one
802                        EntryScenario es=Mobility.entryScenarios.get(first.index);
803
804                        int roadIndexSrc=es.entry.roadIdx;
805                        int pointIndexSrc=es.entry.ptIdx;
806
807                        int ID=lastCarID;
808                        lastCarID++;
809
810                        //which exit is the car going towards?
811                        double rand;
812                        rand=(random.nextDouble())*100;
813                        int i=0;
814                        int sum=0;
815                        while(i<es.entryExits.size()) {
816                                sum+=es.entryExits.elementAt(i).percentOfFlow;
817                                if(rand<sum) {
818                                        //this is the chosen exit
819                                        break;
820                                }
821                                i++;
822                        }
823                        EntryExitScenario ees=null;
824                        if(i==es.entryExits.size()) {
825                                //last exit chosen
826                                ees=es.entryExits.lastElement();
827                        } else 
828                                ees=es.entryExits.elementAt(i);
829
830                        int roadIndexDst=ees.exit.roadIdx;
831                        int pointIndexDst=ees.exit.ptIdx;
832
833                        //which route is the car choosing?
834                        rand=(random.nextDouble())*100;
835                        i=0;
836                        sum=0;
837                        while(i<ees.percentsEachRoute.size()) {
838                                sum+=ees.percentsEachRoute.elementAt(i);
839                                if(rand<sum) {
840                                        //this is the chosen route
841                                        break;
842                                }
843                                i++;
844                        }
845                        Route r=null;
846                        if(i==ees.percentsEachRoute.size()) {
847                                //last route chosen
848                                r=ees.routes.lastElement();
849                        } else 
850                                r=ees.routes.elementAt(i);
851
852                        for(i=0;i<Globals.map.roads.get(roadIndexSrc).laneNo;i++) {
853                                //one vehicle on each lane
854
855                                Personality personality;
856                                rand=(random.nextDouble())*100;
857                                if(rand<es.percentsDriverTypes.elementAt(0)) 
858                                {
859                                        personality=new CalmPersonality();
860                                } else if(rand<es.percentsDriverTypes.elementAt(0)+es.percentsDriverTypes.elementAt(1)) {
861                                        personality=new RegularPersonality();
862                                } else {
863                                        personality=new AggresivePersonality();
864                                }
865                               
866                                CarInstance car = null;
867                                if (simulationType == RoutingConstants.INITIALLY_PROVIDED_ROUTE || simulationType == RoutingConstants.ROUTING_SCFT) {
868                                       
869                                        car = Mobility.createNewCar(roadIndexSrc,
870                                                        pointIndexSrc, 0, i + 1, 0.0, personality, /*personality.getWantedSpeed(roadIndexSrc)*/ 0.0, ID,
871                                                        roadIndexDst, pointIndexDst, r.route);
872                                       
873                                        System.out.println("Finished creating new car "+car);
874                                       
875                                        double d =0;
876                                        if(car!=null)
877                                                d = car.getDistanceToCarInFront();
878                                        if (d < 10 && d!=0) {
879                                                // closer than 5 meters --> do not create
880                                                // System.out.println("Skipping creation...");
881                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad.remove(car.ID);
882                                                continue;
883                                        }
884                                }
885
886                                if (Engine.simulationType == RoutingConstants.DYNAMIC_SELF_ROUTE) {
887                                        System.out.println("Dynamic; we are here");
888                                        percent = random.nextInt(100);
889                                        percent = (int) Math.abs((double) percent);
890                                        if (percent <= Globals.routePlanConstants.percentBestRoute) {
891                                                percent = 1;
892                                        } else {
893                                                percent = 0;
894                                        }
895                                        car = Mobility.createNewCar(roadIndexSrc, pointIndexSrc, 0,
896                                                        i + 1, 0.0, personality, 0.0, ID, roadIndexDst,
897                                                        pointIndexDst, r.route, percent);
898                                        if (car == null) {
899                                       
900                                                continue;
901                                        }
902                                        double d = car.getDistanceToCarInFront();
903                                        if (d < 10) {
904                                                // closer than 10 meters --> do not create
905                                               
906                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad.remove(car.ID);                                         
907                                                continue;
908                                        }
909
910                                }
911                                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
912
913                                        car = Mobility.createNewCarCommunicatingWithInfrastucture(
914                                                        roadIndexSrc, pointIndexSrc, 0, i + 1, 0.0,
915                                                        personality, 0.0, ID, roadIndexDst, pointIndexDst,
916                                                        r.route);
917                                        if (car == null) {
918                                               
919                                                continue;
920                                        }
921                                        double d = car.getDistanceToCarInFront();
922                                        if (d < 10) {
923                                                // closer than 10 meters --> do not create                                             
924                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
925                                                                .remove(car.ID);
926                                               
927
928                                                continue;
929                                        }
930
931                                }
932                               
933                                //create new ezcab client (entity)
934                               
935                                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
936
937                                        car = Mobility.createNewCityCarCommunicatingWithInfrastucture(
938                                                        roadIndexSrc, pointIndexSrc, 0, i + 1, 0.0,
939                                                        personality, 0.0, ID, roadIndexDst, pointIndexDst,
940                                                        r.route);
941                                        if (car == null) {                                     
942                                                continue;
943                                        }
944                                        double d = car.getDistanceToCarInFront();
945                                        if (d < 10) {
946                                                // closer than 10 meters --> do not create                                             
947                                                Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
948                                                                .remove(car.ID);
949                                               
950
951                                                continue;
952                                        }
953
954                                }
955
956                                ID = lastCarID;
957                                lastCarID++;
958                                this.addCar(car);
959                        }
960                        Mobility.events.removeFirst();
961                       
962                        try {
963                                EntryFlowVariation efv=Mobility.entryFlowVariations.get(first.index);
964                               
965                                if(efv.getFirstMom()<crtTime && efv.getFirstMom()!=-1) {
966                                        int newFlow=efv.getFirstValue();
967                                        int old=first.period;
968                                        first.period=(int)((double)(3600 * Globals.SECOND) / newFlow);
969                                        System.out.print("TIME="+crtTime+"; CHANGING PERIOD FOR ENTRY="+first.index+" FROM: "+old+" TO: "+first.period);
970                                        efv.removeFirst();
971                                }
972                        } catch (Exception ex) {
973                               
974                        }
975                        if(Globals.SOCIALNETWORK == 0 )
976                                Mobility.events.addEvent(new NewCarEvent(first.timestamp
977                                                + first.period, first.index, first.period));
978                        first = Mobility.events.first();
979                }
980        }
981
982////////////////////////////////////////// playEvent ////////////////////////////////////////////////////////////////   
983
984        static long messagesSize = 0;
985        static long carInfosSize = 0;
986        /**
987         * Execute the following event in the eventQueue
988         *
989         */
990        public static void playEvent() {
991               
992                //System.out.println(">> Thread:"+Thread.currentThread().getName());
993               
994                if (eventQueue.size() == 0) {
995                        doneFlag = true;
996                        return;
997                }
998
999                Event e = null;
1000                synchronized (eventQueue) {
1001                        e = eventQueue.remove(0);
1002                }
1003                //System.out.print(e.toString()+", ");
1004                //System.out.flush();
1005                               
1006                if (e instanceof GPSEvent) {    //////////// eveniment GPS
1007                       
1008                        Iterator<SimulatedCarInfo> it = cars.iterator();
1009                        while (it.hasNext()) {
1010                                SimulatedCarInfo r = it.next();
1011                                r.update();
1012                        }
1013                        GPSEvent newEvent = new GPSEvent(crtTime + fps);
1014                        schedEvent(newEvent);
1015                }
1016                if (e instanceof CleanupEvent) {        //////////// eveniment CLEANUP
1017
1018                        long t1 = System.currentTimeMillis();
1019                        long deleted = 0;
1020                        Iterator<SimulatedCarInfo> it = cars.iterator();
1021                        while (it.hasNext()) {
1022                                SimulatedCarInfo r = it.next();
1023
1024                                Iterator<CarInfo> j = r.trafficDB.iterator();
1025                                while (j.hasNext()) {
1026                                        CarInfo neighbor = j.next();
1027                                        if ( (crtTime - neighbor.getTimestamp() > Globals.NEIGHBOR_EXPIRES && neighbor.state != 3) ||
1028                                                        (neighbor.state == 3 && crtTime - neighbor.getTimestamp() > Globals.PROMISCUOUS_NEIGHBOR_EXPIRES)){
1029                                                j.remove();
1030                                        }
1031                                }
1032                                carInfosSize += r.trafficDB.size();
1033                        }
1034                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
1035                                WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
1036                                                .get(Globals.map.lightsIndices.get(j));
1037                               
1038                                synchronized(wtl.trafficDB){
1039                                        Iterator<IntersectionCarRecord> wtlit = wtl.trafficDB.iterator();
1040                                        while (wtlit.hasNext()) {
1041                                                IntersectionCarRecord icr = wtlit.next();
1042                                                if (!icr.isPassed() && crtTime - icr.getCar().getTimestamp() > Globals.HOUR 
1043                                                                && icr.getCar().state != 3){
1044                                                        icr.segment.cars.remove(icr);
1045                                                        wtlit.remove();
1046                                                        deleted++;
1047                                                }
1048                                                if (icr.isPassed() && crtTime - icr.getCar().getTimestamp() > Globals.TRAFFICLIGHT_NEIGHBOR_EXPIRES){
1049                                                        icr.segment.cars.remove(icr);
1050                                                        wtlit.remove();
1051                                                }
1052                                        }
1053                                }
1054                        }
1055                        long t2 = System.currentTimeMillis();
1056                        cleanupTime += t2 - t1;
1057                        if (!disableComm) {
1058                                CleanupEvent newCleanupEvent = new CleanupEvent(crtTime + fps);
1059                                schedEvent(newCleanupEvent);
1060                        }
1061                        messagesSize = 0;
1062                }
1063               
1064                if (e instanceof SendEvent) {   /////////////////////////////// eveniment SEND
1065                       
1066                        /**
1067                         * cod mutat in metoda run a lui SendEventProcessingThread - intre timp m-am razgandit.. am pornit threaduri in metoda step
1068                         */
1069                       
1070                        /*SendEventProcessingThread thread=new SendEventProcessingThread(e, crtTime, disableComm, messagesSize);
1071                        synchronized (eventQueue) {
1072                                if(!thread.isAlive()) {
1073                                        thread.start();
1074                                        System.out.println(".........................thread started");
1075                                }
1076                        }*/
1077                       
1078                       
1079                        SendEvent se = (SendEvent) e;
1080                        Communicator sender = se.getSender();
1081                       
1082                        long t1 = System.currentTimeMillis();   
1083                       
1084                        // senderul e un SimulatedCarInfo
1085                       
1086                        if (se.getMessage() == null){
1087                                byte[] message = sender.prepareMessage(se.getMessageType());
1088                                se.setMessage(message);
1089                                if (se.getMessage() == null){
1090                                        if (sender.isPromiscuousMode() && sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1091                                                int eventPeriod = sender.getPeriod(se.getMessageType());
1092                                                if (eventPeriod != -1)
1093                                                        schedEvent(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1094                                        }
1095                                        return;
1096                                }
1097                                messagesSize += message.length;
1098                                long t2 = System.currentTimeMillis();
1099                                codeTime += t2 - t1;
1100
1101                                if (sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1102                                        int eventPeriod = sender.getPeriod(se.getMessageType());
1103                                        if (eventPeriod != -1)
1104                                                schedEvent(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1105                                }
1106                        }
1107                       
1108                        //Petroaca - the DSRC impl
1109                        if(Engine.simulationProtocol==Globals.PROTOCOL_80211)
1110                        {
1111                               
1112                                if (!sender.mediumAvailable(crtTime)) {
1113                                        e.setTime(crtTime + 1);
1114                                        schedEvent(e);
1115                                       
1116                                        return;
1117                                }
1118                               
1119                                sender.getRadio().setRadioTxMode();
1120                                simulateCommunication(se);
1121                       
1122                        }
1123                        else
1124                        {
1125                                if(sender instanceof CarRunningDSRC)
1126                                {
1127                                        MAC80211 macs=((CarRunningDSRC)sender).getMac();
1128                                        WirelessPhy phys=((CarRunningDSRC)sender).getPhysical();
1129                                       
1130                                        macs.refreshFrameTime(crtTime);
1131                                        phys.refreshFrameTime(crtTime);
1132                                       
1133                                        if(macs.sendToPhysical(se.getMessage(),crtTime)!=null)
1134                                        {
1135                                                phys.sendToChannel(se.getMessage(),crtTime);
1136                                                macs.setChannelState(Globals.CCA_BUSY);
1137                                                simulateCommunication(se);
1138                                        }
1139                                        else
1140                                        {
1141                                       
1142                                                e.setTime(crtTime+1);
1143                                                schedEvent(e);
1144                                               
1145                                        }
1146                                        return;
1147                                } 
1148                                else
1149                                {
1150                                        if (!sender.mediumAvailable(crtTime)) {
1151                                                e.setTime(crtTime + 1);
1152                                                schedEvent(e);
1153                                               
1154                                                return;
1155                                        }
1156                                       
1157                                        sender.getRadio().setRadioTxMode();
1158                                        simulateCommunication(se);
1159                                }
1160                        }
1161                }
1162               
1163                if (e instanceof ReceiveEvent) {        //////////////////////// eveniment RECEIVE
1164                        ReceiveEvent re = (ReceiveEvent) e;
1165
1166                                long t1 = System.currentTimeMillis();
1167                               
1168                                //Petroaca - the DSRC impl
1169                                if(Engine.simulationProtocol==Globals.PROTOCOL_80211){
1170                                        RadioDev rxradio = re.receiver.getRadio();
1171                                        ReceiveEvent goodSignal = rxradio.receive(re.signals);
1172                                        re.receiver.removeReceiveEventForTime(re.getTime());
1173                               
1174                                        if (goodSignal != null){
1175                                                        re.receiver.onReceive(goodSignal.getMessage(), goodSignal.getMessageObject(), goodSignal.sender);
1176                                                }
1177                                }
1178                                else
1179                                {
1180                                        if(re.receiver instanceof CarRunningDSRC)
1181                                        {
1182                                                MAC80211 macr=((CarRunningDSRC)re.receiver).getMac();
1183                                                WirelessPhy phyr=((CarRunningDSRC)re.receiver).getPhysical();
1184                                                Application appr=((CarRunningDSRC)re.receiver).getAppLayer();
1185                                               
1186                                                if(Globals.DIFFERENTIAL_CW)
1187                                                        macr.recalculateCW(phyr.getTotalReceivedPackets(),crtTime);
1188                                               
1189                                                macr.refreshFrameTime(crtTime);
1190                                                phyr.refreshFrameTime(crtTime);
1191                                                appr.refreshApplication(crtTime);
1192                                               
1193                                                ReceiveEvent best=phyr.recvFromChannel(re.signals,crtTime);
1194                                                re.receiver.removeReceiveEventForTime(re.getTime());
1195                                               
1196                                                double sinr=phyr.getSINR();
1197                                                if(best!=null)
1198                                                {
1199                                                        macr.setChannelState(Globals.CCA_BUSY); 
1200                                                       
1201                                                        if(macr.recvFromPhysical(best,sinr,crtTime)!=null)
1202                                                        {
1203                                                                appr.ForwardCollisionWarning(best.getMessage(),((CarInfo)re.receiver));
1204                                                                //appr.LaneChangeAssistance(best.getMessage(),((CarInfo)re.receiver));
1205                                                                re.receiver.onReceive(best.getMessage(), best.getMessageObject(), best.sender);
1206                                                        }
1207                                                }
1208                                        }
1209                                        else
1210                                        {
1211                                                RadioDev rxradio = re.receiver.getRadio();
1212                                                ReceiveEvent goodSignal = rxradio.receive(re.signals);
1213                                                re.receiver.removeReceiveEventForTime(re.getTime());
1214                                       
1215                                                if (goodSignal != null){
1216                                                                re.receiver.onReceive(goodSignal.getMessage(), goodSignal.getMessageObject(), goodSignal.sender);
1217                                                        }
1218                                        }
1219                                }       
1220                               
1221                                long t2 = System.currentTimeMillis();
1222                                codeTime += t2 - t1;
1223                        }
1224        }
1225
1226
1227        public void playEventEmergency()
1228        {
1229                if (eventQueueEmergency.size() == 0) {
1230                        doneFlagEmergency = true;
1231                        return;
1232                }
1233
1234                Event e = null;
1235                synchronized (eventQueueEmergency) {
1236                        e = eventQueueEmergency.remove(0);
1237                }
1238               
1239                if (e instanceof SendEvent) {
1240                        SendEvent se = (SendEvent) e;
1241                        Communicator sender = se.getSender();
1242                       
1243                        long t1 = System.currentTimeMillis();   
1244                       
1245                       
1246                        if (se.getMessage() == null){
1247                                byte[] message = sender.prepareMessage(se.getMessageType());
1248                                se.setMessage(message);
1249                                if (se.getMessage() == null){
1250        //                              System.out.println("null message"+se.sender + " "+se.sender.getClass());
1251                                        if (sender.isPromiscuousMode() && sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1252                                                int eventPeriod = sender.getPeriod(se.getMessageType());
1253                                                if (eventPeriod != -1)
1254                                                        schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1255                                        }
1256                                        return;
1257                                }
1258                                messagesSize += message.length;
1259                                long t2 = System.currentTimeMillis();
1260                                codeTime += t2 - t1;
1261
1262                                if (sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
1263                                        int eventPeriod = sender.getPeriod(se.getMessageType());
1264                                        if (eventPeriod != -1)
1265                                                schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
1266                                }
1267                        }
1268                       
1269                        //Petroaca - the DSRC impl
1270                                if(sender instanceof CarRunningDSRC)
1271                                {
1272                                        MAC80211 macs=((CarRunningDSRC)sender).getMac();
1273                                        WirelessPhy phys=((CarRunningDSRC)sender).getPhysical();
1274                                       
1275                                        macs.refreshFrameTime(crtTime);
1276                                        phys.refreshFrameTime(crtTime);
1277                                       
1278                                        if(macs.sendToPhysical(se.getMessage(),crtTime)!=null)
1279                                        {
1280                                                phys.sendToChannel(se.getMessage(),crtTime);
1281                                                macs.setChannelState(Globals.CCA_BUSY);
1282                                                simulateCommunicationEmergency(se);
1283                                        }
1284                                        else
1285                                        {
1286                                       
1287                                                e.setTime(crtTime+1);
1288                                                schedEventEmergency(e);
1289                                               
1290                                        }
1291                                        return;
1292                                }
1293                               
1294                                if(sender instanceof CarRunningDSRC)
1295                                {
1296                                        return;
1297                                }
1298                                else
1299                                {
1300                                        return;
1301                                }
1302                        }
1303                       
1304                if (e instanceof ReceiveEvent) {
1305                        ReceiveEvent re = (ReceiveEvent) e;
1306                       
1307                        long t1 = System.currentTimeMillis();
1308                       
1309                        //Petroaca - the DSRC impl
1310                               
1311                                        if(re.receiver instanceof CarRunningDSRC)
1312                                        {
1313                                                MAC80211 macr=((CarRunningDSRC)re.receiver).getMac();
1314                                                WirelessPhy phyr=((CarRunningDSRC)re.receiver).getPhysical();
1315                                                Application appr=((CarRunningDSRC)re.receiver).getAppLayer();
1316                                                appr.refreshApplication(crtTime);
1317                                               
1318                                                if(Globals.DIFFERENTIAL_CW)
1319                                                        macr.recalculateCW(phyr.getTotalReceivedPackets(),crtTime);
1320                                               
1321                                                macr.refreshFrameTime(crtTime);
1322                                                phyr.refreshFrameTime(crtTime);
1323                                               
1324                                                ReceiveEvent best=phyr.recvFromChannel(re.signals,crtTime);
1325                                                ((SimulatedCarInfo)re.receiver).removeReceiveEventEmergencyForTime(re.getTime());
1326                                               
1327                                                double sinr=phyr.getSINR();
1328                                                if(best!=null)
1329                                                {
1330                                                        macr.setChannelState(Globals.CCA_BUSY); 
1331                                                       
1332                                                        if(macr.recvFromPhysical(best,sinr,crtTime)!=null)
1333                                                        {
1334                                                                //appr.ForwardCollisionWarning(best.getMessage(),((CarInfo)re.receiver));
1335                                                                //appr.LaneChangeAssistance(best.getMessage(),((CarInfo)re.receiver));
1336                                                                re.receiver.onReceive(best.getMessage(), best.getMessageObject(), best.sender);
1337                                                        }
1338                                                }
1339                                        }
1340                                        long t2 = System.currentTimeMillis();
1341                                        codeTime += t2 - t1;
1342                                }       
1343        }
1344       
1345        /**
1346         * Applications may schedule dynamically communication events using this method
1347         * to insert new events in the queue.
1348         *
1349         * @param e Event to schedule
1350         */
1351        public static void schedEvent(Event e) {
1352
1353                long t1 = System.currentTimeMillis();
1354
1355                if (e instanceof ReceiveEvent) {
1356                        ReceiveEvent re = (ReceiveEvent) e;
1357                        ReceiveEvent existing = re.receiver.getReceiveEventForTime(e.getTime());
1358                        //getReceiveEventForTime returneaza evenimentele receive petrecute la momentul e.getTime()
1359                       
1360                        if (existing == null){
1361                                re.receiver.addReceiveEventForTime(re);
1362                        }else{
1363                                existing.signals.add(re);
1364                                return;
1365                        }
1366                }
1367               
1368                // cauta evenimetul in coada, ii gaseste pozitia corecta in lista de evenimente si il adauga
1369                // ce face de fapt? de ce cauta un eveniment si il readauga tot pe el in lista???
1370                int idx = Collections.binarySearch(eventQueue, e);
1371                synchronized (eventQueue) {
1372                        if (idx >= 0) {
1373                                // advance till the end of the sequence of equal events
1374                                if (eventQueue.get(idx).equals(e))
1375                                        idx++;
1376                                eventQueue.add(idx, e);
1377                        } else {
1378                                eventQueue.add(-(idx + 1), e);
1379                        }
1380                }
1381                long t2 = System.currentTimeMillis();
1382                schedTime += t2 - t1;
1383        }
1384
1385        //Petroaca - the message scheduler for the emergency channel
1386        public void schedEventEmergency(Event e)
1387        {
1388                long t1 = System.currentTimeMillis();
1389
1390                if (e instanceof ReceiveEvent) {
1391                        ReceiveEvent re = (ReceiveEvent) e;
1392                        ReceiveEvent existing = ((SimulatedCarInfo)re.receiver).getReceiveEventEmergencyForTime(e.getTime());
1393                        if (existing == null){
1394                                ((SimulatedCarInfo)re.receiver).addReceiveEventEmergencyForTime(re);
1395                        }else{
1396                                existing.signals.add(re);
1397                                return;
1398                        }
1399                }
1400               
1401                int idx = Collections.binarySearch(eventQueueEmergency, e);
1402                synchronized (eventQueueEmergency) {
1403                        if (idx >= 0) {
1404                                // advance till the end of the sequence of equal events
1405                                if (eventQueueEmergency.get(idx).equals(e))
1406                                        idx++;
1407                                eventQueueEmergency.add(idx, e);
1408                        } else {
1409                                eventQueueEmergency.add(-(idx + 1), e);
1410                        }
1411                }
1412                long t2 = System.currentTimeMillis();
1413                schedTime += t2 - t1;
1414        }
1415       
1416        /**
1417         * Generate the receive events corresponding to one send event, for the cars
1418         * in the wireless range of the sending car.
1419         *
1420         */
1421        public static void simulateCommunication(SendEvent e) {
1422               
1423                Road r1 = null;
1424                Point p1 = null;
1425                r1 = (Road) Globals.map.roads.get(e.sender.getRoadIdx());
1426                p1 = (Point) r1.points.get(e.sender.getPointIdx());
1427               
1428                if (e instanceof UnicastSendEvent) {
1429                        long t1 = System.currentTimeMillis();
1430                        Iterator<SimulatedCarInfo> it = cars.iterator();
1431                        ReceiveEvent re = null;
1432                        while (it.hasNext()) {
1433                                SimulatedCarInfo r = it.next();
1434                                if (r.vehicleId == ((UnicastSendEvent) e).getReceiverId()) {
1435                                        Road r2 = (Road) Globals.map.roads.get(r.getRealPos().getRoadIdx());
1436                                        Point p2 = (Point) r2.points.get(r.getRealPos().getPointIdx());
1437
1438                                        // MODIFIED BY CRISTI!!!
1439                                        // ReceiveEvent er = new ReceiveEvent(e.getTime() + 1, r, e.getMessage());
1440
1441                                        re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1442                                        re.setUnicast(true);
1443
1444                                        schedEvent(re);
1445                                        if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
1446                                        } else {
1447                                                System.out.println("EROARE! DISTANCE="+ GPSutil.distance(p1, p2));
1448                                        }
1449                                        // END MODIFIED!!!
1450                                        return;
1451                                }
1452                        }
1453                       
1454                       
1455                        re.setSender(e.getSender());
1456                       
1457                        schedEvent(re);
1458
1459                        long t2 = System.currentTimeMillis();
1460                        netTime += t2 - t1;
1461
1462                } else {
1463                       
1464                        long tmp = 0;
1465                        long t3 = System.currentTimeMillis();
1466                        long t4;
1467
1468//                      re = new ReceiveEvent(e.getTime() + 1, e.getSender(), e.getMessage());
1469                       
1470
1471                        int cnt3 = 0;
1472                        int pkcnt = 0;
1473                        PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
1474
1475                        ListIterator<PeanoKey> pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1476                        PeanoKey maxpk = null;
1477                       
1478                        double wifirange;
1479                        if (e.sender instanceof WirelessTrafficLight){
1480                                maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
1481                                wifirange = EXTENDED_WIRELESS_RANGE;
1482                        }else{
1483                                wifirange = WIRELESS_RANGE;
1484                                maxpk = pk.getMaxpk();
1485                        }
1486                       
1487                        PeanoKey pkx = null;
1488                        for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
1489                                pkcnt++;
1490                                // long tc1 = System.currentTimeMillis();
1491                                if (pkx.compareTo(maxpk) > 0)
1492                                        break;
1493                                // long tc2 = System.currentTimeMillis();
1494                                // comp += (tc2-tc1);
1495
1496                                if (pkx.getCars() != null) {
1497                                        Road r2 = (Road) Globals.map.roads.get(pkx.getRoadIndex());
1498                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1499                                        if (GPSutil.distance(p1, p2) < 5 * wifirange) {
1500                                                cnt3 += pkx.getCars().size();
1501                                                Iterator<SimulatedCarInfo> it = pkx.getCars().iterator();
1502                                                while (it.hasNext()) {
1503                                                        SimulatedCarInfo r = it.next();
1504                                                        if (e.sender instanceof SimulatedCarInfo)
1505                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender).getVehicleId())
1506                                                                        continue;
1507                                                        r.setLastMediumTransmition(crtTime);
1508                                                       
1509                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1510                                                        re.setSender(e.getSender());
1511                                                        schedEvent(re);
1512                                                }
1513                                        }
1514                                }
1515                        }
1516                        PeanoKey minpk = null;
1517                        if (e.sender instanceof WirelessTrafficLight)
1518                                minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
1519                        else
1520                                minpk = pk.getMinpk();
1521                       
1522                        pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1523
1524                        if (pkit.hasPrevious()){
1525                                pkx = pkit.previous();
1526                        }
1527                        for (; pkit.hasPrevious(); pkx = pkit.previous()) {
1528                                pkcnt++;
1529                                // long tc1 = System.currentTimeMillis();
1530                                if (pkx.compareTo(minpk) < 0) {
1531                                        break;
1532                                }
1533                                // long tc2 = System.currentTimeMillis();
1534                                // comp += (tc2-tc1);
1535
1536                                if (pkx.getCars() != null) {
1537                                        Road r2 = (Road) Globals.map.roads.get(pkx.getRoadIndex());
1538                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1539                                        double distance = GPSutil.distance(p1, p2);
1540                                        if (distance < 5 * wifirange) {
1541                                                Iterator<SimulatedCarInfo> it = pkx.getCars().iterator();
1542                                                cnt3 += pkx.getCars().size();
1543                                                while (it.hasNext()) {
1544                                                        SimulatedCarInfo r = it.next();
1545                                                       
1546                                                        r.setLastMediumTransmition(crtTime);
1547                                               
1548                                                        if (e.sender instanceof SimulatedCarInfo)
1549                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender).getVehicleId())
1550                                                                        continue;
1551                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1552                                                        re.setSender(e.getSender());
1553                                                        schedEvent(re);
1554                                                }
1555                                        }
1556                                }
1557                        }
1558                       
1559                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
1560                                WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
1561                                                .get(Globals.map.lightsIndices.get(j));
1562                                long t1sem = System.currentTimeMillis();
1563
1564                                if (GPSutil.distance(p1, wtl.getMapPoint()) < 5 * WIRELESS_RANGE) {
1565                                        wtl.setLastMediumTransmition(crtTime);
1566                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, wtl, e.getMessage(), e.getMessageObject(), e.getMessageType());
1567                                        re.setSender(e.getSender());
1568                                        schedEvent(re);
1569                                }
1570                                long t2sem = System.currentTimeMillis();
1571                                semTime += (t2sem - t1sem);
1572                        }
1573                       
1574                        t4 = System.currentTimeMillis();
1575                        tmp += t4 - t3;
1576                        netTime += tmp;
1577                }
1578        }
1579
1580        //Petroaca - the communication simulation for the emergency channel
1581        public void simulateCommunicationEmergency(SendEvent e) {
1582
1583                Road r1 = null;
1584                Point p1 = null;
1585                r1 = (Road) Globals.map.roads.get(e.sender.getRoadIdx());
1586                p1 = (Point) r1.points.get(e.sender.getPointIdx());
1587               
1588                if (e instanceof UnicastSendEvent) {
1589                        long t1 = System.currentTimeMillis();
1590                        Iterator<SimulatedCarInfo> it = cars.iterator();
1591                        ReceiveEvent re = null;
1592                        while (it.hasNext()) {
1593                                SimulatedCarInfo r = it.next();
1594                                if (r.vehicleId == ((UnicastSendEvent) e).getReceiverId()) {
1595                                        Road r2 = (Road) Globals.map.roads.get(r.getRealPos()
1596                                                        .getRoadIdx());
1597                                        Point p2 = (Point) r2.points.get(r.getRealPos()
1598                                                        .getPointIdx());
1599
1600                                        // MODIFIED BY CRISTI!!!
1601                                        // ReceiveEvent er = new ReceiveEvent(e.getTime() + 1, r,
1602                                        // e.getMessage());
1603
1604                                        re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1605                                        re.setUnicast(true);
1606
1607                                        schedEventEmergency(re);
1608                                        if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
1609                                        } else {
1610                                                System.out.println("EROARE! DISTANCE="
1611                                                                + GPSutil.distance(p1, p2));
1612                                        }
1613                                        // END MODIFIED!!!
1614                                        return;
1615                                }
1616                        }
1617                       
1618                        re.setSender(e.getSender());
1619                        schedEventEmergency(re);
1620
1621                        long t2 = System.currentTimeMillis();
1622                        netTime += t2 - t1;
1623
1624                } else {
1625                       
1626                        long tmp = 0;
1627                        long t3 = System.currentTimeMillis();
1628                        long t4;
1629
1630//                      re = new ReceiveEvent(e.getTime() + 1, e.getSender(), e
1631//                                      .getMessage());
1632                       
1633
1634                        int cnt3 = 0;
1635                        int pkcnt = 0;
1636                        PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
1637
1638                        ListIterator<PeanoKey> pkit = Globals.map.peanoKeys
1639                                        .listIterator(p1.getPeanoKeyIdx());
1640                        PeanoKey maxpk = null;
1641                       
1642                        double wifirange;
1643                        if (e.sender instanceof WirelessTrafficLight){
1644                                maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
1645                                wifirange = EXTENDED_WIRELESS_RANGE;
1646                        }else{
1647                                wifirange = WIRELESS_RANGE;
1648                                maxpk = pk.getMaxpk();
1649                        }
1650                        PeanoKey pkx = null;
1651                        for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
1652                                pkcnt++;
1653                                // long tc1 = System.currentTimeMillis();
1654                                if (pkx.compareTo(maxpk) > 0)
1655                                        break;
1656                                // long tc2 = System.currentTimeMillis();
1657                                // comp += (tc2-tc1);
1658
1659                                if (pkx.getCars() != null) {
1660                                        Road r2 = (Road) Globals.map.roads.get(pkx
1661                                                        .getRoadIndex());
1662                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1663                                        if (GPSutil.distance(p1, p2) < 5 * wifirange) {
1664                                                cnt3 += pkx.getCars().size();
1665                                                Iterator<SimulatedCarInfo> it = pkx.getCars()
1666                                                                .iterator();
1667                                                while (it.hasNext()) {
1668                                                        SimulatedCarInfo r = it.next();
1669                                                        if (e.sender instanceof SimulatedCarInfo)
1670                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender)
1671                                                                        .getVehicleId())
1672                                                                        continue;
1673                                                        r.setLastMediumTransmition(crtTime);
1674                                                       
1675                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1676                                                        re.setSender(e.getSender());
1677                                                        schedEventEmergency(re);
1678                                                }
1679                                        }
1680                                }
1681                        }
1682                        PeanoKey minpk = null;
1683                        if (e.sender instanceof WirelessTrafficLight)
1684                                minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
1685                        else
1686                                minpk = pk.getMinpk();
1687                       
1688                        pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
1689
1690                        if (pkit.hasPrevious()){
1691                                pkx = pkit.previous();
1692                        }
1693                        for (; pkit.hasPrevious(); pkx = pkit
1694                                        .previous()) {
1695                                pkcnt++;
1696                                // long tc1 = System.currentTimeMillis();
1697                                if (pkx.compareTo(minpk) < 0) {
1698                                        break;
1699                                }
1700                                // long tc2 = System.currentTimeMillis();
1701                                // comp += (tc2-tc1);
1702
1703                                if (pkx.getCars() != null) {
1704                                        Road r2 = (Road) Globals.map.roads.get(pkx
1705                                                        .getRoadIndex());
1706                                        Point p2 = (Point) r2.points.get(pkx.getPointIndex());
1707                                        double distance = GPSutil.distance(p1, p2);
1708                                        if (distance < 5 * wifirange) {
1709                                                Iterator<SimulatedCarInfo> it = pkx.getCars()
1710                                                                .iterator();
1711                                                cnt3 += pkx.getCars().size();
1712                                                while (it.hasNext()) {
1713                                                        SimulatedCarInfo r = it.next();
1714                                                        r.setLastMediumTransmition(crtTime);
1715                                               
1716                                                        if (e.sender instanceof SimulatedCarInfo)
1717                                                                if (r.getVehicleId() == ((SimulatedCarInfo)e.sender)
1718                                                                        .getVehicleId())
1719                                                                        continue;
1720                                                        ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
1721                                                        re.setSender(e.getSender());
1722                                                        schedEventEmergency(re);
1723                                                }
1724                                        }
1725                                }
1726                        }
1727                       
1728                        t4 = System.currentTimeMillis();
1729                        tmp += t4 - t3;
1730                        netTime += tmp;
1731                }
1732        }
1733       
1734        /**
1735         * Adds a new car to the simulation.
1736         *
1737         * @param car The object that stores the physical behaviour of the vehicle to add
1738         */
1739        public void addCar(CarInstance car) 
1740        {
1741                if (car == null)
1742                        return;
1743               
1744                car.timestamp = crtTime;
1745                created ++;
1746                synchronized (cars) 
1747                {
1748                        SimulatedCarInfo dc = null;
1749                        if (crtTime == 0) {
1750//                              dc = new SimulatedCarInfo(car.ID, car.getLane(),
1751//                                              car.getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1752//                                              car.getDirection(), car.getOffset());
1753                                /*
1754                                dc = new CarRunningVITP(car.ID, car.getLane(), car.getSpeed(),
1755                                                car.getRoadIdx(), car.getPointIdx(),
1756                                                car.getDirection(), car.getOffset());
1757                                */
1758                                //EZcab car
1759                                if (applicationType == Globals.PROT_EZCAB){
1760                                        dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1761                                                        car.getRoadIdx(), car.getPointIdx(),
1762                                                        car.getDirection(), car.getOffset());
1763                                        System.out.println("new ezcab car created");
1764                                }
1765                                else if (simulationType == RoutingConstants.ROUTING_SCFT) 
1766                                        dc=new CarRunningSCFT(car.ID, car.getLane(), car.getSpeed(),
1767                                                        car.getRoadIdx(), car.getPointIdx(),
1768                                                        car.getDirection(), car.getOffset());
1769                                else
1770                                        dc=new CarRunningDSRC(car.ID, car.getLane(), car.getSpeed(),
1771                                                car.getRoadIdx(), car.getPointIdx(),
1772                                                car.getDirection(), car.getOffset());
1773                               
1774                                dc.setTimestamp(crtTime);
1775                                dc.setRealPos(car);
1776                                cars.add(dc);
1777                                dc.init();
1778                        } 
1779                        else 
1780                        {
1781                                int poz = cars.indexOf(new SimulatedCarInfo(car.ID));
1782                                if (poz == -1) 
1783                                {
1784                                        /*     
1785                                        dc = new CarRunningVITP(car.ID, car.getLane(), car
1786                                                        .getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1787                                                        car.getDirection(), car.getOffset());
1788                                                        */
1789                                        //Ezcab
1790                                        if (applicationType == Globals.PROT_EZCAB){
1791                                                if(System.currentTimeMillis() % 2 == 0){
1792                                                        dc = new EzcabClient(car.ID, car.getLane(), 1.0, //a minimum speed
1793                                                                        car.getRoadIdx(), car.getPointIdx(),
1794                                                                        car.getDirection(), car.getOffset());
1795                                                       
1796//                                                      dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1797//                                                                      car.getRoadIdx(), car.getPointIdx(),
1798//                                                                      car.getDirection(), car.getOffset());
1799                                                        //System.out.println("new client created");
1800                                                }
1801                                                else {
1802                                                        dc=new EzcabCar(car.ID, car.getLane(), car.getSpeed(),
1803                                                                        car.getRoadIdx(), car.getPointIdx(),
1804                                                                        car.getDirection(), car.getOffset());
1805                                                       
1806//                                                      dc = new EzcabClient(car.ID, car.getLane(), 1.0, //a minimum speed
1807//                                                                      car.getRoadIdx(), car.getPointIdx(),
1808//                                                                      car.getDirection(), car.getOffset());
1809                                                        //System.out.println("new ezcab car created");
1810                                                }
1811                                        }
1812                                        else if (simulationType == RoutingConstants.ROUTING_SCFT) 
1813                                                dc=new CarRunningSCFT(car.ID, car.getLane(), car.getSpeed(),
1814                                                                car.getRoadIdx(), car.getPointIdx(),
1815                                                                car.getDirection(), car.getOffset());
1816                                        else
1817                                                dc=new CarRunningDSRC(car.ID, car.getLane(), car.getSpeed(),
1818                                                        car.getRoadIdx(), car.getPointIdx(),
1819                                                        car.getDirection(), car.getOffset());
1820//                                      dc = new SimulatedCarInfo(car.ID, car.getLane(), car
1821//                                                      .getSpeed(), car.getRoadIdx(), car.getPointIdx(),
1822//                                                      car.getDirection(), car.getOffset());
1823                                       
1824                                        dc.setTimestamp(crtTime);
1825                                        dc.setRealPos(car);
1826                                        int t = 1 + random.nextInt(fps / 2 - 5);
1827                                        schedEvent(new SendEvent(crtTime + t, dc,SimulatedCarInfo.STANDARD_MESSAGE_ID));
1828                                        cars.add(dc);
1829                                        dc.init();                                     
1830                                } 
1831                                else 
1832                                {
1833                                        ((SimulatedCarInfo) cars.get(poz)).setRealPos(car);
1834                                }
1835                        }
1836                }
1837        }
1838
1839        /*
1840         * Read a scenario phase from a traces file. Update the vehicle's position
1841         * for the current step.
1842         *
1843         */
1844        public void readScenarioPhase() {
1845                int nrCars = 0;
1846                try {
1847                        int vehId, rdIdx, ptIdx;
1848                        byte dir, lane, speed;
1849                        double offset;
1850                        nrCars = dis.readInt();
1851                        // System.out.println(nrCars+" masini");
1852
1853                        synchronized (cars) 
1854                        {
1855                                for (int i = 0; i < nrCars; i++) 
1856                                {
1857                                        vehId   = dis.readInt();
1858                                        rdIdx   = dis.readInt();
1859                                        ptIdx   = dis.readInt();
1860                                        offset  = dis.readDouble();
1861                                        dir             = (byte) dis.readInt();
1862                                        lane    = (byte) dis.readInt();
1863                                        speed   = (byte) dis.readDouble();
1864
1865                                        SimulatedCarInfo dc = null;
1866                                        if (crtTime == 0) {
1867                                                /*     
1868                                                dc = new CarRunningVITP(vehId, lane, speed,
1869                                                                (short) rdIdx, (short) ptIdx, dir, offset);
1870                                                */
1871                                                //create ezcab car
1872                                                if (applicationType == Globals.PROT_EZCAB){
1873                                                        dc = new EzcabCar(vehId, lane, speed,
1874                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1875                                                        System.out.println("new ezcab car");
1876                                                }
1877                                                else if (simulationType == RoutingConstants.ROUTING_SCFT)
1878                                                        dc = new CarRunningSCFT(vehId, lane, speed,
1879                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1880                                                else
1881                                                        dc = new CarRunningDSRC(vehId, lane, speed,
1882                                                                (short) rdIdx, (short) ptIdx, dir, offset);
1883                                                // dc = new SimulatedCarInfo(vehId, lane, speed,
1884                                                // (short)rdIdx, (short)ptIdx, dir, offset);
1885                                                dc.setTimestamp(crtTime);
1886                                                dc.setRealPos(new CarInstance((CarInfo) dc));
1887                                                cars.add(dc);
1888                                                dc.init();
1889                                        } else {
1890                                                int poz = cars.indexOf(new SimulatedCarInfo(vehId));
1891                                                if (poz == -1) {
1892                                                        /*     
1893                                                        dc = new CarRunningVITP(vehId, lane, speed,
1894                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1895                                                        */
1896                                                        //create new ezcab car or client
1897                                                        if (applicationType == Globals.PROT_EZCAB){
1898                                                                if(System.currentTimeMillis() % 2 == 0){
1899                                                                        dc = new EzcabClient(vehId, lane, 1.0, //minimum allowed speed
1900                                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1901//                                                                      dc = new EzcabCar(vehId, lane, speed,
1902//                                                                                      (short) rdIdx, (short) ptIdx, dir, offset);
1903                                                                        //System.out.println("new ezcab client created");
1904                                                                }
1905                                                                else{
1906                                                                        dc = new EzcabCar(vehId, lane, speed,
1907                                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1908//                                                                      dc = new EzcabClient(vehId, lane, 1.0, //minimum allowed speed
1909//                                                                                      (short) rdIdx, (short) ptIdx, dir, offset);
1910                                                                        //System.out.println("new ezcab car created");
1911                                                                }
1912                                                        }
1913                                                        else if (simulationType == RoutingConstants.ROUTING_SCFT)
1914                                                                dc = new CarRunningSCFT(vehId, lane, speed,
1915                                                                                (short) rdIdx, (short) ptIdx, dir, offset);
1916                                                        else
1917                                                                dc = new CarRunningDSRC(vehId, lane, speed,
1918                                                                        (short) rdIdx, (short) ptIdx, dir, offset);
1919                                                        // dc = new SimulatedCarInfo(vehId, lane, speed,
1920                                                        // (short)rdIdx, (short)ptIdx, dir, offset);
1921                                                        dc.setTimestamp(crtTime);
1922                                                        dc.setRealPos(new CarInstance((CarInfo) dc));
1923                                                        cars.add(dc);
1924                                                        dc.init();
1925                                                } else {
1926                                                        CarInstance ci = ((SimulatedCarInfo) cars.get(poz))
1927                                                                        .getRealPos();
1928                                                        ci.deleteCarToPointMapping();
1929                                                        ci.setSpeed((byte) speed);
1930                                                        ci.setRoadIdx((short) rdIdx);
1931                                                        ci.setPointIdx((short) ptIdx);
1932                                                        ci.setLane(lane);
1933                                                        ci.setDirection((byte) dir);
1934                                                        ci.setOffset(offset);
1935                                                        ci.setTimestamp(crtTime);
1936                                                        ci.updateCarToPointMapping();
1937                                                }
1938                                        }
1939                                }
1940                        }
1941                } catch (Exception e) {
1942                        System.err.println("Error reading scenario file");
1943                        e.printStackTrace();
1944                }
1945        }
1946
1947        public static boolean outputToFile = false;
1948
1949        public void generateScenarioPhase() {
1950               
1951                long t1sem = System.currentTimeMillis();
1952                if (crtTime % Globals.SECOND == 0){
1953                        for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
1954                                IntersectionWithTrafficLights iwtl = (IntersectionWithTrafficLights) Globals.map.allIntersections
1955                                .get(Globals.map.lightsIndices.get(j));
1956                                iwtl.step(crtTime);
1957                        }
1958                }
1959                long t2sem = System.currentTimeMillis();
1960                semTime += (t2sem - t1sem);
1961
1962                int NCARS = 0;
1963
1964                for (int j = 0; j < Globals.map.roads.size(); j++) {
1965
1966                        //Petroaca - random car on road to send emergency message
1967                        Random r;
1968                        int randId=0;
1969                        if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
1970                        {
1971                                r=new Random();
1972                                randId=r.nextInt(Globals.map.roads.get(j).carsOnThisRoad.size()+1);
1973                               
1974                        }
1975                       
1976                        SortedCarVector newVector = new SortedCarVector();
1977                        for (int k = Globals.map.roads.get(j).carsOnThisRoad.size() - 1; k >= 0; k--) {
1978                                CarInstance car = Globals.map.roads.get(j).carsOnThisRoad
1979                                                .get(k);
1980                                if (car.finished) {
1981                                       
1982                                        totalControlDelay += car.totalControlDelay;
1983                                        fincars ++;
1984                                        if (maxControlDelay < car.totalControlDelay)
1985                                                maxControlDelay = car.totalControlDelay;
1986
1987                                        synchronized (cars) {
1988                                                if (car.startMonitor) {
1989                                                        crossedCars++;
1990                                                        totalEM.addEmissionsResults(car.em, 1);
1991                                                        totalkm += car.totalDistance - car.startMonitorDistance;
1992                                                        totalTime += (crtTime - car.startTime)/Globals.SECOND;
1993                                                }
1994                                                Globals.monitoredCars.remove(car.getSimulatedCarInfo());
1995                                                car.finish();
1996                                                car.deleteCarToPointMapping();
1997                                                cars.remove(car.getSimulatedCarInfo());
1998                                        }
1999                                        continue;
2000                                }
2001                                try {
2002                                        long t1 = System.currentTimeMillis();
2003
2004                                        synchronized (cars) {
2005                                                car.deleteCarToPointMapping();
2006                                                car.move();
2007
2008                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_SELF_ROUTE) {
2009                                                        QueryGeneration.generateQueryForCar(car);
2010                                                }
2011
2012                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
2013                                                        GuidanceRequest.generateRequestToInfrastructure(car);
2014                                                }
2015                                               
2016                                                if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
2017                                                        CarToIntersectionComm.updateMetrics(car);
2018                                                }
2019                                               
2020//                                              Petroaca - emergency messages schedule
2021                                               
2022                                                if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC && car.ID==randId && crtTime%50==0)
2023                                                {
2024                                                        EmergencyRequest.generateEmergencyMessage(car);
2025                                                }
2026                                               
2027                                                car.setTimestamp(crtTime);
2028                                       
2029                                               
2030                                               
2031                                                if (car.endMonitor){
2032                                                        crossedCars ++;
2033                                                        totalEM.addEmissionsResults(car.em, 1);
2034                                                        totalkm += car.totalDistance - car.startMonitorDistance;
2035        //                                              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));
2036                                                        car.endMonitor = false;
2037                                                        car.startMonitor = false;
2038                                                }
2039
2040                                                car.updateCarToPointMapping();
2041                                                 
2042                                        }
2043
2044                                        long t2 = System.currentTimeMillis();
2045                                        moveTime += t2 - t1;
2046                                } catch (Exception ex) {
2047                                        ex.printStackTrace();
2048                                }
2049                                // if it has changed road, place it in the vector of its new
2050                                // road
2051                                if (car.getRoadIdx() != j) {
2052                                        if (car.getRoadIdx() > j)
2053                                                NCARS--; // it will be moved again when that road
2054                                                                        // will be processed
2055                                        Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
2056                                                        .addCarInstance(car);
2057                                } else {
2058                                        // it's still on the same road
2059                                        newVector.addCarInstance(Globals.map.roads.get(j).carsOnThisRoad.get(k));
2060                                }
2061                                NCARS++;
2062                        }
2063
2064                        // loop through the new vector and set the indices
2065                        for (int k = 0; k < newVector.size(); k++) {
2066                                newVector.get(k).index = k;
2067                        }
2068                        Globals.map.roads.get(j).carsOnThisRoad = newVector;
2069                }
2070       
2071               
2072                if (!outputToFile)
2073                        return;
2074                // output text
2075                try {
2076                        pwText.print(NCARS + " ");
2077                        outBin.writeInt(NCARS);
2078                        for (int j = 0; j < Globals.map.roads.size(); j++) {
2079                                for (int k = 0; k < Globals.map.roads.get(j).carsOnThisRoad
2080                                                .size(); k++) {
2081                                        CarInstance ci = Globals.map.roads.get(j).carsOnThisRoad
2082                                                        .get(k);
2083                                        pwText.print(ci.ID + " " + ci.getRoadIdx() + " "
2084                                                        + ci.getPointIdx() + " " + ci.getOffset() + " "
2085                                                        + ci.getDirection() + " " + ci.getLane() + "   ");
2086                                        outBin.writeInt(ci.ID);
2087                                        outBin.writeInt(ci.getRoadIdx());
2088                                        outBin.writeInt(ci.getPointIdx());
2089                                        outBin.writeDouble(ci.getOffset());
2090                                        outBin.writeInt(ci.getDirection());
2091                                        outBin.writeInt(ci.getLane());
2092                                        outBin.writeDouble(ci.getSpeed());
2093                                }
2094                        }
2095                        pwText.println();
2096                } catch (IOException e) {
2097                        System.err.println("Error writing traces");
2098                        e.printStackTrace();
2099                        System.exit(0);
2100                }
2101        }
2102       
2103        public int getCrtTime(){
2104                return crtTime;
2105        }
2106       
2107       
2108       
2109       
2110        public SimulatedCarInfo getCarIdx(int rdIdx, int ptIdx) 
2111        {
2112                synchronized (cars) 
2113                {
2114                        Iterator<SimulatedCarInfo> it = cars.iterator();
2115                        while (it.hasNext()) {
2116                                SimulatedCarInfo r = it.next();
2117                                if (r.getRoadIdx() == rdIdx && r.getPointIdx() == ptIdx)
2118                                        return r;
2119                        }
2120                }
2121                return null;
2122        }
2123
2124        public SimulatedCarInfo getCarIdx(int idx) 
2125        {
2126                synchronized (cars) 
2127                {
2128                        Iterator<SimulatedCarInfo> it = cars.iterator();
2129                        while (it.hasNext()) {
2130                                SimulatedCarInfo r = it.next();
2131                                if (r.vehicleId == idx)
2132                                        return r;
2133                        }
2134                }
2135                return null;
2136        }
2137
2138        public static void main(String args[]) {
2139               
2140                // Globals.map = new Map("Intersectie.RT1","Intersectie.RT2");
2141
2142                int tests = 1;
2143                for (int i = 0; i < tests; i++){
2144                        try{
2145                                switch (i){
2146                                        case 0: Globals.pw.println("Adaptive xc  = 1, variations2");
2147                                                break;
2148                                        case 1:Globals.pw.println("Adaptive xc  = 0.95, variations2");
2149                                                break;
2150                                        case 2:break;
2151                                }
2152                               
2153//                              ObjectInputStream ois=new ObjectInputStream(new FileInputStream(".\\maps\\fsc\\Apaca.fsc"));
2154//                              Scenario sc=(Scenario)ois.readObject();
2155//                              Mobility.loadScenario(sc);
2156                       
2157                                Engine e = Globals.engine = new Engine(false, true);
2158                                e.init();
2159//                                              public void run(){
2160//                                                      Globals.demo = new Display();
2161//                                                      Globals.demo.setVisible(true);
2162//                                              }
2163//                                      });
2164//                              t.start();
2165//                              e.play();
2166                                switch (i){
2167                                        case 0:
2168                                                Globals.Xc = 0.95;
2169                                                break;
2170                                        case 1:break;
2171                                        case 2:break;
2172                                }
2173                               
2174                                if (i != tests - 1){
2175                                        Globals.pw.close();
2176                                        String pwname = "rezultate"+System.currentTimeMillis()+".txt";
2177                                        Globals.pw = new PrintWriter(new FileWriter(pwname));
2178                                }
2179                        } catch (Exception ex) {
2180                                ex.printStackTrace();
2181                                System.exit(0);
2182                        }               
2183               
2184                       
2185                }
2186               
2187/*              long t1 = System.currentTimeMillis();
2188                e.play(60);
2189                long t2 = System.currentTimeMillis();
2190
2191                System.out.println("SimTime: " + (t2 - t1));
2192                System.out.println("events: " + (double) (100 * e.eventsTime)
2193                                / (t2 - t1));
2194                System.out.println("mobility: " + (double) (100 * e.mobilityTime)
2195                                / (t2 - t1));
2196                System.out.println("move: " + (double) (100 * e.moveTime) / (t2 - t1));
2197                System.out.println("code: " + (double) (100 * e.codeTime) / (t2 - t1));
2198                System.out.println("net: " + (double) (100 * e.netTime) / (t2 - t1));
2199                System.out.println("cleanup: " + (double) (100 * e.cleanupTime)
2200                                / (t2 - t1));
2201                System.out
2202                                .println("sched: " + (double) (100 * e.schedTime) / (t2 - t1));
2203
2204//              System.out.println("pkavg " + pkavg + "\npkmax" + pkmax
2205//                              + "\ncomp time " + avgTime);
2206                //              e.play();
2207                //              e.step();
2208                //              e.step();
2209                //              e.step();
2210                //              e.step();
2211                //              e.step();
2212                System.exit(0);*/
2213        }
2214
2215       
2216/*      public void createDummyCars() {
2217                Road r = Globals.map.roads.get(1);
2218               
2219                //Stopping a car on a road
2220                int ID = lastCarID;
2221                lastCarID++;
2222                CarInstance car = Mobility.createNewCar(1, 46, 0, 1, 0.0,
2223                                new NotMovingPersonality(), 0.0, ID, 2, 64, null, 1);
2224                if (car == null) {
2225                        lastCarID--;
2226                        System.out.println("Could not create the first stopped car");
2227                } else {
2228                        System.out.println("Jammed car id=" + ID);
2229                        jammed = ID;
2230                }
2231
2232                this.addCar(car);
2233        }
2234*/
2235       
2236       
2237}
Note: See TracBrowser for help on using the repository browser.