Exemplo n.º 1
0
        /// <summary>
        /// 删除路段
        /// </summary>
        /// <param name="sectionId">路段编号</param>
        /// <param name="userName">用户名</param>
        /// <returns>删除结果</returns>
        public IStatusCodeActionResult Remove(int sectionId, string userName = null)
        {
            RoadSection roadSection = _context.RoadSections.SingleOrDefault(d => d.SectionId == sectionId);

            if (roadSection == null)
            {
                return(new NotFoundResult());
            }
            try
            {
                _context.RoadSections.Remove(roadSection);
                _context.SaveChanges();
                _logger.LogInformation(new EventId((int)LogEvent.编辑路段, userName), $"删除路段 {roadSection}");
                return(new OkResult());
            }
            catch (DbUpdateException)
            {
                if (_context.Channels.Count(c => c.SectionId == sectionId) > 0)
                {
                    ModelStateDictionary modelState = new ModelStateDictionary();
                    modelState.AddModelError("Channel", "存在关联的通道");
                    return(new BadRequestObjectResult(modelState));
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 2
0
 /// <summary>
 /// 添加路段
 /// </summary>
 /// <param name="roadSection">路段</param>
 /// <param name="userName">用户名</param>
 /// <returns>添加结果</returns>
 public ObjectResult Add([FromBody] RoadSection roadSection, string userName = null)
 {
     _context.RoadSections.Add(roadSection);
     _context.SaveChanges();
     _logger.LogInformation(new EventId((int)LogEvent.编辑路段, userName), $"添加路段 {roadSection}");
     return(new OkObjectResult(roadSection));
 }
Exemplo n.º 3
0
        // TODO: make this one mesh, not a bunch of line renderers
        private void GenerateRoadLine(RoadSection newSection)
        {
            IEnumerable <RoadSection> sections = _roadNetwork.Sections;

            while (_roadLines.Count != sections.Count())
            {
                if (sections.Count() > _roadLines.Count)
                {
                    _roadLines.Add(Instantiate(roadLinePrefab, roadLinesParent.transform));
                }
                else if (sections.Count() < _roadLines.Count)
                {
                    _roadLines.Remove(_roadLines.Last());
                }
            }

            int i = 0;

            foreach (RoadSection section in sections)
            {
                LineRenderer lineRenderer = _roadLines[i].GetComponent <LineRenderer>();

                Vector3[] linePositions = { section.Source.Position, section.Target.Position };

                linePositions[0].y += 0.2f;
                linePositions[1].y += 0.2f;

                lineRenderer.SetPositions(linePositions);

                i++;
            }
        }
Exemplo n.º 4
0
        public VisualStairsSection(VisualNode first, VisualNode last, RoadSection section, VisualFloor floor) : base(first, last, section, floor)
        {
            normalPen.Brush     = Brushes.RosyBrown;
            normalPen.Thickness = Thickness;

            selectPen.Brush     = Brushes.Yellow;
            selectPen.Thickness = Thickness + 20;
        }
Exemplo n.º 5
0
 public void Render(RoadSection roadSection)
 {
     transform.position = new Vector3(RoadSectionWidth * roadSection.sectionIndex, RoadSectionYAxisPos);
     for (int i = 1; i <= 16; i++)
     {
         spriteShapeController.spline.SetPosition(i, roadSection.shapePoints[i - 1]);
     }
     RoadSectionIndex = roadSection.sectionIndex;
 }
Exemplo n.º 6
0
 /// <summary>
 /// 填充路段缓存
 /// </summary>
 /// <param name="memoryCache">缓存</param>
 /// <param name="section">路段</param>
 /// <returns>路段</returns>
 public static RoadSection FillSection(this IMemoryCache memoryCache, RoadSection section)
 {
     if (section != null)
     {
         section.SectionType_Desc = memoryCache.GetCode(typeof(SectionType), section.SectionType);
         section.Direction_Desc   = memoryCache.GetCode(typeof(SectionDirection), section.Direction);
     }
     return(section);
 }
Exemplo n.º 7
0
        private void DeleteSectionObject(RoadSection section)
        {
            GameObject sectionToBeDeleted = _sectionObjects.Find(sectionObject => sectionObject.GetComponentInChildren <RoadSectionComponent>().RoadSection.ID == section.ID);

            if (sectionToBeDeleted)
            {
                _sectionObjects.Remove(sectionToBeDeleted);
                Destroy(sectionToBeDeleted);
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// 填充路段流量缓存
 /// </summary>
 /// <param name="memoryCache">缓存</param>
 /// <param name="sectionFlow">车道流量</param>
 /// <returns>路段流量</returns>
 public static SectionFlow FillSectionFlowCache(this IMemoryCache memoryCache, SectionFlow sectionFlow)
 {
     if (sectionFlow != null)
     {
         RoadSection section = memoryCache.GetSection(sectionFlow.SectionId);
         if (section != null)
         {
             sectionFlow.SectionName = section.SectionName;
         }
     }
     return(sectionFlow);
 }
Exemplo n.º 9
0
    public void SpawnRoadSection(RoadSection notifierSection)
    {
        //Esta función instancia las secciones del camino según la posición de la sección que llamó a la función.

        int randomRoad = Random.Range(0, RoadSections.Count); //Escoge una sección al azar de la lista de posibles secciones.

        GameObject newRoad = Instantiate(RoadSections[randomRoad], notifierSection.transform.position + new Vector3(0, 0, 220), Quaternion.identity);

        newRoad.transform.parent = notifierSection.transform.parent; //Luego de instanciar la sección, le asigna como parent el objeto Road que contiene todas las secciones.
        newRoad.GetComponent <RoadSection>().SpawnEnemigos();        //Instancia los enemigos de la sección creada.
        newRoad.GetComponent <RoadSection>().SpawnCollectibles();    //Instancia los objetos de la sección creada.
    }
        private static void LebelingMillingQuantity(RoadSection theRoadSection, Transaction acTrans, BlockTableRecord acBlkTblRec, Database acCurDb,
                                                    double deltaRefTextX  = 0, double deltaRefTextY = 0.5, double deltaRefXForEachQuant = 0.18, double deltaRefYForEachQuant = 0, double textRotation = 1.57, double textHight = 0.18,
                                                    bool isForProfileView = false)
        {
            //double deltaRefTextX = 0;
            //double deltaRefTextY = 0.5;
            //double deltaRefXForEachQuant = 0.18;

            // Open the Block table for read
            BlockTable acBlkTbl;

            acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                         OpenMode.ForRead) as BlockTable;

            // Open the Block table record Model space for write
            acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                            OpenMode.ForWrite) as BlockTableRecord;

            foreach (var section in theRoadSection.CrossSections)
            {
                int quantCounter = 0;

                if (section.MillingElements.Count > 0)
                {
                    foreach (var quant in section.MillingQuantity)
                    {
                        // set necessary layer
                        MillingDataEngine.Func.Layers.SetAsCurrent(quant.LayerName, acCurDb);

                        // Create a single-line text object for quant
                        DBText acText = new DBText();
                        acText.SetDatabaseDefaults();
                        acText.Position = new Point3d(section.MillingElements[0].StartPoint.CoordinateX + deltaRefTextX - quantCounter * deltaRefXForEachQuant + (isForProfileView ? section.Width : 0),
                                                      section.MillingElements[0].StartPoint.CoordinateY + quantCounter * deltaRefYForEachQuant +
                                                      deltaRefTextY, section.MillingElements[0].StartPoint.CoordinateZ);
                        acText.Height = textHight;

                        string stringToPut = (quant.Range[1]) > 0 ?
                                             String.Format("tr{0}_{1}={2:0.00}m", quant.Range[0], quant.Range[1], quant.Quant) :
                                             String.Format("str{0}_={1:0.00}m", quant.Range[0], quant.Quant);;

                        acText.TextString = stringToPut;
                        acText.Rotation   = textRotation;
                        acBlkTblRec.AppendEntity(acText);
                        acTrans.AddNewlyCreatedDBObject(acText, true);
                        quantCounter++;
                    }
                    quantCounter = 0;
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 查询路段
        /// </summary>
        /// <param name="sectionId">路段编号</param>
        /// <returns>查询结果</returns>
        public IStatusCodeActionResult Get(int sectionId)
        {
            RoadSection roadSection = _context.RoadSections.SingleOrDefault(c => c.SectionId == sectionId);

            if (roadSection == null)
            {
                return(new NotFoundObjectResult(null));
            }
            else
            {
                _memoryCache.FillSection(roadSection);
                return(new OkObjectResult(roadSection));
            }
        }
Exemplo n.º 12
0
    public void Initialise(GameObject _trafficLight)
    {
        trafficLights = new List <TrafficLight>();

        roadSection = GetComponent <RoadSection>();

        SetupIntersection(_trafficLight);

        currentLight = 0;

        signalState = SignalState.Alternate;

        delayTime   = delayTimeAlternate;
        sectionTime = sectionTimeAlternate;
    }
Exemplo n.º 13
0
        /// <summary>
        /// 更新路段
        /// </summary>
        /// <param name="updateRoadSection">路段</param>
        /// <param name="userName">用户名</param>
        /// <returns>更新结果</returns>
        public IStatusCodeActionResult Update([FromBody] RoadSection updateRoadSection, string userName = null)
        {
            RoadSection roadSection = _context.RoadSections.SingleOrDefault(d => d.SectionId == updateRoadSection.SectionId);

            if (roadSection == null)
            {
                return(new NotFoundResult());
            }
            roadSection.SectionName = updateRoadSection.SectionName;
            roadSection.SectionType = updateRoadSection.SectionType;
            roadSection.Length      = updateRoadSection.Length;
            roadSection.Direction   = updateRoadSection.Direction;
            roadSection.SpeedLimit  = updateRoadSection.SpeedLimit;
            _context.SaveChanges();
            _logger.LogInformation(new EventId((int)LogEvent.编辑路段, userName), $"更新路段 {roadSection}");
            return(new OkResult());
        }
Exemplo n.º 14
0
        public VisualRoadSection(VisualNode first, VisualNode last, RoadSection section, VisualFloor floor) : base(section, floor)
        {
            this.First = first;
            this.Last  = last;

            First.OutgoingSections.Add(this);
            Last.IncomingSections.Add(this);

            First.PositionChanged += NodePositionChanged;
            Last.PositionChanged  += NodePositionChanged;

            normalPen.Brush     = Brushes.Green;
            normalPen.Thickness = Thickness;

            selectPen.Brush     = Brushes.Yellow;
            selectPen.Thickness = Thickness + 20;

            ApplyScale(ParentFloor.Model.Scale);
            Draw();
        }
Exemplo n.º 15
0
        private void CreatingSection(Point position)
        {
            var        entity = CurrentFloor.GetVisualEntity(position);
            VisualNode node   = null;

            if (entity is VisualNode)
            {
                node = entity as VisualNode;
            }
            else
            {
                switch (SelectedActionMode)
                {
                case ActionMode.AddStairs:
                    node = new VisualStairsNode(new StairsNode(CurrentFloor.Model, position), CurrentFloor); break;

                case ActionMode.AddRoad:
                    node = new VisualNode(new RoadNode(CurrentFloor.Model, position), CurrentFloor); break;
                }
                AddVisualEntity(node);
            }

            if (IsCreatingLine)
            {
                if (!node.NodeModel.IncomingSectionsAllowed)
                {
                    return;
                }
                if (CreatingLineInf.FirstUnit == node || !(CreatingLineInf.FirstUnit is VisualNode))
                {
                    return;
                }

                VisualRoadSection section = null;
                Section           model   = null;
                switch (SelectedActionMode)
                {
                case ActionMode.AddStairs:
                    model = new StairsSection(CreatingLineInf.FirstNode.NodeModel, node.NodeModel, CurrentFloor.Model); break;

                case ActionMode.AddRoad:
                    model = new RoadSection(CreatingLineInf.FirstNode.NodeModel, node.NodeModel, CurrentFloor.Model); break;
                }

                // по каким-то причинам (образовывается петля) нет возможности добавить данный участок
                if (!CurrentFloor.Model.CanAddSection(model))
                {
                    return;
                }

                switch (SelectedActionMode)
                {
                case ActionMode.AddStairs:
                    section = new VisualStairsSection(CreatingLineInf.FirstNode, node, model as StairsSection, CurrentFloor); break;

                case ActionMode.AddRoad:
                    section = new VisualRoadSection(CreatingLineInf.FirstNode, node, model as RoadSection, CurrentFloor); break;
                }

                AddVisualEntity(section);
            }

            CreatingLineInf = new CreatingLineInformation(node);

            if (!CreatingLineInf.FirstNode.NodeModel.OutgoingSectionsAllowed)
            {
                IsCreatingLine = false;
            }
        }
Exemplo n.º 16
0
 public IActionResult Update([FromBody] RoadSection roadSection)
 {
     return(_manager.Update(roadSection, User?.Identity?.Name));
 }
Exemplo n.º 17
0
        public static List <FlowDevice> CreateFlowDevice(IServiceProvider serviceProvider, int deviceCount, int channelCount, int laneCount, bool initDatabase = false, string ip1 = "127.0.0.", int ip2 = 1, int id = 100)
        {
            List <FlowDevice> devices = new List <FlowDevice>();

            using (FlowContext context = serviceProvider.CreateScope().ServiceProvider.GetRequiredService <FlowContext>())
            {
                if (initDatabase)
                {
                    ResetDatabase(serviceProvider);
                }

                for (int i = 0; i < deviceCount; ++i)
                {
                    FlowDevice device = new FlowDevice
                    {
                        DeviceId                = id,
                        DeviceName              = $"流量测试设备_{id}",
                        DeviceModel             = (int)DeviceModel.MO_AF_A11_04_4X,
                        Ip                      = $"{ip1}{ip2++}",
                        Port                    = 17000,
                        FlowDevice_FlowChannels = new List <FlowDevice_FlowChannel>()
                    };
                    for (int j = 0; j < channelCount; ++j)
                    {
                        RoadCrossing roadCrossing = new RoadCrossing
                        {
                            CrossingId   = id,
                            CrossingName = $"流量测试路口_{id}"
                        };
                        RoadSection roadSection = new RoadSection
                        {
                            SectionId   = id,
                            SectionName = $"流量测试通路段_{id}",
                            SectionType = (int)SectionType.主干路,
                            SpeedLimit  = 10,
                            Length      = 10,
                            Direction   = (int)LaneDirection.由东向西
                        };
                        FlowChannel channel = new FlowChannel
                        {
                            ChannelId    = $"channel_{id}",
                            ChannelName  = $"流量测试通道_{id}",
                            ChannelIndex = j + 1,
                            CrossingId   = id,
                            SectionId    = id,
                            ChannelType  = (int)ChannelType.GB28181,
                            Lanes        = new List <Lane>(),
                            RoadCrossing = roadCrossing,
                            RoadSection  = roadSection
                        };

                        FlowDevice_FlowChannel relation = new FlowDevice_FlowChannel
                        {
                            DeviceId  = id,
                            ChannelId = channel.ChannelId,
                            Channel   = channel
                        };
                        id++;
                        device.FlowDevice_FlowChannels.Add(relation);
                        for (int k = 0; k < laneCount; ++k)
                        {
                            LaneDirection direction;
                            if (k >= 0 && k < 3)
                            {
                                direction = LaneDirection.由南向北;
                            }
                            else if (k >= 3 && k < 6)
                            {
                                direction = LaneDirection.由北向南;
                            }
                            else if (k >= 6 && k < 9)
                            {
                                direction = LaneDirection.由东向西;
                            }
                            else
                            {
                                direction = LaneDirection.由西向东;
                            }

                            FlowDirection flowDirection;
                            if (k % 3 == 0)
                            {
                                flowDirection = FlowDirection.直行;
                            }
                            else if (k % 3 == 1)
                            {
                                flowDirection = FlowDirection.左转;
                            }
                            else
                            {
                                flowDirection = FlowDirection.右转;
                            }
                            channel.Lanes.Add(new Lane
                            {
                                ChannelId     = channel.ChannelId,
                                LaneId        = $"{k + 1:D2}",
                                LaneName      = $"流量测试车道_{k + 1:D2}",
                                Channel       = channel,
                                Direction     = (int)direction,
                                FlowDirection = (int)flowDirection,
                                LaneIndex     = k + 1,
                                Region        = "[]",
                                Length        = 10
                            });
                        }
                    }
                    context.Devices.Add(device);
                    devices.Add(device);
                    context.SaveChanges();
                }
            }
            return(devices);
        }
Exemplo n.º 18
0
    private void AssignType(RoadSection _section)
    {
        List <RoadSection> neighbours = new List <RoadSection>();

        Vector3 roadPos = _section.transform.position;
        int     index   = 0;

        bool up    = false;
        bool down  = false;
        bool left  = false;
        bool right = false;



        if (roadPos.z + roadSize <= cityLength)
        {
            //Check Up
            if (roadMap[(int)roadPos.z + roadSize, (int)roadPos.x] != null)
            {
                neighbours.Add(roadMap[(int)roadPos.z + roadSize, (int)roadPos.x]);
                up     = true;
                index += 1;
            }
        }

        if (roadPos.z - roadSize >= 0)
        {
            //Check Down
            if (roadMap[(int)roadPos.z - roadSize, (int)roadPos.x] != null)
            {
                neighbours.Add(roadMap[(int)roadPos.z - roadSize, (int)roadPos.x]);
                down   = true;
                index += 8;
            }
        }

        if (roadPos.x - roadSize >= 0)
        {
            //Check Left
            if (roadMap[(int)roadPos.z, (int)roadPos.x - roadSize] != null)
            {
                neighbours.Add(roadMap[(int)roadPos.z, (int)roadPos.x - roadSize]);
                left   = true;
                index += 2;
            }
        }


        if (roadPos.x + roadSize <= cityWidth)
        {
            //Check Right
            if (roadMap[(int)roadPos.z, (int)roadPos.x + roadSize] != null)
            {
                neighbours.Add(roadMap[(int)roadPos.z, (int)roadPos.x + roadSize]);
                right  = true;
                index += 4;
            }
        }

        _section.SetIndex(index);

        _section.GetComponent <MeshFilter>().mesh = roadMeshPrefabs[GetLookupValue(index)];

        Material[] _sectionMats = new Material[2];

        // 3DS Max flips the Mats after Index_7? so a quick fix
        if (index <= 7)
        {
            _sectionMats[0] = roadMaterials[0];
            _sectionMats[1] = roadMaterials[1];
        }

        else
        {
            _sectionMats[0] = roadMaterials[1];
            _sectionMats[1] = roadMaterials[0];
        }

        _section.GetComponent <Renderer>().sharedMaterials = _sectionMats;

        _section.gameObject.AddComponent <MeshCollider>();

        // Compensate for 3Ds Max's Rotations
        _section.transform.rotation = Quaternion.Euler(-90.0f, 180.0f, 0.0f);

        _section.transform.parent = roadContainer.transform;

        _section.SetNeighbours(neighbours);


        if (_section.Index() == 6 || _section.Index() == 9)
        {
            _section.GetComponent <RoadSection>().SetWaypoints();
        }

        else if (_section.GetNeighbours().Count > 2)
        {
            _section.gameObject.AddComponent <Intersection>();
            _section.GetComponent <Intersection>().Initialise(TrafficLightPrefab);
        }
    }
Exemplo n.º 19
0
        protected override void OnUpdate()
        {
            Entities.ForEach((Path path) =>
            {
                var entity = GetPrimaryEntity(path);

                int numPathNodes = path.GetNumNodes();
                PathMap.Add(path.GetInstanceID(), RIndex);

                RoadSettings roadSettings = path.gameObject.GetComponentInParent <RoadSettings>();

                uint spawnPool = 0;
                if (roadSettings != null)
                {
                    spawnPool = roadSettings.vehicleSelection;
                }

                for (int n = 1; n < numPathNodes; n++)
                {
                    var rs = new RoadSection();

                    path.GetSplineSection(n - 1, out rs.p0, out rs.p1, out rs.p2, out rs.p3);
                    rs.arcLength = CatmullRom.ComputeArcLength(rs.p0, rs.p1, rs.p2, rs.p3, 1024);

                    rs.vehicleHalfLen  = Constants.VehicleLength / rs.arcLength;
                    rs.vehicleHalfLen /= 2;

                    rs.sortIndex = RIndex;
                    rs.linkNext  = RIndex + 1;
                    if (n == numPathNodes - 1)
                    {
                        rs.linkNext = -1;
                        MergeMap[math.round((path.GetReversibleRawPosition(n) + new float3(path.transform.position)) * Constants.NodePositionRounding) / Constants.NodePositionRounding] = RIndex;
                    }

                    rs.linkExtraChance = 0.0f;
                    rs.linkExtra       = -1;

                    rs.width  = path.width;
                    rs.height = path.height;

                    rs.minSpeed = path.minSpeed;
                    rs.maxSpeed = path.maxSpeed;

                    rs.occupationLimit = math.min(Constants.RoadOccupationSlotsMax, (int)math.round(rs.arcLength / Constants.VehicleLength));

                    var sectionEnt = CreateAdditionalEntity(path);

                    IdxMap[RIndex] = sectionEnt;

                    if (!path.isOnRamp)
                    {
                        RampMap[math.round((path.GetReversibleRawPosition(n - 1) + new float3(path.transform.position)) * Constants.NodePositionRounding) / Constants.NodePositionRounding] = RIndex;
                        if (n == 1)
                        {
                            int x          = 2; // Only spawn in right lane
                            float t        = rs.vehicleHalfLen;
                            float pathTime = (n - 1) + t;

                            var spawner  = new Spawner();
                            spawner.Time = math.frac(pathTime);

                            spawner.Direction = math.normalize(path.GetTangent(pathTime));

                            float3 rightPos  = (x - 1) * math.mul(spawner.Direction, Vector3.right) * ((rs.width - Constants.VehicleWidth) / 2.0f);
                            spawner.Position = path.GetWorldPosition(pathTime) + rightPos;

                            spawner.RoadIndex = RIndex;

                            spawner.minSpeed = path.minSpeed;
                            spawner.maxSpeed = path.maxSpeed;

                            var speedInverse = 1.0f / spawner.minSpeed;

                            spawner.random     = new Unity.Mathematics.Random((uint)RIndex + 1);
                            spawner.delaySpawn = (int)Constants.VehicleLength + spawner.random.NextInt((int)(speedInverse * 60.0f),
                                                                                                       (int)(speedInverse * 120.0f));

                            spawner.LaneIndex = x;
                            spawner.poolSpawn = spawnPool;

                            // Each path will only have one spawner, so use the Primary Entity
                            DstEntityManager.AddComponentData(entity, spawner);
                        }
                    }

                    RIndex++;
                    DstEntityManager.AddComponentData(sectionEnt, rs);
                }
            });

            // Loop over the paths again to start building the ramps and merges
            Entities.ForEach((Path path) =>
            {
                int numPathNodes = path.GetNumNodes();

                // Handle On Ramp roads
                if (path.isOnRamp)
                {
                    int rsRampIdx    = PathMap[path.GetInstanceID()];
                    float3 rampEntry = math.round((path.GetReversibleRawPosition(0) + new float3(path.transform.position)) * Constants.NodePositionRounding) / Constants.NodePositionRounding;
                    if (RampMap.ContainsKey(rampEntry))
                    {
                        int rsIndex = RampMap[rampEntry];
                        if (rsIndex > 0)
                        {
                            rsIndex -= 1;
                            if (IdxMap.ContainsKey(rsIndex))
                            {
                                Entity ramp    = IdxMap[rsIndex];
                                RoadSection rs = DstEntityManager.GetComponentData <RoadSection>(ramp);
                                if (rs.linkNext == rsIndex + 1)
                                {
                                    rs.linkExtra       = rsRampIdx;
                                    rs.linkExtraChance = path.percentageChanceForOnRamp / 100.0f;
                                    DstEntityManager.SetComponentData(ramp, rs);
                                }
                            }
                        }
                    }
                }

                // Handle merging roads
                {
                    int n = 0;

                    float3 pos =
                        math.round((path.GetReversibleRawPosition(n) + new float3(path.transform.position)) *
                                   Constants.NodePositionRounding) / Constants.NodePositionRounding;
                    if (MergeMap.ContainsKey(pos))
                    {
                        int mergeFromIndex = MergeMap[pos];
                        int mergeToBase    = PathMap[path.GetInstanceID()];

                        if (mergeFromIndex > 0 && mergeFromIndex != mergeToBase + n)
                        {
                            Entity merge   = IdxMap[mergeFromIndex];
                            RoadSection rs = DstEntityManager.GetComponentData <RoadSection>(merge);
                            if (rs.linkNext == -1)
                            {
                                rs.linkNext = mergeToBase + n;
                                DstEntityManager.SetComponentData(merge, rs);
                            }
                        }
                    }
                }
            });

            RIndex = 0;
            PathMap.Clear();
            RampMap.Clear();
            MergeMap.Clear();
            IdxMap.Clear();
        }
Exemplo n.º 20
0
        private void CreateSectionObject(RoadSection section)
        {
            GameObject sectionObjectParent = new GameObject("RoadSectionContainer");

            sectionObjectParent.transform.SetParent(roadSectionObjectsParent.transform);

            GameObject sectionObject;

            if (section.RoadType == RoadType.Crawler)
            {
                sectionObject = Instantiate(crawlerRoadSectionObjectPrefab, sectionObjectParent.transform);
            }
            else
            {
                sectionObject = Instantiate(trafficRoadSectionObjectPrefab, sectionObjectParent.transform);
            }

            sectionObject.GetComponent <RoadSectionComponent>().RoadSection = section;

            Vector3 roadVector = section.Target.Position - section.Source.Position;

            // POSITION section half way between its intersections
            sectionObject.transform.position = (roadVector / 2) + section.Source.Position;

            // ROTATION
            Vector2 roadVector2D = new Vector2(roadVector.x, roadVector.z);
            float   roadAngle    = Vector2.SignedAngle(roadVector2D, Vector2.up);
            Vector3 roadRotation = new Vector3(0, roadAngle, 0);

            sectionObject.transform.rotation = Quaternion.Euler(roadRotation);

            // SCALE in z direction by the road length and by the road width in the x direction
            Vector3 sectionScale = sectionObject.transform.localScale;

            sectionScale.z = roadVector.magnitude;

            float roadWidth = section.RoadType == RoadType.Crawler ? crawlerRoadWidth : trafficRoadWidth;

            sectionScale.x = roadWidth;

            sectionObject.transform.localScale = sectionScale;

            // Point count
            float availableLength = roadVector.magnitude - crawlerRoadWidth;
            int   pointCount      = Mathf.FloorToInt(availableLength / roadPointObjectMinSize);

            float stretchedPointSize = availableLength / pointCount;

            // Generate points
            for (int i = 0; i < pointCount; i++)
            {
                // POSITION
                float   horizontalOffset = roadVector.magnitude - ((crawlerRoadWidth / 2) + (stretchedPointSize / 2) + (stretchedPointSize * i));
                Vector3 offsetPosition   = roadVector.normalized * horizontalOffset;
                Vector3 pointPosition    = offsetPosition + section.Source.Position;

                GameObject pointObject = Instantiate(roadPointObjectPrefab, sectionObjectParent.transform);
                RoadPoint  point       = new RoadPoint(section.ID, pointPosition);
                // Store point in pointObject
                pointObject.GetComponent <RoadPointComponent>().RoadPoint = point;

                // Bump y position of pointObject slightly above the point position to avoid z-fighting
                pointPosition.y += 0.05f;
                pointObject.transform.position = pointPosition;

                // ROTATION
                pointObject.transform.localRotation = Quaternion.Euler(roadRotation);

                // SCALE collider in z direction to match stretchedPointSize and by the road width in the x direction
                // TODO: this is not at all safe
                Transform colliderTransform = pointObject.transform.GetComponentInChildren <Collider>().gameObject.transform;
                Vector3   colliderScale     = colliderTransform.localScale;
                colliderScale.z = stretchedPointSize;
                colliderScale.x = roadWidth * 1.5f;
                colliderTransform.localScale = colliderScale;
            }

            _sectionObjects.Add(sectionObjectParent);
        }
Exemplo n.º 21
0
        public Building Load(string filename)
        {
            var formatter = new BinaryFormatter();
            var files     = new List <SavedFile>();

            using (var fs = new FileStream(filename, FileMode.OpenOrCreate))
            {
                files = (List <SavedFile>)formatter.Deserialize(fs);
            }

            Type t = typeof(Building);

            var sBuilding = (BuildingSavedFile)files.FirstOrDefault(x => x.FileType == typeof(Building));

            if (sBuilding == null)
            {
                return(null);
            }

            Building building   = new Building(sBuilding.Title);
            var      dictionary = new Dictionary <int, dynamic>();

            foreach (var file in files.Where(x => x.FileType == typeof(ZoomTool)))
            {
                var sScale = file as ZoomToolSavedFile;
                dictionary.Add(sScale.HashCode, new ZoomTool(sScale.ActualLength, sScale.GraphicLength));
            }


            foreach (var file in files.Where(x => x.FileType == typeof(Floor)))
            {
                var sFloor = file as FloorSavedFile;
                var floor  = new Floor(sFloor.Title, building)
                {
                    Scale          = dictionary[sFloor.Scale],
                    FloorPlanImage = SettingsManager.GetBitmapImage(sFloor.FloorPlanImage)
                };
                dictionary.Add(sFloor.HashCode, floor);
                building.AddFloor(floor);
            }



            foreach (var file in files)
            {
                if (file is StartNodeSavedFile)
                {
                    var   sNode = file as StartNodeSavedFile;
                    Floor floor = dictionary[sNode.ParentHashCode];

                    var node = new StartNode(floor, sNode.Position, sNode.Title)
                    {
                        PeopleCount    = sNode.PeopleCount,
                        ProjectionArea = sNode.ProjectionArea,
                        AutoSize       = sNode.AutoSize
                    };
                    dictionary.Add(sNode.HashCode, node);
                    floor.AddObject(node);
                    continue;
                }
                if (file is EntryNodeSavedFile)
                {
                    var   sNode = file as EntryNodeSavedFile;
                    Floor floor = dictionary[sNode.ParentHashCode];

                    var node = new EntryNode(floor, sNode.Position, sNode.Title)
                    {
                        AutoSize = sNode.AutoSize,
                        Width    = sNode.Width
                    };
                    dictionary.Add(sNode.HashCode, node);
                    floor.AddObject(node);
                    continue;
                }

                if (file is StairsNodeSavedFile)
                {
                    var   sNode = file as StairsNodeSavedFile;
                    Floor floor = dictionary[sNode.ParentHashCode];

                    var node = new StairsNode(floor, sNode.Position, sNode.Title)
                    {
                        AutoSize          = sNode.AutoSize,
                        IsFloorsConnected = sNode.IsFloorsConnected
                    };
                    dictionary.Add(sNode.HashCode, node);
                    floor.AddObject(node);
                    continue;
                }

                if (file is NodeSavedFile)
                {
                    var   sNode = file as NodeSavedFile;
                    Floor floor = dictionary[sNode.ParentHashCode];
                    Node  node  = null;
                    if (sNode.FileType == typeof(ExitNode))
                    {
                        node = new ExitNode(floor, sNode.Position, sNode.Title)
                        {
                            AutoSize = sNode.AutoSize
                        }
                    }
                    ;
                    if (sNode.FileType == typeof(RoadNode))
                    {
                        node = new RoadNode(floor, sNode.Position, sNode.Title)
                        {
                            AutoSize = sNode.AutoSize
                        }
                    }
                    ;

                    dictionary.Add(sNode.HashCode, node);
                    floor.AddObject(node);
                    continue;
                }

                if (file is SectionSavedFile)
                {
                    var     sSection = file as SectionSavedFile;
                    Floor   floor    = dictionary[sSection.ParentHashCode];
                    Section section  = null;
                    if (sSection.FileType == typeof(RoadSection))
                    {
                        section = new RoadSection((Node)dictionary[sSection.FirstNodeHashCode], (Node)dictionary[sSection.LastNodeHashCode], floor, sSection.Title)
                        {
                            AutoSize = sSection.AutoSize,
                            Length   = sSection.Length,
                            Width    = sSection.Width
                        }
                    }
                    ;
                    else if (sSection.FileType == typeof(StairsSection))
                    {
                        section = new StairsSection((Node)dictionary[sSection.FirstNodeHashCode], (Node)dictionary[sSection.LastNodeHashCode], floor, sSection.Title)
                        {
                            AutoSize = sSection.AutoSize,
                            Length   = sSection.Length,
                            Width    = sSection.Width
                        }
                    }
                    ;
                    else if (sSection.FileType == typeof(FloorsConnectionSection))
                    {
                        continue;                                                            // следует произвести добавление в самом конце
                    }
                    dictionary.Add(sSection.HashCode, section);
                    floor.AddObject(section);
                    continue;
                }
            }

            foreach (var file in files.Where(x => x.FileType == typeof(FloorsConnectionSection)))
            {
                var   sSection = file as SectionSavedFile;
                Floor floor    = dictionary[sSection.ParentHashCode];
                var   section  = new FloorsConnectionSection((Node)dictionary[sSection.FirstNodeHashCode], (Node)dictionary[sSection.LastNodeHashCode], floor);
                dictionary.Add(sSection.HashCode, section);
                floor.AddObject(section);
            }

            return(building);
        }
    }
}