Ejemplo n.º 1
0
    bool IsChunkInLoadDistance(int chunkIndex)
    {
        float   firstTileAngle    = (float)chunkIndex / (float)chunks.Length * Mathf.PI * 2f;
        Vector2 firstTilePosition = ChunkController.RotateAroundPoint(transform.position, firstTileAngle, radius);

        return(Vector2.Distance(transform.TransformPoint(firstTilePosition), Camera.main.transform.position) <= chunkLoadDistance);
    }
Ejemplo n.º 2
0
    void LoadChunk(int chunkIndex)
    {
        ChunkController newChunk = chunkObjectPool.Spawn(transform.position, Quaternion.identity, transform).GetComponent <ChunkController>();

        newChunk.Init(chunkIndex);
        chunks[chunkIndex] = newChunk;
    }
Ejemplo n.º 3
0
    void LightChunks()
    {
        WorldController world       = GameObject.FindGameObjectWithTag("World").GetComponent <WorldController>();
        ChunkController lowerchunk  = world.GetChunk(ChunkID - 1);
        ChunkController higherchunk = world.GetChunk(ChunkID + 1);

        if (lowerchunk != null)
        {
            lowerchunk.ResetLight();
        }
        if (higherchunk != null)
        {
            higherchunk.ResetLight();
        }
        currentChunk.ResetLight();
        if (lowerchunk != null)
        {
            lowerchunk.LightUpdate(false);
        }
        if (higherchunk != null)
        {
            higherchunk.LightUpdate(false);
        }
        currentChunk.LightUpdate(false);
    }
Ejemplo n.º 4
0
        /// <summary>
        /// Try to get a chunk controller named with the given ID
        /// </summary>
        /// <param name="chunkControllerID"></param>
        /// <param name="chunkController"></param>
        /// <returns></returns>
        public bool tryToGetChunkControllerByID(int chunkControllerID, out ChunkController chunkController)
        {
            chunkController = null;

            /// check used chunks
            foreach (ChunkController controller in usedChunkControllers.Values)
            {
                if (controller.gameObject.name.Contains($"#{chunkControllerID}#"))
                {
                    chunkController = controller;

                    return(true);
                }
            }

            /// check free chunks
            foreach (ChunkController controller in freeChunkControllerPool)
            {
                if (controller.gameObject.name.Contains($"#{chunkControllerID}#"))
                {
                    chunkController = controller;

                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 5
0
 public List <Transform> GetAdjacent()
 {
     if (adjacentcoords.Count == 0)
     {
         CalculateAdjacent();
     }
     adjacenttiles = new List <Transform>();
     foreach (int[] coords in adjacentcoords) // For all adjacent co-ordinates
     {
         if (coords[0] == chunkID)
         {
             //Debug.Log(coords[1] + " " + coords[2]);
             try
             {
                 adjacenttiles.Add(currentChunk.tiles[coords[1], coords[2]]); // Add the tile from the current chunk
             }
             catch
             {
                 Debug.Log("Error in GetAdjacent()! Tried to access tile with co-ords: " + coords[1] + " " + coords[2]);
             }
         }
         else
         {
             WorldController world        = GameObject.FindGameObjectWithTag("World").GetComponent <WorldController>();
             ChunkController fetchedchunk = world.GetChunk(coords[0]);                     // Get an adjacent chunk
             if (fetchedchunk != null)                                                     // If the chunk is loaded,
             {
                 adjacenttiles.Add(world.GetChunk(coords[0]).tiles[coords[1], coords[2]]); // Get the tile
             }
         }
     }
     return(adjacenttiles); // Return the adjacent tiles
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Get an unused chunk controller from the pool we made, while also making sure the chunk isn't already part of said pool.
        /// </summary>
        /// <returns></returns>
        bool getUnusedChunkController(Coordinate chunkLocationToSet, out ChunkController unusedChunkController)
        {
            unusedChunkController = null;
            bool foundUnusedController = false;

            foreach (ChunkController chunkController in chunkControllerPool)
            {
                // if the chunk is active and already has the location we're looking for, we return false
                if (chunkController.isActive) // these ifs are seprate because of the else if below.
                {
                    if (chunkController.chunkLocation == chunkLocationToSet)
                    {
                        if (unusedChunkController != null)
                        {
                            unusedChunkController.isActive = false;
                            unusedChunkController          = null;
                        }

                        return(false);
                    }
                    // if we found an inactive controller, and we're still looking for that, lets snag it and stop looking.
                }
                else if (!foundUnusedController)
                {
                    chunkController.isActive = true;
                    unusedChunkController    = chunkController;
                    foundUnusedController    = true;
                }
            }

            // return true if we never found a chunkController already set to this new chunk location.
            return(foundUnusedController);
        }
Ejemplo n.º 7
0
 public object CaptureState()
 {
     foreach (Vector2 chunkCoord in terrainChunkDictionary.Keys)
     {
         data[chunkCoord.ToString()] = ChunkController.MapToOneDimensionalMap(terrainChunkDictionary[chunkCoord].GetMap());
     }
     return(data);
 }
Ejemplo n.º 8
0
    private ChunkController SpawnChunk(Vector2 viewedChunkCoord)
    {
        ChunkController chunk = Instantiate(chunkObject, new Vector3(viewedChunkCoord.x * chunkSize, viewedChunkCoord.y * chunkSize, 0), Quaternion.identity).GetComponent <ChunkController>();

        chunk.transform.SetParent(transform);
        chunk.SetNoiseScale(noiseScale + 0.123f);
        return(chunk);
    }
Ejemplo n.º 9
0
 void Start()
 {
     chunks         = vm.components.chunks;
     chunkSize      = chunks.chunkSize;
     chunkPositions = ChunkLoadOrder.ChunkPositions(chunkLoadRadius);
     distanceToDeleteInUnitsSquared  = (int)(DistanceToDeleteChunks * chunkSize * chunks.blockSize);
     distanceToDeleteInUnitsSquared *= distanceToDeleteInUnitsSquared;
 }
Ejemplo n.º 10
0
 public void AssignCoords(int xloc, int yloc, int chunkIDval, ChunkController chunk)
 {
     x              = xloc;
     y              = yloc;
     chunkID        = chunkIDval;
     currentChunk   = chunk;
     adjacentcoords = new List <int[]>(); // Store block metadata
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Initilize the level queue manager to follow the foci and appetures of the level
        /// </summary>
        /// <param name="level"></param>
        public void initializeFor(Level level)
        {
            if (chunkObjectPrefab == null)
            {
                World.Debugger.logError("UnityLevelController Missing chunk prefab, can't work");
            }
            else if (level == null)
            {
                World.Debugger.logError("No level provided to level controller");
            }
            else
            {
                /// init
                this.level = level;

                // build the controller pool based on the maxed meshed chunk area we should ever have:
                ChunkResolutionAperture meshResolutionAperture = level.getApetureByPriority(Level.AperturePriority.Meshed);
                int diameterToMeshManager = meshResolutionAperture != null ? meshResolutionAperture.managedChunkRadius : level.chunkBounds.x;
                chunkControllerPool = new ChunkController[diameterToMeshManager * diameterToMeshManager * level.chunkBounds.y * 2];
                for (int index = 0; index < chunkControllerPool.Length; index++)
                {
                    // for each chunk we want to be able to render at once, create a new pooled gameobject for it with the prefab that has a unitu chunk controller on it
                    GameObject chunkObject = Instantiate(chunkObjectPrefab);
                    chunkObject.transform.parent = gameObject.transform;
                    ChunkController chunkController = chunkObject.GetComponent <ChunkController>();
                    if (chunkController == null)
                    {
                        World.Debugger.logError($"No chunk controller on {chunkObject.name}");
                    }
                    else
                    {
                        chunkControllerPool[index]   = chunkController;
                        chunkController.levelManager = this;
                        chunkObject.SetActive(false);
                    }
                }

                /// this controller is now loaded
                isLoaded = true;

                /// add the focus initilization jobs to the queue for each apeture
                level.forEachFocus(focus => {
                    level.forEachAperture(aperture => {
                        foreach (ChunkResolutionAperture.ApetureChunkAdjustment chunkAdjustment in aperture.getAdjustmentsForFocusInitilization(focus))
                        {
                            apertureJobQueue.Enqueue(getCurrentPriorityForChunk(chunkAdjustment.chunkID, aperture), chunkAdjustment);
                        }
                    });
                });

                /// start the manager job in a seperate thread
                apertureJobQueueManagerThread = new Thread(() => ManageQueue())
                {
                    Name = "Level Aperture Queue Manager"
                };
                apertureJobQueueManagerThread.Start();
            }
        }
Ejemplo n.º 12
0
    public virtual void VmStart(Pos position, ChunkController chunkController)
    {
        pos = position;
        this.chunkController = chunkController;

        chunkController.vm.components.chunkFiller.FillChunk(this);

        gameObject.SetActive(true);
    }
Ejemplo n.º 13
0
    private void OnDie()
    {
        ChunkController chunk = transform.GetComponentInParent <ChunkController>();

        if (chunk != null)
        {
            chunk.SetBlock(new Vector2(transform.position.x, transform.position.y), 0);
        }
        Destroy(gameObject);
    }
Ejemplo n.º 14
0
 /// <summary>
 /// Remove a block on a button press
 /// </summary>
 /// <param name="hitBlock"></param>
 void removeBlockOnClick(Coordinate hitCoordinate)
 {
     if (Input.GetMouseButtonDown(0))
     {
         ChunkController chunkController = player.level.chunkAtWorldLocation(hitCoordinate).controller;
         if (chunkController != null)
         {
             player.level.chunkAtWorldLocation(hitCoordinate).controller.destroyBlock(hitCoordinate);
         }
     }
 }
Ejemplo n.º 15
0
 protected void CreateChunkNeighbors()
 {
     Utils.ProfileCall(() =>
     {
         // First time this chunk is rendered - make sure that all neighboring
         // chunks are filled before this chunk can be rendered
         foreach (var dir in DirectionUtils.Directions)
         {
             ChunkController.CreateChunk(Pos + (ChunkController.chunkSize * (Pos)dir));
         }
     }, "Create neighbors");
 }
 private void Awake()
 {
     if (instance != null)
     {
         Destroy(gameObject);
         return;
     }
     else
     {
         instance = this;
     }
 }
Ejemplo n.º 17
0
    /// <summary>
    /// Returns the block at the specified position
    /// </summary>
    /// <param name="blockPos">Position</param>
    public override Block GetBlock(Pos blockPos)
    {
        if (blockPos.x > Pos.x + ChunkSize - 1 || blockPos.y > Pos.y + ChunkSize - 1 ||
            blockPos.z > Pos.z + ChunkSize - 1 || blockPos.x < Pos.x ||
            blockPos.y < Pos.y || blockPos.z < Pos.z)
        {
            return(ChunkController.GetBlock(blockPos));
        }

        return(blocks[
                   blockPos.x - Pos.x,
                   blockPos.y - Pos.y
               ]);
    }
Ejemplo n.º 18
0
    public void Generate(ChunkController controller, int chunkIndex, ChunkController.ChunkSettings chunkSettings, bool empty)
    {
        mController    = controller;
        mChunkIndex    = chunkIndex;
        mChunkSettings = chunkSettings;

        Sanitize();
        GenerateTiles(empty);
        ResetData();
        CalculateTileDepth();
        GenerateMeshData();
        GenerateColliderData();
        Build();
    }
Ejemplo n.º 19
0
        /// <summary>
        /// Get the chunk controller that's already assigned to the given chunk location
        /// </summary>
        /// <param name="chunkLocation"></param>
        /// <returns></returns>
        bool tryToGetAssignedChunkController(Coordinate chunkLocation, out ChunkController assignedChunkController)
        {
            assignedChunkController = null;
            foreach (ChunkController chunkController in chunkControllerPool)
            {
                if (chunkController.isActive && chunkController.chunkLocation == chunkLocation.vec3)
                {
                    assignedChunkController = chunkController;
                    return(true);
                }
            }

            return(false);
        }
    public void InstantiateChunkControllers()
    {
        GameObject lastCreatedObject;

        for (int currentPosX = 0; currentPosX < WorldManager.fillMap.GetUpperBound(0); currentPosX += chunkManagerWidth)
        {
            for (int currentPosY = 0; currentPosY < WorldManager.fillMap.GetUpperBound(1); currentPosY += chunkManagerHeight)
            {
                lastCreatedObject = GameObject.Instantiate(pfab_chunkManager, new Vector3(currentPosX * WorldManager.tileLength,
                                                                                          currentPosY * WorldManager.tileLength * (-1), 0),
                                                           Quaternion.identity, transform);
                ChunkController lastCreatedController = lastCreatedObject.GetComponent <ChunkController>();
                lastCreatedController.InitializeVariables(currentPosX, currentPosX + chunkManagerWidth, currentPosY,
                                                          currentPosY + chunkManagerHeight);
            }
        }
    }
Ejemplo n.º 21
0
    void CreateChunk(float x, float y, float perlinX, int orderX)
    {
        Transform newChunk = Instantiate(chunk, gameObject.transform);          // Create a new chunk

        newChunk.transform.position = new Vector3(x, y);                        // Move it to the proper position
        ChunkController controller = newChunk.GetComponent <ChunkController>(); // Grab the controller

        controller.orderX = orderX;                                             // Set it's position
        controller.GenerateChunk(perlinX, seed);                                // Generate the terrain
        IEnumerator coroutine = controller.CreateTiles();

        StartCoroutine(coroutine); // Create all tiles
        chunks.Add(newChunk);      // Add it to the loaded chunks
        ChunkIDs.Add(orderX);      // ID the new chunk
        chunks = chunks.OrderBy(o => o.GetComponent <ChunkController>().orderX).ToList();
        ChunkIDs.Sort();           // Sort the chunks
    }
Ejemplo n.º 22
0
    void CreateChunkFromMap(float x, float y, int orderX, int[,] map, int[,] backMap)
    {
        Debug.Log("Loading Chunk from Memory");
        Transform newChunk = Instantiate(chunk, gameObject.transform);          // Create a new chunk

        newChunk.transform.position = new Vector3(x, y);                        // Move it to the proper position
        ChunkController controller = newChunk.GetComponent <ChunkController>(); // Get the controller

        controller.orderX  = orderX;                                            // Set the position
        controller.map     = map;                                               // Create the map from the data
        controller.backMap = backMap;
        controller.CreateTiles();                                               // Create all tiles
        chunks.Add(newChunk);                                                   // Add to loaded chunks
        ChunkIDs.Add(orderX);                                                   // ID the new chunk
        chunks = chunks.OrderBy(o => o.GetComponent <ChunkController>().orderX).ToList();
        ChunkIDs.Sort();                                                        // Sort the chunks
    }
Ejemplo n.º 23
0
        /// <summary>
        /// Spawn a new player in and initialize their level focus
        /// </summary>
        /// <param name="newFocus"></param>
        void initilizePlayerFocus(ILevelFocus newFocus)
        {
            IFocusLens newLens = level.addPlayerFocus(newFocus);
            int        requiredControllerCount = newLens.initialize();

            // create the nodes the new lens will need to render
            for (int i = 0; i < requiredControllerCount; i++)
            {
                ChunkController chunkController = Instantiate(ChunkPrefab).GetComponent <ChunkController>();
                chunkController.gameObject.SetActive(false);
                chunkController.gameObject.name = $"Chunk #{++currentMaxChunkObjectID}#";
                chunkController.initalize(this);
                chunkController.transform.SetParent(transform);
                freeChunkControllerPool.Enqueue(chunkController);
            }

            // activate the new focus so it's being tracked
            newFocus.activate();
        }
Ejemplo n.º 24
0
    public void Initialize()
    {
        cam = GameController.cam;
        playerTrans = GameController.playerTrans;
        chunkCont = GameController.chunkController;
        playerTrans.position = Vector3.up * 20;

        layermask = 1<<8;   // Layer 8 is set up as "Chunk" in the Tags & Layers manager
        digDistSquared = digDistance*digDistance;

        center = new Vector2(Screen.width/2, Screen.height/2);

        InputController.RegisterKeyDownEvent(ActionKeys.Hotbar1, OnHotbar1);
        InputController.RegisterKeyDownEvent(ActionKeys.Hotbar2, OnHotbar2);
        InputController.RegisterKeyDownEvent(ActionKeys.Hotbar3, OnHotbar3);
        InputController.RegisterKeyDownEvent(ActionKeys.Hotbar4, OnHotbar4);

        heldBlock = BlockType.Stone;
    }
Ejemplo n.º 25
0
    private Transform GetChunkByBlock(Vector3 pos)
    {
        var x        = pos.x < 0 ? ((int)pos.x - ChunkSizeX + 1) / ChunkSizeX : (int)pos.x / ChunkSizeX;
        var y        = pos.y < 0 ? ((int)pos.y - ChunkSizeY + 1) / ChunkSizeY : (int)pos.y / ChunkSizeY;
        var z        = pos.z < 0 ? ((int)pos.z - ChunkSizeZ + 1) / ChunkSizeZ : (int)pos.z / ChunkSizeZ;
        var chunkPos = new Vector3(x, y, z);

        var chunkName = ChunkController.GetChunkName(chunkPos);
        //Debug.Log(chunkName);

        var chunk = transform.FindChild(chunkName);

        if (chunk == null)
        {
            Debug.Log("Не найдена область: " + chunkName);
        }

        return(chunk);
    }
Ejemplo n.º 26
0
 private void MapGrid()
 {
     for (int x = 0; x < gridSizeX; x += ChunkController.width)
     {
         for (int y = 0; y < gridSizeY; y += ChunkController.height)
         {
             Vector2         worldChunkPosition = (Vector2)transform.position + new Vector2(x, y);
             ChunkController chunk = ChunksController.instance.GetChunk(worldChunkPosition);
             int[,] map = chunk?.GetMap();
             for (int xx = 0; xx < ChunkController.width; xx++)
             {
                 for (int yy = 0; yy < ChunkController.height; yy++)
                 {
                     grid[x + xx, y + yy] = new Node(map?[xx, yy] == 0, worldChunkPosition + new Vector2(xx + nodeRadius, yy + nodeRadius), x + xx, y + yy);
                 }
             }
         }
     }
 }
Ejemplo n.º 27
0
 private void UnloadOldChunks(List <Transform> oldChunks)
 {
     foreach (Transform toDelete in oldChunks)                                                        // For every old chunk
     {
         chunks.Remove(toDelete);                                                                     // Remove it from the list of chunks
         ChunkController controller = toDelete.GetComponent <ChunkController>();                      // Get its controller
         if (genchunkids.Contains(controller.orderX))                                                 // If the chunk is already stored,
         {
             int index = genchunkids.IndexOf(controller.orderX);                                      // Get the index
             genchunkids.RemoveAt(index);
             generatedChunks.RemoveAt(index);                                                         // Delete it
         }
         generatedChunks.Add(new storedChunk(controller.orderX, controller.map, controller.backMap)); // Store the chunk
         generatedChunks = generatedChunks.OrderBy(o => o.orderX).ToList();                           // Sort the chunk list
         genchunkids.Add(controller.orderX);                                                          // Add it to the index list
         genchunkids.Sort();                                                                          // Sort it
         ChunkIDs.Remove(controller.orderX);
         Destroy(toDelete.gameObject);                                                                // Delete it from the map
     }
 }
Ejemplo n.º 28
0
    public override void OnInspectorGUI() {
      /// Just info about the chunk
      EditorGUILayout.LabelField("Chunk Info:", "-----");
      EditorGUI.BeginDisabledGroup(true);
      ChunkController chunkController = target as ChunkController;
      EditorGUILayout.Vector3Field("Current Controlled Chunk ID", chunkController.chunkLocation.vec3);
      EditorGUILayout.Toggle("Is Active", chunkController.isActive);
      EditorGUILayout.Toggle("Is Meshed", chunkController.isMeshed);
      EditorGUI.EndDisabledGroup();

      if (GUILayout.Button("Print Chunk Controller Edit History Log")) {
        LevelDataTester.PrintChunkControllerRecords(
          int.Parse(chunkController.gameObject.name.Split('#')[1]),
          chunkController.terrainManager
        );
      }

      chunkHistoryItemsToGet = LevelDataTester.InspectorDrawChunkHistoryGUIButton(chunkController.chunkLocation, chunkHistoryItemsToGet);
      DrawDefaultInspector();
    }
Ejemplo n.º 29
0
    void UpdateVisibleChunks()
    {
        for (int i = 0; i < terrainChunksVisibleLastUpdate.Count; i++)
        {
            terrainChunksVisibleLastUpdate [i].SetVisible(false);
        }
        terrainChunksVisibleLastUpdate.Clear();

        int currentChunkCoordX = Mathf.RoundToInt(viewerPosition.x / chunkSize);
        int currentChunkCoordY = Mathf.RoundToInt(viewerPosition.y / chunkSize);

        for (int yOffset = -chunkVisibleInViewDst; yOffset <= chunkVisibleInViewDst; yOffset++)
        {
            for (int xOffset = -chunkVisibleInViewDst; xOffset <= chunkVisibleInViewDst; xOffset++)
            {
                Vector2 viewedChunkCoord = new Vector2(currentChunkCoordX + xOffset, currentChunkCoordY + yOffset);

                if (terrainChunkDictionary.ContainsKey(viewedChunkCoord))
                {
                    terrainChunkDictionary[viewedChunkCoord].UpdateTerrainChunk();
                    if (terrainChunkDictionary[viewedChunkCoord].IsVisible())
                    {
                        terrainChunksVisibleLastUpdate.Add(terrainChunkDictionary[viewedChunkCoord]);
                    }
                }
                else
                {
                    ChunkController chunk = SpawnChunk(viewedChunkCoord);
                    if (data.ContainsKey(viewedChunkCoord.ToString()))
                    {
                        chunk.SetMap(data[viewedChunkCoord.ToString()]);
                    }
                    else
                    {
                        chunk.GenereteMap();
                    }
                    terrainChunkDictionary.Add(viewedChunkCoord, chunk);
                }
            }
        }
    }
Ejemplo n.º 30
0
    public override void VmStart(Pos position, ChunkController chunkController)
    {
        Pos = position;
        transform.position   = position;
        this.ChunkController = chunkController;
        Vm = chunkController.vm;

        blocks = new Block[ChunkSize, ChunkSize, ChunkSize];
        Vm.components.chunkFiller.FillChunk(this);

        if (filter == null)
        {
            col    = gameObject.AddComponent <MeshCollider>();
            filter = gameObject.AddComponent <MeshFilter>();
            var renderer = gameObject.AddComponent <MeshRenderer>();
            renderer.material = chunkController.vm.components.textureLoader.material;
        }

        transform.parent = chunkController.transform;
        gameObject.SetActive(true);
    }
Ejemplo n.º 31
0
 // Use this for initialization
 public void SetPos(float x, float y)
 {
     gameObject.transform.position = new Vector2(x, y);                                                           // Sets the position to the new position
     AbsTileX = System.Convert.ToInt32(x / tileDims);                                                             // Resolve the x position as absolute
     ChunkID  = System.Convert.ToInt32(System.Math.Truncate(System.Convert.ToDecimal((AbsTileX) / chunkLength))); // Work out the chunk from the x co-ord
     if (x < 0)
     {
         ChunkID--;                                                   // Correct the weird difference I get around chunk 0
     }
     ChunkTileX = System.Convert.ToInt32(x / tileDims) % chunkLength; // Work out the position in the current chunk
     if (ChunkTileX < 0)
     {
         ChunkTileX = chunkLength + ChunkTileX;
     }                                                                                          // Make sure it isn't negative
     ChunkTileY = (System.Convert.ToInt32(y / tileDims) % chunkHeight) + (chunkHeight / 2) + 8; // Work out the y position - only works for this y-height
     if (ChunkTileY >= chunkHeight)
     {
         ChunkTileY = chunkHeight - 1;                                                           // Ensures the height can't go above the limit
     }
     currentChunk = GameObject.Find("World").GetComponent <WorldController>().GetChunk(ChunkID); // Get the current chunk that the cursor is in
 }
Ejemplo n.º 32
0
    void PreInitialize()
    {
        InputController.Initialize();

        networkController = GetComponent<NetworkController>();
        networkController.Initialize();
        chunkController = chunks.GetComponent<ChunkController>();

        chatUI = GetComponent<ChatUI>();
        chatUI.Initialize();
    }
Ejemplo n.º 33
0
 public Chunk(ChunkController chunkController)
 {
     this.parent = chunkController;
 }