Exemplo n.º 1
0
        public void Initiate()
        {
            if (CinematographyAttributes.lensFovData != null && (cameraList != null && cameraList.Count > 0))
            {
                initiated = true;
                return;
            }
            ProCamsLensDataTable.Instance.LoadData();
            CinematographyAttributes.lensFovData   = ProCamsLensDataTable.Instance.GetFilmFormat("35mm 16:9 Aperture (1.78:1)").GetLensKitData(0)._fovDataset;
            CinematographyAttributes.standardNoise = Instantiate(Resources.Load("Handheld_tele_mild", typeof(NoiseSettings))) as NoiseSettings;

            //FrameTypeList = new List<FramingType>() { FramingType.ExtremeLong, FramingType.Full, FramingType.Waist, FramingType.ExtremeCloseUp };

            // problem information may not be useful here
            problemStates = GameObject.FindGameObjectWithTag("Problem").GetComponent <UnityProblemCompiler>();

            // locations are the basic anchor for camera positioning
            tileMap = GameObject.FindGameObjectWithTag("Locations").GetComponent <TileGraph>();

            // actors
            var actorHost = GameObject.FindGameObjectWithTag("ActorHost");

            actors = new List <GameObject>();
            for (int i = 0; i < actorHost.transform.childCount; i++)
            {
                actors.Add(actorHost.transform.GetChild(i).gameObject);
            }

            initiated = true;
            Debug.Log("Initiated");
        }
Exemplo n.º 2
0
    // finalLoc teleports this render somewhere once it's complete.
    // Note that it will still render around the origin before teleporting away, so DON'T SET FINALLOC TO ZERO
    //   UNLESS YOU'RE DELETING IMMEDIATELY / ONLY RENDERING ONE.

    public static Dictionary <TileNode, RenderedTileInfo> FinalRender(TileGraph g, Vector3 loc, List <float> fitVals, GameObject parent)
    {
        Dictionary <TileNode, RenderedTileInfo> ret = RenderNodes(g, parent);

        renderedGraph.transform.position = loc;
        DisplayFitness df = renderedGraph.AddComponent <DisplayFitness>();

        df.fitnessValues = fitVals;
        return(ret);
    }
Exemplo n.º 3
0
    //
    // Summary:
    // Divide the x-z plane of the ground into a grid given the cell size
    void MakeGraph()
    {
        Bounds  bounds         = ground.GetComponent <Renderer>().bounds;
        Vector3 xzBoundsCenter = bounds.center + new Vector3(0, bounds.extents.y, 0);
        Vector3 gridTopLeft    = xzBoundsCenter + new Vector3(-bounds.extents.x, 0, bounds.extents.z);

        int maxRowCount = (int)Mathf.Floor(bounds.size.z / cellSize);
        int maxColCount = (int)Mathf.Floor(bounds.size.x / cellSize);

        Tile[,] grid = new Tile[maxRowCount, maxColCount];

        Vector3 offsetToCenter = new Vector3(cellSize / 2, 0, -cellSize / 2);

        for (int r = 0; r < grid.GetLength(0); r++)
        {
            for (int c = 0; c < grid.GetLength(1); c++)
            {
                // World space point that corresponds to the center of the tile
                Vector3 worldPoint = gridTopLeft + new Vector3(c * cellSize, 0, -(r * cellSize)) + offsetToCenter;

                // Determine overlapping obstacles
                TileType   tileType  = TileType.Free;
                Collider[] colliders = Physics.OverlapSphere(worldPoint, cellSize / 4);
                if (colliders != null && colliders.Length > 0)
                {
                    bool foundCollision = true;

                    // Check for collision with someone other than ourselves
                    Collider ourCollider = ground.GetComponent <Collider>();
                    if (ourCollider != null)
                    {
                        foundCollision = false;
                        for (int i = 0; i < colliders.Length; i++)
                        {
                            if (colliders[i] != ourCollider)
                            {
                                foundCollision = true;
                                break;
                            }
                        }
                    } // if we don't have a collider, we are definitely colliding with something else

                    if (foundCollision)
                    {
                        tileType = TileType.Obstacle;
                    }
                }

                // Make tile
                grid[r, c] = new Tile(new Vector2Int(r, c), tileType, worldPoint);
            }
        }

        graph = new TileGraph(grid);
    }
Exemplo n.º 4
0
        private void AddRoadsFromTemplateToMap(ObjectTemplate template, Map map, MapInfo info, string roadType)
        {
            var tileGraph = new TileGraph(info.Tiles, TileInfo.Free);
            var roads     = template.Objects.Where(o => o.RoadOptions != RoadOptions.None && o.Type == ObjectTemplate.RoadTemplate).ToArray();
            int count     = info.Roads.Nodes.Count;

            ScriptObject road1, road2;

            for (int i = 0; i < roads.Length; i += 2)
            {
                road1 = roads[i];
                road2 = roads[i + 1];

                var start = info.Roads.FindNode(new Point(road1.X, road1.Y));
                if (start == null)
                {
                    start = new RoadGraphNode(new Point(road1.X, road1.Y), !road1.RoadOptions.HasFlag(RoadOptions.Join) && roads.Count(r2 => road1.X == r2.X && road1.Y == r2.Y) == 1, true);
                    info.Roads.Nodes.AddLast(start);
                }

                var end = info.Roads.FindNode(new Point(road2.X, road2.Y));
                if (end == null)
                {
                    end = new RoadGraphNode(new Point(road2.X, road2.Y), !road2.RoadOptions.HasFlag(RoadOptions.Join) && roads.Count(r2 => road2.X == r2.X && road2.Y == r2.Y) == 1, true);
                    info.Roads.Nodes.AddLast(end);
                }

                start.LinkTo(end);

                road1.Type = roadType;
                road2.Type = roadType;

                info.Roads.Segments.Add(new Tuple <ScriptObject, ScriptObject>(road1, road2));
                tileGraph.UpdateTiles(new[] { map.PositionToCoordinates(start.Position), map.PositionToCoordinates(end.Position) }, TileInfo.Road);
            }

            IEnumerable <RoadGraphNode> nodes = info.Roads.Nodes.Skip(count).ToArray();

            var endpoints = from r in nodes
                            where !r.CanBeConnected && r.Neighbors.Count == 1
                            select r;

            foreach (var endpoint in endpoints)
            {
                foreach (var node in nodes)
                {
                    if (node != endpoint && (node.Position - endpoint.Position).VectorLengthSquared() < endpointConnectionRange * endpointConnectionRange)
                    {
                        endpoint.LinkTo(node);
                    }
                }
            }
        }
Exemplo n.º 5
0
        public void Process(Map map, MapInfo info)
        {
            this.map       = map;
            this.info      = info;
            this.tileGraph = new TileGraph(info.Tiles, invalidTiles);
            this.random    = new Random(info.MapId);

            this.heightConstraints = new Grid <byte>(map.HeightMap.Width, map.HeightMap.Height);
            for (int i = 0; i < map.Tiles.Width; i++)
            {
                for (int j = 0; j < map.Tiles.Height; j++)
                {
                    heightConstraints[i, j] = 255;

                    var invalidNeighbors = tileGraph.GetNeighbors(i, j, invalidTileRadius, false, true);
                    foreach (var neighbor in invalidNeighbors)
                    {
                        if (map.HeightMap.CheckCoordinates(neighbor.X, neighbor.Y))
                        {
                            int distance = System.Math.Max(System.Math.Abs(neighbor.X - i), System.Math.Abs(neighbor.Y - j));
                            heightConstraints[i, j] = (byte)System.Math.Min(heightConstraints[i, j], map.HeightMap[neighbor.X, neighbor.Y] + (distance - 1) * MaxHeightDifferencePerTile);
                        }
                    }
                }
            }

            int min, max;

            switch (info.Settings.NumberOfCliffs)
            {
            case Frequency.Low:
                min = 0;
                max = (int)(map.Tiles.Count / lowDivisor);
                break;

            case Frequency.High:
                min = (int)(map.Tiles.Count / mediumDivisor);
                max = (int)(map.Tiles.Count / highDivisor);
                break;

            default:
                min = (int)(map.Tiles.Count / lowDivisor);
                max = (int)(map.Tiles.Count / mediumDivisor);
                break;
            }

            int count = random.Next(min, max);

            for (int i = 0; i < count && !info.IsCancellationRequested; i++)
            {
                AddCliff();
            }
        }
Exemplo n.º 6
0
        public void Process(Map map, MapInfo info)
        {
            if (info.Settings.Scenery.Rocks.Count == 0)
            {
                return;
            }

            this.info      = info;
            this.tileGraph = new TileGraph(info.Tiles, invalidTiles);

            int count;

            switch (Frequency)
            {
            case Frequency.High:
                count = map.Tiles.Count / 1000;
                break;

            case Frequency.Low:
                count = map.Tiles.Count / 3000;
                break;

            default:
                count = map.Tiles.Count / 2000;
                break;
            }

            Random random = new Random(info.MapId);

            int width  = map.HeightMap.MapWidth * (int)Map.TileWidth;
            int height = map.HeightMap.MapHeight * (int)Map.TileWidth;

            while (count > 0 && !info.IsCancellationRequested)
            {
                float x = random.Next(width);
                float y = random.Next(height);

                var coordinates = map.PositionToCoordinates(new Point(x, y));

                if (info.IsWithinStartingRange(coordinates, 10))
                {
                    continue;
                }

                if (IsTileValid(coordinates.X, coordinates.Y))
                {
                    int rock = random.Next(info.Settings.Scenery.Rocks.Count);
                    map.Objects.Add(info.ObjectFactory.CreateObject(info.Settings.Scenery.Rocks[rock], x, y, 0, (float)(((random.NextDouble() * 2) - 1) * System.Math.PI)));
                    count--;
                }
            }
        }
Exemplo n.º 7
0
        public static Stack <TileNode> Astar(TileGraph tg, TileNode start, TileNode end)
        {
            frontier = new SimplePriorityQueue <TileNode, float>();
            frontier.Enqueue(start, 0f);
            node_dict = new Dictionary <TileNode, NodeInfo>();
            List <TileNode> Expanded = new List <TileNode>();

            while (frontier.Count > 0)
            {
            }

            return(Path);
        }
Exemplo n.º 8
0
        public void Process(Map map, MapInfo info)
        {
            this.map       = map;
            this.info      = info;
            this.tileGraph = new TileGraph(info.Tiles, invalidTiles);
            this.random    = new Random(info.MapId);

            for (int i = 0; i < map.HeightMap.Width - 1; i++)
            {
                for (int j = 1; j < map.HeightMap.Height - 1; j++)
                {
                    Flatten(i, j);
                }
            }
        }
Exemplo n.º 9
0
        public static Stack <TileNode> Astar(TileGraph tg, TileNode start, TileNode end)
        {
            frontier = new SimplePriorityQueue <TileNode, float>();
            frontier.Enqueue(start, 0f);
            //node_dict = new Dictionary<TileNode, NodeInfo>();
            node_dict = DijkstraInitialDictLoad(start, tg);
            List <TileNode> Expanded = new List <TileNode>();

            TileNode v;
            TileNode other;
            float    cost_so_far;
            float    edge_weight;
            float    dist_to_node;
            float    manhattanDistance;

            while (frontier.Count > 0)
            {
                v           = frontier.Dequeue();
                cost_so_far = node_dict[v].dist;
                Expanded.Add(v);

                List <Edge> experiment = tg.getAdjacentEdges(v) as List <Edge>;
                foreach (Edge adj_edge in tg.getAdjacentEdges(v))
                {
                    other             = adj_edge.getNeighbor(v);
                    edge_weight       = adj_edge.weight;
                    dist_to_node      = node_dict[other].dist;
                    manhattanDistance = Mathf.Abs(end.transform.position.z - other.transform.position.z) + Mathf.Abs(end.transform.position.x - other.transform.position.x);

                    if (cost_so_far + edge_weight < dist_to_node)
                    {
                        node_dict[other].dist      = cost_so_far + edge_weight;
                        node_dict[other].heuristic = node_dict[other].dist + manhattanDistance;
                        node_dict[other].parent    = v;
                    }

                    if (!Expanded.Any(node => node.isEqual(other)) && !frontier.Any(node => node.isEqual(other)))
                    {
                        frontier.Enqueue(other, node_dict[other].heuristic);
                    }
                }
            }

            Path = NodeDictToPath(node_dict, start, end);

            return(Path);
        }
Exemplo n.º 10
0
        public void Process(Map map, MapInfo info)
        {
            var graph     = new TileGraph(info.Tiles, TileInfo.Free);
            var generator = new RampGenerator(info.MapId);

            foreach (var area in info.FlattenedAreas)
            {
                if (info.IsCancellationRequested)
                {
                    return;
                }

                var coordinates = map.PositionToCoordinates(area.Center);
                var height      = (byte)graph.GetNeighbors(coordinates, (int)(area.Radius / Map.TileWidth) + 3, true, true).Average(c => map.HeightMap[c.X, c.Y]);
                generator.GenerateFlatArea(map, coordinates, height, (int)(area.Radius / Map.TileWidth), area.Radius);
            }
        }
Exemplo n.º 11
0
        public void Process(Map map, MapInfo info)
        {
            this.map                  = map;
            this.info                 = info;
            this.tileGraph            = new TileGraph(info.Tiles, TileInfo.Structure | TileInfo.Cliff);
            this.roadsLeadingOutOfMap = new List <RoadGraphEdge>();

            this.random = new Random(info.MapId);

            AddRoadsBetweenNodes();
            AddRoadsLeadingOutOfMapForDanglingNodes();
            AddAdditionalRoadsLeadingOutOfMap();

            CheckTightCurves();

            AddOffsets();
        }
Exemplo n.º 12
0
        public static Stack <TileNode> Dijkstra(TileGraph tg, TileNode start, TileNode end)
        {
            frontier = new SimplePriorityQueue <TileNode, float>();
            frontier.Enqueue(start, 0f);
            node_dict = DijkstraInitialDictLoad(start, tg);
            List <TileNode> Expanded = new List <TileNode>();

            TileNode v;
            TileNode other;
            float    edge_weight;
            float    dist_to_node;
            float    cost_so_far;

            while (frontier.Count > 0)
            {
                v           = frontier.Dequeue();
                cost_so_far = node_dict[v].dist;
                Expanded.Add(v);

                //List<Edge> experiment = tg.getAdjacentEdges(v) as List<Edge>;
                foreach (Edge adj_edge in tg.getAdjacentEdges(v))
                {
                    other        = adj_edge.getNeighbor(v);
                    edge_weight  = adj_edge.weight;
                    dist_to_node = node_dict[other].dist;
                    if (cost_so_far + edge_weight < dist_to_node)
                    {
                        node_dict[other].dist   = cost_so_far + edge_weight;
                        node_dict[other].parent = v;
                    }

                    if (!Expanded.Any(node => node.isEqual(other)) && !frontier.Any(node => node.isEqual(other)))
                    {
                        frontier.Enqueue(other, node_dict[other].dist);
                    }
                }
            }

            Path = NodeDictToPath(node_dict, start, end);

            return(Path);
        }
Exemplo n.º 13
0
    // Use this for initialization
    public void Start()
    {
        teleporterTiles           = new Dictionary <int, List <GameObject> >();
        teleporterPads            = new Dictionary <int, GameObject>();
        receiverTile              = new Dictionary <int, GameObject>();
        levelSelectTeleporterTile = new Dictionary <int, List <GameObject> >();
//		MinX = float.MaxValue;
//		MinZ = float.MaxValue;
//		MaxX = float.MinValue;
//		MaxZ = float.MinValue;

        //this is only going tobe attached to an empty object but center
        //it at the origin anyway
        gameObject.transform.position = Vector3.zero;

        _recentlyVisitedTiles = new List <DJ_Point>();
        _tileGlowTimes        = new List <float>();

        _recentlyLaserVisitedTiles = new List <DJ_Point>();
        _tileLaserGlowTimes        = new Dictionary <DJ_Point, float>();

        _prevPlayerPos = new DJ_Point(int.MaxValue, int.MaxValue);

        tilePool = new Stack <TileNode>();
        tileMap  = new Dictionary <DJ_Point, TileNode>(DJ_PointComparer.Default);

        // Instantiate the checkpoint system
        checkpointList  = new List <DJ_Point>();
        exitPoint       = new DJ_Point(0, 0);
        levelselectList = new List <DJ_Point>();
        onBeat          = false;

        //Instantiate level select points
        tileGraph = new TileGraph(this.gameObject, m_tilePrefab);
        LinkTeleporters();
        LinkLevelSelectTeleporters();
        tileMap = tileGraph.tileMap;
        //print (tilegraph);
    }
Exemplo n.º 14
0
        private static Dictionary <TileNode, NodeInfo> DijkstraInitialDictLoad(TileNode start, TileGraph tg)
        {
            node_dict = new Dictionary <TileNode, NodeInfo>();
            foreach (TileNode tn in tg.nodes)
            {
                NodeInfo ni = new NodeInfo();
                if (start.isEqual(tn))
                {
                    ni.dist = 0f;
                }

                node_dict[tn] = ni;
            }

            return(node_dict);
        }
Exemplo n.º 15
0
        public void Process(Map map, MapInfo info)
        {
            InitializeTypes();

            this.map   = map;
            this.info  = info;
            this.tiles = new TileGraph(info.Tiles, TileInfo.Base | TileInfo.FuelDepotFar | TileInfo.FlagFar);

            this.resourcesPlayer = map.Players.FirstOrDefault(p => p.Properties["playerName"].Value.Equals("Resources"));

            this.axesOfSymmetry   = new SymmetryAnalyzer().Analyze(map, info.StartingPositions);
            this.villagePositions = new List <Point>();

            this.random = new Random(info.MapId);

            // There are always at least two axes which should intersect at the map center.
            Point center = axesOfSymmetry[0].Intersect(axesOfSymmetry[1]);

            // Generate a village in the center.
            if (random.Next(3) == 0)
            {
                GenerateVillage(center, villages[random.Next(villages.Count)]);
            }

            // Generate two villages along the primary axis.
            if (random.Next(3) == 0)
            {
                Point[] positions = new Point[2];

                var direction = axesOfSymmetry[0].IsVertical ? new Point(0, 1) : new Point(1, axesOfSymmetry[0].Slope).Normalize();
                var maxLength = System.Math.Min(center.X, center.Y);

                do
                {
                    float distance = (float)random.NextDouble() * maxLength;

                    positions[0] = center + direction * distance;
                    positions[1] = center - direction * distance;
                }while (!CheckVillagePositions(positions) && !info.IsCancellationRequested);

                GenerateVillages(positions);
            }

            // Generate a village for every player.
            if (random.Next(3) == 0)
            {
                Point[] positions = null;

                int count = 0;
                do
                {
                    positions = GetRandomMirroredPositions();
                    count++;
                }while (!CheckVillagePositions(positions) && !info.IsCancellationRequested);

                if (count < 100)
                {
                    GenerateVillages(positions);
                }
            }

            while (smallFlag.Info.Count < 2 * info.NumberOfPlayers && !info.IsCancellationRequested)
            {
                GenerateResource(random.NextDouble() < 0.5 ? smallFlag : largeFlag);
            }

            while (smallFuelDepot.Info.Count < 2 * info.NumberOfPlayers && !info.IsCancellationRequested)
            {
                GenerateResource(random.NextDouble() < 0.5 ? smallFuelDepot : largeFuelDepot);
            }
        }
Exemplo n.º 16
0
    public static List <Vector3> Pathfind(TileGraph graph, Node fromNode, Node toNode)
    {
        List <Vector3> waypoints = new List <Vector3>();

        //TODO : implement Dijkstra
        List <PathfindingNode> openList   = new List <PathfindingNode>();
        List <PathfindingNode> closedList = new List <PathfindingNode>();

        Dictionary <Node, PathfindingNode> pathfindingNodes = new Dictionary <Node, PathfindingNode>();

        pathfindingNodes.Add(fromNode, new PathfindingNode(fromNode));
        openList.Add(pathfindingNodes[fromNode]);

        while (openList.Count > 0 && !DoesListContainNode(toNode, closedList))
        {
            //TODO find connections from the lowest cost so far point to all connected points
            // How do I know what the lowest cost so far is?
            openList.Sort();
            PathfindingNode smallestCostSoFar = openList[0];


            // How do we get connections?
            foreach (Node connectedNode in smallestCostSoFar.graphNode.connections.Keys)
            {
                if (!DoesListContainNode(connectedNode, closedList))
                {
                    if (!DoesListContainNode(connectedNode, openList))
                    {
                        float           costToConnectedNode = smallestCostSoFar.costSoFar + smallestCostSoFar.graphNode.connections[connectedNode];
                        PathfindingNode predecessor         = smallestCostSoFar;

                        pathfindingNodes.Add(connectedNode, new PathfindingNode(connectedNode, costToConnectedNode, predecessor));
                        openList.Add(pathfindingNodes[connectedNode]);
                    }
                    else
                    {
                        // Is my connection from the current processing node faster than the existing connectino to this node?
                        // If so, update it.

                        float currentCostToTarget            = pathfindingNodes[connectedNode].costSoFar;
                        float costToTargetThroughCurrentNode = smallestCostSoFar.costSoFar + smallestCostSoFar.graphNode.connections[connectedNode];

                        if (costToTargetThroughCurrentNode < currentCostToTarget)
                        {
                            pathfindingNodes[connectedNode].costSoFar   = costToTargetThroughCurrentNode;
                            pathfindingNodes[connectedNode].predecessor = smallestCostSoFar;
                        }
                    }
                }
            }

            closedList.Add(smallestCostSoFar);
            openList.Remove(smallestCostSoFar);
        }//end of while loop - pathfinding complete


        //TODO fill out waypoints

        //Destination node is on closed list
        //All of its predecessors are on the closed list

        for (PathfindingNode waypoint = pathfindingNodes[toNode]; waypoint != null; waypoint = waypoint.predecessor)
        {
            waypoints.Add(waypoint.graphNode.pos);
            Debug.Log(waypoint.graphNode.pos);
        }

        waypoints.Reverse();

        return(waypoints);
    }
Exemplo n.º 17
0
 public void Generate() {
     graph = GraphGenerator.GenerateGraph();
 }
Exemplo n.º 18
0
    public static Dictionary <TileNode, RenderedTileInfo> RenderNodes(TileGraph g, GameObject parent)
    {
        renderedGraph = new GameObject();
        renderedGraph.transform.position = Vector3.zero;
        if (parent != null)
        {
            renderedGraph.transform.parent = parent.transform;
        }
        GameObject origin = new GameObject();

        origin.name             = "Origin";
        origin.transform.parent = renderedGraph.transform;
        Dictionary <TileNode, RenderedTileInfo> renderedTiles = new Dictionary <TileNode, RenderedTileInfo>();

        //List<TileNode> nodesToRemove = new List<TileNode>();
        renderedTiles.Add(g.nodes[0], new RenderedTileInfo(g.nodes[0].type, Vector3.zero, 0, g.nodes[0], renderedGraph));

        // Unexplored nodes HAVE BEEN RENDERED but have not been explored for connections.
        Queue <TileNode> unexploredNodes = new Queue <TileNode>();
        // Explored nodes HAVE BEEN RENDERED and have been explored.
        List <TileNode> exploredNodes = new List <TileNode>();

        unexploredNodes.Enqueue(g.nodes[0]);
        while (unexploredNodes.Count > 0)
        {
            TileNode curr = unexploredNodes.Dequeue();
            exploredNodes.Add(curr);
            // For each node connected to this one...
            foreach (TileNode newTile in curr.connectedNodes)
            {
                if (renderedTiles.ContainsKey(newTile))
                {
                    continue;
                }
                Vector3 doorLoc   = renderedTiles[curr].GetDoorLoc();
                Vector3 firstDoor = doorLoc;
                Vector3 tileLoc   = Vector3.zero;
                float   rotation  = 0;
                bool    placeable = true;
                for (int d = 0; d < newTile.type.doorLocs.Length; d++)
                {
                    int rotationCount = 0;
                    for (rotation = (newTile.seed % 4) * 90; rotationCount < 4; rotation += 90, rotationCount++)
                    {
                        do
                        {
                            tileLoc   = doorLoc - Quaternion.Euler(0, rotation, 0) * newTile.type.doorLocs[d];
                            placeable = true;
                            for (int k = 0; k < newTile.type.boundingBoxes.Length; k++)
                            {
                                if (!newTile.type.boundingBoxes[k].IsPlaceable(tileLoc, rotation))
                                {
                                    placeable = false;
                                    break;
                                }
                            }
                            if (placeable)
                            {
                                break;
                            }
                            doorLoc = renderedTiles[curr].GetDoorLoc();
                        } while (doorLoc != firstDoor);
                        if (placeable)
                        {
                            break;
                        }
                    }
                    if (placeable)
                    {
                        break;
                    }
                }
                if (!placeable)
                {
                    continue;
                }
                RenderedTileInfo newRenderedTile = new RenderedTileInfo(newTile.type, tileLoc, rotation, newTile, renderedGraph);
                // door detection should do this.
                //renderedTiles[connections[j]].OccupyLastDoor(newRenderedTile);
                renderedTiles.Add(newTile, newRenderedTile);
                unexploredNodes.Enqueue(newTile);
            }
        }

        List <TileNode> nodesToRemove = new List <TileNode>();

        foreach (TileNode t in g.nodes)
        {
            if (!renderedTiles.ContainsKey(t))
            {
                nodesToRemove.Add(t);
            }
        }
        // Backpropogate removed nodes.
        foreach (TileNode t in nodesToRemove)
        {
            g.nodes.Remove(t);
        }
        // Backpropogate removed node connections.
        foreach (TileNode t in g.nodes)
        {
            foreach (TileNode r in nodesToRemove)
            {
                t.connectedNodes.Remove(r);
            }
        }
        // Check for other connections to remove.
        foreach (TileNode t in g.nodes)
        {
            List <TileNode> connsToRemove = new List <TileNode>();
            foreach (TileNode c in t.connectedNodes)
            {
                bool found = false;
                foreach (RenderedTileInfo r in renderedTiles[t].connectedTiles)
                {
                    if (c == r.sourceNode)
                    {
                        found = true;
                    }
                }
                if (!found)
                {
                    connsToRemove.Add(c);
                }
            }
            foreach (TileNode c in connsToRemove)
            {
                t.RemoveConnectedNode(c);
            }
        }
        return(renderedTiles);
    }
Exemplo n.º 19
0
        public void Process(Map map, MapInfo info)
        {
            if (info.Settings.Scenery.Trees.Count == 0)
            {
                return;
            }

            this.info      = info;
            this.tileGraph = new TileGraph(info.Tiles, invalidTiles);

            int min, max;

            double formula = map.Tiles.Count / 300.0;

            switch (info.Settings.NumberOfTrees)
            {
            case Frequency.High:
                min = max = (int)(formula * 6);
                break;

            case Frequency.Low:
                min = max = (int)(formula * 1.5);
                break;

            default:
                min = max = (int)(formula * 3);
                break;
            }

            Random random = new Random(info.MapId);

            IList <ScriptObject> trees = new List <ScriptObject>();

            int width  = map.HeightMap.MapWidth * (int)Map.TileWidth;
            int height = map.HeightMap.MapHeight * (int)Map.TileWidth;

            int count = random.Next(min, max + 1);

            while (trees.Count < count && !info.IsCancellationRequested)
            {
                float x = random.Next(width);
                float y = random.Next(height);
                for (int j = 0; j < random.Next(20); j++)
                {
                    float dx = (float)(random.NextDouble() * 40) + 10;
                    float dy = (float)(random.NextDouble() * 40) + 10;

                    int direction = random.Next(3);
                    switch (direction)
                    {
                    case 1:
                        dx *= -1;
                        break;

                    case 2:
                        dy *= -1;
                        break;
                    }

                    x = (x + dx + width) % width;
                    y = (y + dy + height) % height;

                    var coordinates = map.PositionToCoordinates(new Point(x, y));

                    if (info.IsWithinStartingRange(coordinates, 10))
                    {
                        continue;
                    }

                    if (IsTileValid(coordinates.X, coordinates.Y))
                    {
                        int tree = random.Next(info.Settings.Scenery.Trees.Count);
                        trees.Add(info.ObjectFactory.CreateObject(info.Settings.Scenery.Trees[tree], x, y, 0, (float)(((random.NextDouble() * 2) - 1) * System.Math.PI)));
                    }
                }
            }

            for (int i = 0; i < trees.Count - 1; i++)
            {
                if (trees[i] != null)
                {
                    for (int j = i + 1; j < trees.Count; j++)
                    {
                        if (trees[j] != null && trees[i].SquaredDistanceOnGround(trees[j]) < 100)
                        {
                            trees[j] = null;
                        }
                    }
                    map.Objects.Add(trees[i]);
                }
            }
        }