Exemplo n.º 1
0
    void Start()
    {
        miner = GameObject.Find("Player").GetComponent <VoxelMining>();

        Array3 <Voxel> voxels = WorldGenerator.CreateVoxels(33, 0, 1.0f, Vector3.zero);
        //Array3<Voxel> voxels = WorldGenerator.CreateVoxels(64, 0, 1.0f, Vector3.zero);

        MeshData data = MarchingCubes.CalculateMeshData(voxels, 1.0f);
        Mesh     mesh = data.CreateMesh();

        go                      = SplitManager.GetObject();
        go.mr.enabled           = false;
        go.mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.TwoSided;
        go.mf.sharedMesh        = mesh;
        go.mr.material          = testMat;

        MeshData data2 = MarchingTetrahedra.CalculateMeshData(voxels, 1.0f);

        data2.CalculateSharedNormals();
        Mesh mesh2 = data2.CreateMesh();

        go2 = SplitManager.GetObject();
        go2.mf.sharedMesh        = mesh2;
        go2.mr.material          = testMat;
        go2.mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.TwoSided;
        miner.forceDrawChunk     = go2;
    }
Exemplo n.º 2
0
    // PopulateNoiseMap(), UpdateMesh()
    public Chunk(World _world, Vector2Int _chunkCoord)
    {
        world       = _world;
        chunkCoord  = _chunkCoord;
        verts       = new List <Vector3>();
        tris        = new List <int>();
        chunkWidth  = GameData.chunkWidth;
        chunkHeight = GameData.chunkHeight;

        chunkPosInWorldSpace = new Vector3Int(chunkCoord.x * chunkWidth, 0, chunkCoord.y * chunkWidth);

        chunkObject                  = new GameObject();
        chunkObject.name             = $"Chunk: {chunkCoord.x}, {chunkCoord.y}";
        chunkObject.transform.parent = world.transform;

        chunkObject.transform.position = chunkPosInWorldSpace;

        player = GameObject.FindGameObjectWithTag("Player").transform;

        meshFilter   = chunkObject.AddComponent <MeshFilter>();
        meshRenderer = chunkObject.AddComponent <MeshRenderer>();
        meshCollider = chunkObject.AddComponent <MeshCollider>();

        chunkObjectScript = chunkObject.AddComponent <ChunkObject>();

        PopulateNoiseMap();
        CreateMeshData();
        CreateMesh();
    }
Exemplo n.º 3
0
    // Use this for initialization
    void Start()
    {
        float voxelSize = 1.0f;
        int   size      = 33;

        Array3 <Voxel> voxels = WorldGenerator.CreateVoxels(size, 0, voxelSize, Vector3.zero);
        MeshData       data   = MarchingCubes.CalculateMeshData(voxels, voxelSize);

        data.CalculateNormals();

        Mesh mesh = null;

        if (data != null)
        {
            mesh = data.CreateMesh();
        }

        ChunkObject obj = SplitManager.GetObject();

        obj.ov.shouldDraw = true;
        obj.mr.material   = mat;
        obj.mf.mesh       = mesh;


        Vector3 center = Vector3.one * (size - 1) / 2.0f;
        Bounds  area   = new Bounds(center, Vector3.one * voxelSize * (size - 1));

        obj.ov.init(0, 0, center, area, null, Color.red);
    }
Exemplo n.º 4
0
    void CreateWorldMesh(int x, int y, int z)
    {
        ChunkObject chunkObject = Instantiate(_chunkPrefab) as ChunkObject;

        chunkObject.name               = "Chunk[" + x + "," + y + "," + z + "]";
        chunkObject.transform.parent   = _worldTransform;
        chunkObject.transform.position = new Vector3(x * Chunk.SizeX, y * Chunk.SizeY, z * Chunk.SizeZ);
        _world.CreateChunkMesh(x, y, z, chunkObject);
    }
Exemplo n.º 5
0
    public Block(ChunkObject parent, string materialName, Vector3Int position)
    {
        ControlPoint = new Vector3(.5f, .5f, .5f);

        Parent               = parent;
        Position             = position;
        SearchMarker         = 0;
        IsControlPointLocked = false;
        _materialName        = materialName;
    }
Exemplo n.º 6
0
    /// <summary>
    /// Adds a feature to the feature dictionary;
    /// </summary>
    /// <param name="go">GameObject to treat as a feature to add</param>
    public void AddFeature(GameObject go)
    {
        ChunkObject feature = go.AddComponent <ChunkObject>();

        feature.myId  = objects.Count;
        feature.chunk = this;

        objects.Add(latestId, feature);
        latestId++;
    }
Exemplo n.º 7
0
    //// Update is called once per frame
    //void Update() {
    //    int newTasks = 0;
    //    while (splitList.Count > 0   // while there are things to split
    //       && newTasks < taskLaunchesPerFrame  // and havent launched too many tasks this frame
    //       && taskList.Count < maxConcurrentTasks) { // and there are less tasks going than max

    //        // find lowest depth of trees on list
    //        int count = splitList.Count;
    //        int minDepth = Octree.MAX_DEPTH;
    //        for (int i = 0; i < count; ++i) {
    //            minDepth = Mathf.Min(minDepth, splitList[i].depth);
    //        }

    //        int closest = 0;
    //        float closestDist = float.MaxValue;
    //        for (int i = 0; i < count; ++i) {
    //            if (splitList[i].depth > minDepth) {
    //                continue;
    //            }

    //            float dist = splitList[i].GetSqrDistToCamFromCenter();
    //            if (dist < closestDist) {
    //                closest = i;
    //                closestDist = dist;
    //            }
    //        }

    //        Octree toSplit = splitList[closest];
    //        if (count > 1) {    // remove from list fast
    //            splitList[closest] = splitList[count - 1];
    //            splitList.RemoveAt(count - 1);
    //        } else {
    //            splitList.Clear();
    //        }

    //        // one last check before queueing up task
    //        if (toSplit.ShouldSplit()) {
    //            taskList.Add(toSplit.SplitAsync());
    //            newTasks++;
    //        } else {    // otherwise just remove from list
    //            toSplit.SetSplitting(false);
    //        }

    //    }

    //    // check and resolve tasks that are complete
    //    int resolutionsPerFrame = 1;
    //    for (int i = 0; i < taskList.Count;) {
    //        if (taskList[i].IsCompleted) {
    //            //Debug.Log("resolved: " + ++totalResolved);
    //            SplitData sd = taskList[i].Result;
    //            sd.tree.SplitResolve(sd.data);
    //            taskList.RemoveAt(i);
    //            if (--resolutionsPerFrame <= 0) {
    //                break;
    //            }
    //        } else {
    //            ++i;
    //        }
    //    }

    //    //splitCountText.text = "splits: " + splitList.Count;
    //    //if(splitList.Count == 0) {
    //    //    Debug.Log(Time.time);
    //    //}

    //}

    //public static void AddToSplitList(Octree node) {
    //    splitList.Add(node);
    //}

    //// todo reimplement these to generate closest first
    //public int NearestToFarthest(Octree o1, Octree o2) {
    //    return o1.GetSqrDistToCamFromCenter().CompareTo(o2.GetSqrDistToCamFromCenter());
    //}

    //public int FurthestToNearest(Octree o1, Octree o2) {
    //    return o2.GetSqrDistToCamFromCenter().CompareTo(o1.GetSqrDistToCamFromCenter());
    //}

    // returns a gameobject with proper components
    public static ChunkObject GetObject()
    {
        if (freeObjects.Count > 0)
        {
            ChunkObject free = freeObjects.Pop();
            free.go.SetActive(true);
            return(free);
        }

        return(new ChunkObject());
    }
        private static RenderMesh InitRenderMesh(ChunkObject chunkObject)
        {
            var meshRenderer = chunkObject.GetComponent <MeshRenderer>();

            return(new RenderMesh
            {
                material = meshRenderer.sharedMaterial,
                castShadows = meshRenderer.shadowCastingMode,
                receiveShadows = meshRenderer.receiveShadows,
                subMesh = 0
            });
        }
Exemplo n.º 9
0
 /* Initialize 3D grid of chunks */
 private void InitChunks()
 {
     for (int y = 0; y < numChunks; y++)
     {
         for (int x = 0; x < numChunks; x++)
         {
             for (int z = 0; z < numChunks; z++)
             {
                 chunks[x, y, z] = new ChunkObject(new Vector3Int(x * chunkSize, y * chunkSize, z * chunkSize), chunkPrefab);
             }
         }
     }
 }
Exemplo n.º 10
0
    public void InitializeChunk(int x, int z)
    {
        float xPos = x * (HexChunk.xOffset * HexChunk.size);
        float zPos = z * (HexChunk.zOffset * HexChunk.size);

        goChunk = new GameObject("Chunk " + x + "_" + z);
        goChunk.transform.position = new Vector3(xPos, 0, zPos);
        goChunk.transform.rotation = Quaternion.identity;
        goChunk.transform.SetParent(GridManager.I.transform);
        goChunk.tag = "Chunk";

        chunkObject = goChunk.AddComponent <ChunkObject>();
        chunkObject.InitializeChunkObject(new Chunk(x, z, xPos, zPos));
    }
Exemplo n.º 11
0
        public VoxelWorld(string name, int maxLights) : base(name, maxLights)
        {
            Initializer = () =>
            {
                var           green         = new Vector3(0x7e, 0xc8, 0x50) / 255.0f;
                ChunkStreamer chunkStreamer = new ChunkStreamer(1 << 16, this.Renderer);
                var           mat_id        = chunkStreamer.MaterialMap.Register(green, green * 0.25f, 0.9f, 0.0f);
                ChunkObject   obj           = new ChunkObject(chunkStreamer);

                //Engine.CurrentPlayer.Position += Vector3.UnitY * 110;

                Random rng = new Random(0);
                ulong  cnt = 0;
                Perlin p   = new Perlin();
                for (int x = ChunkConstants.Side * -10; x < ChunkConstants.Side * 10; x++)
                {
                    //for (int y = ChunkConstants.Side * -1; y < ChunkConstants.Side * 1; y++)
                    for (int z = ChunkConstants.Side * -10; z < ChunkConstants.Side * 10; z++)
                    {
                        //if (x * x + y * y + z * z <= 200 * 200)
                        //if(y > -32 && y < 32)
                        {
                            int y = (x == -300) ? 400 : (int)((p.GetValue(x * 0.005f, z * 0.005f, 0) * 0.5f + 0.5f) * 128);
                            if (y >= 0)
                            {
                                for (int y0 = y; y0 >= 0; y0--)
                                {
                                    obj.Set(x, y0, z, mat_id);
                                }
                            }
                            //else
                            //if (rng.NextDouble() > 0.5f)
                            //    obj.Set(x, y, z, mat_id);
                            cnt++;
                        }
                    }
                }
                obj.RebuildAll();

                Console.WriteLine(cnt);


                //AddRenderable(new StaticRenderable(Kokoro.Graphics.Prefabs.SphereFactory.Create(grp)));
                AddRenderable(chunkStreamer);
                AddRenderable(obj);

                AddRenderable(chunkStreamer.Ender);
                //w.AddInterpreter(new Input.DefaultControlInterpreter("/actions/vrworld/in/hand_left", "/actions/vrworld/in/hand_right", grp));
            };
        }
Exemplo n.º 12
0
    public void AddFeature(GameObject go, bool buffer = true)
    {
        ChunkObject c = go.GetComponent <ChunkObject>(); //to get it to work, assign every ChunkObject prefab the script and add an id.

        c.myId  = objects.Count;
        c.chunk = this;
        objects.Add(nid, c);
        nid++;
        if (buffer)
        {
            ChunkMod result = new ChunkMod(ChunkMod.ChunkModType.Add, go.transform.position, c.myId, c.model);
            Server.bufferedChunkmods.Add(result);
            ServerSend.ChunkMod(result);
        }
    }
Exemplo n.º 13
0
    public static ChunkObject Instance(World world, Chunk chunk)
    {
        GameObject gameObject = new GameObject("Chunk @ (" + chunk.WorldX + "," + chunk.WorldZ + ")");

        gameObject.transform.parent   = world.transform;
        gameObject.transform.position = new Vector3(chunk.WorldX, 0, chunk.WorldZ);
        gameObject.transform.rotation = Quaternion.identity;
        gameObject.AddComponent <MeshRenderer> ().sharedMaterials = world.materials;
        gameObject.renderer.castShadows    = true;
        gameObject.renderer.receiveShadows = true;
        ChunkObject chunkObject = gameObject.AddComponent <ChunkObject> ();

        chunkObject.Initialize(world, chunk, gameObject.AddComponent <MeshFilter> (), gameObject.AddComponent <MeshCollider> ());
        return(chunkObject);
    }
Exemplo n.º 14
0
    public bool TryGetPooledObject(out ChunkObject chunk)
    {
        chunk = null;

        foreach (var obj in pooledObjects)
        {
            if (!obj.gameObject.activeInHierarchy)
            {
                chunk = obj;
                return(true);
            }
        }

        return(false);
    }
Exemplo n.º 15
0
    void Start()
    {
        voxels = WorldGenerator.CreateVoxels(65, 0, 1, Vector3.zero);

        data = MarchingCubes.CalculateMeshData(voxels, 1);
        data.CalculateVertexSharing();
        data.CalculateNormals();

        simp = new Simplification(data.vertices, data.triangles);

        mesh = data.CreateMesh();

        go               = SplitManager.GetObject();
        go.mr.material   = mat;
        go.mf.sharedMesh = mesh;
    }
Exemplo n.º 16
0
    public void SetupChunk()
    {
        obj = SplitManager.GetObject();
        //obj.go.name = GetTreeName();

        obj.go.transform.parent        = body.transform;
        obj.go.transform.localPosition = worldPos;
        obj.go.transform.localRotation = Quaternion.identity;
        //obj.go.transform.position = pos;

        obj.mr.material = body.terrainMat; // incase terrain is edited after
                                           //obj.mpb.SetVector(ShaderProps.LocalOffset, worldPos); // not sure what this was for
                                           //obj.UpdatePropBlock();

        obj.ov.init(depth, branch, worldPos, localArea, body, depth == 0 ? Color.blue : Color.red);
    }
Exemplo n.º 17
0
    public InMemoryWorldStream(int worldSeed)
    {
        for (var i = 0; i < 100000; i++) {
            float xLocation = UnityEngine.Random.Range(-25000, 25000);
            float yLocation = UnityEngine.Random.Range(-25000, 25000);
            float zLocation = UnityEngine.Random.Range(-25000, 25000);

                ChunkObject newobject = new ChunkObject(){
                    Position = new Vector3(xLocation, yLocation, zLocation),
                    Scale = Vector3.one,
                    Rotation = Quaternion.identity,
                    ChunkObjectType = "Asteroid"};

            octree.Insert(new Bounds(newobject.Position, newobject.Scale), newobject);
        }
    }
Exemplo n.º 18
0
    public List<ChunkObject> GetObjects(Bounds mapbounds)
    {
        int numberOfObjects = UnityEngine.Random.Range(0, 10000);

        List<ChunkObject> retEnum = new List<ChunkObject>(numberOfObjects);
        for (int i = 0; i < numberOfObjects; i++)
        {
            // Get the position of the new object
            float xLocation = UnityEngine.Random.Range(mapbounds.min.x, mapbounds.max.x);
            float yLocation = UnityEngine.Random.Range(mapbounds.min.y, mapbounds.max.y);
            float zLocation = UnityEngine.Random.Range(mapbounds.min.z, mapbounds.max.z);

            ChunkObject newobject = new ChunkObject(){
                Position = new Vector3(xLocation, yLocation, zLocation),
                Scale = Vector3.one,
                Rotation = Quaternion.identity,
                ChunkObjectType = "Asteroid"};

            retEnum.Add(newobject);
        }

        return retEnum;
    }
Exemplo n.º 19
0
 public BlockGeometry(ChunkObject parent, Vector3Int position, byte blockType)
 {
     this.parent    = parent;
     this.position  = position;
     this.blockType = blockType;
 }
Exemplo n.º 20
0
        /// <summary>
        /// Generates block types with hp and hp level.
        /// Chunks and their objects (if first run = true).
        /// And calculates faces.
        /// </summary>
        public IEnumerator LoadWorld(bool firstRun, Action callback)
        {
            ResetProgressBarVariables();
            _stopwatch.Restart();

            ProgressDescription = "Loading data...";
            Status = WorldGeneratorStatus.NotReady;
            var          storage = new PersistentStorage(CHUNK_SIZE);
            SaveGameData save    = storage.LoadGame();

            Settings.WorldSizeX  = save.WorldSizeX;
            Settings.WorldSizeZ  = save.WorldSizeZ;
            PlayerLoadedPosition = save.PlayerPosition;
            PlayerLoadedRotation = save.PlayerRotation;
            AlreadyGenerated    += _progressStep;
            yield return(null); // give back control

            ProgressDescription = "Creating game objects...";
            if (firstRun)
            {
                _worldScene = SceneManager.CreateScene(name);
            }

            Blocks            = save.Blocks;
            Status            = WorldGeneratorStatus.TerrainReady;
            AlreadyGenerated += _progressStep;
            yield return(null); // give back control

            if (firstRun)
            {
                ProgressDescription = "Chunk data initialization...";
                // chunkData need to be initialized earlier in order to allow main loop iterate over chunks before their meshes are ready
                // thanks to this we can display chunk as soon as they become ready
                Chunks = new ChunkData[Settings.WorldSizeX, WORLD_SIZE_Y, Settings.WorldSizeZ];
                for (int x = 0; x < Settings.WorldSizeX; x++)
                {
                    for (int z = 0; z < Settings.WorldSizeZ; z++)
                    {
                        for (int y = 0; y < WORLD_SIZE_Y; y++)
                        {
                            Chunks[x, y, z] = new ChunkData(
                                new Vector3Int(x, y, z),
                                new Vector3Int(x * CHUNK_SIZE, y * CHUNK_SIZE, z * CHUNK_SIZE));
                        }
                    }
                }

                ChunkObjects      = new ChunkObject[Settings.WorldSizeX, WORLD_SIZE_Y, Settings.WorldSizeZ];
                AlreadyGenerated += _progressStep;
                yield return(null); // give back control
            }

            ProgressDescription = "Calculating faces...";
            _meshGenerator.CalculateFaces(ref Blocks);
            AlreadyGenerated += _progressStep;
            yield return(null); // give back control

            ProgressDescription = "World boundaries check...";
            _meshGenerator.WorldBoundariesCheck(ref Blocks);
            Status            = WorldGeneratorStatus.FacesReady;
            AlreadyGenerated += _progressStep;
            yield return(null); // give back control

            ProgressDescription = "Creating chunks...";
            // create chunk objects one by one
            for (int x = 0; x < Settings.WorldSizeX; x++)
            {
                for (int z = 0; z < Settings.WorldSizeZ; z++)
                {
                    for (int y = 0; y < WORLD_SIZE_Y; y++)
                    {
                        ChunkData chunkData = Chunks[x, y, z];
                        _meshGenerator.CalculateMeshes(ref Blocks, chunkData.Position, out Mesh terrainMesh, out Mesh waterMesh);

                        if (firstRun)
                        {
                            var chunkObject = new ChunkObject();
                            CreateChunkGameObjects(ref chunkData, ref chunkObject, terrainMesh, waterMesh);
                            SceneManager.MoveGameObjectToScene(chunkObject.Terrain.gameObject, _worldScene);
                            SceneManager.MoveGameObjectToScene(chunkObject.Water.gameObject, _worldScene);
                            ChunkObjects[x, y, z] = chunkObject;
                        }
                        else
                        {
                            SetMeshesAndCollider(ref chunkData, ref ChunkObjects[x, y, z], terrainMesh, waterMesh);
                        }

                        Chunks[x, y, z].Status = ChunkStatus.NeedToBeRedrawn;
                        AlreadyGenerated++;

                        yield return(null); // give back control
                    }
                }
            }

            Status = WorldGeneratorStatus.AllReady;

            _stopwatch.Stop();
            UnityEngine.Debug.Log($"It took {_stopwatch.ElapsedTicks / TimeSpan.TicksPerMillisecond} ms to load all terrain.");

            AlreadyGenerated    = TerrainProgressSteps + MeshProgressSteps; // hardcoded end indicator
            ProgressDescription = "Game Load Completed";

            callback?.Invoke();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Generates block types with hp and hp level.
        /// Chunks and their objects (if first run = true).
        /// And calculates faces.
        /// </summary>
        public IEnumerator CreateWorld(bool firstRun, Action callback)
        {
            _terrainGenerator.Initialize(Settings);
            _meshGenerator.Initialize(Settings);

            _stopwatch.Restart();
            ResetProgressBarVariables();

            ProgressDescription = "Initialization...";
            Status            = WorldGeneratorStatus.NotReady;
            Blocks            = new BlockData[Settings.WorldSizeX * CHUNK_SIZE, WORLD_SIZE_Y *CHUNK_SIZE, Settings.WorldSizeZ *CHUNK_SIZE];
            AlreadyGenerated += _progressStep;
            yield return(null);

            if (Settings.ComputingAcceleration == ComputingAcceleration.UnityJobSystem)
            {
                ProgressDescription = "Calculating heights...";
                var heights = _terrainGenerator.CalculateHeightsJobSystem();
                AlreadyGenerated += _progressStep;
                yield return(null);

                ProgressDescription = "Calculating block types...";
                var types = _terrainGenerator.CalculateBlockTypes(heights);
                AlreadyGenerated += _progressStep;
                yield return(null);

                ProgressDescription = "Job output deflattenization...";
                DeflattenizeOutput(ref types);
                AlreadyGenerated += _progressStep;
                yield return(null);
            }
            else if (Settings.ComputingAcceleration == ComputingAcceleration.PureCSParallelisation)
            {
                ProgressDescription = "Calculating block types...";
                _terrainGenerator.CalculateBlockTypesParallel();
                AlreadyGenerated += _progressStep * 3;
                yield return(null);
            }

            if (Settings.IsWater)
            {
                ProgressDescription = "Generating water...";
                _terrainGenerator.AddWater(ref Blocks);
            }
            AlreadyGenerated += _progressStep;
            yield return(null);

            ProgressDescription = "Generating trees...";
            _terrainGenerator.AddTreesParallel(Settings.TreeProbability);
            AlreadyGenerated += _progressStep;
            yield return(null);

            ProgressDescription = "Chunk data initialization...";
            if (firstRun)
            {
                _worldScene = SceneManager.CreateScene(name);
            }

            // chunkData need to be initialized earlier in order to allow main loop iterate over chunks before their meshes are ready
            // thanks to this we can display chunk as soon as they become ready
            Chunks = new ChunkData[Settings.WorldSizeX, WORLD_SIZE_Y, Settings.WorldSizeZ];
            for (int x = 0; x < Settings.WorldSizeX; x++)
            {
                for (int z = 0; z < Settings.WorldSizeZ; z++)
                {
                    for (int y = 0; y < WORLD_SIZE_Y; y++)
                    {
                        Chunks[x, y, z] = new ChunkData(new Vector3Int(x, y, z), new Vector3Int(x * CHUNK_SIZE, y * CHUNK_SIZE, z * CHUNK_SIZE));
                    }
                }
            }

            ChunkObjects = new ChunkObject[Settings.WorldSizeX, WORLD_SIZE_Y, Settings.WorldSizeZ];
            yield return(null);

            ProgressDescription = "Calculating faces...";
            _meshGenerator.CalculateFaces(ref Blocks);
            AlreadyGenerated += _progressStep;
            yield return(null);

            ProgressDescription = "World boundaries check...";
            _meshGenerator.WorldBoundariesCheck(ref Blocks);
            AlreadyGenerated += _progressStep;
            yield return(null);

            ProgressDescription = "Creating chunks...";
            // create chunk objects one by one
            for (int x = 0; x < Settings.WorldSizeX; x++)
            {
                for (int z = 0; z < Settings.WorldSizeZ; z++)
                {
                    for (int y = 0; y < WORLD_SIZE_Y; y++)
                    {
                        ChunkData chunkData = Chunks[x, y, z];
                        _meshGenerator.CalculateMeshes(ref Blocks, chunkData.Position, out Mesh terrainMesh, out Mesh waterMesh);

                        if (firstRun)
                        {
                            var chunkObject = new ChunkObject();
                            CreateChunkGameObjects(ref chunkData, ref chunkObject, terrainMesh, waterMesh);
                            SceneManager.MoveGameObjectToScene(chunkObject.Terrain.gameObject, _worldScene);
                            SceneManager.MoveGameObjectToScene(chunkObject.Water.gameObject, _worldScene);
                            ChunkObjects[x, y, z] = chunkObject;
                        }
                        else
                        {
                            SetMeshesAndCollider(ref chunkData, ref ChunkObjects[x, y, z], terrainMesh, waterMesh);
                        }

                        Chunks[x, y, z].Status = ChunkStatus.NeedToBeRedrawn;
                        AlreadyGenerated++;

                        yield return(null); // give back control
                    }
                }
            }

            Status            = WorldGeneratorStatus.AllReady;
            AlreadyGenerated += _progressStep;

            _stopwatch.Stop();
            UnityEngine.Debug.Log($"It took {_stopwatch.ElapsedTicks / TimeSpan.TicksPerMillisecond} ms to generate the world.");

            ProgressDescription = "Generation Completed";
            callback?.Invoke();
        }
Exemplo n.º 22
0
	// Create a chunk
	public void CreateChunkMesh(int x, int y, int z, ChunkObject chunkObject)
	{
		chunkObject.ChunkMesh.mesh = ChunkRenderer.Render(_chunks[x,y,z]);
		chunkObject.ChunkCollider.sharedMesh = chunkObject.ChunkMesh.mesh;
		_chunks[x,y,z].ChunkObject = chunkObject;
	}
Exemplo n.º 23
0
 static void Postfix(TerrainGeneration __instance, ref ChunkObject chunk)
 {
     chunk.MeshRenderer.sharedMaterial.SetVector("_WorldOrigin", WorldManager.OriginPositionLoading + new Vector3(0, 150, 0));
 }
Exemplo n.º 24
0
 // Create a chunk
 public void CreateChunkMesh(int x, int y, int z, ChunkObject chunkObject)
 {
     chunkObject.ChunkMesh.mesh           = ChunkRenderer.Render(_chunks[x, y, z]);
     chunkObject.ChunkCollider.sharedMesh = chunkObject.ChunkMesh.mesh;
     _chunks[x, y, z].ChunkObject         = chunkObject;
 }
Exemplo n.º 25
0
 private void OnChunkBuilt(ChunkObject chunk)
 {
     _loadCount++;
     WatchdogTimer.Reset();
     WatchdogTimer.Start();
 }
Exemplo n.º 26
0
        /// <summary>
        /// Generates block types with hp and hp level.
        /// Chunks and their objects (if first run = true).
        /// And calculates faces.
        /// </summary>
        public IEnumerator CreateWorld(bool firstRun, Action callback)
        {
            MainController.InitializeOnWorldSizeChange();

            _stopwatch.Restart();
            ResetProgressBarVariables();

            ProgressDescription = "Initialization...";
            Status = WorldGeneratorStatus.NotReady;
            GlobalVariables.Blocks = new BlockData[
                GlobalVariables.Settings.WorldSizeX * Constants.CHUNK_SIZE,
                Constants.WORLD_SIZE_Y *Constants.CHUNK_SIZE, GlobalVariables.Settings.WorldSizeZ *Constants.CHUNK_SIZE];

            AlreadyGenerated += _progressStep;
            yield return(null); // return control

            ProgressDescription = "Calculating block types...";
            TerrainGenerationAbstractionLayer.CalculateBlockTypes();
            AlreadyGenerated += _progressStep;
            yield return(null); // return control to update the UI

            if (GlobalVariables.Settings.IsWater)
            {
                ProgressDescription = "Generating water...";
                TerrainGenerationAbstractionLayer.AddWater();
            }
            AlreadyGenerated += _progressStep;
            yield return(null); // return control

            ProgressDescription = "Generating trees...";
            TerrainGenerationAbstractionLayer.AddTrees();
            AlreadyGenerated += _progressStep;
            yield return(null); // return control

            ProgressDescription = "Chunk data initialization...";
            if (firstRun)
            {
                _worldScene = SceneManager.CreateScene(name);
            }

            // chunkData need to be initialized earlier in order to allow main loop iterate over chunks before their meshes are ready
            // thanks to this we can display chunk as soon as they become ready
            GlobalVariables.Chunks = new ChunkData[GlobalVariables.Settings.WorldSizeX, Constants.WORLD_SIZE_Y, GlobalVariables.Settings.WorldSizeZ];
            for (int x = 0; x < GlobalVariables.Settings.WorldSizeX; x++)
            {
                for (int z = 0; z < GlobalVariables.Settings.WorldSizeZ; z++)
                {
                    for (int y = 0; y < Constants.WORLD_SIZE_Y; y++)
                    {
                        GlobalVariables.Chunks[x, y, z] = new ChunkData(
                            coord: new ReadonlyVector3Int(x, y, z),
                            position: new ReadonlyVector3Int(x * Constants.CHUNK_SIZE, y * Constants.CHUNK_SIZE, z * Constants.CHUNK_SIZE));
                    }
                }
            }

            ChunkObjects = new ChunkObject[GlobalVariables.Settings.WorldSizeX, Constants.WORLD_SIZE_Y, GlobalVariables.Settings.WorldSizeZ];
            yield return(null); // return control

            ProgressDescription = "Calculating faces...";
            MeshGenerationAbstractionLayer.CalculateFaces();
            AlreadyGenerated += _progressStep;
            yield return(null); // return control

            ProgressDescription = "World boundaries check...";
            MeshGenerationAbstractionLayer.WorldBoundariesCheck();
            AlreadyGenerated += _progressStep;
            yield return(null); // return control

            ProgressDescription = "Creating chunks...";
            // create chunk objects one by one
            for (int x = 0; x < GlobalVariables.Settings.WorldSizeX; x++)
            {
                for (int z = 0; z < GlobalVariables.Settings.WorldSizeZ; z++)
                {
                    for (int y = 0; y < Constants.WORLD_SIZE_Y; y++)
                    {
                        ChunkData chunkData = GlobalVariables.Chunks[x, y, z];
                        MeshGenerationAbstractionLayer.CalculateMeshes(in chunkData.Position, out Mesh terrainMesh, out Mesh waterMesh);

                        if (firstRun)
                        {
                            var chunkObject = new ChunkObject();
                            CreateChunkGameObjects(ref chunkData, ref chunkObject, terrainMesh, waterMesh);
                            SceneManager.MoveGameObjectToScene(chunkObject.Terrain.gameObject, _worldScene);
                            SceneManager.MoveGameObjectToScene(chunkObject.Water.gameObject, _worldScene);
                            ChunkObjects[x, y, z] = chunkObject;
                        }
                        else
                        {
                            SetMeshesAndCollider(ref chunkData, ref ChunkObjects[x, y, z], terrainMesh, waterMesh);
                        }

                        GlobalVariables.Chunks[x, y, z].Status = ChunkStatus.NeedToBeRedrawn;
                        AlreadyGenerated++;

                        yield return(null); // return control
                    }
                }
            }

            Status            = WorldGeneratorStatus.AllReady;
            AlreadyGenerated += _progressStep;

            _stopwatch.Stop();
            UnityEngine.Debug.Log($"It took {_stopwatch.ElapsedTicks / TimeSpan.TicksPerMillisecond} ms to generate the world.");

            ProgressDescription = $"Generation Completed {_stopwatch.ElapsedTicks / TimeSpan.TicksPerMillisecond} ms";
            callback?.Invoke();
        }
Exemplo n.º 27
0
 public static void ReturnObject(ChunkObject obj)
 {
     obj.Reset(tform);
     freeObjects.Push(obj);
 }