Exemple #1
0
    private IEnumerator init()
    {
        this._player = GameObject.FindGameObjectWithTag("Player");

        if (NetworkClient.allClients[0] != null)
        {
            NetworkClient.allClients[0].RegisterHandler((short)NetworkMessageType.MSG_DATA_FILE_LOADING, this.recieveNetworkMessage);
            NetworkClient.allClients[0].RegisterHandler((short)NetworkMessageType.MSG_DATA_FILE_PROGRESS, this.recieveNetworkMessage);
            NetworkClient.allClients[0].RegisterHandler((short)NetworkMessageType.MSG_DATA_FILE_READY, this.recieveNetworkMessage);
        }

        while (this._islandData == null)
        {
            this._islandData = Object.FindObjectOfType <IslandData>();
            yield return(0);
        }

        WorldData.init(_islandData);

        if (!WorldData.worldGrid.readFromFile())
        {
            // Tell the server that we have to load (create) the data file.
            if (NetworkClient.allClients[0] != null)
            {
                NetworkClient.allClients[0].Send((short)NetworkMessageType.MSG_DATA_FILE_LOADING, new IntegerMessage());
            }

            StartCoroutine(calcWorldData());
        }
        else
        {
            WorldData.worldGrid.lateInit();
            WorldData.ready = true;
        }
    }
        public Island PlaceIsland(IslandData data)
        {
            var island = CreateIsland(data.Position);

            island.Initialize(data);
            return(island);
        }
Exemple #3
0
    public void GenMesh()
    {
        data = GetComponent <IslandData>();
        verts.Clear();
        tris.Clear();
        uvs.Clear();
        vertNumber = 0;

        AddTiles();
        if (verts.Count != tris.Count || verts.Count != uvs.Count)
        {
            Debug.Log(verts.Count + " " + tris.Count + " " + uvs.Count);
            Debug.Break();
        }
        //CollapseDoubles();
        //if (addNoise)
        //	AddNoise();
        //ExpandDoubles();
        //CollapseDoubles();
        Mesh mesh = GetComponent <MeshFilter>().mesh;

        mesh.Clear();
        mesh.vertices  = verts.ToArray();
        mesh.triangles = tris.ToArray();
        mesh.uv        = uvs.ToArray();
        mesh.RecalculateNormals();
        GetComponent <MeshCollider>().sharedMesh = mesh;
        Debug.Log(verts.Count);
        GetComponent <Spawner>().SpawnTrees();
        StartCoroutine(Unflatten());
    }
 static partial void FillBinaryIslandCustom(MutagenFrame frame, INavigationMapInfo item)
 {
     if (frame.ReadUInt8() > 0)
     {
         item.Island = IslandData.CreateFromBinary(frame);
     }
 }
    public IslandData Generate(WorldGenerator.IslandSize size, int seed, Vector3 position, float[][] moistureNoise, float[][] tempNoise, int numHeightLevels, bool fromTool = false)
    {
        if (_terrainSplats == null)
        {
            _terrainSplats = LoadPrototypes();
        }

        _id = IslandID++;
        int             realSize       = (int)size;
        PerlinGenerator islandNoiseGen = new PerlinGenerator();
        int             octaves        = 5;

        float[][] noise = islandNoiseGen.Generate(seed, octaves, realSize);
        float[,] heights = CreateHeightMap(noise, realSize, numHeightLevels);

        Vector3 posWithOffset = new Vector3(position.x - (realSize / 2f), position.y, position.z - (realSize / 2f));

        TerrainData tData = ApplyDataToTerrain(ref _currentTerrain, heights, realSize, numHeightLevels, fromTool);

        _currentTerrain.transform.position = posWithOffset;

        IslandData data = new IslandData(_id, realSize, posWithOffset, ref tData);

        //PopulateTiles(ref data, posWithOffset, moistureNoise, tempNoise, heights, realSize, ref tData);
        //DebugDrawGrid(posWithOffset, realSize, heights);

        PlaceDetails(heights, realSize, ref data, seed);

        return(data);
    }
Exemple #6
0
 public void Start()
 {
     Registry.Islands.Add(Uid, this.gameObject);
     InitLineRender();
     Island         = GetComponent <IslandData>();
     cameraMovement = Camera.main.GetComponent <MoveCamera>();
 }
        public virtual void Start()
        {
            _startTime = 0;

            if (Game.IsSinglePlayer())
            {
                Island = GetComponent <IslandData>();
            }
        }
        public void Initialize(IslandData source)
        {
            Name      = source.Name;
            Alignment = source.Alignment;
            level     = source.Level;
            resources = source.CurrentResources;

            Startup();
        }
        void ReloadIsland(IslandData islandData, int i)
        {
            pooledMinimapIsland[i].RegionName           = islandData.RegionName;
            pooledMinimapIsland[i].transform.localScale = new Vector3(islandData.IslandSize.x, 1, islandData.IslandSize.z);

            pooledMinimapIsland[i].transform.position = islandData.GCECoord;
            pooledMinimapIsland[i].transform.rotation = Quaternion.identity;
            pooledMinimapIsland[i].gameObject.name    = islandData.RegionName;
        }
    public IslandData GenerateDungeon()
    {
        rnd = new System.Random(randomSeed);

        currentIsland = new IslandData(mapWidth, mapHeight);

        GenerateTiles();

        return(currentIsland);
    }
Exemple #11
0
    void Start()
    {
        _islands = new List <IslandData>(NumberOfIslands);

        // TODO
        // will need to load the save file and get the seed
        // if there is no save, create a new seed
        if (WorldSeed == -1)
        {
            WorldSeed = UnityEngine.Random.Range(0, int.MaxValue);
        }

        GenerateWorld(WorldSeed);

        _currentIsland = _islands[0];
    }
Exemple #12
0
    public static void init(IslandData data)
    {
        _ready = false;

        _cellCount = data.cellCount;
        _worldSize = data.worldSize;
        _cellSize  = worldSize / cellCount;
        _yOffsets  = data.yOffsets;
        _name      = data.name;

        _xzOffset = new Vector2(
            -(cellCount * cellSize / 2.0f + cellSize / 2.0f),
            -(cellCount * cellSize / 2.0f + cellSize / 2.0f)
            );

        _worldGrid = new WorldGrid(name, yOffsets, xzOffset, cellCount, worldSize);
    }
Exemple #13
0
    public void SetIslandList()
    {
        stage = CSVReader.Read("stage_demo");
        Debug.Log("stage count : " + stage);
        for (int i = 0; i < stage.Count; i++)
        {
            int title = int.Parse(stage[i]["title"].ToString());

            Map newMap = Instantiate(mapPrefab, default);
            newMap.map_title  = stage[i]["title_text"].ToString();
            newMap.total_snow = int.Parse(stage[i]["snow_total"].ToString());
            int width  = int.Parse(stage[i]["width"].ToString());
            int height = int.Parse(stage[i]["height"].ToString());


            List <List <int> > datas  = MapString(stage[i]["data"].ToString().Split(','), height, width);
            List <List <int> > styles = new List <List <int> >();


            for (int h = 0; h < height; h++)
            {
                for (int w = 0; w < width; w++)
                {
                    int blockNumber = datas[h][w];
                    styles.Add(GetStyleList(blockNumber, title));
                }
            }

            //           Debug.Log(stage[i]["posA"].ToString());
            Vector3    posA       = GetVector3(stage[i]["posA"].ToString().Split('/'));
            Vector3    posB       = GetVector3(stage[i]["posB"].ToString().Split('/'));
            bool       isParfait  = int.Parse(stage[i]["parfait"].ToString()) == 0 ? false : true;
            List <int> star_limit = GetList(stage[i]["star_limit"].ToString().Split('/'));

            newMap.Initialize(new Vector2(height, width), isParfait, posA, posB, datas, styles, star_limit);
            newMap.transform.SetParent(transform);

            islands[title].maps.Add(newMap);
        }

        islandData = new IslandData(islands[0].maps.Count,
                                    islands[1].maps.Count,
                                    islands[2].maps.Count,
                                    islands[3].maps.Count,
                                    islands[4].maps.Count);
    }
Exemple #14
0
    private void MakeNewIsland(IslandGenerator gen, int islandSeed, float[][] moistNoise, float[][] tempNoise)
    {
        System.Random islandPRNG = new System.Random(islandSeed);

        IslandSize size              = DetermineIslandSize(islandPRNG.Next());
        int        islandSize        = (int)size;
        int        x                 = islandPRNG.Next(islandSize, MaxWorldSize - islandSize);
        int        z                 = islandPRNG.Next(islandSize, MaxWorldSize - islandSize);
        Vector3    position          = new Vector3(x, 0f, z);
        int        numOfHeightLevels = islandPRNG.Next(MinNumberOfHeightLevels) + MinNumberOfHeightLevels;  // dont want island with < min height levels

        // should check to make sure islands can't overlap each other

        // copy out the relevant climate noise
        float[][] islandSpecificMoistureData = new float[islandSize][];
        float[][] islandSpecificTempData     = new float[islandSize][];
        //Debug.LogFormat("specific: {0}x{1}", islandSpecificBiomeData.Length, islandSpecificBiomeData[0].Length);
        //Debug.LogFormat("base: {0}x{1}", biomeNoise.Length, biomeNoise[0].Length);

        for (int i = 0; i < islandSize; ++i)
        {
            islandSpecificMoistureData[i] = new float[islandSize];
            islandSpecificTempData[i]     = new float[islandSize];

            for (int j = 0; j < islandSize; ++j)
            {
                //Debug.LogFormat("specific -> i: {0}, j:{1}, base -> i:{2} j:{3}",i, j, i + x, j + z);
                islandSpecificMoistureData[i][j] = moistNoise[i + x][j + z];
                islandSpecificTempData[i][j]     = tempNoise[i + x][j + z];
            }
        }


        Debug.LogFormat("new island at {0} of size {1} with {2} levels ({3})", position, size.ToString(), numOfHeightLevels, islandSeed);

        // TODO
        // create an island data class that will be returned from this function
        // should hold things like:
        // tile array, native species of plants/vegetables/etc, general climate, size, soil classification, ...

        IslandData data = gen.Generate(size, islandSeed, position, islandSpecificMoistureData, islandSpecificTempData, numOfHeightLevels);

        _islands.Add(data);
    }
        public void FixedUpdate()
        {
            if (!Game.IsRunning())
            {
                return;
            }

            _startTime += Time.deltaTime;
            if (_startTime < AssaultShipData.AttackSpeed)
            {
                return;
            }
            _startTime -= AssaultShipData.AttackSpeed;

            // current island
            var islandData = transform.parent.gameObject.GetComponent <IslandData>();

            // current enemy ships
            var enemyShips = IslandData.GetEnemyShips(islandData, AssaultShipData.PlayerData.uid);

            // 1) if is enemy island and has no there are no enemy ships => convert
            if (IsOnEnemyIsland() && enemyShips.Count == 0)
            {
//                Debug.Log(ShipData.uid + " invades " + transform.parent.gameObject.GetComponent<IslandData>().uid);
                islandData.Convert(AssaultShipData.PlayerData);
            }

            // 2) attack every enemy ship
            if (enemyShips.Count <= 0)
            {
                return;
            }

            var enemyShip = (GameObject)enemyShips[Random.Range(0, enemyShips.Count)]; // Important! actual range 0 to list size - 1
//            Debug.Log(ShipData.playerUid +"[" + ShipData.uid + "] attacks " + enemyShip.GetComponent<ShipData>().playerUid + "[" + enemyShip.GetComponent<ShipData>().uid + "]");

            var rocket    = Prefabs.Instance.GetNewRocket();
            var behaviour = rocket.AddComponent <RocketMove>();

            behaviour.Attacker     = gameObject.transform.position;
            behaviour.AttackDamage = AssaultShipData.AttackDamage;
            behaviour.Defender     = enemyShip;
            behaviour.Velocity     = 0.6f;
        }
        private void LateUpdate()
        {
            if (Selection.activeGameObject != null)
            {
                if (Selection.activeGameObject.GetComponent <OverworldEditor_Island>() != null)
                {
                    disableUpdate = false;
                }
                else
                {
                    disableUpdate = true;
                }
            }
            else
            {
                disableUpdate = true;
            }

            if (disableUpdate)
            {
                return;
            }
            foreach (OverworldEditor_Island editor_Island in pooledMinimapIsland)
            {
                if (editor_Island == null)
                {
                    continue;
                }
                else if (mapData.GlobalIslands.Find(x => x.RegionName == editor_Island.RegionName) == null)
                {
                    continue;
                }

                Vector3 GCE_Coord = editor_Island.transform.position;
                GCE_Coord.x = Mathf.Floor(GCE_Coord.x);
                GCE_Coord.y = Mathf.Floor(GCE_Coord.y);
                GCE_Coord.z = Mathf.Floor(GCE_Coord.z);

                IslandData islandData = mapData.GlobalIslands.Find(x => x.RegionName == editor_Island.RegionName);
                islandData.GCECoord = GCE_Coord;
            }
        }
Exemple #17
0
 public void SpawnTrees()
 {
     data = GetComponent <IslandData>();
     for (int i = 0; i < treeCount; i++)
     {
         Tile       t    = new List <Tile>(data.tiles.Values)[Random.Range(0, data.tiles.Count)];
         GameObject tree = gameObject;
         if (t.landType == 0)
         {
             tree = Instantiate(palm, t.verts[6], Quaternion.Euler(0, Random.Range(0, 360), 0)) as GameObject;
         }
         if (t.landType == 1)
         {
             tree = Instantiate(blob, t.verts[6], Quaternion.Euler(0, Random.Range(0, 360), 0)) as GameObject;
         }
         else if (t.landType == 2)
         {
             tree = Instantiate(pine, t.verts[6], Quaternion.Euler(0, Random.Range(0, 360), 0)) as GameObject;
         }
         tree.transform.parent = transform;
     }
 }
    private void PopulateTiles(ref IslandData data, Vector3 terrainPos, float[][] moisture, float[][] temps, float[,] heights, int size, ref TerrainData tData)
    {
        GameObject container = new GameObject();

        container.name = "Tile Colliders";
        container.transform.SetParent(_currentTerrain.transform);
        container.transform.position = Vector3.zero;
        GameObject tileObject    = null;
        Tile       t             = null;
        int        tilesPerMeter = 3;

        //int[] offsets = new int[] { 0, 4, 7, 10, 13, 16, 19 };
        //float[,,] splatData = new float[size, size, _terrainSplats.Length];

        float   subTileOffset  = 1 / (float)tilesPerMeter;
        Vector3 offsetPosition = new Vector3(0f, 0.05f, 0f);

        for (int i = 0; i < size; ++i)
        {
            for (int j = 0; j < size; ++j)
            {
                float height = heights[j, i];

                // don't put tiles on the bottom most layer
                if (height > 0f)
                {
                    int terrainX, terrainY;
                    GetWorldTerrainPosition(terrainPos, i, j, out terrainX, out terrainY);

                    GameObject tileContainer = new GameObject();
                    tileContainer.name = string.Format("Tile[{0},{1}]", i, j);
                    tileContainer.transform.SetParent(container.transform);
                    tileContainer.transform.position = Vector3.zero;

                    // for multiple tiles per meter
                    for (int k = 0; k < tilesPerMeter; ++k)
                    {
                        for (int l = 0; l < tilesPerMeter; ++l)
                        {
                            // create physical tile
                            offsetPosition.x = (subTileOffset / 2f) + subTileOffset * k;
                            offsetPosition.z = (subTileOffset / 2f) + subTileOffset * l;

                            tileObject      = (GameObject)Instantiate(_tilePrefab);
                            tileObject.name = string.Format("Sub Tile[{0},{1}]", k, l);
                            t = tileObject.AddComponent <Tile>();
                            t.Init(i, j, height, terrainX + offsetPosition.z, terrainY + offsetPosition.x);
                            tileObject.transform.position = t.WorldPosition;

                            // add to parent container for a neat hierarchy
                            tileObject.transform.SetParent(tileContainer.transform);
                        }
                    }

                    // determine biome
                    eMoisture    moist = GetMoistureEnumFromValue(moisture[i][j]);
                    eTemperature temp  = GetTempEnumFromValue(temps[i][j]);
                    eBiome       biome = _biomeTable[(int)moist, (int)temp];

                    t.SetBiomeFields(moist, temp, biome);

                    // set terrain texture
                    //int textureIndex = offsets[(int)biome] + (int)eTileType.Grass;
                    //splatData[j, i, textureIndex] = 1;
                }
                else
                {
                    // just dirt if height is zero
                    //int textureIndex = offsets[(int)eBiome.Jungle] + (int)eTileType.Dirt;
                    //splatData[j, i, textureIndex] = 1;
                }

                // need to fill the island data with values, even if no tile is actually created
                data.AddTile(t, i, j);
            }
        }

        //tData.SetAlphamaps(0, 0, splatData);
    }
Exemple #19
0
 public MissionData(IslandData island) => MissionIsland = island;
    private void PlaceDetails(float[,] heights, int size, ref IslandData data, int seed)
    {
        System.Random prng            = new System.Random(seed);
        int           noiseSeed       = prng.Next();
        GameObject    detailContainer = new GameObject();

        detailContainer.name = "Details Container";
        detailContainer.transform.SetParent(_currentTerrain.transform);
        eBiome currentBiome = eBiome.Forest;

        PerlinGenerator detailNoiseGen = new PerlinGenerator();

        float[][] noise = detailNoiseGen.Generate(noiseSeed, 3, size);

        int detailID = -1;

        for (int i = 0; i < size; ++i)
        {
            for (int j = 0; j < size; ++j)
            {
                detailID = -1;
                bool  changeScale = false;
                float height      = heights[j, i];
                if (height > 0f)
                {
                    float value = noise[i][j];
                    //currentBiome = data.GetTile(i, j).Biome;

                    // slope
                    // need to map x/z to terrain space
                    float y_01 = (float)i / (float)size;
                    float x_01 = (float)j / (float)size;

                    // Calculate the steepness of the terrain
                    float steepness = data.Data.GetSteepness(y_01, x_01);

                    if (steepness < _maxVegetationSlope)
                    {
                        if (value > 0.85f)
                        {
                            detailID    = (int)eDetailType.Tree;
                            changeScale = true;

                            if (value > 0.95f)
                            {
                                // TODO set scale modifier here or something
                                //detail = _detailObjects[(int)DetailType.Tree_Pine_0];
                            }
                            else if (value > 0.9f)
                            {
                                //detail = _detailObjects[(int)DetailType.Tree_Pine_1];
                            }
                            else
                            {
                                //detail = _detailObjects[(int)DetailType.Tree_Pine_2];
                            }
                        }
                        else if (value > 0.75f)
                        {
                            detailID = (int)eDetailType.Flower;
                            //detail = _detailObjects[(int)DetailType.Flower_Bud];
                        }
                        else if (value > 0.68f)
                        {
                            detailID = (int)eDetailType.Grass;
                            //detail = _detailObjects[(int)DetailType.Grass];
                        }
                        else if (value > 0.65f)
                        {
                            detailID = (int)eDetailType.Fern;
                            //detail = _detailObjects[(int)DetailType.Fern];
                        }
                        else if (value < 0.025f)
                        {
                            detailID = (int)eDetailType.Rock;
                            //detail = _detailObjects[(int)DetailType.Rock_Medium];
                        }

                        //if (detail != null)
                        if (detailID > -1)
                        {
                            //GameObject detail = null;
                            GameObject detail    = GetDetailsForBiome(currentBiome)[detailID];
                            GameObject detailObj = (GameObject)Instantiate(detail, Vector3.zero, Quaternion.identity);

                            float angle = prng.Next(359) + 1;
                            detailObj.transform.Rotate(Vector3.up, angle);

                            if (changeScale)
                            {
                                float scaleFactor = (float)prng.NextDouble() + 0.25f;
                                detailObj.transform.localScale = new Vector3(scaleFactor, scaleFactor, scaleFactor);
                            }

                            detailObj.transform.SetParent(detailContainer.transform);

                            // need to place a tile here
                            PlaceTile(i, j, ref data, _currentTerrain.transform.position);

                            data.AddObjectToTile(detailObj, i, j);
                        }
                    }
                }
            }
        }
    }
Exemple #21
0
 public MinPointIslandData(uint minPoint, IslandData islandData)
 {
     MinPoint   = minPoint;
     IslandData = islandData;
 }
        public override void UpdateAfterSimulation()
        {
            base.UpdateAfterSimulation();

            m_rootIslands.Clear();
            m_rootEntityIslandIndex.Clear();

            var clusterList = MyPhysics.GetClusterList();

            if (clusterList != null)
            {
                foreach (Havok.HkWorld havokWorld in MyPhysics.GetClusterList())
                {
                    var islandCount = havokWorld.GetActiveSimulationIslandsCount();

                    for (int i = 0; i < islandCount; i++)
                    {
                        havokWorld.GetActiveSimulationIslandRigidBodies(i, m_rigidBodies);

                        HashSet <IMyEntity> island = null;

                        foreach (var rigidBody in m_rigidBodies)
                        {
                            var ents = rigidBody.GetAllEntities();
                            foreach (var entity in ents)
                            {
                                var topParent = entity.GetTopMostParent();

                                foreach (var rootIsland in m_rootIslands)
                                {
                                    if (rootIsland.RootEntities.Contains(topParent))
                                    {
                                        island = rootIsland.RootEntities;
                                        break;
                                    }
                                }
                            }
                            ents.Clear();
                        }

                        if (island == null)
                        {
                            IslandData islandData = new IslandData()
                            {
                                AABB           = BoundingBoxD.CreateInvalid(),
                                RootEntities   = new HashSet <IMyEntity>(),
                                ClientPriority = new Dictionary <ulong, float>()
                            };
                            island = islandData.RootEntities;
                            m_rootIslands.Add(islandData);
                        }

                        foreach (var rigidBody in m_rigidBodies)
                        {
                            var ents = rigidBody.GetAllEntities();
                            foreach (var entity in ents)
                            {
                                var topParent = entity.GetTopMostParent();
                                island.Add(topParent);
                            }
                            ents.Clear();
                        }

                        m_rigidBodies.Clear();
                    }
                }

                for (int i = 0; i < m_rootIslands.Count; i++)
                {
                    var islandData = m_rootIslands[i];
                    islandData.AABB = BoundingBoxD.CreateInvalid();

                    foreach (var entity in islandData.RootEntities)
                    {
                        islandData.AABB.Include(entity.PositionComp.WorldAABB);

                        m_rootEntityIslandIndex[entity] = i;
                    }

                    m_rootIslands[i] = islandData;
                }
            }
        }
 private bool HasReachedMaxSpawn()
 {
     return(Game.Shared.World.MaxPopulationLimitReached() || IslandData.AmountFriendlyUnits(Island) >= Island.MaxSpawn);
 }
    void AddIsland(int islandSize)
    {
        if (islandSize < 2)
        {
            islandSize = 2;
        }
        List <Vector2Int> tiles     = new List <Vector2Int>();
        List <Vector2Int> possTiles = new List <Vector2Int>();

        IslandData currentIsland = new IslandData();
        Vector2Int loc           = new Vector2Int(Random.Range(-worldSize, worldSize), Random.Range(-worldSize, worldSize));
        int        x             = 0;

        while (usedTiles.Contains(loc))
        {
            if (x >= 10)
            {
                worldSize++;
                x = 0;
                Debug.Log("X");
            }
            Vector3 spot = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f)) * worldSize;
            loc = HexGrid.RoundToGrid(spot);
            x++;
        }
        tiles.Add(loc);

        foreach (Vector2Int v in HexGrid.FindAdjacentGridLocs(loc))
        {
            if (!tiles.Contains(v) && !possTiles.Contains(v) && !usedTiles.Contains(v))
            {
                possTiles.Add(v);
            }
        }
        while (tiles.Count < islandSize && possTiles.Count > 0)
        {
            Vector2Int tile = possTiles[Random.Range(0, possTiles.Count)];
            foreach (Vector2Int v in HexGrid.FindAdjacentGridLocs(tile))
            {
                if (!tiles.Contains(v) && !possTiles.Contains(v) && !usedTiles.Contains(v))
                {
                    possTiles.Add(v);
                }
            }
            possTiles.Remove(tile);
            tiles.Add(tile);
        }
        if (tiles.Count == islandSize)
        {
            foreach (Vector2Int v in HexGrid.FindOutline(tiles))
            {
                tiles.Add(v);
            }
            List <Vector2Int> remove = new List <Vector2Int>();
            remove.AddRange(tiles);
            remove.AddRange(HexGrid.FindOutline(remove));
            remove.AddRange(HexGrid.FindOutline(remove));
            remove.AddRange(HexGrid.FindOutline(remove));

            foreach (Vector2Int v in remove)
            {
                usedTiles.Add(v);
            }
            foreach (Vector2Int v in tiles)
            {
                currentIsland.tiles.Add(new WorldTile(v));
                currentIsland.gridLocs.Add(v);
            }
            foreach (Vector2Int v in tiles)
            {
                foreach (Vector2Int adj in HexGrid.FindAdjacentGridLocs(v))
                {
                    if (tiles.Contains(adj))
                    {
                        currentIsland.tiles[currentIsland.gridLocs.IndexOf(v)].connections.Add(adj);
                    }
                }
            }
            currentIsland.CalcHeights();
            islands.Add(currentIsland);
        }
        else
        {
            AddIsland(islandSize);
        }
    }
Exemple #25
0
 public void SetCurrentIsland(int id)
 {
     _currentIsland = _islands[id];
     Debug.Log("Current island is now " + id);
 }
    public void PlaceTile(float x, float z, ref IslandData data, Vector3 terrainPos)
    {
        TerrainData tData = data.Data;

        float[,] heights = tData.GetHeights(0, 0, data.Size, data.Size);
        int     tilesPerMeter  = 3;
        float   subTileOffset  = 1 / (float)tilesPerMeter;
        Vector3 offsetPosition = new Vector3(0f, 0.05f, 0f);
        int     i = Mathf.RoundToInt(x);
        int     j = Mathf.RoundToInt(z);

        if (_tileContainer == null)
        {
            _tileContainer = new GameObject("Tile Container");
            _tileContainer.transform.SetParent(_currentTerrain.transform);
            _tileContainer.transform.localPosition = Vector3.zero;
        }

        float      height     = heights[j, i];
        GameObject tileObject = null;
        Tile       t          = null;

        // don't put tiles on the bottom most layer
        if (height > 0f)
        {
            int terrainX, terrainY;
            GetWorldTerrainPosition(terrainPos, i, j, out terrainX, out terrainY);

            // TODO this will need to be removed and only 1 tile be placed; not all 9

            //for multiple tiles per meter
            for (int k = 0; k < tilesPerMeter; ++k)
            {
                for (int l = 0; l < tilesPerMeter; ++l)
                {
                    // create physical tile
                    offsetPosition.x = (subTileOffset / 2f) + subTileOffset * k;
                    offsetPosition.z = (subTileOffset / 2f) + subTileOffset * l;

                    tileObject      = (GameObject)Instantiate(_tilePrefab);
                    tileObject.name = string.Format("Sub Tile[{0},{1}]", k, l);
                    t = tileObject.AddComponent <Tile>();
                    t.Init(i, j, height, terrainX + offsetPosition.z, terrainY + offsetPosition.x);
                    tileObject.transform.position = t.WorldPosition;

                    // add to parent container for a neat hierarchy
                    tileObject.transform.SetParent(_tileContainer.transform);
                }
            }

            // determine biome
            eMoisture    moist = eMoisture.Wet;       //GetMoistureEnumFromValue(moisture[i][j]);
            eTemperature temp  = eTemperature.Normal; //GetTempEnumFromValue(temps[i][j]);
            eBiome       biome = _biomeTable[(int)moist, (int)temp];

            t.SetBiomeFields(moist, temp, biome);

            // set terrain texture
            //int textureIndex = offsets[(int)biome] + (int)eTileType.Grass;
            //splatData[j, i, textureIndex] = 1;
        }
        else
        {
            // just dirt if height is zero
            //int textureIndex = offsets[(int)eBiome.Jungle] + (int)eTileType.Dirt;
            //splatData[j, i, textureIndex] = 1;
        }

        // need to fill the island data with values, even if no tile is actually created
        data.AddTile(t, i, j);
    }
Exemple #27
0
 public void AddIsland(IslandData _island)
 {
     islands.Add(_island);
 }
Exemple #28
0
    private void MakeIslandConnections(Vector2 _ourIslandLocalCoordinates, int _pathWidth, MapData _mapData, int _mapChunkSize)
    {
        int activeConnectionsAmount = 0;

        //a dictionary with the distance between us and the other island, and chunkcoordinates of the other island
        Dictionary <float, IslandData> shortestDistanceIslandsData = new Dictionary <float, IslandData>();
        float longestDistanceInDict = 0;

        for (int n = 0; n < _mapData.allNeighboursCoords.Count; n++)
        {
            if (islandsChunkContainer.ContainsKey(_mapData.allNeighboursCoords[n]))
            {
                Vector2 chunkOffset = _mapData.coordinate - _mapData.allNeighboursCoords[n];

                for (int i = 0; i < islandsChunkContainer[_mapData.allNeighboursCoords[n]].Count; i++)
                {
                    IslandData otherIsland = islandsChunkContainer[_mapData.allNeighboursCoords[n]][i];

                    Vector2 vertorDifference = _ourIslandLocalCoordinates - otherIsland.localCoordinates + new Vector2(chunkOffset.x * _mapChunkSize, chunkOffset.y * _mapChunkSize);

                    if (Mathf.Abs(vertorDifference.x) < maxAxisDifference || Mathf.Abs(vertorDifference.y) < maxAxisDifference)
                    {
                        float dist = Vector2.Distance(
                            new Vector2(_ourIslandLocalCoordinates.x + (_mapData.coordinate.x * _mapChunkSize), _ourIslandLocalCoordinates.y + (_mapData.coordinate.y * _mapChunkSize)),
                            new Vector2(otherIsland.localCoordinates.x + (otherIsland.chunkCoordinates.x * _mapChunkSize), otherIsland.localCoordinates.y + (otherIsland.chunkCoordinates.y * _mapChunkSize))
                            );

                        if (!shortestDistanceIslandsData.ContainsKey(dist))
                        {
                            //add the first few results we get to the list
                            if (shortestDistanceIslandsData.Count < maxSearchableIslands)
                            {
                                shortestDistanceIslandsData.Add(dist, otherIsland);

                                //increment our connections amount, and the other islands connections amount
                                activeConnectionsAmount++;
                                otherIsland.IncrementConnections();
                            }//then if we get more results, check if they are lower that our highest distance result, and if so replace them
                            else
                            {
                                longestDistanceInDict = FindLongestDistance(shortestDistanceIslandsData);

                                if (dist < longestDistanceInDict)
                                {
                                    shortestDistanceIslandsData.Remove(longestDistanceInDict);
                                    shortestDistanceIslandsData.Add(dist, otherIsland);
                                }
                            }
                        }

                        break;
                    }
                }
            }
        }

        //randomconnectionamout is random between chosen min and max, and cannot be greater than maxSearchableIslands
        int randomConnectionsAmount = Random.Range(minRandomConnections, maxRandomConnections);

        if (shortestDistanceIslandsData.Count > 0)
        {
            if (randomConnectionsAmount > maxSearchableIslands)
            {
                randomConnectionsAmount = maxSearchableIslands;
            }

            //out of all the closest islands (limited maxSearchableIsland), a random amount of of random connections are picked.
            List <float> closestIslandsKeysleftOvers = new List <float>(shortestDistanceIslandsData.Keys);

            for (int i = 0; i < randomConnectionsAmount; i++)
            {
                int randomIndex = Random.Range(0, closestIslandsKeysleftOvers.Count);

                Paths.CreatePathChunksOverflow(_mapData.coordinate, shortestDistanceIslandsData[closestIslandsKeysleftOvers[randomIndex]].chunkCoordinates, _ourIslandLocalCoordinates, shortestDistanceIslandsData[closestIslandsKeysleftOvers[randomIndex]].localCoordinates, 0, _pathWidth, pathSmoothness, false, _mapChunkSize);
                closestIslandsKeysleftOvers.Remove(randomIndex);
            }
        }
        if (activeConnectionsAmount < randomConnectionsAmount)
        {
            islandsChunkContainer[_mapData.coordinate].Add(new IslandData(activeConnectionsAmount, randomConnectionsAmount, _ourIslandLocalCoordinates, _mapData.coordinate));
        }
    }