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

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