Beispiel #1
0
        public void OnTrue()
        {
//            windowOnTrueBtnClick?.Invoke(this, EventArgs.Empty);

            this.OnWindowOff();

            BlockLibrary.AddBlockToBlocksLib(_newBlock);

            _newBlock.isBlockPlaced = true; // TODO: state maschine tady začnou makat boti

            _newBlock.UpdateNeighboursActivityOnBuild();

            _newBlock.BaseCheckerNextTo?.ResetCheckerMaterial();

            // grid
            _newBlock.BlockGrid?.SetGridOrientation();

            UI.BlockBuildGizmosState(false);

            SetBuildTimer();

            // Nastavíme AUTOMATICKÝ SWTITCH CHECKERU NA DALŠÍ
            if (Settings.switchCheckers && _newBlock.Checkers.Count > 1)
            {
                SwitchFocusToAnotherChecker();
            }
            else
            {
                GameModesManager.Instance.subModesHandler.StopCurrentSubMode(typeof(BuildSubModePlace));
            }
        }
Beispiel #2
0
    // Use this for initialization
    void Start()
    {
        generationDistance = viewDistance + 2;
        initializeDistance = generationDistance + 1;
        material           = Resources.Load("Materials/GameWorld", typeof(Material)) as Material;

        dirtTexture  = Resources.Load("textures/dirt", typeof(Texture)) as Texture;
        stoneTexture = Resources.Load("textures/stone", typeof(Texture)) as Texture;
        sandTexture  = Resources.Load("textures/sand", typeof(Texture)) as Texture;


        //Resources.Load("textureSheet", type

        initializing = true;
        seed         = Random.Range(int.MinValue, int.MaxValue);
        chunkMap     = new Dictionary <string, Chunk>();

        BlockUVLibrary.Initialize();
        BlockLibrary.initialize();

        generators = new GeneratorSpec[1];
        GeneratorSpec testGenerator = new GeneratorSpec(seed, new byte[] { 0, 1, 2, 3, 4, 5 });

        generators [0] = testGenerator;

        StartCoroutine(InitialGenerate());
    }
Beispiel #3
0
    void UpdateMesh(BlockLibrary blockLibrary)
    {
        mesh.Clear();
        mesh.subMeshCount = blockLibrary.GetTypeCount();

        var vertices = new List <Vector3>();
        var normals  = new List <Vector3>();
        var UVs      = new List <Vector2>();

        int vertexCount = 0;

        foreach (KeyValuePair <int, BlockLibrary.SurfaceData> keyValuePair in surfaces)
        {
            for (int i = 0; i < keyValuePair.Value.indices.Count; ++i)
            {
                keyValuePair.Value.indices[i] += vertexCount;
            }

            vertices.AddRange(keyValuePair.Value.vertices);
            normals.AddRange(keyValuePair.Value.normals);
            UVs.AddRange(keyValuePair.Value.UVs);
            vertexCount += keyValuePair.Value.vertices.Count;
        }

        mesh.SetVertices(vertices);
        mesh.SetNormals(normals);
        mesh.SetUVs(0, UVs);

        foreach (KeyValuePair <int, BlockLibrary.SurfaceData> keyValuePair in surfaces)
        {
            mesh.SetIndices(keyValuePair.Value.indices, MeshTopology.Triangles, keyValuePair.Key);
        }
    }
Beispiel #4
0
    public void CreateNewWorld()
    {
        CreateCityHallBlock();

        BlockLibrary.AddBlockToBlocksLib(_newBlock); // Úspěšně vytvořený blok do db
        _newBlock.BuildBlock();                      // Postavíme blok
    }
Beispiel #5
0
 void Awake()
 {
     worldGenerator = GameObject.Find("WorldGenerator").transform;
     chunkManager   = worldGenerator.GetComponent <ChunkManager> ();
     blockLibrary   = worldGenerator.GetComponent <BlockLibrary> ();
     xPos           = int.Parse(transform.position.x.ToString());
     GenerateChunk();
 }
Beispiel #6
0
 void Start()
 {
     blockLibrary = GameObject.Find ("WorldGenerator").GetComponent<BlockLibrary> ();
     chunkManager = GameObject.Find ("WorldGenerator").GetComponent<ChunkManager> ();
     /*if (currentItem != null) {
         savedCurrentItem = Instantiate(currentItem);
         savedCurrentItem.SetParent(transform.Find ("arm left"));
         savedCurrentItem.localPosition = new Vector3(0f, -0.5f, 0);
         savedCurrentItem = currentItem;
     }*/
     UpdateBlocks ();
 }
Beispiel #7
0
    void Start()
    {
        blockLibrary = GameObject.Find("WorldGenerator").GetComponent <BlockLibrary> ();
        chunkManager = GameObject.Find("WorldGenerator").GetComponent <ChunkManager> ();

        /*if (currentItem != null) {
         *      savedCurrentItem = Instantiate(currentItem);
         *      savedCurrentItem.SetParent(transform.Find ("arm left"));
         *      savedCurrentItem.localPosition = new Vector3(0f, -0.5f, 0);
         *      savedCurrentItem = currentItem;
         * }*/
        UpdateBlocks();
    }
Beispiel #8
0
    /**********************************************************************************/
    //  защищаемся от повторного создания объекта
    //
    /**********************************************************************************/
    void Awake()
    {
        // защищаемся от повторного создания объекта
        if (s_instance == null)
        {
            s_instance = this;
        }
        else if (s_instance != this)
        {
            Destroy(gameObject);
        }

        // делаем GameManager неучтожимым при загрузке новой сцены (?)
        DontDestroyOnLoad(gameObject);
    }
Beispiel #9
0
    public void Init(int x, int y, WorldData worldData, BlockLibrary blockLibrary)
    {
        this.x   = x;
        this.y   = y;
        surfaces = new Dictionary <int, BlockLibrary.SurfaceData>();

        worldData.TryInit(x, y);

        transform.position = new Vector3(x, 0f, y) * WorldData.CHUNK_SIZE;

        mesh = new Mesh();
        GetComponent <MeshFilter>().mesh = mesh;

        GenerateMesh(worldData, blockLibrary);

        UpdateMesh(blockLibrary);

        GetComponent <Renderer>().materials = blockLibrary.materials.ToArray();
    }
Beispiel #10
0
 void Start()
 {
     blockLibrary = GameObject.Find ("WorldGenerator").GetComponent<BlockLibrary> ();
     chunkManager = GameObject.Find ("WorldGenerator").GetComponent<ChunkManager> ();
     transform.name = name;
     if (name == "Sapling") {
         chunkManager.DestroyDirectBlock (transform.position.x, transform.position.y, false);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y, blockLibrary.logBottom);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y + 1, blockLibrary.log);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y + 2, blockLibrary.log);
         chunkManager.PlaceDirectBlock(transform.position.x - 1, transform.position.y + 3, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x - 1, transform.position.y + 4, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x - 1, transform.position.y + 5, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y + 3, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y + 4, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y + 5, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x + 1, transform.position.y + 3, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x + 1, transform.position.y + 4, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x + 1, transform.position.y + 5, blockLibrary.leaves);
     }
 }
Beispiel #11
0
 void Start()
 {
     blockLibrary   = GameObject.Find("WorldGenerator").GetComponent <BlockLibrary> ();
     chunkManager   = GameObject.Find("WorldGenerator").GetComponent <ChunkManager> ();
     transform.name = name;
     if (name == "Sapling")
     {
         chunkManager.DestroyDirectBlock(transform.position.x, transform.position.y, false);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y, blockLibrary.logBottom);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y + 1, blockLibrary.log);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y + 2, blockLibrary.log);
         chunkManager.PlaceDirectBlock(transform.position.x - 1, transform.position.y + 3, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x - 1, transform.position.y + 4, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x - 1, transform.position.y + 5, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y + 3, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y + 4, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x, transform.position.y + 5, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x + 1, transform.position.y + 3, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x + 1, transform.position.y + 4, blockLibrary.leaves);
         chunkManager.PlaceDirectBlock(transform.position.x + 1, transform.position.y + 5, blockLibrary.leaves);
     }
 }
Beispiel #12
0
    /**********************************************************************************/
    // функция генерирует внутренности блока
    //
    // порядок генерации объектов:
    // - Здания
    // - Дороги
    // - Генерируемое окружение
    /**********************************************************************************/
    void GenerateBlockContent(GameObject block, BlockDescriptor descriptor, int x, int y)
    {
        // определяемся с ограничениями на соединение дорог
        RoadManager.GetInstance().SetRoadRulesToBlock(descriptor, x, y);


        // обновляем карту занятых и свободных клеток
        descriptor.UpdateFreeSpaceMap(SizeOfBlocks);


        // определяем тип блока для генерации
        Base.BLOCK_TYPE blockToGenerate = GetBlockTypeToGenerate();

        // олучаем настройки для данного блока из библиотеки блоков
        BlockSettings settingsForGeneration = BlockLibrary.GetInstance().GetBlockSettings(blockToGenerate);

        // устанавливаем здания
        // для это выбираем его(их) из имеющейся коллекции
        List <GameObject> toInstantiateCollection = GetBuildingToInstance(settingsForGeneration);

        foreach (GameObject toInstantiate in toInstantiateCollection)
        {
            // получаем контроллер у объекта шаблона, он нам потребуется для определения размеров здания
            BuildingController bcOfPattern = toInstantiate.GetComponent <BuildingController>();

            // пробуем установить здание в блок
            bool success  = false;
            int  attempts = 10;
            while (!success && attempts > 0)
            {
                int xBuildingSize = bcOfPattern.XBuildingSize;
                int yBuildingSize = bcOfPattern.YBuildingSize;


                int xCorToPlace = Random.Range(0, (descriptor.xSize * SizeOfBlocks) - xBuildingSize + 1);
                int yCorToPlace = Random.Range(0, (descriptor.ySize * SizeOfBlocks) - yBuildingSize + 1);

                bool isPossible = true;

                // проверяем тушку здания
                for (int xCorToCheck = xCorToPlace; xCorToCheck < xCorToPlace + xBuildingSize; xCorToCheck++)
                {
                    for (int yCorToCheck = yCorToPlace; yCorToCheck < yCorToPlace + yBuildingSize; yCorToCheck++)
                    {
                        if (descriptor.FreeSpaceMap[xCorToCheck, yCorToCheck] != true)
                        {
                            isPossible = false;
                        }
                    }
                }

                // проверяем точку выхода из здания
                if (isPossible)
                {
                    Point roadPoint = new Point(xCorToPlace, yCorToPlace) + bcOfPattern.RoadPoint;
                    if (roadPoint.x < 0 || roadPoint.y < 0 || roadPoint.x >= SizeOfBlocks || roadPoint.y >= SizeOfBlocks)
                    {
                        isPossible = false;
                    }
                    else
                    {
                        if (descriptor.FreeSpaceMap[roadPoint.x, roadPoint.y] != true)
                        {
                            isPossible = false;
                        }
                    }
                }

                // если получилось подобрать координаты, устанавливаем новое здание в позицию и выходим из цикла
                if (isPossible)
                {
                    // правильные координаты будут выставлены несколькими шагами дальше через localPosition
                    GameObject instance = Instantiate(toInstantiate, new Vector3(0.0f, 0.0f, 0.0f), Quaternion.identity) as GameObject;

                    // устанавливаем в родителя
                    instance.transform.SetParent(block.transform);
                    instance.transform.localPosition = new Vector3((float)(xCorToPlace + xBuildingSize / 2) * SizeOfCell,
                                                                   (float)(yCorToPlace + yBuildingSize / 2) * SizeOfCell, 0.0f);

                    // сохраняем ссылку на все сгенерированные здания
                    descriptor.Buildings.Add(instance);

                    // обновляем карту свободных клеток в блоке
                    descriptor.UpdateFreeSpaceMap(SizeOfBlocks);

                    success = true;
                }

                // уменьшаем оставшееся кол-во попыток
                attempts--;
            }
        }


        // достраиваем дороги
        RoadManager.GetInstance().BuildRoadInBlock(descriptor, x, y, SizeOfBlocks);

        // генерируем прочие декоротивные и не только объекты
        GenerateBlockEnviroment(block, descriptor, settingsForGeneration, SizeOfBlocks);
    }
Beispiel #13
0
    public void Awake()
    {
#if UNITY_EDITOR
        if (debugBack && VariablesStorage.levelJson == "")
        {
            SceneManager.LoadScene("GameListScene");
        }
#endif


        if (blockLibrary == null && GameObject.FindGameObjectWithTag("BlockLibrary") != null)
        {
            blockLibrary = GameObject.FindGameObjectWithTag("BlockLibrary").GetComponent <BlockLibrary>();
        }

        if (blockLibrary != null)
        {
            Debug.Log(VariablesStorage.levelJson);
            var jsonO = MiniJSON.Json.Deserialize(VariablesStorage.levelJson) as Dictionary <string, object>;

            gameEnv = jsonO["gameEnv"] as string;
            gameEnv = gameEnv.Replace("\n", "");
            dir     = Direction.DOWN;

            if (jsonO.ContainsKey("playerDir"))
            {
                dir = (Direction)(long)jsonO["playerDir"];

                Debug.Log((int)dir);
                Debug.Log((int)Direction.UP);
                Debug.Log((int)Direction.RIGHT);
                Debug.Log((int)Direction.DOWN);
                Debug.Log((int)Direction.LEFT);
            }

            Dictionary <int, (BlockType, int, Dictionary <string, string>)> dict = new Dictionary <int, (BlockType, int, Dictionary <string, string>)>();

            foreach (KeyValuePair <string, object> kvp in jsonO["blocksList"] as Dictionary <string, object> )
            {
                //dict[dict.Count] = ( GameUtility.StringToBlockType( kvp.Key.ToString() ), (int)kvp.Value );
                string[] keyargs = kvp.Key.ToString().Split(':');
                Dictionary <string, string> args = new Dictionary <string, string>();
                BlockType blockType = GameUtility.StringToBlockType(keyargs[0]);

                if (blockType == BlockType.MoveBlock)
                {
                    if (keyargs.Length - 1 >= 1)
                    {
                        args.Add("direction", keyargs[1]);
                    }
                }
                else if (blockType == BlockType.RepeatBlock)
                {
                    if (keyargs.Length - 1 >= 1)
                    {
                        args.Add("repeat_n", keyargs[1]);
                    }
                }

                dict[dict.Count] = (blockType, int.Parse(kvp.Value.ToString()), args);
            }
            blockLibrary.blockList = dict;
        }
        else
        {
            var jsonO = MiniJSON.Json.Deserialize("{" +
                                                  "\"blocksList\":{" +
                                                  "\"StartBlock\":1, " +
                                                  "\"DefineBlock\":1, " +
                                                  "\"SetBlock\":1," +
                                                  "\"ForBlock\":1," +
                                                  "}, " +
                                                  "\"gameEnv\":\"001001010010001000100013120000000001000100\"" +
                                                  "}") as Dictionary <string, object>;

            gameEnv = jsonO["gameEnv"] as string;
            gameEnv = gameEnv.Replace("\n", "");


            Dictionary <int, (BlockType, int, Dictionary <string, string>)> dict = new Dictionary <int, (BlockType, int, Dictionary <string, string>)>();

            foreach (KeyValuePair <string, object> kvp in jsonO["blocksList"] as Dictionary <string, object> )
            {
                //dict[dict.Count] = ( GameUtility.StringToBlockType( kvp.Key.ToString() ), (int)kvp.Value );
                string[] keyargs = kvp.Key.ToString().Split(':');
                Dictionary <string, string> args = new Dictionary <string, string>();
                BlockType blockType = GameUtility.StringToBlockType(keyargs[0]);

                if (blockType == BlockType.MoveBlock)
                {
                    if (keyargs.Length - 1 >= 1)
                    {
                        args.Add("direction", keyargs[1]);
                    }
                }
                else if (blockType == BlockType.RepeatBlock)
                {
                    if (keyargs.Length - 1 >= 1)
                    {
                        args.Add("repeat_n", keyargs[1]);
                    }
                }

                dict[dict.Count] = (blockType, int.Parse(kvp.Value.ToString()), args);
            }
            blockLibrary.blockList = dict;
        }
        ResetGameView();
    }
Beispiel #14
0
    void GenerateMesh(WorldData worldData, BlockLibrary blockLibrary)
    {
        //Clear mesh
        //Clear collider

        {
            foreach (KeyValuePair <int, BlockLibrary.SurfaceData> keyValuePair in surfaces)
            {
                keyValuePair.Value.Clear();
            }

            /*Array owners = staticBody.Get_shape_owners();
             * for (int i = 0; i < owners.size(); i++)
             *      staticBody.shape_owner_clear_shapes(owners[i]);*/
        }

        bool[,,] voxelMask = new bool[WorldData.CHUNK_SIZE, WorldData.WORLD_HEIGHT, WorldData.CHUNK_SIZE];

        Vector3 pos, cubeSize;

        for (int i = 0; i < WorldData.CHUNK_SIZE; i++)
        {
            for (int j = 0; j < WorldData.WORLD_HEIGHT; j++)
            {
                for (int k = 0; k < WorldData.CHUNK_SIZE; k++)
                {
                    if (!voxelMask[i, j, k] && worldData.GetBlock(x, y, i, j, k).type > 0)
                    {
                        voxelMask[i, j, k] = true;
                        cubeSize           = new Vector3(1, 1, 1);

                        for (int di = 1; di < WorldData.CHUNK_SIZE - i; di++)
                        {
                            if (voxelMask[i + di, j, k] || !worldData.GetBlock(x, y, i + di, j, k).Same(worldData.GetBlock(x, y, i, j, k)))
                            {
                                cubeSize.x += di - 1;
                                goto fullbreak1;
                            }
                            else
                            {
                                voxelMask[i + di, j, k] = true;
                            }
                        }

                        cubeSize.x += WorldData.CHUNK_SIZE - i - 1;         //This is skipped if goto fullbreak1
fullbreak1:

                        for (int dk = 1; dk < WorldData.CHUNK_SIZE - k; dk++)
                        {
                            for (int di = 0; di < cubeSize.x; di++)
                            {
                                if (voxelMask[i + di, j, k + dk] || !worldData.GetBlock(x, y, i + di, j, k + dk).Same(worldData.GetBlock(x, y, i, j, k)))
                                {
                                    cubeSize.z += dk - 1;
                                    goto fullbreak2;
                                }
                            }

                            for (int di = 0; di < cubeSize.x; di++)
                            {
                                voxelMask[i + di, j, k + dk] = true;
                            }
                        }

                        cubeSize.z += WorldData.CHUNK_SIZE - k - 1;         //This is skipped if goto fullbreak2
fullbreak2:

                        for (int dj = 1; dj < WorldData.WORLD_HEIGHT - j; dj++)
                        {
                            for (int dk = 0; dk < cubeSize.z; dk++)
                            {
                                for (int di = 0; di < cubeSize.x; di++)
                                {
                                    if (voxelMask[i + di, j + dj, k + dk] || !worldData.GetBlock(x, y, i + di, j + dj, k + dk).Same(worldData.GetBlock(x, y, i, j, k)))
                                    {
                                        cubeSize.y += dj - 1;
                                        goto fullbreak3;
                                    }
                                }
                            }

                            for (int dk = 0; dk < cubeSize.z; dk++)
                            {
                                for (int di = 0; di < cubeSize.x; di++)
                                {
                                    voxelMask[i + di, j + dj, k + dk] = true;
                                }
                            }
                        }

                        cubeSize.y += WorldData.WORLD_HEIGHT - j - 1;         //This is skipped if goto fullbreak3
fullbreak3:

                        pos = new Vector3(i, j, k);

                        var box = gameObject.AddComponent <BoxCollider>();
                        box.size   = cubeSize;
                        box.center = pos + cubeSize * 0.5f;

                        blockLibrary.AddBoxSurfaces(pos, cubeSize, blockLibrary.GetBlockType(worldData.GetBlock(x, y, i, j, k).type), ref surfaces);
                    }
                }
            }
        }
    }
Beispiel #15
0
 void Awake()
 {
     worldGenerator = GameObject.Find ("WorldGenerator").transform;
     chunkManager = worldGenerator.GetComponent<ChunkManager> ();
     blockLibrary = worldGenerator.GetComponent<BlockLibrary> ();
     xPos = int.Parse (transform.position.x.ToString ());
     GenerateChunk ();
 }
Beispiel #16
0
 private void Awake()
 {
     instance = this;
 }