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

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