예제 #1
0
        public static DistanceLevel.WorkshopLevelRetreiver RetrieveDistanceLevels(WorkshopItem[] items, string gameMode = "Sprint")
        {
            List <string> levelIds = new List <string>(items.Length);

            foreach (var item in items)
            {
                levelIds.Add(item.PublishedFileId);
            }
            return(DistanceLevel.RetrieveWorkshopLevel(levelIds, true, gameMode));
        }
    public IEnumerator NavigateTowardsTargetCoroutine()
    {
        animator.SetInteger(actionState, (int)ActionState.WALKING);

        DistanceLevel originalDistanceLevel = GetDistanceLevel();
        float         addedMoveSpeed        = 0.0f;

        while (GetDistanceLevel() == originalDistanceLevel && Random.Range(0.0f, 1.0f) < 0.99f)
        {
            Vector2 displacement = target.transform.position - transform.position;
            rigidBody.velocity = (moveSpeed + addedMoveSpeed) * displacement.normalized;
            animator.SetFloat(horizontalVelocity, rigidBody.velocity.x);
            addedMoveSpeed += Time.deltaTime * moveSpeed;
            yield return(null);
        }
        DetermineNextAction();
    }
        public System.Collections.IEnumerator Retrieve()
        {
            Log.SetDebugLineEnabled("Retrieve", true);
            var search      = Parameters.Search;
            var searchCount = 0;

            while ((Parameters.MaxSearch <= 0 || searchCount < Parameters.MaxSearch) && (Parameters.MaxResults <= 0 || Results.Count < Parameters.MaxResults))
            {
                Log.DebugLine("Retrieve", 1);
                var searchResult = search.Search();
                yield return(searchResult.TaskCoroutine);

                if (searchResult.HasError)
                {
                    Error    = searchResult.Error;
                    Finished = true;
                    yield break;
                }
                Log.DebugLine("Retrieve");
                var levelIds = new List <string>();

                if (searchResult.Result == null)
                {
                    Log.Warn("HtmlAgilityPack might not be loaded");
                }
                foreach (var item in searchResult.Result.Items)
                {
                    levelIds.Add(item.PublishedFileId);
                }
                Log.DebugLine("Retrieve");
                var levelsResult = DistanceLevel.RetrieveWorkshopLevel(levelIds);
                yield return(levelsResult.WebCoroutine);

                var searchResults = new List <DistanceSearchResultItem>();
                for (int i = 0; i < searchResult.Result.Items.Length; i++)
                {
                    searchCount++;
                    if (Parameters.MaxSearch > 0 && searchCount > Parameters.MaxSearch)
                    {
                        break;
                    }
                    var item = searchResult.Result.Items[i];
                    if (levelsResult.LevelsByPublishedFileId.ContainsKey(item.PublishedFileId))
                    {
                        searchResults.Add(new DistanceSearchResultItem(searchResult.Result.Items[i], levelsResult.LevelsByPublishedFileId[item.PublishedFileId]));
                    }
                }
                Log.DebugLine("Retrieve");
                var cont = true;
                if (Parameters.DistanceLevelFilter != null)
                {
                    cont = Parameters.DistanceLevelFilter(searchResults);
                }
                Log.DebugLine("Retrieve");
                if (Parameters.MaxResults > 0)
                {
                    var max = Results.Count + searchResults.Count - Parameters.MaxResults;
                    for (int i = 0; i < max; i++)
                    {
                        searchResults.RemoveAt(searchResults.Count - 1);
                    }
                }
                Log.DebugLine("Retrieve");
                Results.AddRange(searchResults);
                Log.DebugLine("Retrieve");
                if (!searchResult.Result.HasNextPage || !cont)
                {
                    break;
                }
                else
                {
                    search = searchResult.Result.NextPage;
                }
                Log.DebugLine("Retrieve");
            }
            Finished = true;
            yield break;
        }
 public DistanceSearchResultItem(WorkshopItem item, DistanceLevel level)
 {
     WorkshopItemResult  = item;
     DistanceLevelResult = level;
 }
예제 #5
0
        void OnAdvancingToNextLevel()
        {
            LastMapVoters.Clear();
            var levelLookup = new Dictionary <string, DistanceLevel>();
            var validVotes  = new Dictionary <string, int>();

            foreach (var vote in PlayerVotes)
            {
                var distancePlayer = Server.GetDistancePlayer(vote.Key);
                if (distancePlayer == null)
                {
                    if (!LeftAt.ContainsKey(vote.Key) || DistanceServerMain.UnixTime - LeftAt[vote.Key] > 5 * 60)
                    {
                        PlayerVotes.Remove(vote.Key);
                        PlayerVoteTimes.Remove(vote.Key);
                        LeftAt.Remove(vote.Key);
                    }
                }
                else
                {
                    var isBadVoter = IsBadVoter(distancePlayer, DistanceServerMain.UnixTime);
                    var isLateVote = PlayerVoteTimes[vote.Key] > DistanceServerMain.UnixTime - VoteNotSafetyTime;
                    if (isBadVoter && isLateVote)
                    {
                        Server.SayLocalChat(distancePlayer.UnityPlayer, DistanceChat.Server("VoteCommands:LateVote", "Your vote has been skipped this round because you voted late!\nYour vote will apply on the next round."));
                    }
                    else
                    {
                        int count = 0;
                        validVotes.TryGetValue(vote.Value.RelativeLevelPath, out count);
                        validVotes[vote.Value.RelativeLevelPath] = count + 1;
                        if (!levelLookup.ContainsKey(vote.Value.RelativeLevelPath))
                        {
                            levelLookup[vote.Value.RelativeLevelPath] = vote.Value;
                        }
                    }
                }
            }

            foreach (var pair in RecentMaps.ToArray())
            {
                if (Server.CurrentLevelId > pair.Value)
                {
                    RecentMaps.Remove(pair.Key);
                }
            }

            var votesSum = 0;

            foreach (var vote in validVotes.ToArray())
            {
                var data = new FilterLevelRealtimeEventData(levelLookup[vote.Key]);
                OnFilterLevelRealtime.Fire(data);
                if (data.HardBlocklist || (data.SoftBlocklist && vote.Value < NeededVotesToOverrideSoftBlocklist))
                {
                    validVotes.Remove(vote.Key);
                }
                else
                {
                    var value = vote.Value;
                    if (AgainstVotes.ContainsKey(vote.Key))
                    {
                        var count = 0;
                        foreach (var guid in AgainstVotes[vote.Key])
                        {
                            if (Server.GetDistancePlayer(guid) != null)
                            {
                                count++;
                                value--;
                            }
                        }
                    }
                    if (value <= 0)
                    {
                        validVotes.Remove(vote.Key);
                    }
                    else
                    {
                        validVotes[vote.Key] = value;
                        votesSum            += value;
                    }
                }
            }

            foreach (var pair in LeftAt.ToArray())
            {
                if (DistanceServerMain.UnixTime - pair.Value > 5 * 60)
                {
                    LeftAt.Remove(pair.Key);
                    foreach (var votePair in AgainstVotes.ToArray())
                    {
                        votePair.Value.Remove(pair.Key);
                        if (votePair.Value.Count == 0)
                        {
                            AgainstVotes.Remove(votePair.Key);
                        }
                    }
                }
            }

            if (validVotes.Count == 0)
            {
                return;
            }
            var           choiceInt = new Random().Next(votesSum);
            var           choiceSum = 0;
            DistanceLevel level     = null;

            foreach (var pair in validVotes)
            {
                choiceSum += pair.Value;
                if (choiceInt < choiceSum)
                {
                    level = levelLookup[pair.Key];
                    break;
                }
            }
            if (level == null)
            {
                return;
            }
            autoServer.SetNextLevel(level);
            var    voteCount   = 0;
            string firstPlayer = null;

            foreach (var vote in PlayerVotes.ToArray())
            {
                var distancePlayer = Server.GetDistancePlayer(vote.Key);
                if (vote.Value.RelativeLevelPath == level.RelativeLevelPath && distancePlayer != null)
                {
                    voteCount++;
                    PlayerVotes.Remove(vote.Key);
                    PlayerVoteTimes.Remove(vote.Key);
                    LastMapVoters.Add(new MapVoterInfo(distancePlayer));
                    if (firstPlayer == null)
                    {
                        firstPlayer = vote.Key;
                    }
                }
            }
            var          nextLevelId = Server.CurrentLevelId + 1;
            EventCleaner conns       = new EventCleaner();

            conns.Add(
                Server.OnModeStartedEvent.Connect(() =>
            {
                var chat = DistanceChat.Server("VoteCommands:ChosenLevel", $"Chosen level is [00FF00]{level.Name}[-], voted for by {Server.GetDistancePlayer(firstPlayer).Name}" + (voteCount > 1 ? $" and {voteCount - 1} others" : ""));
                Server.SayChat(chat);
                conns.Clean();
            }),
                Server.OnLevelStartInitiatedEvent.Connect(() =>
            {
                if (Server.CurrentLevelId != nextLevelId)
                {
                    conns.Clean();
                }
            })
                );
        }
예제 #6
0
 public FilterLevelRealtimeEventData(DistanceLevel level)
 {
     Level = level;
 }
예제 #7
0
        private void Validate(string fileName)
        {
            if (Shape.LodControls.Count < 1)
            {
                Trace.TraceWarning("Missing at least one LOD Control element in shape {0}", fileName);
            }

            for (int distanceLevelIndex = 0; distanceLevelIndex < Shape.LodControls[0].DistanceLevels.Count; distanceLevelIndex++)
            {
                DistanceLevel distanceLevel = Shape.LodControls[0].DistanceLevels[distanceLevelIndex];

                if (distanceLevel.DistanceLevelHeader.Hierarchy.Length != Shape.Matrices.Count)
                {
                    Trace.TraceWarning("Expected {2} hierarchy elements; got {3} in distance level {1} in shape {0}", fileName, distanceLevelIndex, Shape.Matrices.Count, distanceLevel.DistanceLevelHeader.Hierarchy.Length);
                }

                for (int hierarchyIndex = 0; hierarchyIndex < distanceLevel.DistanceLevelHeader.Hierarchy.Length; hierarchyIndex++)
                {
                    int matrixIndex = distanceLevel.DistanceLevelHeader.Hierarchy[hierarchyIndex];
                    if (matrixIndex < -1 || matrixIndex >= Shape.Matrices.Count)
                    {
                        Trace.TraceWarning("Hierarchy element {2} out of range (expected {3} to {4}; got {5}) in distance level {1} in shape {0}", fileName, distanceLevelIndex, hierarchyIndex, -1, Shape.Matrices.Count - 1, matrixIndex);
                    }
                }

                for (int subObjectIndex = 0; subObjectIndex < distanceLevel.SubObjects.Count; subObjectIndex++)
                {
                    SubObject subObject = distanceLevel.SubObjects[subObjectIndex];

                    if (subObject.SubObjectHeader.GeometryInfo.GeometryNodeMap.Length != Shape.Matrices.Count)
                    {
                        Trace.TraceWarning("Expected {3} geometry node map elements; got {4} in sub-object {2} in distance level {1} in shape {0}", fileName, distanceLevelIndex, subObjectIndex, Shape.Matrices.Count, subObject.SubObjectHeader.GeometryInfo.GeometryNodeMap.Length);
                    }

                    int[] geometryNodeMap = subObject.SubObjectHeader.GeometryInfo.GeometryNodeMap;
                    for (int geometryNodeMapIndex = 0; geometryNodeMapIndex < geometryNodeMap.Length; geometryNodeMapIndex++)
                    {
                        int geometryNode = geometryNodeMap[geometryNodeMapIndex];
                        if (geometryNode < -1 || geometryNode >= subObject.SubObjectHeader.GeometryInfo.GeometryNodes.Count)
                        {
                            Trace.TraceWarning("Geometry node map element {3} out of range (expected {4} to {5}; got {6}) in sub-object {2} in distance level {1} in shape {0}", fileName, distanceLevelIndex, subObjectIndex, geometryNodeMapIndex, -1, subObject.SubObjectHeader.GeometryInfo.GeometryNodes.Count - 1, geometryNode);
                        }
                    }

                    Vertices vertices = subObject.Vertices;
                    for (int vertexIndex = 0; vertexIndex < vertices.Count; vertexIndex++)
                    {
                        Vertex vertex = vertices[vertexIndex];

                        if (vertex.PointIndex < 0 || vertex.PointIndex >= Shape.Points.Count)
                        {
                            Trace.TraceWarning("Point index out of range (expected {4} to {5}; got {6}) in vertex {3} in sub-object {2} in distance level {1} in shape {0}", fileName, distanceLevelIndex, subObjectIndex, vertexIndex, 0, Shape.Points.Count - 1, vertex.PointIndex);
                        }

                        if (vertex.NormalIndex < 0 || vertex.NormalIndex >= Shape.Normals.Count)
                        {
                            Trace.TraceWarning("Normal index out of range (expected {4} to {5}; got {6}) in vertex {3} in sub-object {2} in distance level {1} in shape {0}", fileName, distanceLevelIndex, subObjectIndex, vertexIndex, 0, Shape.Normals.Count - 1, vertex.NormalIndex);
                        }

                        if (vertex.VertexUVs.Length < 1)
                        {
                            Trace.TraceWarning("Missing UV index in vertex {3} in sub-object {2} in distance level {1} in shape {0}", fileName, distanceLevelIndex, subObjectIndex, vertexIndex);
                        }
                        else if (vertex.VertexUVs[0] < 0 || vertex.VertexUVs[0] >= Shape.UVPoints.Count)
                        {
                            Trace.TraceWarning("UV index out of range (expected {4} to {5}; got {6}) in vertex {3} in sub-object {2} in distance level {1} in shape {0}", fileName, distanceLevelIndex, subObjectIndex, vertexIndex, 0, Shape.UVPoints.Count - 1, vertex.VertexUVs[0]);
                        }
                    }

                    for (int primitiveIndex = 0; primitiveIndex < subObject.Primitives.Count; primitiveIndex++)
                    {
                        IndexedTriList triangleList = subObject.Primitives[primitiveIndex].IndexedTriList;
                        for (int triangleListIndex = 0; triangleListIndex < triangleList.VertexIndices.Count; triangleListIndex++)
                        {
                            if (triangleList.VertexIndices[triangleListIndex].A < 0 || triangleList.VertexIndices[triangleListIndex].A >= vertices.Count)
                            {
                                Trace.TraceWarning("Vertex out of range (expected {4} to {5}; got {6}) in primitive {3} in sub-object {2} in distance level {1} in shape {0}", fileName, distanceLevelIndex, subObjectIndex, primitiveIndex, 0, vertices.Count - 1, triangleList.VertexIndices[triangleListIndex].A);
                            }
                        }
                    }
                }
            }
        }
예제 #8
0
        IEnumerator RetrieveLevel()
        {
            var body    = GenerateWorkshopInfoBody(WorkshopLevelIds);
            var request = new UnityWebRequest(fileDetailsUrl);

            request.uploadHandler             = new UploadHandlerRaw(Encoding.ASCII.GetBytes(body));
            request.downloadHandler           = new DownloadHandlerBuffer();
            request.method                    = UnityWebRequest.kHttpVerbPOST;
            request.uploadHandler.contentType = "application/x-www-form-urlencoded";

            yield return(request.SendWebRequest());

            if (request.isNetworkError || request.isHttpError)
            {
                Finished = true;
                Error    = request.error;
                yield break;
            }

            var reader = new JsonFx.Json.JsonReader();
            Dictionary <string, object> responseJson;

            try
            {
                responseJson = reader.Read <Dictionary <string, object> >(request.downloadHandler.text);
            }
            catch (Exception e)
            {
                Finished = true;
                Error    = e.ToString();
                yield break;
            }

            if (!responseJson.ContainsKey("response"))
            {
                Finished = true;
                Error    = "No response key returned from server";
                yield break;
            }

            var response = (Dictionary <string, object>)responseJson["response"];

            if (!response.ContainsKey("publishedfiledetails"))
            {
                Finished = true;
                Error    = "No publishedfiledetails key returned from server";
                yield break;
            }

            var fileDetails = (object[])response["publishedfiledetails"];
            var index       = 0;

            foreach (var detailBase in fileDetails)
            {
                var detail = (Dictionary <string, object>)detailBase;
                if (!detail.ContainsKey("result") || (int)detail["result"] != 1 || !detail.ContainsKey("title") || !detail.ContainsKey("creator") || !detail.ContainsKey("filename"))
                {
                    continue;
                }
                if (!detail.ContainsKey("publishedfileid") || detail["publishedfileid"].GetType() != typeof(string) || (string)detail["publishedfileid"] == string.Empty)
                {
                    continue;
                }
                if (detail["title"].GetType() != typeof(string))
                {
                    continue;
                }
                if (detail["creator"].GetType() != typeof(string) || (string)detail["creator"] == string.Empty)
                {
                    continue;
                }
                if (detail["filename"].GetType() != typeof(string) || (string)detail["filename"] == "")
                {
                    continue;
                }
                string levelVersion = "";
                if (detail.ContainsKey("time_updated"))
                {
                    DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                    dtDateTime   = dtDateTime.AddSeconds((int)detail["time_updated"]).ToLocalTime();
                    levelVersion = dtDateTime.ToBinary().ToString();
                }

                var                    difficulty       = LevelDifficulty.Unknown;
                List <string>          difficultyNames  = new List <string>(Enum.GetNames(typeof(LevelDifficulty)));
                List <LevelDifficulty> difficultyValues = new List <LevelDifficulty>((LevelDifficulty[])Enum.GetValues(typeof(LevelDifficulty)));

                List <string> supportedModes = new List <string>();
                if (detail.ContainsKey("tags"))
                {
                    foreach (var tagBase in (object[])detail["tags"])
                    {
                        var tag = (Dictionary <string, object>)tagBase;
                        if (tag.ContainsKey("tag") && (string)tag["tag"] != "Level")
                        {
                            var difficultyIndex = difficultyNames.IndexOf((string)tag["tag"]);
                            if (difficultyIndex != -1)
                            {
                                difficulty = difficultyValues[difficultyIndex];
                            }
                            supportedModes.Add((string)tag["tag"]);
                        }
                    }
                }
                var level = new DistanceLevel()
                {
                    Name = (string)detail["title"],
                    RelativeLevelPath = $"WorkshopLevels/{(string)detail["creator"]}/{(string)detail["filename"]}",
                    // Example: "WorkshopLevels/76561198145035078/a digital frontier.bytes"
                    LevelVersion   = levelVersion,
                    WorkshopFileId = (string)detail["publishedfileid"],
                    GameMode       = DefaultGameMode,
                    SupportedModes = supportedModes.ToArray(),
                    Difficulty     = difficulty,
                };
                ValidLevels.Add(level);
                LevelsByPublishedFileId.Add(level.WorkshopFileId, level);
                index++;
            }
            Finished = true;
        }
예제 #9
0
 public void SetNextLevel(DistanceLevel level)
 {
     OverridePlaylist.Insert(0, level);
 }