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

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