Example #1
0
 public void Refresh()
 {
     if (!HasParentDungeon)
     {
         //if dungeon chunk is -1 then it can be found in our chunk
         WorldChunk chunk = null;
         if (State.DungeonChunkID < 0)
         {
             chunk = worlditem.Group.GetParentChunk();
         }
         else
         {
             if (!GameWorld.Get.ChunkByID(State.DungeonChunkID, out chunk))
             {
                 Debug.Log("Couldn't get dungeon parent chunk in dungeon entrance " + name);
             }
         }
         if (!chunk.GetOrCreateDungeon(State.DungeonName, out ParentDungeon))
         {
             Debug.Log("Couldn't get parent dungeon in dungeon entrance " + name);
             return;
         }
     }
     ParentDungeon.OnEntranceVisible();
     Structures.AddMinorToload(State.EntranceStructure, 0, worlditem);
 }
Example #2
0
    protected void FixedUpdate()
    {
        UnloadChunksOutOfRange();

        int cpt = 0;

        for (int i = ChunkList.Count - 1; i >= 0; i--)
        {
            WorldChunk chunk = ChunkList[i];

            if (chunk.DeleteRequested && !chunk.Busy)
            {
                ChunkList.RemoveAt(i);
                Chunks.Remove(chunk.Position);
                continue;
            }

            if (chunk.MeshDataLoaded && cpt++ < MaxRenderPerFrame)
            {
                chunk.MeshDataLoaded = false;
                RenderChunk(chunk);
                chunk.MeshData = null;
                chunk.Busy     = false;
            }
        }
    }
        void BuildChunk(WorldChunk chunk)
        {
            chunk.ChunkContainer = new GameObject();
            chunk.ChunkContainer.transform.localScale = new Vector3(Settings.CunkScale, Settings.CunkScale, Settings.CunkScale);
            if (chunk.HasLocation)
            {
                PlaceAtLocation.AddPlaceAtComponent(chunk.ChunkContainer, chunk.ChunkLocation, new PlaceAtLocation.PlaceAtOptions {
                    MaxNumberOfLocationUpdates = 2
                });
                chunk.ChunkContainer.transform.localEulerAngles = new Vector3(0, chunk.ChunkRotation, 0);
            }
            else
            {
                chunk.ChunkContainer.transform.position = chunk.Origin;
                chunk.Bounds = new Bounds(chunk.Origin, new Vector3(chunk.Length, chunk.Length, chunk.Length));
                chunk.ChunkContainer.AddComponent <GroundHeight>();
            }

            foreach (var v in chunk.Voxels)
            {
                v.Instance = Instantiate(PrefabDatabase.GetEntryById(v.PrefabId), chunk.ChunkContainer.transform);
                v.Instance.transform.localPosition = new Vector3(v.i, v.j, v.k);
            }

            //if (Elements.ChunkPlanePrefab != null)
            //{
            //    chunk.ChunkPlaneInstance = Instantiate(Elements.ChunkPlanePrefab, chunk.ChunkContainer.transform);
            //    chunk.ChunkPlaneInstance.transform.localPosition = new Vector3(0, -0.5f, 0);
            //    //chunk.ChunkPlaneInstance.transform.localScale = new Vector3(5, 1, 5);
            //    chunk.ChunkPlaneInstance.transform.localScale = new Vector3(chunk.Length/10, 1, chunk.Length/10);
            //    //chunk.ChunkPlaneInstance.GetComponent<MeshRenderer>().material.mainTextureScale = new Vector2(50, 50);
            //    chunk.ChunkPlaneInstance.GetComponent<MeshRenderer>().material.mainTextureScale = new Vector2(chunk.Length, chunk.Length);
            //    chunk.ChunkPlaneInstance.GetComponent<MeshRenderer>().material.mainTextureOffset = new Vector2(0.5f, 0.5f);
            //}
        }
 public override void InitFromRawDecompressed(byte[] decompressedBytes)
 {
     using (var reader = new BinaryReader(new MemoryStream(decompressedBytes)))
     {
         this.Resource = Read_WorldChunkSource(reader);
     }
 }
 public void addChunk(WorldChunk chunk)
 {
     if (!getBucket(WorldChunk.GetAbsoluteIndex(chunk.getX(), chunk.getZ())).elementExists(WorldChunk.GetAbsoluteIndex(chunk.getX(), chunk.getZ())))
     {
         getBucket(WorldChunk.GetAbsoluteIndex(chunk.getX(), chunk.getZ())).addElement(chunk);
     }
 }
Example #6
0
 public void addChunk(WorldChunk chunk)
 {
     if (!chunkExists (chunk.getX (), chunk.getZ ())) {
         chunks.Add (chunk);
         Debug.Log (chunk.indexToString () + " was loaded in memory.");
     }
 }
Example #7
0
    public bool CanPlace(int _databaseID, Vector3 _position)
    {
        bool canPlace = true;

        WorldChunk insideChunk = IsInsideWorldChunk(_position);

        if (insideChunk != null)
        {
            Vector3 chunkPos = WorldToChunk(insideChunk, _position);
            int     chunkX = (int)chunkPos.x, chunkY = (int)chunkPos.y, chunkZ = (int)chunkPos.z;

            BuildingPart part = FindObjectOfType <BuildingPartDatabaseManager>().GetBuildingPart(_databaseID);

            for (int x = chunkX - (int)part.gridOffset.x; x < chunkX - (int)part.gridOffset.x + (int)part.gridSize.x; x++)
            {
                for (int y = chunkY - (int)part.gridOffset.y; y < chunkY - (int)part.gridOffset.y + (int)part.gridSize.y; y++)
                {
                    for (int z = chunkZ - (int)part.gridOffset.z; z < chunkZ - (int)part.gridOffset.z + (int)part.gridSize.z; z++)
                    {
                        if (insideChunk.gridData[x, y, z] != 0)
                        {
                            canPlace = false;
                            break;
                        }
                    }
                }
            }
        }
        else
        {
            canPlace = false;
        }

        return(canPlace);
    }
Example #8
0
 /// <summary>
 /// Add a WorldChunk. (If we add new ones after the game has launched.)
 /// </summary>
 /// <param name="item">a world chunk item.</param>
 public void Add(WorldChunk item)
 {
     if (mInternalChunkCollection != null)
     {
         mInternalChunkCollection.Add(item);
     }
 }
Example #9
0
    static void UpdateVertexesOnRange(WorldChunk chunk,
                                      int min_x, int max_x, int min_y, int max_y,
                                      int[,] vertexIndicesMap, int meshSize, int borderedSize, float offset,
                                      WorldChunkSettings setting)
    {
        for (int y = min_y; y < max_y; y++)
        {
            for (int x = min_x; x < max_x; x++)
            {
                Coord chunkCoord = new Coord(x - 1, y - 1, setting);                  // It's start with [-1;-1]

                int vertexIndex = vertexIndicesMap [x, y];

                // @TODO We already know the concerned sideChunk (it's `keyValue.Value` on `UpdateChunkMesh` loop
                // (can be pass throw GetHeightValue to avoid search it on the list)
                float height = chunk.GetHeightValue(chunkCoord, setting);

                Vector2 uv             = new Vector2((x - 1) / (float)(borderedSize - 2), (y - 1) / (float)(borderedSize - 2));
                Vector3 vertexPosition = new Vector3(
                    offset + uv.x * meshSize,
                    height,
                    offset + uv.y * meshSize
                    );
                chunk.meshData.AddOrUpdateVertex(vertexPosition, uv, vertexIndex);
            }
        }
    }
        public void SpawnGuards( )
        {
            //get the spawn guard nodes
            GuardSpawnNodes.Clear();
            WorldChunk      chunk     = worlditem.Group.GetParentChunk();
            ActionNodeState nodeState = null;

            for (int i = 0; i < State.GuardSpawnNodeNames.Count; i++)
            {
                if (chunk.GetNode(State.GuardSpawnNodeNames [i], false, out nodeState))
                {
                    GuardSpawnNodes.Add(nodeState.actionNode);
                }
            }
            if (chunk.GetNode(State.AlbertSpawnNodeName, false, out nodeState))
            {
                AlbertSpawnNode = nodeState.actionNode;
            }

            for (int i = 0; i < GuardSpawnNodes.Count; i++)
            {
                Character newGuard = null;
                if (Characters.SpawnCharacter(GuardSpawnNodes [i], State.GuardTemplateName, State.GuardFlags, worlditem.Group, out newGuard))
                {
                    //something something, tell them to follow
                    SpawnedGuards.Add(newGuard);
                }
            }

            Characters.GetOrSpawnCharacter(AlbertSpawnNode, "Albert", worlditem.Group, out SpawnedAlbert);

            mHasSpawnedGuards = true;
            enabled           = true;
        }
    // World Zone created on a chunk, and expended after
    public WorldZone(WorldChunk chunk, WorldChunkComputed.WorldChunkZone zone)
    {
        this.randomInt    = (int)Random.Range(1f, 100f);
        this.randomColor  = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f));
        this.type         = zone.type;
        this.isMainGround = false;
        this.isDeleted    = false;

        if (zone.IsOnChunkBorder())
        {
            this.state            = WorldZoneStates.Created;
            this.requireZoneState = (chunk.requireState >= ChunkStates.Merged) ? WorldZoneStates.Merged : WorldZoneStates.Created;

            /*
             * for (int e = 0; e < Coord.directions.Length; e++) {
             *      Direction direction = Coord.directions [e];
             *      Coord directionCoord = chunk.coord.GetDirection (direction);
             *      if (zone.isDirectionChunkBorder [direction]) {
             *              this.missingChunks.Add (directionCoord);
             *      }
             * }*/
        }
        else
        {
            this.state            = WorldZoneStates.Merged;
            this.requireZoneState = WorldZoneStates.Merged;
        }
        // Have chunk border
        this.chunks.Add(chunk.coord);

        // ref to this zone
        this.chunkZones[chunk.coord] = new List <WorldChunkComputed.WorldChunkZone>();
        this.chunkZones [chunk.coord].Add(zone);          // Add a ref to it
    }
Example #12
0
    public void TryAddPlayerToScene(LitePlayer p, int sceneId)
    {
        AtlasWorld world = WorldAtlas.current.GetWorld(sceneId); //this naming convention is awful

        // Remove player from his current chunk
        WorldChunk currChunk = GetChunk(p.GetChunkId());

        currChunk.connectedPlayers.Remove(p);

        if (world.instanced)
        {
            // {Todo}
        }
        else
        {
            List <WorldChunk> chunks = chunkRefs[sceneId];

            if (chunks == null)
            {
                WorldChunk chunk = RequestChunk(sceneId);
                chunk.connectedPlayers.Add(p);
            }
            else
            {
                chunks[0].connectedPlayers.Add(p);
            }
        }
    }
    void OnGUI()
    {
        WorldChunkSettings setting = MapEngine.instance.worldChunkSetting;
        Coord viewer = new Coord(Viewer.instance.bound.center, setting);

        GUI.color = Color.black;
        GUI.Label(new Rect(10f, 30f, 250f, 30f), viewer + " - " + Viewer.instance.scale + ": " + GetChunkLevel(Viewer.instance.scale));
        float y = 50f;

        if (/* Display all zones ? */ false)
        {
            for (int i = 0; i < this.worldZones.Count; i++)
            {
                y = this.OnGUIZone(this.worldZones [i], y);
            }
        }
        else
        {
            Bounds     viewerBound      = Viewer.instance.bound;
            Coord      viewerChunkCoord = new Coord(viewerBound.center, setting);
            WorldChunk chunk            = this.worldChunks [viewerChunkCoord];
            for (int i = 0; i < chunk.worldZonesRefs.Count; i++)
            {
                y = this.OnGUIZone(chunk.worldZonesRefs[i], y);
            }
        }
    }
    // setting already retrieved when new Chunk are created
    public WorldChunkData(WorldChunk chunk, WorldChunkSettings setting)
    {
        DevNoiseType devNoiseType = MapEndless.instance.devNoiseType;

        // Get Height Map
        FastNoise fastNoiseGround = setting.fastNoiseGround.fastNoise;
        FastNoise fastNoiseRegion = setting.fastNoiseRegion.fastNoise;
        int       length          = setting.scaledSize * setting.scaledSize;
        int       chunkOffsetX    = chunk.coord.x * setting.scaledSize - (setting.scaledSize / 2);
        int       chunkOffsetY    = chunk.coord.y * setting.scaledSize - (setting.scaledSize / 2);

        this.heightMap = new float[length];
        this.regionMap = new float[length];
        for (int y = 0; y < setting.scaledSize; y++)
        {
            for (int x = 0; x < setting.scaledSize; x++)
            {
                // Test and return only a mountain on [1;1] to [9;1]
                Coord c = new Coord(x, y, setting);

                if (devNoiseType != DevNoiseType.NoDev)
                {
                    // Use dev noise
                    this.heightMap [c.idx] = this.getZonesHeightTest(new Coord(c.x + chunkOffsetX, c.y + chunkOffsetY), devNoiseType);
                }
                else
                {
                    // Use fastNoiseGround
                    this.heightMap [c.idx] = (fastNoiseGround.GetNoise(c.x + chunkOffsetX, c.y + chunkOffsetY) + 1f) / 2f;
                }
                this.regionMap [c.idx] = (fastNoiseRegion.GetNoise(c.x + chunkOffsetX, c.y + chunkOffsetY) + 1f) / 2f;
            }
        }
    }
        public static WorldChunk GetChunk(int x, int y, int z, FastNoise fn)
        {
            WorldChunk chunk = new WorldChunk();


            for (int bx = 0; bx < WorldChunk.Size; bx++)
            {
                for (int by = 0; by < WorldChunk.Size + 1; by++)
                {
                    for (int bz = 0; bz < WorldChunk.Size; bz++)
                    {
                        noisecache[bx, by, bz] = 0.5f - ((float)(y * WorldChunk.Size + by) / 40) + fn.GetSimplexFractal(x * WorldChunk.Size + bx, y * WorldChunk.Size + by, z * WorldChunk.Size + bz);
                    }
                }
            }

            for (int bx = 0; bx < WorldChunk.Size; bx++)
            {
                for (int by = 0; by < WorldChunk.Size; by++)
                {
                    for (int bz = 0; bz < WorldChunk.Size; bz++)
                    {
                        chunk.SetBlockDirect(bx, by, bz, noisecache[bx, by + 1, bz] > 0 ? Blocks.Stone : noisecache[bx, by, bz] > 0 ? Blocks.Grass : Blocks.Air);
                    }
                }
            }

            return(chunk);
        }
Example #16
0
    /// <summary>
    /// Build mesh data (vertices, triangles, etc.) of the chunk
    /// </summary>
    /// <param name="chunk"></param>
    public void BuildChunk(WorldChunk chunk)
    {
        if (chunk == null)
        {
            return;
        }

        if (MultiThreading)
        {
            ThreadPool.QueueUserWorkItem(c =>
            {
                if (!chunk.UpdatePending)
                {
                    if (chunk.Busy)
                    {
                        chunk.UpdatePending = true;
                        while (chunk.Busy)
                        {
                            Thread.Sleep(0);
                        }
                        chunk.UpdatePending = false;
                    }

                    Build(chunk);
                }
            });
        }
        else
        {
            Build(chunk);
        }
    }
Example #17
0
    public Vector3 ChunkToWorld(WorldChunk _chunk, Vector3 _pos)
    {
        //Check that position is an int
        if (_pos.x % 1 != 0)
        {
            Debug.LogError("X is not an int");
        }

        if (_pos.y % 1 != 0)
        {
            Debug.LogError("Y is not an int");
        }

        if (_pos.z % 1 != 0)
        {
            Debug.LogError("Z is not an int");
        }

        int   gridWidth = (int)_chunk.Size().x, gridHeight = (int)_chunk.Size().y, gridLength = (int)_chunk.Size().z;
        float halfWidth = gridWidth / 2f, halfLength = gridLength / 2f;

        Vector3 bottomEdge = _chunk.centrePoint - new Vector3(halfWidth, 0f, halfLength);

        return(bottomEdge + _pos);
    }
Example #18
0
    // Use this for initialization
    void Awake()
    {
        i          = this;
        numColumns = (int)(maxXYValue / gridWidth);
        numRows    = (int)(maxXYValue / gridHeight);

        allChunks = new WorldChunk[numColumns][];
        chunkRefs = new Dictionary <int, List <WorldChunk> >();

        startingChunkX = (numColumns / 2);
        startingChunkY = (numRows / 2);

        for (int i = 0; i < numColumns; i++)
        {
            allChunks[i] = new WorldChunk[numRows];
        }

        if (waitingAnchor != null)
        {
            MakeChunkForDefaultScene(waitingAnchor);
        }
        else
        {
            Debug.Log("No waiting chunk!");
        }
    }
        WorldChunk FindClosestChunk(Location l, out double distance, double maxDistance)
        {
            WorldChunk current         = null;
            double     currentDistance = 0;

            foreach (var c in world.Chunks)
            {
                var d = Location.HorizontalDistance(c.ChunkLocation, l);

                if (current == null || d < currentDistance)
                {
                    current         = c;
                    currentDistance = d;
                }
            }

            distance = currentDistance;

            if (currentDistance > maxDistance)
            {
                return(null);
            }

            return(current);
        }
Example #20
0
    /// <summary>
    /// Attach each mesh of the chunk to a GameObject
    /// </summary>
    /// <param name="chunk">the chunk</param>
    public void RenderChunk(WorldChunk chunk)
    {
        if (chunk.GameObjects != null && chunk.GameObjects.Length != 0)
        {
            for (int i = 0; i < chunk.GameObjects.Length; i++)
            {
                chunk.GameObjects[i].SetActive(false);
            }
        }


        List <GameObject> GOs = new List <GameObject>();

        Vector3 goPosition = chunk.GetGlobalPosition();

        for (int i = 0; i < chunk.MeshData.Length; i++)
        {
            GameObject go = _Pool.NextObject();

            if (go == null)
            {
                Debug.LogError("Pool has no GameObject available");
                break;
            }
            AttachMesh(go, chunk, chunk.MeshData[i]);

            go.transform.position = goPosition;
            GOs.Add(go);
        }

        chunk.GameObjects = GOs.ToArray();
    }
    public void StartBuildMode()
    {
        if (!isActivated)
        {
            isActivated = true;
            isAnimating = true;

            //Turn off Player
            playerMovement.lockMovements = true;
            playerMovement.isThinking    = true;

            //Set Cursor as Target
            IsoCam   isoCam   = playerMovement.playerCamera.GetComponent <IsoCam>();
            OrbitCam orbitCam = playerMovement.playerCamera.GetComponent <OrbitCam>();

            if (isoCam != null)
            {
                isoCam.target = cameraTarget.transform;
            }
            else if (orbitCam != null)
            {
                orbitCam.target = cameraTarget.transform;
            }


            Vector3    playerPos  = player.transform.position + Vector3.up;
            WorldChunk localChunk = worldStateManager.IsInsideWorldChunk(playerPos);
            if (localChunk != null)
            {
                Vector3 newPos = SnapToGrid(playerPos, localChunk);
                newPos.y = Mathf.Clamp(newPos.y, 0.5f, 10.5f);

                cursor.transform.position = newPos;
                actualCursorPos           = cursor.transform.position;

                fluidCursor.transform.position  = newPos;
                cameraTarget.transform.position = newPos;
            }

            StartCoroutine(DoSwapAnimation());

            itemsPanel.SetActive(true);

            foreach (ItemHide itemHide in FindObjectsOfType <ItemHide>())
            {
                itemHide.UpdateAvailablilty();
            }

            ChangeSelection(currentSelection);

            foreach (PhysicsPrefab prefab in FindObjectsOfType <PhysicsPrefab>())
            {
                prefab.Reset();
                prefab.GetComponent <Rigidbody>().isKinematic = true;
            }

            SetupCursorObject();
        }
    }
Example #22
0
    public void UpdateChunksFromPlayerPosition()
    {
        if (m_CurrentChunk == null)
        {
            return;
        }

        Vector3 playerPos       = m_Player.transform.position;
        Bounds  currChunkBounds = m_CurrentChunk.GetComponent <BoxCollider2D>().bounds;

        //Nothing to do if we're still in the current chunk
        if (currChunkBounds.Contains(new Vector3(playerPos.x,
                                                 playerPos.y,
                                                 m_CurrentChunk.transform.position.z)))
        {
            return;
        }

        Bounds     prevChunkBounds = m_CurrentChunk.m_Prev.GetComponent <BoxCollider2D>().bounds;
        WorldChunk newNextChunk, newCurrChunk, newPrevChunk = null;

        if (prevChunkBounds.Contains(new Vector3(playerPos.x,
                                                 playerPos.y,
                                                 m_CurrentChunk.transform.position.z)))
        {
            WorldChunk oldNext = m_CurrentChunk.m_Next;
            Destroy(oldNext.gameObject);

            newNextChunk      = m_CurrentChunk;
            newNextChunk.name = "next_chunk";

            newCurrChunk      = m_CurrentChunk.m_Prev;
            newCurrChunk.name = "current_chunk";

            newPrevChunk = CreateChunk(newCurrChunk.transform.position + new Vector3(0f, 10f, 0f), "prev_chunk");

            m_CurrentChunk        = newCurrChunk;
            m_CurrentChunk.m_Prev = newPrevChunk;
            m_CurrentChunk.m_Next = newNextChunk;

            return;
        }

        WorldChunk oldPrev = m_CurrentChunk.m_Prev;

        Destroy(oldPrev.gameObject);

        newPrevChunk      = m_CurrentChunk;
        newPrevChunk.name = "prev_chunk";

        newCurrChunk      = m_CurrentChunk.m_Next;
        newCurrChunk.name = "current_chunk";

        newNextChunk = CreateChunk(newCurrChunk.transform.position + new Vector3(0f, -10f, 0f), "next_chunk");

        m_CurrentChunk        = newCurrChunk;
        m_CurrentChunk.m_Prev = newPrevChunk;
        m_CurrentChunk.m_Next = newNextChunk;
    }
Example #23
0
 public MapObjectWater(WorldChunk chunk)
 {
     TextColor       = ConsoleColor.White;
     BackgroundColor = ConsoleColor.DarkBlue;
     MapCharacter    = " ";
     PositionX       = chunk.PositionX;
     PositionY       = chunk.PositionY;
 }
Example #24
0
 public ClaimedTerritory(WorldChunk chunk)
 {
     TextColor       = ConsoleColor.Black;
     BackgroundColor = ConsoleColor.DarkCyan;
     MapCharacter    = chunk.MonsterLevel.ToString();
     PositionX       = chunk.PositionX;
     PositionY       = chunk.PositionY;
 }
Example #25
0
 public NotSet(WorldChunk chunk)
 {
     TextColor       = ConsoleColor.Black;
     BackgroundColor = ConsoleColor.Gray;
     MapCharacter    = "N";
     PositionX       = chunk.PositionX;
     PositionY       = chunk.PositionY;
 }
Example #26
0
 public StartingPosition(WorldChunk chunk)
 {
     TextColor       = ConsoleColor.Yellow;
     BackgroundColor = ConsoleColor.Blue;
     MapCharacter    = "S";
     PositionX       = chunk.PositionX;
     PositionY       = chunk.PositionY;
 }
Example #27
0
 public MapObjectMountains(WorldChunk chunk)
 {
     TextColor       = ConsoleColor.White;
     BackgroundColor = ConsoleColor.DarkGray;
     MapCharacter    = "^";
     PositionX       = chunk.PositionX;
     PositionY       = chunk.PositionY;
 }
Example #28
0
 /// <summary>
 /// When a world chunk is destroyed, it should be removed. We could probably set up a messaging system to make this auto
 /// but it's fine for now.
 /// </summary>
 /// <param name="item">a world chunk item</param>
 /// <returns>true if successful.</returns>
 public bool Remove(WorldChunk item)
 {
     if (mInternalChunkCollection != null)
     {
         return(mInternalChunkCollection.Remove(item));
     }
     return(false);
 }
Example #29
0
    /// <summary>
    /// Get the chunk at the given position if it has already been loaded
    /// </summary>
    /// <param name="position">The position of the chunk</param>
    /// <returns>The chunk if it is loaded or null otherwise</returns>
    public WorldChunk GetChunk(GridPosition position)
    {
        WorldChunk chunk = null;

        Chunks.TryGetValue(position, out chunk);

        return(chunk);
    }
Example #30
0
    public Vector3 WorldToChunk(WorldChunk _chunk, Vector3 _pos)
    {
        Vector3 local = _pos - _chunk.centrePoint;

        local += new Vector3((_chunk.Size().x / 2f) + 0.5f, 0f, (_chunk.Size().z / 2f) + 0.5f);

        return(new Vector3(Mathf.Floor(local.x), Mathf.Floor(Mathf.Clamp(local.y, 0.5f, 10.5f)), Mathf.Floor(local.z)));
    }
Example #31
0
 private void ReleaseChunk(WorldChunk chunk)
 {
     chunk.gameObject.SetActive(false);
     if (ChunksPoolHost)
     {
         chunk.transform.SetParent(ChunksPoolHost);
     }
 }
    public void loadChunk(WorldChunk chunk)
    {
        switch (dataStructure) {
            case LoadedChunks_DataStructure.HashTable:
                loadedWorldChunks_HT.addChunk(chunk);
                break;

            case LoadedChunks_DataStructure.List:
                loadedWorldChunks_L.addChunk(chunk);
                break;
        }
    }
    public static WorldChunk GenerateChunk(int x, int z)
    {
        WorldChunk newChunk = new WorldChunk (x, z);
        Debug.Log ("Generating "+newChunk.indexToString());

        for (int x_ind = 0; x_ind < GameSettings.LoadedConfig.ChunkLength_Sectors; ++x_ind) {
            for (int z_ind = 0; z_ind < GameSettings.LoadedConfig.ChunkLength_Sectors; ++z_ind) {
                GenerateSector(newChunk.getSector(x_ind, z_ind));
            }
        }

        return newChunk;
    }
        public Mesh GenLodCell(WorldChunk<sbyte> chunk)
        {
            Mesh mesh = new Mesh();
            int lod = 1;

            for (int x = 0; x < volume.ChunkSize; x++)
            {
                for (int y = 0; y < volume.ChunkSize; y++)
                {
                    for (int z = 0; z < volume.ChunkSize; z++)
                    {
                        Vector3i position; //new Vector3i(x, y, z);
                        position.X = x;
                        position.Y = y;
                        position.Z = z;
                        PolygonizeCell(chunk.GetPosition(), position, ref mesh, lod);
                    }
                }
            }

            return mesh;
        }
        public void ExtractMesh(WorldChunk<sbyte> wc)
        {
            int lod = 1;
            Vector3i position = wc.GetPosition();
            Vector3 posXna = position.ToVector3();

            //Logger.GetLogger().Log(null, "" + dst);

            var m = _surfaceExtractor.GenLodCell(wc);
            var v = Converters.ConvertMeshToXna(m, LodColors[0]);
            var i = m.GetIndices();

            var chunk = new Chunk
            {
                BoundingBox = new BoundingBox(posXna, posXna + new Vector3(wc.Size(), wc.Size(), wc.Size())),
                Position = posXna,
                Lod = lod
            };

            if (i.Length > 0 && v.Length > 0)
            {
                chunk.VertexBuffer = new VertexBuffer(_gd, typeof(VertexPositionTextureNormalColor), v.Length, BufferUsage.WriteOnly);
                chunk.VertexBuffer.SetData(v);
                chunk.IndexBuffer = new IndexBuffer(_gd, IndexElementSize.SixteenBits, i.Length, BufferUsage.WriteOnly);
                chunk.IndexBuffer.SetData(i);

                Console.WriteLine("Chunk has : " + v.Length + " Vertices " + i.Length + " Indices");

                if (_chunks.ContainsKey(posXna))
                {
                    Chunk removed;
                    _chunks.TryRemove(posXna, out removed);
                }
                _chunks.TryAdd(posXna, chunk);
            }
        }
Example #36
0
 public static void LoadChunk(WorldChunk chunk)
 {
     GameWorld.loadedChunks.loadChunk (chunk);
 }
Example #37
0
    public WorldSector(int x_index, int z_index, WorldChunk parent)
    {
        //Debug.Log ("------Creating sector: (" + x_index + ", " + z_index + ")");
        x = x_index;
        z = z_index;
        this.parent = parent;

        initLevels();
    }
Example #38
0
    public static WorldChunk LoadChunk(int x, int z)
    {
        string savesDirPath = Path.Combine (Application.persistentDataPath, GameSettings.LoadedConfig.SavesPath);
        bool savesDirExists = System.IO.Directory.Exists (savesDirPath);
        if (!savesDirExists) {
            return null;
        }

        string activeWorldDirPath = Path.Combine (savesDirPath, GameSettings.LoadedConfig.ActiveWorldDir);
        bool activeWorldDirExists = System.IO.Directory.Exists (activeWorldDirPath);
        if (!activeWorldDirExists) {
            return null;
        }

        string chunksDirPath = Path.Combine (activeWorldDirPath, WSerializer.chunksDirName);
        bool chunksDirExists = System.IO.Directory.Exists (chunksDirPath);
        if (!chunksDirExists) {
            return null;
        }

        string chunkFilePath = Path.Combine (chunksDirPath, WSerializer.chunkFilePrefix + x + "-" + z + ".sav");
        bool chunkFileExists = System.IO.File.Exists (chunkFilePath);
        if (!chunkFileExists) {
            return null;
        }

        XmlSerializer serializer = new XmlSerializer (typeof(SerializableChunk));
        FileStream stream = new FileStream (chunkFilePath, FileMode.Open);
        SerializableChunk loadedChunk = serializer.Deserialize (stream) as SerializableChunk;
        stream.Close ();

        WorldChunk restoredChunk = new WorldChunk (x, z);
        restoredChunk.restoreChunkData (loadedChunk);
        Debug.Log("Chunk: ("+x+", "+z+") was restored from file.");

        return restoredChunk;
    }
 public void addChunk(WorldChunk chunk)
 {
     if (!getBucket(WorldChunk.GetAbsoluteIndex (chunk.getX(), chunk.getZ())).elementExists(WorldChunk.GetAbsoluteIndex (chunk.getX(), chunk.getZ())))
         getBucket(WorldChunk.GetAbsoluteIndex (chunk.getX(), chunk.getZ())).addElement(chunk);
 }
    public void addElement(WorldChunk elem)
    {
        if (elements.Count >= GameSettings.LoadedConfig.ChunkHT_BucketSize)
            Debug.LogWarning ("Loaded chunk HT bucket has exceeded it's max size.");

        elements.Add (elem);
    }
Example #41
0
    void CreateChunkMesh(int x, int y, ref WorldChunk chunk)
    {
        // create a vertex list
        List<Vector3> verts = new List<Vector3>();
        // create a triangle list
        List<int> tris = new List<int>();
        // create a uv list
        List<Vector2> uvs = new List<Vector2>();
        // create a new mesh
        /*Mesh newMesh = new Mesh();
        newMesh.name = ("Chunk_"+x+","+y);*/

        // setup the tile height variables for the walls
        short nextTileHeight = 0;
        short currentTileHeight = 0;

        #region FLOOR

        // calculate the possible end points of the chunk
        // so we know what to fill in
        int startXPos = x*chunkSize;
        int startYPos = y*chunkSize;
        int endXPos = (x+1)*chunkSize;
        int endYPos = (y+1)*chunkSize;

        // these are the real ends of the chunk, so we dont overflow
        int endXChunk = -1;
        int endYChunk = -1;

        // set the real ends of the chunk
        if(endXPos > world.GetLength(0)){
            endXChunk = world.GetLength(0)-startXPos;
        }
        else{
            endXChunk = chunkSize;
        }

        if(endYPos > world.GetLength(1)){
            endYChunk = world.GetLength(1)-startYPos;
        }
        else{
            endYChunk = chunkSize;
        }

        // draw the floor
        for(int i=0;i<endXChunk;i++){
            for(int j=0;j<endYChunk;j++){

                // calculate the world array coordinates
                int worldXCoord = i+startXPos;
                int worldYCoord = j+startYPos;

                // check if the current tile height is zero, since this shouldnt be drawn
                if(world[worldXCoord,worldYCoord].height != 0){

                    // calculate the position of this tile,relative to the chunk
                    // create the local position, so that the centre of the chunk is in the origin of the object
                    Vector3 tilePos = new Vector3(i-(chunkSize/2),world[worldXCoord,worldYCoord].height,j-(chunkSize/2));

                    // draw a face here
                    Vector3[] newVerts = new Vector3[4];
                    newVerts[0] = new Vector3(0,0,0)+tilePos;
                    newVerts[1] = new Vector3(0,0,1)+tilePos;
                    newVerts[2] = new Vector3(1,0,1)+tilePos;
                    newVerts[3] = new Vector3(1,0,0)+tilePos;

                    int[] newTris = new int[6];
                    newTris[0] = 0+verts.Count;
                    newTris[1] = 1+verts.Count;
                    newTris[2] = 2+verts.Count;
                    newTris[3] = 0+verts.Count;
                    newTris[4] = 2+verts.Count;
                    newTris[5] = 3+verts.Count;

                    for(int n=0;n<newVerts.Length;n++){
                        verts.Add(newVerts[n]);
                    }

                    for(int n=0;n<newTris.Length;n++){
                        tris.Add(newTris[n]);
                    }

                }
            }
        }

        // now optimise this
        RemoveDuplicateVertices(ref verts, ref tris);
        // now calculate the uvs, after optimising the vertices
        for(int i=0;i<verts.Count;i++){
            uvs.Add (new Vector2(verts[i].x,verts[i].z));
        }

        #endregion

        #region WALLS

        // draw the walls down
        for(int i=0;i<endXChunk;i++){
            for(int j=0;j<endYChunk;j++){

                // calculate the world array coordinates
                int worldXCoord = i+startXPos;
                int worldYCoord = j+startYPos;

                // set our tile pos
                Vector3 tilePos = new Vector3(i-(chunkSize/2),world[worldXCoord,worldYCoord].height,j-(chunkSize/2));
                // 	1------2
                //	|	   |
                //	|	   |
                //	0------3
                // determine if the neighbours are below us
                // dont bother building edges up, since we can just build them down

                // get our current height
                currentTileHeight = world[worldXCoord,worldYCoord].height;

                #region UPPER TILE
                // create the upper tile pos
                Vector2 upperTilePos = new Vector2(worldXCoord,worldYCoord+1);

                //short nextTileHeight = 0;
                // check for out of bounds
                if(OutOfBounds(upperTilePos) == false){
                    nextTileHeight = world[(int)upperTilePos.x,(int)upperTilePos.y].height;
                }
                else{
                    nextTileHeight = 0;
                }

                    // check if the tile is lower than us
                    if(nextTileHeight < currentTileHeight){

                        // we have found a tile that is lower than us...
                        // create some walls down

                        // create the vertices
                        Vector3[] newVerts = new Vector3[4];
                        newVerts[0] = new Vector3(1,0,1)+tilePos;
                        newVerts[1] = new Vector3(0,0,1)+tilePos;
                        newVerts[2] = new Vector3(0,nextTileHeight-currentTileHeight,1)+tilePos;
                        newVerts[3] = new Vector3(1,nextTileHeight-currentTileHeight,1)+tilePos;

                        // create the triangles
                        int[] newTris = new int[6];
                        newTris[0] = 0+verts.Count;
                        newTris[1] = 1+verts.Count;
                        newTris[2] = 2+verts.Count;
                        newTris[3] = 0+verts.Count;
                        newTris[4] = 2+verts.Count;
                        newTris[5] = 3+verts.Count;

                        // add these to the mesh
                        for(int n=0;n<newVerts.Length;n++){
                            verts.Add(newVerts[n]);
                        }

                        for(int n=0;n<newTris.Length;n++){
                            tris.Add(newTris[n]);
                        }

                        // add appropriate uvs for the vertices
                        for(int n=0;n<newVerts.Length;n++){
                            uvs.Add (new Vector2((newVerts[n].y),(newVerts[n].x)));
                        }
                    }

                #endregion

                #region DOWN TILE
                // create the down tile pos
                Vector2 downTilePos = new Vector2(worldXCoord,worldYCoord-1);

                // check for out of bounds
                if(OutOfBounds(downTilePos) == false){
                    nextTileHeight = world[(int)downTilePos.x,(int)downTilePos.y].height;
                }
                else{
                    nextTileHeight = 0;
                }

                    // check if the tile is lower than us
                    if(nextTileHeight < currentTileHeight){

                        // we have found a tile that is lower than us...
                        // create some walls down

                        // create the vertices
                        Vector3[] newVerts = new Vector3[4];
                        newVerts[0] = new Vector3(0,0,0)+tilePos;
                        newVerts[1] = new Vector3(1,0,0)+tilePos;
                        newVerts[2] = new Vector3(1,nextTileHeight-currentTileHeight,0)+tilePos;
                        newVerts[3] = new Vector3(0,nextTileHeight-currentTileHeight,0)+tilePos;

                        // create the triangles
                        int[] newTris = new int[6];
                        newTris[0] = 0+verts.Count;
                        newTris[1] = 1+verts.Count;
                        newTris[2] = 2+verts.Count;
                        newTris[3] = 0+verts.Count;
                        newTris[4] = 2+verts.Count;
                        newTris[5] = 3+verts.Count;

                        // add these to the mesh
                        for(int n=0;n<newVerts.Length;n++){
                            verts.Add(newVerts[n]);
                        }

                        for(int n=0;n<newTris.Length;n++){
                            tris.Add(newTris[n]);
                        }

                        // add appropriate uvs for the vertices
                        for(int n=0;n<newVerts.Length;n++){
                            uvs.Add (new Vector2((newVerts[n].y),(newVerts[n].x)));
                        }
                    }

                #endregion

                #region LEFT TILE
                // create the upper tile pos
                Vector2 leftTilePos = new Vector2(worldXCoord-1,worldYCoord);

                // check for out of bounds
                if(OutOfBounds(leftTilePos) == false){
                    nextTileHeight = world[(int)leftTilePos.x,(int)leftTilePos.y].height;
                }
                else{
                    nextTileHeight = 0;
                }

                    // check if the tile is lower than us
                    if(nextTileHeight < currentTileHeight){

                        // we have found a tile that is lower than us...
                        // create some walls down

                        // create the vertices
                        Vector3[] newVerts = new Vector3[4];
                        newVerts[0] = new Vector3(0,0,1)+tilePos;
                        newVerts[1] = new Vector3(0,0,0)+tilePos;
                        newVerts[2] = new Vector3(0,nextTileHeight-currentTileHeight,0)+tilePos;
                        newVerts[3] = new Vector3(0,nextTileHeight-currentTileHeight,1)+tilePos;

                        // create the triangles
                        int[] newTris = new int[6];
                        newTris[0] = 0+verts.Count;
                        newTris[1] = 1+verts.Count;
                        newTris[2] = 2+verts.Count;
                        newTris[3] = 0+verts.Count;
                        newTris[4] = 2+verts.Count;
                        newTris[5] = 3+verts.Count;

                        // add these to the mesh
                        for(int n=0;n<newVerts.Length;n++){
                            verts.Add(newVerts[n]);
                        }

                        for(int n=0;n<newTris.Length;n++){
                            tris.Add(newTris[n]);
                        }

                        // add appropriate uvs for the vertices
                        for(int n=0;n<newVerts.Length;n++){
                            uvs.Add (new Vector2((newVerts[n].y),(newVerts[n].z)));
                        }
                    }

                #endregion

                #region RIGHT TILE
                // create the upper tile pos
                Vector2 rightTilePos = new Vector2(worldXCoord+1,worldYCoord);

                // check for out of bounds
                if(OutOfBounds(rightTilePos) == false){
                    nextTileHeight = world[(int)rightTilePos.x,(int)rightTilePos.y].height;
                }
                else{
                    nextTileHeight = 0;
                }

                    // check if the tile is lower than us
                    if(nextTileHeight < currentTileHeight){

                        // we have found a tile that is lower than us...
                        // create some walls down

                        // create the vertices
                        Vector3[] newVerts = new Vector3[4];
                        newVerts[0] = new Vector3(1,0,0)+tilePos;
                        newVerts[1] = new Vector3(1,0,1)+tilePos;
                        newVerts[2] = new Vector3(1,nextTileHeight-currentTileHeight,1)+tilePos;
                        newVerts[3] = new Vector3(1,nextTileHeight-currentTileHeight,0)+tilePos;

                        // create the triangles
                        int[] newTris = new int[6];
                        newTris[0] = 0+verts.Count;
                        newTris[1] = 1+verts.Count;
                        newTris[2] = 2+verts.Count;
                        newTris[3] = 0+verts.Count;
                        newTris[4] = 2+verts.Count;
                        newTris[5] = 3+verts.Count;

                        // add these to the mesh
                        for(int n=0;n<newVerts.Length;n++){
                            verts.Add(newVerts[n]);
                        }

                        for(int n=0;n<newTris.Length;n++){
                            tris.Add(newTris[n]);
                        }

                        // add appropriate uvs for the vertices
                        for(int n=0;n<newVerts.Length;n++){
                            uvs.Add (new Vector2((newVerts[n].y),(newVerts[n].z)));
                        }

                    }

                #endregion
            }
        }

        #endregion

        // finally write this mesh data back to the chunk, so it can be rendered
        //RemoveDuplicateVertices(ref verts, ref tris, ref uvs);
        chunk.chunkMesh.Clear();
        chunk.chunkMesh.vertices = verts.ToArray();
        chunk.chunkMesh.triangles = tris.ToArray();
        chunk.chunkMesh.uv = uvs.ToArray();
        chunk.chunkMesh.RecalculateBounds();
        chunk.chunkMesh.RecalculateNormals();
        chunk.chunkMesh.Optimize();
        chunk.UpdateMesh();
    }
Example #42
0
    void serializeChunkData(SerializableChunk copyTo, WorldChunk copyFrom)
    {
        // save indexes
        copyTo.x = copyFrom.getX();
        copyTo.z = copyFrom.getZ();

        // save chunk sectors
        WorldSector[,] sectors = copyFrom.getAllSectors();
        for (int i = 0; i < GameSettings.LoadedConfig.ChunkLength_Sectors*GameSettings.LoadedConfig.ChunkLength_Sectors; ++i) {
            copyTo.sectors.Add(new SerializableSector());

            int sx = i%GameSettings.LoadedConfig.ChunkLength_Sectors;
            int sz = Mathf.FloorToInt(i/GameSettings.LoadedConfig.ChunkLength_Sectors);
            serializeSectorData(copyTo.sectors[i], sectors[sx, sz]);
        }
    }
Example #43
0
 public static void UnloadChunk(WorldChunk chunk)
 {
     GameWorld.loadedChunks.unloadChunk (chunk.getX(), chunk.getZ());
 }