예제 #1
0
        /// <summary>
        /// select the next vechile. Intra_Routing.
        /// </summary>
        /// <param name="candidateVe"></param>
        /// <param name="rs"></param>
        /// <returns></returns>
        public VehicleUi MatchVehicle(List <VehicleUi> candidateVe, RoadSegment rs, Packet packet)
        {
            IntraRouting     rou = new IntraRouting(rs);
            CandidateVehicle can = rou.GetCandidateVehicleUis(this, candidateVe, packet.DestinationVehicle, packet.IsRouted);

            if (can != null)
            {
                VehicleUi next = can.SelectedVehicle;
                if (packet.HopsVehicles > 3)
                {
                    int lastMinuse1 = Convert.ToInt16(packet.VehiclesString.Split('-')[packet.HopsVehicles - 1]);
                    if (next.VID != lastMinuse1)
                    {
                        packet.CommunicationOverhead += (candidateVe.Count - 1); // / (CurrentLane.MyRoadSegment.LanesCount / 2); // divided tha lane in the same direction.
                        return(next);
                    }
                    else
                    {
                        // looop: no thing.
                    }
                }
                else
                {
                    return(next);
                }
            }

            return(null);
        }
예제 #2
0
파일: TKMDemo.cs 프로젝트: snmz216/libTKM
        public void GenerateMapData()
        {
            // init road data
            var roads = RoadSegment.ParseRoadData(File.ReadAllText(Path.Combine(dataDir, "r0.txt")));

            // serialize as geojson
            FeatureCollection trafficData = new FeatureCollection();

            foreach (RoadSegment road in roads)
            {
                // find the sensor and determine color
                var sensor = sensorData.Where(s => s.ID == road.ID).FirstOrDefault();
                List <IPosition> segments = new List <IPosition>();
                for (int i = 0; i < road.Nodes.Count; i++)
                {
                    segments.Add(new GeographicPosition(road.Nodes[i].Lat, road.Nodes[i].Lon));
                }

                var featureProperties = new Dictionary <string, object> {
                    { "id", road.ID }, { "l", road.Semt }, { "s", sensor == null ? -1 : sensor.Speed }
                };
                var feat = new Feature(new LineString(segments), featureProperties);
                trafficData.Features.Add(feat);
            }
            var serializedData = JsonConvert.SerializeObject(trafficData);
            var dateTime       = String.Format("{2:00}/{3:00}/{4} {0:00}:{1:00}", acqTimeLocal.Hour, acqTimeLocal.Minute, acqTimeLocal.Day, acqTimeLocal.Month, acqTimeLocal.Year);

            StringBuilder sb = new StringBuilder();

            sb.Append("var mapData=" + serializedData + ";\r\n");
            sb.Append("var acqTime='" + dateTime + "';\r\n");
            sb.Append("var trafficIndex=" + trafficIndex + ";\r\n");

            File.WriteAllText(Path.Combine(dataDir, "tkmData.js"), sb.ToString());
        }
예제 #3
0
    public static bool areRoadsIntersects(RoadSegment rs0, RoadSegment rs1)
    {
        bool lineIntersection = ccw(rs0.getStart(), rs1.getStart(), rs1.getEnd()) != ccw(rs0.getEnd(), rs1.getStart(), rs1.getEnd()) && ccw(rs0.getStart(), rs0.getEnd(), rs1.getStart()) != ccw(rs0.getStart(), rs0.getEnd(), rs1.getEnd());

        if (lineIntersection)
        {
            return(true);
        }
        Vector2[] rs0StartPoints = getRoadOffsetVectors(rs0.getStart(), rs0.getEnd(), rs0.width);
        Vector2[] rs0EndPoints   = getRoadOffsetVectors(rs0.getEnd(), rs0.getStart(), rs0.width);
        Vector2[] rs1StartPoints = getRoadOffsetVectors(rs1.getStart(), rs1.getEnd(), rs1.width);
        Vector2[] rs1EndPoints   = getRoadOffsetVectors(rs1.getEnd(), rs1.getStart(), rs1.width);

        for (int rs0SPoint = 0; rs0SPoint < rs0StartPoints.Length; rs0SPoint++)
        {
            for (int rs0EPoint = 0; rs0EPoint < rs0EndPoints.Length; rs0EPoint++)
            {
                for (int rs1SPoint = 0; rs1SPoint < rs1StartPoints.Length; rs1SPoint++)
                {
                    for (int rs1EPoint = 0; rs1EPoint < rs1EndPoints.Length; rs1EPoint++)
                    {
                        if (areLinesIntersects(rs0StartPoints[rs0SPoint], rs0EndPoints[rs0EPoint], rs1StartPoints[rs1SPoint], rs1EndPoints[rs1EPoint]))
                        {
                            return(true);
                        }
                    }
                }
            }
        }

        return(false);
    }
예제 #4
0
파일: City.cs 프로젝트: Xillez/CityGen
 public void AddSegment(RoadSegment segment)
 {
     if (this.roadSegments != null)
     {
         this.roadSegments.Add(segment);
     }
 }
예제 #5
0
        protected bool makeCrossJunction(
            ref RoadSegment <MetaInformation> seg)
        {
            Road     originalRoad = seg.getLastRoad();
            Junction closest      =
                findClosestJunction(originalRoad.end, Config.DETECTIVE_RADIUS_FROM_ENDS);

            // There's no junction near the end.
            if (closest == null)
            {
                return(false);
            }

            // A new road connected to closest junction.
            var newRoad = new Road(originalRoad.start, closest, originalRoad.width);

            // Roads which maybe have intersections.
            var intersectiveRoads = map.Roads.Intersects(newRoad.Bound);

            // Finding out if overlapped.
            if (intersectiveRoads
                .Any(road => road.getAngleWith(newRoad) == 0f))
            {
                seg.tooShortJudgment = false;
                seg.deleteLastRoad();
                return(true);
            }

            // There's no overlapping, then accept the new road.
            seg.updateLastRoad(newRoad);
            return(true);
        }
예제 #6
0
    public static float getDistance(RoadNetwork roadNetwork, RoadSegment rs0, RoadSegment rs1)
    {
        if (rs0 == rs1)
        {
            return(rs0.getLength() / 2.0f);
        }
        float result   = float.MaxValue;
        float distance = getDistance(roadNetwork, rs0.getStart(), rs1.getStart());

        if (distance < result)
        {
            result = distance;
        }
        distance = getDistance(roadNetwork, rs0.getStart(), rs1.getEnd());
        if (distance < result)
        {
            result = distance;
        }
        distance = getDistance(roadNetwork, rs0.getEnd(), rs1.getStart());
        if (distance < result)
        {
            result = distance;
        }
        distance = getDistance(roadNetwork, rs0.getEnd(), rs1.getEnd());
        if (distance < result)
        {
            result = distance;
        }
        return(result + (rs0.getLength() / 2.0f) + (rs1.getLength() / 2.0f));
    }
예제 #7
0
    /// <summary>
    /// starting city blueprint O-type
    /// </summary>
    /// <param name="center"></param>
    /// <param name="angle"></param>
    public void AddCityCentreO(Vector2 center, float angle)
    {
        angle = 360f / 8f;
        RoadSegment last = null;
        RoadSegment first = null;
        for (int i=0; i<8; i++)
        {
            Quaternion rotationA = Quaternion.Euler (0, 0, angle * i);
            Quaternion rotationB = Quaternion.Euler (0, 0, angle * (i + 1));

            RoadPoint a = new RoadPoint ();
            a.point = rotationA * (new Vector2 (this.scale / 2.5f, 0) + center);
            RoadPoint b = new RoadPoint ();
            b.point = rotationB * (new Vector2 (this.scale / 2.5f, 0) + center);

            RoadSegment rA = new RoadSegment (a, b, 0);
            this.RoadSegments.Add(rA);
            if(first == null)
                first = rA;

            if(last != null)
            {
                Intersection iA = new Intersection (new List<RoadPoint> (){rA.PointA,last.PointA});
                this.RoadIntersections.Add (iA);
            }
            last = rA;
        }

        Intersection iB = new Intersection (new List<RoadPoint> (){first.PointA,last.PointA});
        this.RoadIntersections.Add (iB);
    }
예제 #8
0
        /// <summary>
        /// Random interval. related to speed.
        /// </summary>
        public static double RandomTimeInterval(RoadSegment rs)
        {
            double ranInSegment = RandomSpeedkmh(rs);
            double conver       = GetTimeIntervalInSecond(ranInSegment);

            return(conver);
        }
    public override void agentAction()
    {
        RoadNetwork network = generator.roadNetwork;
        Crossroad   cr0 = network.crossroads[Random.Range(0, network.crossroads.Count)];
        Crossroad   cr1 = network.crossroads[Random.Range(0, network.crossroads.Count)];
        bool        cr0_founded = false, cr1_founded = false;

        for (int i = 0; i < network.crossroads.Count; i++)
        {
            if (cr0.adjacentSegemnts.Count < 3)
            {
                cr0_founded = true;
                break;
            }
            cr0 = network.crossroads[Random.Range(0, network.crossroads.Count)];
        }
        for (int i = 0; i < network.crossroads.Count; i++)
        { // Not guarantee checking all possible crossrods
            if (cr1.adjacentSegemnts.Count < 3 && cr1 != cr0 && !hasIntersections(network, cr0, cr1))
            {
                cr1_founded = true;
                break;
            }
            cr1 = network.crossroads[Random.Range(0, network.crossroads.Count)];
        }
        if (!cr0_founded || !cr1_founded)
        {
            return;
        }

        RoadSegment segment = new RoadSegment(cr0, cr1);

        network.roadSegments.Add(segment);
        Debug.Log("Roads connected");
    }
예제 #10
0
파일: City.cs 프로젝트: Xillez/CityGen
 public void RemoveSegment(RoadSegment segment)
 {
     if (this.roadSegments != null)
     {
         this.roadSegments.Remove(segment);
     }
 }
        private int DistanceToSegmentFromLocation(RoadSegment roadSegment, double longitude, double latitude)
        {
            List <int> distanceToLine = new List <int>();
            // iterate over roadSegment coordinates
            var roadSegLatLong = roadSegment.Location.Value.Coordinates;

            for (int i = 1; i < roadSegLatLong.Length; i++)
            {
                // Create lines between coordinate pairs - between coordinate 0-1, 1-2, 2-3, 2-3
                double[] startPoint = roadSegLatLong[i - 1];
                double[] endPoint   = roadSegLatLong[i];

                distanceToLine.Add(DistanceToLineFromLocation(startPoint[0], startPoint[1], endPoint[0], endPoint[1], longitude, latitude));
            }

            // distance to closest line is distance to roadsegment
            int distanceToSegment = distanceToLine.Min();

            _logger.LogInformation(
                "The closest line segment of {RoadSegment} is {Distance} meters away.",
                roadSegment.ID, distanceToSegment
                );

            return(distanceToSegment);
        }
예제 #12
0
 public void Encode(RoadSegment Seg)
 {
     Idx      = Seg.Idx;
     SectnIdx = Seg.SectnIdx;
     //roadMaterial = Road.Instance.Sectns[SectnIdx].RoadMaterial;
     HasMesh = Seg.HasMesh;
 }
예제 #13
0
    void CreateFwdBckZAxis(int fwd_bck, RoadSegment segment)
    {
        //fwd_bck is 1 when going forward, -1 when going back
        Vector3 pos;
        Vector3 scale;

        GameObject proposed_road = Instantiate(road_segment);

        float value = GM_.Instance.procedural.GetPointCutOff(segment.transform.position.x + (fwd_bck * min_segment_length), segment.transform.position.z);

        float random_length_forward = min_segment_length + ((max_segment_length - min_segment_length) * value);

        pos     = segment.transform.position;
        pos.z  += fwd_bck * ((segment.transform.localScale.x / 2) + (random_length_forward / 2));
        scale   = segment.transform.localScale;
        scale.x = random_length_forward;
        scale.z = segment_width;
        proposed_road.GetComponent <RoadSegment>().RoadSegmentInit(pos, scale, Mathf.Round(segment.transform.rotation.eulerAngles.y), segment.GetTransform(), new Vector3(0, 0, fwd_bck), proposed_road);
        proposed_road.GetComponent <RoadSegment>().AddConnectedSegmentEndPoint(segment.GetObj());
        segment.AddConnectedSegmentEndPoint(proposed_road);
        segment.AddChildNode(proposed_road);


        road_segment_queue.Enqueue(proposed_road);
    }
예제 #14
0
        /// <summary>
        ///  build a grid of road segments
        /// </summary>
        /// <param name="rows"> junctions i n rows </param>
        /// <param name="cols">junctions in  cols </param>
        /// <param name="hLen">Horizontal length</param>
        /// <param name="vLen">Vertical length</param>
        /// <param name="laneCount"> number of lanes</param>
        public static void ConstructGird(MainWindow mainWindow, int rows, int cols, double hLen, double vLen, int laneCount)
        {
            /// the length of junction should be custimizeble, according to the number of lanes.
            double JunHw = 1.6 * (laneCount * PublicParamerters.LaneWidth); // the width- hgigh or jubction.
            double startLocationJunction = 20;

            for (int Rindex = 0; Rindex < rows; Rindex++)
            {
                for (int Cindex = 0; Cindex < cols; Cindex++)
                {
                    double   JunX = startLocationJunction + (Cindex * hLen);
                    double   junY = startLocationJunction + (Rindex * vLen);
                    Junction jun  = new Junction(mainWindow);
                    jun.Margin = new Thickness(JunX, junY, 0, 0);
                    jun.Height = JunHw;
                    jun.Width  = JunHw;
                    mainWindow.canvas_vanet.Children.Add(jun);

                    // add vertical and horizontal
                    if (Cindex < cols - 1 && Rindex < rows - 1)
                    {
                        // add the horizontal First:
                        RoadSegment hrs = new RoadSegment(mainWindow, laneCount, RoadOrientation.Horizontal);
                        hrs.Height = (laneCount * PublicParamerters.LaneWidth) + 1.5;
                        hrs.Width  = hLen - (jun.Width / 2);
                        hrs.Margin = new Thickness(jun.RightCenter.X - (jun.Width / 4), (jun.RightCenter.Y) - (hrs.Height / 2), 0, 0);
                        mainWindow.canvas_vanet.Children.Add(hrs);
                        // add the vertical:
                        RoadSegment vrs = new RoadSegment(mainWindow, laneCount, RoadOrientation.Vertical);
                        vrs.Height = vLen - (jun.Height / 2);;
                        vrs.Width  = (laneCount * PublicParamerters.LaneWidth) + 1.5;
                        vrs.Margin = new Thickness(jun.BottomCenter.X - (vrs.Width / 2), jun.BottomCenter.Y - (jun.Height / 4), 0, 0);
                        mainWindow.canvas_vanet.Children.Add(vrs);
                    }
                    else if (Rindex == rows - 1 && Cindex < cols - 1)
                    {
                        // add the horizontal:
                        RoadSegment hrs = new RoadSegment(mainWindow, laneCount, RoadOrientation.Horizontal);
                        hrs.Height = (laneCount * PublicParamerters.LaneWidth) + 1.5;
                        hrs.Width  = hLen - (jun.Width / 2);
                        hrs.Margin = new Thickness(jun.RightCenter.X - (jun.Width / 4), (jun.RightCenter.Y) - (hrs.Height / 2), 0, 0);
                        mainWindow.canvas_vanet.Children.Add(hrs);
                    }
                    else if (Cindex == cols - 1 && Rindex < rows - 1)
                    {
                        // add the vertical:
                        RoadSegment vrs = new RoadSegment(mainWindow, laneCount, RoadOrientation.Vertical);
                        vrs.Height = vLen - (jun.Height / 2);
                        vrs.Width  = (laneCount * PublicParamerters.LaneWidth) + 1.5;
                        vrs.Margin = new Thickness(jun.BottomCenter.X - (vrs.Width / 2), jun.BottomCenter.Y - (jun.Height / 4), 0, 0);
                        mainWindow.canvas_vanet.Children.Add(vrs);
                    }
                }
            }

            // build:
            BuildRoadNetwork builder = new BuildRoadNetwork(mainWindow);

            builder.Build();
        }
예제 #15
0
    bool LocalConstraints(GameObject working_obj)
    {
        RoadSegment working_segment = working_obj.GetComponent <RoadSegment>();

        foreach (GameObject accepted_segment in accepted_segments) //check againts every road segments that have already been created
        {
            Physics.SyncTransforms();

            if (use_city_limits) //check if it is within a user defined boundry
            {
                if (Mathf.Abs(accepted_segment.transform.position.x) > GM_.Instance.config.city_limits_x || Mathf.Abs(accepted_segment.transform.position.z) > GM_.Instance.config.city_limits_z)
                {
                    return(false);
                }
            }

            //make sure this new road doesn't intersect iwth other roads
            if (working_obj.GetComponent <BoxCollider>().bounds.Intersects(accepted_segment.GetComponent <BoxCollider>().bounds))
            {
                return(false);
            }
            //ensure these roads arnt too close ot other roads
            if (RoadTooClose(working_segment, accepted_segment))
            {
                return(false);
            }
        }

        return(true);
    }
예제 #16
0
    void CreateLftRgtXAxis(int lft_rgt, RoadSegment segment)
    {
        //lft_rgt is 1 when going left, -1 when going right
        Vector3 pos;
        Vector3 scale;

        GameObject proposed_road = Instantiate(road_segment);

        float value = GM_.Instance.procedural.GetPointCutOff(segment.transform.position.x, segment.transform.position.z + (lft_rgt * min_segment_length));

        float random_length_up = min_segment_length + ((max_segment_length - min_segment_length) * value);


        pos    = segment.transform.position;
        pos.x += lft_rgt * (random_length_up / 2) + (lft_rgt * segment_width / 2);

        pos.z = Random.Range(segment.transform.position.z - ((segment.transform.localScale.x / 2) - (0.3f * (segment.transform.localScale.x / 2))), segment.transform.position.z + ((segment.transform.localScale.x / 2) - (0.3f * (segment.transform.localScale.x / 2))));

        scale   = segment.transform.localScale;
        scale.x = random_length_up;
        scale.z = segment_width;
        proposed_road.GetComponent <RoadSegment>().RoadSegmentInit(pos, scale, Mathf.Round(segment.transform.rotation.eulerAngles.y + (90)), segment.GetTransform(), new Vector3(lft_rgt, 0, 0), proposed_road);
        proposed_road.GetComponent <RoadSegment>().AddConnectedSegmentEndPoint(segment.GetObj());
        segment.AddConnectedSegmentMidPoints(proposed_road);
        segment.AddChildNode(proposed_road);


        road_segment_queue.Enqueue(proposed_road);
    }
예제 #17
0
    private static void DrawRoadGuidelines(RoadGuideline guidelines, int child, RoadSegment roadSegment, Vector3 mousePosition, GameObject objectToMove, GameObject extraObjectToMove)
    {
        if (roadSegment.transform.parent.parent.GetComponent <RoadCreator>().settings == null)
        {
            roadSegment.transform.parent.parent.GetComponent <RoadCreator>().settings = RoadCreatorSettings.GetSerializedSettings();
        }

        if (child == 1)
        {
            Handles.color = roadSegment.transform.parent.parent.GetComponent <RoadCreator>().settings.FindProperty("roadControlGuidelinesColour").colorValue;
        }
        else
        {
            Handles.color = roadSegment.transform.parent.parent.GetComponent <RoadCreator>().settings.FindProperty("roadGuidelinesColour").colorValue;
        }

        if (guidelines != null && roadSegment.transform.GetChild(0).GetChild(child).gameObject != objectToMove && roadSegment.transform.GetChild(0).GetChild(child).gameObject != extraObjectToMove)
        {
            Vector2 mousePositionXZ = new Vector3(mousePosition.x, mousePosition.z);
            Vector2 nereastPoint    = Misc.FindNearestPointOnLine(new Vector2(guidelines.startPoint.x, guidelines.startPoint.z), new Vector2(guidelines.endPoint.x, guidelines.endPoint.z), mousePositionXZ);

            if (Vector2.Distance(mousePositionXZ, nereastPoint) < roadSegment.transform.parent.parent.GetComponent <RoadCreator>().settings.FindProperty("roadGuidelinesDistance").floatValue)
            {
                Handles.DrawLine(guidelines.centerPoint, guidelines.startPoint);
                Handles.DrawLine(guidelines.centerPoint, guidelines.endPoint);
                Handles.DrawSolidDisc(guidelines.centerPoint, Vector3.up, roadSegment.transform.parent.parent.GetComponent <RoadCreator>().settings.FindProperty("pointSize").floatValue * 0.75f);

                Vector3 left = CalculateLeft(guidelines.startPoint, guidelines.endPoint);
                Handles.DrawLine(guidelines.startPoint - left * 0.5f, guidelines.startPoint + left * 0.5f);
                Handles.DrawLine(guidelines.endPoint - left * 0.5f, guidelines.endPoint + left * 0.5f);
            }
        }
    }
예제 #18
0
    //
    public void Init(float road_width, Vector2Int pos)
    {
        m_roadWidth = road_width;

        m_segments.Add(pos, m_tail = m_head = new RoadSegment());
        m_headPos = m_tailPos = pos;
    }
예제 #19
0
    public RoadSegment buildRoadRight()
    {
        if (canBuildRoad(currentSegment.transform.right))
        {
            Quaternion newRoadDirection = currentSegment.transform.rotation;
            Vector3    rotation         = newRoadDirection.eulerAngles;
            rotation.y += 90f;
            newRoadDirection.eulerAngles = rotation;

            GameObject newRoadGameObj = Instantiate(roadPrefab,
                                                    currentSegment.transform.position + currentSegment.transform.right * currentSegment.size,
                                                    newRoadDirection) as GameObject;
            RoadSegment newRoad = newRoadGameObj.GetComponent <RoadSegment>();

            RoadSegment.WireSide(currentSegment.nodeRight, newRoad.nodeBack);

            currentSegment.sidewalkRight.gameObject.SetActive(false);
            newRoad.sidewalkBack.gameObject.SetActive(false);

            currentSegment = newRoad;
            age++;
            return(currentSegment);
        }
        makeFrontLoop();
        return(null);
    }
예제 #20
0
 // inSegment(): determine if a point is inside a segment
 //    Input:  a point P, and a collinear segment S
 //    Return: 1 = P is inside S
 //            0 = P is  not inside S
 int inSegment(RoadPoint P, RoadSegment S)
 {
     if (S.PointA.point.x != S.PointB.point.x)              // S is not  vertical
     {
         if (S.PointA.point.x <= P.point.x && P.point.x <= S.PointB.point.x)
         {
             return(1);
         }
         if (S.PointA.point.x >= P.point.x && P.point.x >= S.PointB.point.x)
         {
             return(1);
         }
     }
     else              // S is vertical, so test y  coordinate
     {
         if (S.PointA.point.y <= P.point.y && P.point.y <= S.PointB.point.y)
         {
             return(1);
         }
         if (S.PointA.point.y >= P.point.y && P.point.y >= S.PointB.point.y)
         {
             return(1);
         }
     }
     return(0);
 }
예제 #21
0
파일: LaneQueue.cs 프로젝트: howbani/VSIM
        /// <summary>
        /// get the neighbors for the vehicle within the roadSegment. note that the vechile now is not in the roadSegment. This required when the vechile is almost in the junction. so it required to switch to a new road segment.
        /// </summary>
        /// <param name="vehicle">current ve</param>
        /// <param name="Packetdirection"> the packet direction </param>
        /// <param name="selectedNextRoadSegment"> the road segment</param>
        /// <returns>the inter_nei for vehicle</returns>
        public void GetInterNeighbors(VehicleUi vehicle, Direction Packetdirection, RoadSegment selectedNextRoadSegment)
        {
            vehicle.Dispatcher.Invoke((Action) delegate
            {
                vehicle.Inter_Neighbores.Clear();
                List <VehicleUi> allInSameDirection = new List <RoadNet.Components.VehicleUi>();
                foreach (LaneUi lane in selectedNextRoadSegment.Lanes)
                {
                    if (lane.LaneDirection == Packetdirection)
                    {
                        allInSameDirection.AddRange(lane.LaneVehicleAndQueue.LaneVechilesList);
                    }
                }

                int vid = vehicle.VID;
                int rid = selectedNextRoadSegment.RID;

                List <VehicleUi> neibore = new List <RoadNet.Components.VehicleUi>();
                foreach (VehicleUi Inter_vehicle in allInSameDirection)
                {
                    double dis = Computations.Distance(vehicle.InstanceLocation, Inter_vehicle.InstanceLocation);
                    if (dis < Settings.Default.CommunicationRange)
                    {
                        vehicle.Inter_Neighbores.Add(Inter_vehicle);
                        int v_id = Inter_vehicle.VID;
                    }
                }

                // consider the vhicles which are in the front of me and in the same direction too.
                GetIntraNeighborOneWayInfront(vehicle);
                vehicle.Inter_Neighbores.AddRange(vehicle.Intra_Neighbores);
            });
        }
예제 #22
0
    public void ProcessNextRoadAsStraight()
    {
        RoadSegment road = UnprossedRoads.Dequeue();

        EnteredNewRoad();
        if (road.RoadType == Player.ActionType.Straight)
        {
            Waypoints.Enqueue(road.GetRandomMidpoint());
            Waypoints.Enqueue(road.GetRandomEndpoint());
        }
        else
        {
            int diff = Player.ActionType.Straight - road.RoadType;
            // MISS RIGHT
            if (diff > 0)
            {
                Debug.Log("MISS RIGHT");
                Waypoints.Enqueue(road.MidMissRight);
                Waypoints.Enqueue(road.MissRight);
            }
            // MISS LEFT
            else if (diff < 0)
            {
                Debug.Log("MISS LEFT");
                Waypoints.Enqueue(road.MidMissLeft);
                Waypoints.Enqueue(road.MissLeft);
            }
        }

        HighlightNextRoad();
    }
예제 #23
0
    void GlobalConstraints(RoadSegment segment)
    {
        Vector3 pos;
        Vector3 scale;

        int rot = (int)Mathf.Abs(segment.transform.rotation.eulerAngles.y);

        //spawn 4 new roads off this segment
        foreach (int i in angle)
        {
            if (Mathf.Approximately(rot, i))
            {
                switch (i)
                {
                case 0:
                {
                    CreateFwdBckXAxis(1, segment);
                    CreateLftRgtZAxis(1, segment);
                    CreateFwdBckXAxis(-1, segment);
                    CreateLftRgtZAxis(-1, segment);
                    break;
                }

                case 90:
                {
                    CreateFwdBckZAxis(1, segment);
                    CreateLftRgtXAxis(1, segment);
                    CreateFwdBckZAxis(-1, segment);
                    CreateLftRgtXAxis(-1, segment);
                    break;
                }

                case 180:
                {
                    CreateFwdBckXAxis(1, segment);
                    CreateLftRgtZAxis(1, segment);
                    CreateFwdBckXAxis(-1, segment);
                    CreateLftRgtZAxis(-1, segment);
                    break;
                }

                case 270:
                {
                    CreateFwdBckZAxis(1, segment);
                    CreateLftRgtXAxis(1, segment);
                    CreateFwdBckZAxis(-1, segment);
                    CreateLftRgtXAxis(-1, segment);
                    break;
                }

                default:
                {
                    Debug.Log("Rejected Angle");
                    break;
                }
                }
            }
        }
    }
예제 #24
0
        /// <summary>
        /// we have three lanes per segments. the index should be 1,2,3. ONLY.
        /// </summary>
        /// <param name="lindex"></param>
        public void ChangeLaneRandomly()
        {
            Dispatcher.Invoke((Action) delegate
            {
                int lanConut = CurrentLane.MyRoadSegment.LanesCount;
                if (lanConut > 2)
                {
                    RoadSegment rs  = CurrentLane.MyRoadSegment;
                    LaneUi prevLane = CurrentLane;
                    LaneUi newlane  = null;

                    if (prevLane.LaneDirection == Direction.N)
                    {
                        newlane = rs.Lanes[LaneIndex.RandomLaneIndex.North(rs.LanesCount)];

                        prevLane.LaneVehicleAndQueue.RemoveFromLane(this);
                        this.CurrentLane = newlane;
                        this.Margin      = new Thickness(newlane.MyCenterLeft, this.Margin.Top, 0, 0);
                        this.SetVehicleDirection(Direction.N);
                    }
                    else if (prevLane.LaneDirection == Direction.S)
                    {
                        newlane = rs.Lanes[LaneIndex.RandomLaneIndex.South(rs.LanesCount)];

                        prevLane.LaneVehicleAndQueue.RemoveFromLane(this);
                        this.CurrentLane = newlane;
                        this.Margin      = new Thickness(newlane.MyCenterLeft, this.Margin.Top, 0, 0);
                        this.SetVehicleDirection(Direction.S);
                    }

                    else if (prevLane.LaneDirection == Direction.E)
                    {
                        newlane = rs.Lanes[LaneIndex.RandomLaneIndex.East(rs.LanesCount)];

                        prevLane.LaneVehicleAndQueue.RemoveFromLane(this);
                        this.CurrentLane = newlane;
                        this.Margin      = new Thickness(this.Margin.Left, newlane.MyCenterTop, 0, 0);
                        this.SetVehicleDirection(Direction.E);
                    }

                    else if (prevLane.LaneDirection == Direction.W)
                    {
                        newlane = rs.Lanes[LaneIndex.RandomLaneIndex.West(rs.LanesCount)];

                        prevLane.LaneVehicleAndQueue.RemoveFromLane(this);
                        this.CurrentLane = newlane;
                        this.Margin      = new Thickness(this.Margin.Left, newlane.MyCenterTop, 0, 0);
                        this.SetVehicleDirection(Direction.W);
                    }

                    // change my speed to random.
                    double instanceSpeed = Computations.GetTimeIntervalInSecond(Computations.RandomSpeedkmh(CurrentLane.MyRoadSegment)); // slow the speed.
                    InstantaneousSpeed   = instanceSpeed;

                    // display:
                    prevLane._MainWindow.Dispatcher.Invoke(new Action(() => prevLane.lbl_info.Text = prevLane.LaneVehicleAndQueue.CountInLane.ToString()), DispatcherPriority.Send);
                }
            });
        }
예제 #25
0
파일: CarTextBox.cs 프로젝트: travip/Rally
 public void DisplayActionFromRoad(RoadSegment road)
 {
     if (!road.wasCorrect)
     {
         DisplayMissMessage();
     }
     StartCoroutine(DisplayAction(road));
 }
예제 #26
0
    public void EnteredNewRoad()
    {
        // Add a new road to the processing pipeline
        roadGenerator.GenerateNextRoad();
        RoadSegment newRoad = roadGenerator.currentRoads[RoadsAdded++].GetComponent <RoadSegment>();

        UnprossedRoads.Enqueue(newRoad);
    }
예제 #27
0
        /// <summary>
        /// Get the candidates of the i.
        /// get the candidate for the jucntion i.
        /// An Inter-path is a sequence of road intersections that connect the source to the destination, satisfying two key requirements, shorter routing distances, and higher connectivity. To meet these two requirements, we developed a heuristic function with two probability distributions, the connectivity distribution (denoted by ξ ̃_(i,j)) and the shortest distance distribution (denoted by〖 Φ ̃〗_(i,j)).
        /// </summary>
        /// <param name="_i"></param>
        /// <returns></returns>
        public CandidateJunction CandidateJunction(Junction _i, Junction _des)
        {
            List <CandidateJunction>    candidateJunctions = new List <Routing.CandidateJunction>();
            ShortestDistanceSelector    computer           = new ShortestDistanceSelector();
            SegmentConnectivitySelector connect            = new SegmentConnectivitySelector();

            // values:
            foreach (Junction _j in _i.Adjacentjunctions)
            {
                RoadSegment roadSegment = GetRoadSegment(_i, _j);
                if (roadSegment != null)
                {
                    CandidateJunction can = new Routing.CandidateJunction();
                    can.CurrentJunction     = _i;
                    can.NextJunction        = _j;
                    can.NextJunction        = _j; // CAN id.
                    can.DestinationJunction = _des;
                    can.NextRoadSegment     = roadSegment;

                    // values:
                    //1- shortes distance:
                    can.Perpendiculardistance = computer.Perpendiculardistance(_j.CenterLocation, _i.CenterLocation, _des.CenterLocation);

                    if (_des.JID == _j.JID)
                    {
                        can.AngleDotProdection = 1;
                    }
                    else
                    {
                        computer.AngleDotProdection(_i.CenterLocation, _j.CenterLocation, _des.CenterLocation);
                    }

                    can.Length = computer.Length(_i.CenterLocation, _j.CenterLocation);
                    //-2 connectivity.
                    can.Connectivity = connect.SegmentConnectivity(roadSegment.SegmentLength, roadSegment.VehiclesCount, roadSegment.VehicleInterArrivalMean, Settings.Default.CommunicationRange, roadSegment.LanesCount);


                    candidateJunctions.Add(can);
                }
            }

            // get the max priority.
            if (candidateJunctions.Count > 0)
            {
                CandidateJunction max = candidateJunctions[0];
                for (int j = 1; j < candidateJunctions.Count; j++)
                {
                    if (candidateJunctions[j].HeuristicFunction > max.HeuristicFunction)
                    {
                        max = candidateJunctions[j];
                    }
                }

                return(max);
            }

            return(null);
        }
예제 #28
0
    public void CreatePoints(Vector3 hitPosition)
    {
        if (transform.GetChild(0).childCount > 0)
        {
            if (transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0).childCount == 1)
            {
                if (globalSettings.roadCurved == true)
                {
                    // Create control point
                    Undo.RegisterCreatedObjectUndo(CreatePoint("Control Point", transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0), hitPosition), "Created point");
                }
                else
                {
                    // Create control and end points
                    Undo.RegisterCreatedObjectUndo(CreatePoint("Control Point", transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0), Misc.GetCenter(transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0).GetChild(0).position, hitPosition)), "Created point");
                    Undo.RegisterCreatedObjectUndo(CreatePoint("End Point", transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0), hitPosition), "Created point");
                    CreateMesh();
                }
            }
            else if (transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0).childCount == 2)
            {
                // Create end point
                Undo.RegisterCreatedObjectUndo(CreatePoint("End Point", transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0), hitPosition), "Created Point");
                CreateMesh();
            }
            else
            {
                RoadSegment segment = CreateSegment(transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0).GetChild(2).position);
                Undo.RegisterCreatedObjectUndo(segment.gameObject, "Create Point");
                Undo.RegisterCreatedObjectUndo(CreatePoint("Start Point", segment.transform.GetChild(0), segment.transform.position), "Created Point");

                if (globalSettings.roadCurved == true)
                {
                    Undo.RegisterCreatedObjectUndo(CreatePoint("Control Point", segment.transform.GetChild(0), hitPosition), "Created Point");
                }
                else
                {
                    segment.curved = false;
                    Undo.RegisterCreatedObjectUndo(CreatePoint("Control Point", transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0), Misc.GetCenter(transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0).GetChild(0).position, hitPosition)), "Created point");
                    Undo.RegisterCreatedObjectUndo(CreatePoint("End Point", transform.GetChild(0).GetChild(transform.GetChild(0).childCount - 1).GetChild(0), hitPosition), "Created point");
                    CreateMesh();
                }
            }
        }
        else
        {
            // Create first segment
            RoadSegment segment = CreateSegment(hitPosition);
            Undo.RegisterCreatedObjectUndo(segment.gameObject, "Create Point");
            Undo.RegisterCreatedObjectUndo(CreatePoint("Start Point", segment.transform.GetChild(0), hitPosition), "Created Point");

            if (globalSettings.roadCurved == false)
            {
                segment.curved = false;
            }
        }
    }
    public void Init(RoadSegment p, RoadSegmentValues vals, MeshCrossection shape, Material mat)
    {
        this.parentScript     = p;
        this.values           = vals;
        this.materialToAssign = mat;
        this.shape2D          = shape;

        GenerateMeshAndInit();
    }
예제 #30
0
        /// <summary>
        /// we have three lanes per segments. the index should be 1,2,3. ONLY.
        /// </summary>
        /// <param name="lindex"></param>
        public void ChangeLaneRandomly()
        {
            Dispatcher.Invoke((Action) delegate
            {
                int lanConut = CurrentLane.MyRoadSegment.LanesCount;
                if (lanConut > 2)
                {
                    RoadSegment rs  = CurrentLane.MyRoadSegment;
                    LaneUi prevLane = CurrentLane;
                    LaneUi newlane  = null;

                    if (prevLane.LaneDirection == Direction.N)
                    {
                        newlane = rs.Lanes[LaneIndex.RandomLaneIndex.North(rs.LanesCount)];

                        prevLane.LaneVehicleAndQueue.RemoveFromLane(this);
                        this.CurrentLane = newlane;
                        this.Margin      = new Thickness(newlane.MyCenterLeft, this.Margin.Top, 0, 0);
                        this.SetVehicleDirection(Direction.N);
                    }
                    else if (prevLane.LaneDirection == Direction.S)
                    {
                        newlane = rs.Lanes[LaneIndex.RandomLaneIndex.South(rs.LanesCount)];

                        prevLane.LaneVehicleAndQueue.RemoveFromLane(this);
                        this.CurrentLane = newlane;
                        this.Margin      = new Thickness(newlane.MyCenterLeft, this.Margin.Top, 0, 0);
                        this.SetVehicleDirection(Direction.S);
                    }

                    else if (prevLane.LaneDirection == Direction.E)
                    {
                        newlane = rs.Lanes[LaneIndex.RandomLaneIndex.East(rs.LanesCount)];

                        prevLane.LaneVehicleAndQueue.RemoveFromLane(this);
                        this.CurrentLane = newlane;
                        this.Margin      = new Thickness(this.Margin.Left, newlane.MyCenterTop, 0, 0);
                        this.SetVehicleDirection(Direction.E);
                    }

                    else if (prevLane.LaneDirection == Direction.W)
                    {
                        newlane = rs.Lanes[LaneIndex.RandomLaneIndex.West(rs.LanesCount)];

                        prevLane.LaneVehicleAndQueue.RemoveFromLane(this);
                        this.CurrentLane = newlane;
                        this.Margin      = new Thickness(this.Margin.Left, newlane.MyCenterTop, 0, 0);
                        this.SetVehicleDirection(Direction.W);
                    }

                    SetInstansSpeed(PublicParamerters.AccellerationType);

                    // display:
                    prevLane._MainWindow.Dispatcher.Invoke(new Action(() => prevLane.lbl_info.Text = prevLane.LaneVehicleAndQueue.CountInLane.ToString()), DispatcherPriority.Send);
                }
            });
        }
예제 #31
0
    RoadBuilder newBuilderFromSegment(RoadBuilder builder, RoadSegment theSeg)
    {
        GameObject theGamOb = Instantiate(builder.gameObject) as GameObject;

        theGamOb.GetComponent <RoadBuilder>().age            = 0;
        theGamOb.GetComponent <RoadBuilder>().currentSegment = theSeg;

        return(theGamOb.GetComponent <RoadBuilder>());
    }
예제 #32
0
    private bool MinPointDistance(RoadSegment a, RoadSegment b, float min)
    {
        if (Vector2.Distance (a.PointA.point, b.PointA.point) < min)
            return true;
        if (Vector2.Distance (a.PointA.point, b.PointB.point) < min)
            return true;
        if (Vector2.Distance (a.PointB.point, b.PointA.point) < min)
            return true;
        if (Vector2.Distance (a.PointB.point, b.PointB.point) < min)
            return true;

        return false;
    }
예제 #33
0
    /// <summary>
    /// starting city blueprint Y-type
    /// </summary>
    /// <param name="center"></param>
    /// <param name="angle"></param>
    public void AddCityCentreY(Vector2 center, float angle)
    {
        Quaternion rotation = Quaternion.Euler (0, 0, angle);

        RoadPoint a = new RoadPoint ();
        a.point = rotation * center;
        RoadPoint b = new RoadPoint ();
        b.point = rotation * (new Vector2 (this.scale, 0) + center);

        Quaternion localA = Quaternion.Euler (0, 0, 120f);
        RoadPoint c = new RoadPoint ();
        c.point = rotation * center;
        RoadPoint d = new RoadPoint ();
        d.point = localA * rotation * (new Vector2 (this.scale, 0) + center);

        Quaternion localB = Quaternion.Euler (0, 0, 240f);
        RoadPoint e = new RoadPoint ();
        e.point = rotation * center;
        RoadPoint f = new RoadPoint ();
        f.point = localB * rotation * (new Vector2 (this.scale, 0) + center);

        RoadSegment rA = new RoadSegment (a, b, 0);
        RoadSegment rB = new RoadSegment (c, d, 0);
        RoadSegment rC = new RoadSegment (e, f, 0);

        this.RoadSegments.AddRange (new RoadSegment[]{rA,rB,rC});

        Intersection iA = new Intersection (new List<RoadPoint> (){rA.PointA,rB.PointA,rC.PointA});
        this.RoadIntersections.Add (iA);
    }
예제 #34
0
        private static void PlacementSequential()
        {
            if (sequentialPlaceObject == null)
                return;

            SceneView.RepaintAll();

            if (firstSequentialObject == null)
            {
                // raycast to position/place object
                Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit))
                {
                    Vector3 point = hit.point;
                    point.y = gridHeight;

                    point.x = Mathf.RoundToInt((point.x / gridSteps)) * gridSteps;
                    point.z = Mathf.RoundToInt((point.z / gridSteps)) * gridSteps;

                    sequentialPlaceObject.transform.position = point;

                    bool cont = (Event.current.shift);

                    // place object
                    if (Event.current.type == EventType.mouseDown && Event.current.button == 0)
                    {
                        firstSequentialObject = Instantiate(sequentialPlaceObject) as GameObject;
                        currentSequentialSegment = firstSequentialObject.GetComponent<RoadSegment>();
                        Destroy(sequentialPlaceObject);
                    }
                }
            }
            else
            {
                if (Event.current.type == EventType.keyDown && Event.current.keyCode == KeyCode.KeypadPlus)
                {
                    sequentialIndex++;
                    if (sequentialIndex > currentSequentialSegment.connectors.Length - 1)
                        sequentialIndex = 0;
                }

                if (Event.current.type == EventType.keyDown && Event.current.keyCode == KeyCode.KeypadMinus)
                {
                    sequentialIndex--;
                    if (sequentialIndex < 0)
                        sequentialIndex = currentSequentialSegment.connectors.Length - 1;
                }

                sequentialPlaceObject.transform.position = currentSequentialSegment.connectors[sequentialIndex].transform.position;
                sequentialPlaceObject.transform.rotation = currentSequentialSegment.connectors[sequentialIndex].transform.rotation;

                if (Event.current.type == EventType.keyDown && Event.current.keyCode == KeyCode.Return)
                {
                    GameObject placedObject = Instantiate(sequentialPlaceObject) as GameObject;
                    currentSequentialSegment = placedObject.GetComponent<RoadSegment>();
                    Destroy(sequentialPlaceObject);
                    currentSequentialOffset = 0.0f;
                }
            }
        }
예제 #35
0
 // inSegment(): determine if a point is inside a segment
 //    Input:  a point P, and a collinear segment S
 //    Return: 1 = P is inside S
 //            0 = P is  not inside S
 int inSegment( RoadPoint P, RoadSegment S)
 {
     if (S.PointA.point.x != S.PointB.point.x) {    // S is not  vertical
         if (S.PointA.point.x <= P.point.x && P.point.x <= S.PointB.point.x)
             return 1;
         if (S.PointA.point.x >= P.point.x && P.point.x >= S.PointB.point.x)
             return 1;
     }
     else {    // S is vertical, so test y  coordinate
         if (S.PointA.point.y <= P.point.y && P.point.y <= S.PointB.point.y)
             return 1;
         if (S.PointA.point.y >= P.point.y && P.point.y >= S.PointB.point.y)
             return 1;
     }
     return 0;
 }
예제 #36
0
    /// <summary>
    /// http://geomalgorithms.com/a02-_lines.html#Distance-to-Ray-or-Segment
    /// </summary>
    /// <returns>Distance between segments.</returns>
    /// <param name="P">P.</param>
    /// <param name="S">S.</param>
    private float distPointSegment( RoadPoint P, RoadSegment S)
    {
        Vector2 v = S.PointB.point - S.PointA.point;
        Vector2 w = P.point - S.PointA.point;

        float c1 = Vector2.Dot(w,v);
        if ( c1 <= 0 )
            return Vector2.Distance(P.point, S.PointA.point);

        float c2 = Vector2.Dot(v,v);
        if ( c2 <= c1 )
            return Vector2.Distance(P.point, S.PointB.point);

        float b = c1 / c2;
        Vector2 Pb = S.PointA.point + (v * b);
        return Vector2.Distance(P.point, Pb);
    }
예제 #37
0
    private RoadSegment[] patchSegment(RoadSegment segment, RoadPoint newPoint)
    {
        this.RoadSegments.RemoveAll(p => p.IsEqual(segment));

        RoadSegment left = new RoadSegment (segment.PointA, new RoadPoint(newPoint.point), segment.Level);
        RoadSegment right = new RoadSegment (segment.PointB, new RoadPoint(newPoint.point), segment.Level);

        this.RoadSegments.Add (left);
        this.RoadSegments.Add (right);

        return new RoadSegment[] {left,right};
    }
예제 #38
0
    //http://geomalgorithms.com/a05-_intersect-1.html
    // intersect2D_2Segments(): find the 2D intersection of 2 finite segments
    //    Input:  two finite segments S1 and S2
    //    Output: *I0 = intersect point (when it exists)
    //            *I1 =  endpoint of intersect segment [I0,I1] (when it exists)
    //    Return: 0=disjoint (no intersect)
    //            1=intersect  in unique point I0
    //            2=overlap  in segment from I0 to I1
    int inter2Segments(RoadSegment S1, RoadSegment S2, out Vector2 I0, out Vector2 I1)
    {
        Vector2 u = S1.PointB.point - S1.PointA.point;
        Vector2 v = S2.PointB.point - S2.PointA.point;
        Vector2 w = S1.PointA.point - S2.PointA.point;
        float D = perp(u,v);

        I0 = Vector2.zero;
        I1 = Vector2.zero;

        // test if  they are parallel (includes either being a point)
        if (Mathf.Abs(D) < 0.01f) {           // S1 and S2 are parallel
            if (perp(u,w) != 0 || perp(v,w) != 0)  {
                return 0;                    // they are NOT collinear
            }
            // they are collinear or degenerate
            // check if they are degenerate  points
            float du = Vector2.Dot(u,u);
            float dv = Vector2.Dot(v,v);
            if (du==0 && dv==0) {            // both segments are points
                if (S1.PointA.point !=  S2.PointA.point)         // they are distinct  points
                    return 0;
                I0 = S1.PointA.point;                 // they are the same point
                return 1;
            }
            if (du==0) {                     // S1 is a single point
                if  (inSegment(S1.PointA, S2) == 0)  // but is not in S2
                    return 0;
                I0 = S1.PointA.point;
                return 1;
            }
            if (dv==0) {                     // S2 a single point
                if  (inSegment(S2.PointA, S1) == 0)  // but is not in S1
                    return 0;
                I0 = S2.PointA.point;
                return 1;
            }
            // they are collinear segments - get  overlap (or not)
            float t0, t1;                    // endpoints of S1 in eqn for S2
            Vector2 w2 = S1.PointB.point - S2.PointA.point;
            if (v.x != 0) {
                t0 = w.x / v.x;
                t1 = w2.x / v.x;
            }
            else {
                t0 = w.y / v.y;
                t1 = w2.y / v.y;
            }
            if (t0 > t1) {                   // must have t0 smaller than t1
                float t=t0; t0=t1; t1=t;    // swap if not
            }
            if (t0 > 1 || t1 < 0) {
                return 0;      // NO overlap
            }
            t0 = t0<0? 0 : t0;               // clip to min 0
            t1 = t1>1? 1 : t1;               // clip to max 1
            if (t0 == t1) {                  // intersect is a point
                I0 = S2.PointA.point +  t0 * v;
                return 1;
            }

            // they overlap in a valid subsegment
            I0 = S2.PointA.point + t0 * v;
            I1 = S2.PointA.point + t1 * v;
            return 2;
        }

        // the segments are skew and may intersect in a point
        // get the intersect parameter for S1
        float     sI = perp(v,w) / D;
        if (sI < 0 || sI > 1)                // no intersect with S1
            return 0;

        // get the intersect parameter for S2
        float     tI = perp(u,w) / D;
        if (tI < 0 || tI > 1)                // no intersect with S2
            return 0;

        I0 = S1.PointA.point + sI * u;                // compute S1 intersect point
        return 1;
    }
예제 #39
0
    private int segmentIntersection(RoadSegment segment, out Vector2 intersection, out RoadSegment other, RoadSegment skip)
    {
        intersection = Vector2.zero;
        other = null;

        Vector2 tmp = Vector2.zero;
        Vector2 interTmp = Vector3.zero;

        int count = 0;
        // foreach (RoadSegment seg in this.RoadSegments)
        for (int i=0; i<this.RoadSegments.Count; i++) {
            RoadSegment seg = this.RoadSegments[i];
            if (seg.IsEqual(skip))
                continue;
            else if (Vector2.Distance (seg.PointA.point, segment.PointA.point) < 0.01f || Vector2.Distance (seg.PointB.point, segment.PointB.point) < 0.01f)
                continue;
            else if (Vector2.Distance (seg.PointA.point, segment.PointB.point) < 0.01f || Vector2.Distance (seg.PointB.point, segment.PointA.point) < 0.01f)
                continue;
            else if (inter2Segments (segment, seg, out interTmp, out tmp) != 0) {
                other = seg;
                intersection = new Vector2(interTmp.x,interTmp.y);
                count++;
            }
        }

        return count;
    }
예제 #40
0
    /// <summary>
    /// evaluate segment for potential building placement
    /// </summary>
    /// <param name="segment"></param>
    private void checkSegment(RoadSegment segment)
    {
        Vector2 start = segment.PointA.point;
        Vector2 end = segment.PointB.point;
        Vector2 dir = (end - start).normalized;
        float distance = Vector2.Distance (start, end);

        Vector2 current = start;
        bool side = true;
        for(float f=RoadRenderer.RoadWidth;f<distance || side;f+=4.5f)
        {
            //switch side of the road
            if(f > distance && side)
            {
                side = false;
                f=RoadRenderer.RoadWidth;
            }

            Vector2 per = new Vector2(-dir.y, dir.x);
            if(side)
                per *=-1;

            //try to put some building into the spot
            for(int i=0;i<10;i++)
            {
                //get road level adjustment
                float level = 2.0f - (segment.Level / 3f);//0,0.33,0.66,1

                //get building dimensions
                float width = Random.Range(1.75f,2f) * level;
                float length = Random.Range(1.75f,2f) * level;
                float height = Random.Range(2.5f,10f) * level;

                //get building center
                Vector2 roadOffset = per.normalized * (RoadRenderer.RoadWidth * 1.25f + length);
                Vector2 tc = start + (dir * f) + roadOffset;

                if(f - width < 0 || f + width > distance)
                    continue;

                Vector3 center = new Vector3(tc.x,0,tc.y);

                //get building size
                Vector3 size = new Vector3(length,width,height);

                //set building
                GameObject buildingObj = GameObject.Instantiate(this.BuildingStatic);
                buildingObj.transform.parent = this.Instances.transform;
                buildingObj.transform.name = "building_" + this.BuildingsList.Count.ToString("D5");

                Building building = new Building(center,size,this.GetRotation(dir) - (side ? 180 : 0));
                building.AddMyGameObject(buildingObj);
                this.AddBuildingMesh(building);
                building.AddCollider();

                if(this.CheckValidPlacement(building))
                {
                    this.BuildingsList.Add(building);
                    break;
                }
                else
                    GameObject.DestroyImmediate(buildingObj);
            }
        }
    }
예제 #41
0
    private bool SegmentWithin(RoadSegment segment, float max)
    {
        foreach (RoadSegment seg in this.RoadSegments) {
            bool amax = distPointSegment (seg.PointA, segment) < max;
            bool bmax = distPointSegment (seg.PointB, segment) < max;

            bool amin = MinPointDistance(seg,segment,max / 1.0f);

            if(amax || bmax || amin)
                return true;
        }

        return false;
    }
예제 #42
0
    private void splitSegment(RoadSegment segment)
    {
        //get split ratio
        float splitDistance = Random.Range (0.33f, 0.66f);

        //get split distance
        Vector3 p1 = new Vector3 (segment.PointA.point.x, 0, segment.PointA.point.y);
        Vector3 p2 = new Vector3 (segment.PointB.point.x, 0, segment.PointB.point.y);
        float length = Vector3.Distance (p1, p2);
        length *= splitDistance;

        //get direction vector for segment
        Vector3 direction = (p1 - p2).normalized;

        //get new point and patch the segment
        Vector3 newPoint = p2 + (direction * length);

        //calaculate other new point
        Vector3 per = Vector3.Cross (p1 - p2, Vector3.down).normalized;// * (Random.Range (0f, 1f) < 0.5f ? -1 : 1);
        float newLength = this.scale / ((segment.Level + 1) * Random.Range(1f,2f));
        Vector3 newPointEnd = newPoint + (per * newLength);

        //add new segment
        RoadSegment newSegment = new RoadSegment (new RoadPoint(new Vector2 (newPoint.x, newPoint.z),null), new RoadPoint(new Vector2 (newPointEnd.x, newPointEnd.z),null), segment.Level + 1);

        //calaculate other new point
        Vector3 perA = Vector3.Cross (p1 - p2, Vector3.down).normalized * -1;
        Vector3 newPointEndOther = newPoint + (perA * newLength);
        RoadSegment newSegmentOther = new RoadSegment (new RoadPoint (new Vector2 (newPoint.x, newPoint.z), null), new RoadPoint (new Vector2 (newPointEndOther.x, newPointEndOther.z), null), segment.Level + 1);

        //check what segments to add and add them
        bool seg1 = false;
        bool seg2 = false;

        bool with1 = this.SegmentWithin (newSegment, CloseCutoff);
        bool with2 = this.SegmentWithin (newSegmentOther, CloseCutoff);

        if (!with1)
        {
            Vector2 intersection = Vector3.zero;
            RoadSegment other = null;

            int iCount = segmentIntersection(newSegment,out intersection,out other,segment);

            if(iCount <= 1)
            {
                this.RoadSegments.RemoveAll(p => p.IsEqual(newSegment));
                this.RoadSegments.Add (newSegment);
                seg1 = true;
            }

            if(iCount == 1)
            {
                RoadSegment[] segmentsA = this.patchSegment (other, new RoadPoint (intersection, other));
                RoadSegment[] segmentsB = this.patchSegment (newSegment, new RoadPoint (intersection, newSegment));

                //kill very short dead-ends
                bool sa = segmentsA[0].SegmentLength() > ShortCutoff;
                bool sb = segmentsA[1].SegmentLength() > ShortCutoff;
                bool sc = segmentsB[0].SegmentLength() > ShortCutoff;
                bool sd = segmentsB[1].SegmentLength() > ShortCutoff;

                List<RoadPoint> points = new List<RoadPoint>();
                if(sa)
                    points.Add(segmentsA [0].PointB);
                else
                    this.RoadSegments.RemoveAll(p => p.IsEqual(segmentsA[0]));

                if(sb)
                    points.Add(segmentsA [1].PointB);
                else
                    this.RoadSegments.RemoveAll(p => p.IsEqual(segmentsA[1]));

                if(sc)
                    points.Add(segmentsB [0].PointB);
                else
                    this.RoadSegments.RemoveAll(p => p.IsEqual(segmentsB[0]));

                if(sd)
                    points.Add(segmentsB [1].PointB);
                else
                    this.RoadSegments.RemoveAll(p => p.IsEqual(segmentsB[1]));

                Intersection inter = new Intersection (points);
                this.RoadIntersections.Add (inter);
            }
        }

        //other side of intersection
        if (!with2)
        {
            Vector2 intersection = Vector3.zero;
            RoadSegment other = null;

            int iCount = segmentIntersection(newSegmentOther,out intersection,out other,segment);

            if(iCount <= 1)
            {
                this.RoadSegments.RemoveAll(p => p.IsEqual(newSegmentOther));
                this.RoadSegments.Add (newSegmentOther);
                seg2 = true;
            }

            if(iCount == 1)
            {
                RoadSegment[] segmentsA = this.patchSegment (other, new RoadPoint (intersection, other));
                RoadSegment[] segmentsB = this.patchSegment (newSegmentOther, new RoadPoint (intersection, newSegmentOther));

                //kill very short dead-ends
                bool sa = segmentsA[0].SegmentLength() > ShortCutoff;
                bool sb = segmentsA[1].SegmentLength() > ShortCutoff;
                bool sc = segmentsB[0].SegmentLength() > ShortCutoff;
                bool sd = segmentsB[1].SegmentLength() > ShortCutoff;

                List<RoadPoint> points = new List<RoadPoint>();
                if(sa)
                    points.Add(segmentsA [0].PointB);
                else
                    this.RoadSegments.RemoveAll(p => p.IsEqual(segmentsA[0]));

                if(sb)
                    points.Add(segmentsA [1].PointB);
                else
                    this.RoadSegments.RemoveAll(p => p.IsEqual(segmentsA[1]));

                if(sc)
                    points.Add(segmentsB [0].PointB);
                else
                    this.RoadSegments.RemoveAll(p => p.IsEqual(segmentsB[0]));

                if(sd)
                    points.Add(segmentsB [1].PointB);
                else
                    this.RoadSegments.RemoveAll(p => p.IsEqual(segmentsB[1]));

                Intersection inter = new Intersection (points);
                this.RoadIntersections.Add (inter);
            }
        }

        if (seg1 || seg2) {
            RoadSegment[] segments = this.patchSegment (segment, new RoadPoint (new Vector2 (newPoint.x, newPoint.z), segment));

            if (seg1 && seg2) {
                Intersection inter = new Intersection (new List<RoadPoint>{segments [0].PointB,segments [1].PointB,newSegment.PointA,newSegmentOther.PointA});
                this.RoadIntersections.Add (inter);
            } else if (seg1) {
                Intersection inter = new Intersection (new List<RoadPoint>{segments [0].PointB,segments [1].PointB,newSegment.PointA});
                this.RoadIntersections.Add (inter);
            } else if (seg2) {
                Intersection inter = new Intersection (new List<RoadPoint>{segments [0].PointB,segments [1].PointB,newSegmentOther.PointA});
                this.RoadIntersections.Add (inter);
            }
        }
    }
예제 #43
0
 public RoadPoint(Vector2 point, RoadSegment segment = null)
 {
     this.point = new Vector2(point.x, point.y);
     this.mySegement = segment;
 }
예제 #44
0
    /// <summary>
    /// Determines whether this instance is equal the specified segment.
    /// </summary>
    /// <returns><c>true</c> if this instance is equal the specified segment; otherwise, <c>false</c>.</returns>
    /// <param name="segment">Segment.</param>
    public bool IsEqual(RoadSegment segment)
    {
        if (this.PointA.Equals(segment.PointA) && this.PointB.Equals(segment.PointB))
            return true;
        else if (this.PointA.Equals(segment.PointB) && this.PointB.Equals(segment.PointA))
            return true;

        return false;
    }
예제 #45
0
    /// <summary>
    /// Adds the city centre x.
    /// </summary>
    /// <param name="center">Center.</param>
    /// <param name="angle">Angle.</param>
    public void AddCityCentreX(Vector2 center, float angle)
    {
        Quaternion rotation = Quaternion.Euler (0, 0, angle);

        RoadPoint a = new RoadPoint ();
        a.point = rotation * center;
        RoadPoint b = new RoadPoint ();
        b.point = rotation * (new Vector2 (this.scale, 0) + center);

        RoadPoint c = new RoadPoint ();
        c.point = rotation * center;
        RoadPoint d = new RoadPoint ();
        d.point = rotation * (new Vector2 (0, this.scale) + center);

        RoadPoint e = new RoadPoint ();
        e.point = rotation * center;
        RoadPoint f = new RoadPoint ();
        f.point = rotation * (new Vector2 (-this.scale, 0) + center);

        RoadPoint g = new RoadPoint ();
        g.point = rotation * center;
        RoadPoint h = new RoadPoint ();
        h.point = rotation * (new Vector2 (0, -this.scale) + center);

        RoadSegment rA = new RoadSegment (a, b, 0);
        RoadSegment rB = new RoadSegment (c, d, 0);
        RoadSegment rC = new RoadSegment (e, f, 0);
        RoadSegment rD = new RoadSegment (g, h, 0);

        this.RoadSegments.AddRange (new RoadSegment[]{rA,rB,rC,rD});

        Intersection iA = new Intersection (new List<RoadPoint> (){rA.PointA,rB.PointA,rC.PointA,rD.PointA});
        this.RoadIntersections.Add (iA);
    }