private void OnValidate()
    {
        terrainSystem = gameObject.GetComponent <TerrainSystem>();

        cells    = new TerrainCell[21];
        cells[0] = new TerrainCell(M0000);
        cells[1] = new TerrainCell(M000A);
        cells[2] = new TerrainCell(M000A, true, 3);// 000B
        cells[3] = new TerrainCell(M00AB);
        cells[4] = new TerrainCell(M00BA);
        cells[5] = new TerrainCell(M0A0B);

        cells[6]  = new TerrainCell(M0AAB);
        cells[7]  = new TerrainCell(M0AAB, true, 1); // 0ABB
        cells[8]  = new TerrainCell(M0BBA);
        cells[9]  = new TerrainCell(M0BBA, true, 1); // 0BAA
        cells[10] = new TerrainCell(M0ABA);
        cells[11] = new TerrainCell(M0ABA, true, 1); // 0BAB

        cells[12] = new TerrainCell(MAAAB);
        cells[13] = new TerrainCell(MAAAB, true, 0);// ABBB
        cells[14] = new TerrainCell(MAABB0);
        cells[15] = new TerrainCell(MAABB1);
        cells[16] = new TerrainCell(MAABB1, true, 0);// AABB2
        cells[17] = new TerrainCell(MABAB0);
        cells[18] = new TerrainCell(MABAB1);
        cells[19] = new TerrainCell(MABAB2);
        cells[20] = new TerrainCell(MABAB3);
    }
Exemplo n.º 2
0
 void Awake()
 {
     if (TerrainSystem == null)
     {
         TerrainSystem = ScriptableObject.CreateInstance <TerrainSystem>().Initialise(this);
     }
 }
Exemplo n.º 3
0
 public void UpdateHeight(float value, TerrainSystem terrainSystem)
 {
     terrainSystem.heightMap[index] += value;
     for (int i = 0; i < vertexIndices.Length; i++)
     {
         terrainSystem.vertexData[vertexIndices[i]].y = terrainSystem.heightMap[index];
     }
 }
Exemplo n.º 4
0
 public void SetPosition(float x, float y, TerrainSystem terrainSystem)
 {
     for (int i = 0; i < vertexIndices.Length; i++)
     {
         terrainSystem.vertexData[vertexIndices[i]].x = x;
         terrainSystem.vertexData[vertexIndices[i]].z = y;
     }
 }
 public void SetHeight(float value, TerrainSystem terrainSystem)
 {
     terrainSystem.HeightMap[Index] = value;
     for (int i = 0; i < VertexIndices.Length; i++)
     {
         terrainSystem.VertexData[VertexIndices[i]].y = terrainSystem.HeightMap[Index];
     }
 }
Exemplo n.º 6
0
    public static void SaveTerrain(TerrainSystem terrain)
    {
        string          path      = Application.persistentDataPath + defaultFileName;
        BinaryFormatter formatter = new BinaryFormatter();
        FileStream      stream    = new FileStream(path, FileMode.OpenOrCreate);

        TerrainData data = new TerrainData(TerrainSystem.local);

        formatter.Serialize(stream, data);
        stream.Close();
    }
        public VerletDebrisSystem(int maxNumParticles, float timestep, int maxIterations, Material material, Bounds bounds, TerrainSystem terrainSystem)
        {
            this.timestep      = timestep;
            this.maxIterations = maxIterations;
            this.material      = material;
            this.bounds        = bounds;
            this.terrainSystem = terrainSystem;

            positionsBuffer     = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)));
            velocitiesBuffer    = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)));
            lifetimesBuffer     = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)));
            predictedBuffers    = new ComputeBuffer[2];
            predictedBuffers[0] = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)));
            predictedBuffers[1] = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)));
            deadBuffer          = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(uint)), ComputeBufferType.Append);
            deadBuffer.SetCounterValue(0);
            aliveBuffer = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(uint)), ComputeBufferType.Append);
            aliveBuffer.SetCounterValue(0);
            emitBuffer = new ComputeBuffer(THREADS, Marshal.SizeOf(typeof(Vector4)));
            counter    = new ComputeBuffer(4, Marshal.SizeOf(typeof(uint)), ComputeBufferType.IndirectArguments);
            counter.SetData(new int[] { 0, 1, 0, 0 });
            emitCounter = new ComputeBuffer(4, Marshal.SizeOf(typeof(uint)), ComputeBufferType.IndirectArguments);
            emitCounter.SetData(new int[] { 0, 1, 0, 0 });
            argsBuffer = new ComputeBuffer(5, Marshal.SizeOf(typeof(uint)), ComputeBufferType.IndirectArguments);

            GameObject o = GameObject.CreatePrimitive(PrimitiveType.Quad);

            mesh = o.GetComponent <MeshFilter>().sharedMesh;
            GameObject.DestroyImmediate(o);
            uint[] argsData = new uint[] { mesh.GetIndexCount(0), 0, 0, 0, 0 };
            argsBuffer.SetData(argsData);

            computeShader = (ComputeShader)Resources.Load("VerletDebrisSystem");
            computeShader.SetFloat("DT", timestep);
            computeShader.SetVector("Gravity", new Vector2(0, -98.1f));
            computeShader.SetFloat("Damping", 0.5f);
            computeShader.SetVector("_TerrainDistanceFieldScale", terrainSystem.terrainDistanceFieldScale);
            computeShader.SetFloat("_TerrainDistanceFieldMultiplier", terrainSystem.terrainDistanceFieldMultiplier);

            int initKernel = computeShader.FindKernel("Init");

            computeShader.SetInt("Width", positionsBuffer.count);
            computeShader.SetBuffer(initKernel, "PositionsWRITE", positionsBuffer);
            computeShader.SetBuffer(initKernel, "VelocitiesWRITE", velocitiesBuffer);
            computeShader.SetBuffer(initKernel, "Lifetimes", lifetimesBuffer);
            computeShader.SetBuffer(initKernel, "Dead", deadBuffer);
            computeShader.Dispatch(initKernel, Groups(maxNumParticles), 1, 1);

            hash = new GridHash(bounds, maxNumParticles, 1);
            computeShader.SetFloat("HashScale", hash.InvCellSize);
            computeShader.SetVector("HashSize", hash.Bounds.size);
            computeShader.SetVector("HashTranslate", hash.Bounds.min);
        }
Exemplo n.º 8
0
    protected override void OnCreateManager()
    {
        entityManager  = World.Active.GetOrCreateManager <EntityManager>();
        terrainSystem  = World.Active.GetOrCreateManager <TerrainSystem>();
        sectorSize     = TerrainSettings.sectorSize;
        cubeDirections = new CubeDirections();

        EntityArchetypeQuery adjSectorsQuery = new EntityArchetypeQuery
        {
            Any  = new ComponentType[] { typeof(InnerDrawRangeSectorTag), typeof(OuterDrawRangeSectorTag) },
            None = new ComponentType[] { typeof(NotInDrawRangeSectorTag), typeof(GetSectorTopography), typeof(GenerateSectorGeology) },
            All  = new ComponentType[] { typeof(Sector), typeof(GetAdjacentSectors) }
        };

        adjSectorsGroup = GetComponentGroup(adjSectorsQuery);
    }
Exemplo n.º 9
0
    public void Build(
        TerrainSystem terrainSystem,
        int xPosition,
        int zPosition,
        int blockWidth,
        int blockLength
        )
    {
        this.terrainSystem = terrainSystem;
        this.XPosition     = xPosition;
        this.ZPosition     = zPosition;
        this.BlockWidth    = blockWidth;
        this.BlockLength   = blockLength;

        Sample();
        GenerateMesh();
    }
Exemplo n.º 10
0
    public static void CommandSetGround(CommandArg[] args)
    {
        TerrainSystem terrain = FindObjectOfType <TerrainSystem>();
        BlockStyle    style;
        int           shape = 0;

        // Special argument 'Empty' means empty shape.
        if (args[0].ToString() == "Empty")
        {
            style = BlockStyle.SolidColor0;
            shape = -1;
        }
        else if (!Util.TryParseEnum <BlockStyle>(args[0].ToString(), out style, true))
        {
            HeadlessTerminal.Log("Invalid block style: " + args[0].ToString() +
                                 ". Valid values are: " + string.Join("\n", Util.ValuesOf <BlockStyle>()));
            return;
        }
        TerrainSystem ts = FindObjectOfType <TerrainSystem>();

        ts.SetSlices(0, (0 - BlocksYStart), (int)style, shape, 0);
    }
Exemplo n.º 11
0
    private void InspectWorld(TerrainSystem terrainSystem)
    {
        if (terrainSystem == null)
        {
            return;
        }
        using (new EditorGUILayout.VerticalScope("Button")) {
            GUI.backgroundColor = Color.white;
            EditorGUILayout.HelpBox("World", MessageType.None);

            terrainSystem.SetSize(EditorGUILayout.Vector2Field("Size", terrainSystem.Size));
            Vector2 resolution = EditorGUILayout.Vector2Field("Resolution", new Vector2(Resolution.x, Resolution.y));
            Resolution = new Vector2i((int)resolution.x, (int)resolution.y);
            if (Resolution.x != terrainSystem.Resolution.x || Resolution.y != terrainSystem.Resolution.y)
            {
                EditorGUILayout.HelpBox("Changing the resolution will reset the world.", MessageType.Warning);
                if (GUILayout.Button("Apply"))
                {
                    terrainSystem.SetResolution(Resolution);
                }
            }
        }
    }
Exemplo n.º 12
0
    public virtual void Start()
    {
        time   = 0;
        locked = true;

        m_Animator = gameObject.GetComponent <Animator>();


        if (tracker != null)
        {
            basecolor = (ColorTracker)tracker.GetComponent(typeof(ColorTracker));
            if (basecolor == null)
            {
                Debug.Log("not in color");
            }
        }

        if (master != null)
        {
            puzzleboss = (PuzzleSystem)master.GetComponent(typeof(PuzzleSystem));
            if (puzzleboss == null)
            {
                Debug.Log("why though");
            }
        }



        if (square1 != null)
        {
            script1 = (TerrainSystem)square1.GetComponent(typeof(TerrainSystem));
        }
        if (square2 != null)
        {
            script2 = (TerrainSystem)square2.GetComponent(typeof(TerrainSystem));
        }
        if (square3 != null)
        {
            script3 = (TerrainSystem)square3.GetComponent(typeof(TerrainSystem));
        }
        if (square4 != null)
        {
            script4 = (TerrainSystem)square4.GetComponent(typeof(TerrainSystem));
        }
        if (square5 != null)
        {
            script5 = (TerrainSystem)square5.GetComponent(typeof(TerrainSystem));
        }
        if (square6 != null)
        {
            script6 = (TerrainSystem)square6.GetComponent(typeof(TerrainSystem));
        }
        if (square7 != null)
        {
            script7 = (TerrainSystem)square7.GetComponent(typeof(TerrainSystem));
        }
        if (square8 != null)
        {
            script8 = (TerrainSystem)square8.GetComponent(typeof(TerrainSystem));
        }

        //Additional();
    }
        public LeapfrogDebrisSystem(int maxNumParticles, float timestep, int maxIterations, Material material, Bounds bounds, TerrainSystem terrainSystem)
        {
            this.timestep      = timestep;
            this.maxIterations = maxIterations;
            this.material      = material;
            this.bounds        = bounds;
            this.terrainSystem = terrainSystem;

            explosionsBuffer = new ComputeBuffer(16, Marshal.SizeOf(typeof(Vector4)), ComputeBufferType.Default);

            positionsBuffers     = new ComputeBuffer[2];
            positionsBuffers[0]  = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)));
            positionsBuffers[1]  = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)));
            velocitiesBuffers    = new ComputeBuffer[2];
            velocitiesBuffers[0] = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)));
            velocitiesBuffers[1] = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)));
            lifetimesBuffer      = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)));
            motionsBuffer        = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(float)));
            colorsBuffer         = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector4)));

            deadBuffer = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(uint)), ComputeBufferType.Append);
            deadBuffer.SetCounterValue(0);
            aliveBuffer = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(uint)), ComputeBufferType.Append);
            aliveBuffer.SetCounterValue(0);
            addTerrainBuffer = new ComputeBuffer(maxNumParticles, Marshal.SizeOf(typeof(Vector2)), ComputeBufferType.Append);
            addTerrainBuffer.SetCounterValue(0);

            counter = new ComputeBuffer(4, Marshal.SizeOf(typeof(uint)), ComputeBufferType.IndirectArguments);
            counter.SetData(new int[] { 0, 1, 0, 0 });
            counterIndex = new ComputeBuffer(1, Marshal.SizeOf(typeof(uint)), ComputeBufferType.Raw);
            emitCounter  = new ComputeBuffer(4, Marshal.SizeOf(typeof(uint)), ComputeBufferType.IndirectArguments);
            emitCounter.SetData(new uint[] { 0, 1, 0, 0 });
            argsBuffer = new ComputeBuffer(5, Marshal.SizeOf(typeof(uint)), ComputeBufferType.IndirectArguments);

            GameObject o = GameObject.CreatePrimitive(PrimitiveType.Quad);

            mesh = o.GetComponent <MeshFilter>().sharedMesh;
            GameObject.DestroyImmediate(o);
            uint[] argsData = new uint[] { mesh.GetIndexCount(0), 0, 0, 0, 0 };
            argsBuffer.SetData(argsData);

            computeShader = (ComputeShader)Resources.Load("LeapfrogDebrisSystem");
            computeShader.SetFloat("DT", timestep);
            computeShader.SetVector("Gravity", new Vector2(0, -98.1f));
            computeShader.SetFloat("Damping", 0.99f);
            computeShader.SetVector("_TerrainDistanceFieldScale", terrainSystem.terrainDistanceFieldScale);
            computeShader.SetFloat("_TerrainDistanceFieldMultiplier", terrainSystem.terrainDistanceFieldMultiplier);
            computeShader.SetVector("_TerrainSize", new Vector2(terrainSystem.width, terrainSystem.height));

            Vector2 boundsMin    = bounds.min;
            Vector2 boundsMax    = bounds.max;
            Vector4 boundsVector = new Vector4(boundsMin.x, boundsMin.y, boundsMax.x, boundsMax.y);

            computeShader.SetVector("Bounds", boundsVector);

            int initKernel = computeShader.FindKernel("Init");

            computeShader.SetInt("Width", maxNumParticles);
            computeShader.SetBuffer(initKernel, "Lifetimes", lifetimesBuffer);
            computeShader.SetBuffer(initKernel, "Dead", deadBuffer);
            computeShader.Dispatch(initKernel, Groups(maxNumParticles), 1, 1);

            hash = new GridHash(bounds, maxNumParticles, 1.1283791671f);
            computeShader.SetFloat("HashScale", hash.InvCellSize);
            computeShader.SetVector("HashSize", hash.Bounds.size);
            computeShader.SetVector("HashTranslate", hash.Bounds.min);
        }
 void OnEnable()
 {
     terrainSystem = (TerrainSystem)target;
 }
Exemplo n.º 15
0
 public float GetHeight(TerrainSystem terrainSystem)
 {
     return(terrainSystem.heightMap[index]);
 }
Exemplo n.º 16
0
    public void Reset(
        Vector2 worldSize, byte[] terrainV2Data,
        bool loadingDataFromBeforeDigging,
        byte[] legacyData,
        ulong[] customStyleWorkshopIds = null,
        string simpleData = null)
    {
        Debug.Assert(worldSize.magnitude > 0f);
        Util.Log($"Resetting terrain!");

        float groundSizeX = worldSize.x;
        float groundSizeZ = worldSize.y;

        var newDims = new Int3(
            Mathf.CeilToInt(groundSizeX / BLOCK_SIZE.x),
            BlocksYCount,
            Mathf.CeilToInt(groundSizeZ / BLOCK_SIZE.z));

        Debug.Assert(newDims >= new Int3(10, 10, 10));

        Int3 newBotCenter = new Int3(newDims.x / 2, 0, newDims.z / 2);

        // If old data exists, make sure we restore it. This is the resize use case.
        byte[] restoreData = null;
        Int3   restoreDims = Int3.zero();

        if (terrainV2 != null)
        {
            var oldDims = terrainV2.GetWorldDimensions();
            restoreDims = Int3.Min(oldDims, newDims);
            Int3 start = oldDims / 2 - restoreDims / 2;
            Int3 end   = start + restoreDims;
            Debug.Assert(start >= Int3.zero());
            Debug.Assert(end <= oldDims);
            restoreData = terrainV2.Serialize(start, end);

            Destroy(terrainV2.gameObject);
            terrainV2 = null;
        }

        using (Util.Profile("terrainV2 instantiate"))
            terrainV2 = Instantiate(terrainV2Prefab, Vector3.zero, Quaternion.identity, this.transform);

        using (Util.Profile("terrainV2 SetWorldDimensions"))
            terrainV2.SetWorldDimensions(newDims);

        terrainV2.SetRootOffset(new Vector3(
                                    -newDims.x / 2 * 2.5f,
                                    BlocksYStart * BlockHeight + BlockHeight / 2f,
                                    -newDims.z / 2 * 2.5f));

        using (Util.Profile("Create color terrain textures"))
        {
            int texSize = terrainV2.GetStyleTextureResolution();
            // Color32 way faster in general than Color.
            for (int i = 0; i < NumSolidColorStyles; i++)
            {
                Color32[] pixels  = new Color32[texSize * texSize];
                Color32   color32 = rendering.blockColors[i];
                for (int j = 0; j < pixels.Length; j++)
                {
                    pixels[j] = color32;
                }
                terrainV2.SetStyleTextures(i, pixels); // color

                // 10 is orange
                if (i == (int)BlockStyle.SolidColor10)
                {
                    fallbackTexture = pixels;
                }
            }
        }

        Debug.Assert(fallbackTexture != null, "Could not find fallbackTexture?");

        // TODO why do we do these specifically? Are they not read in via the loop below?
        terrainV2.SetStyleTextures((int)BlockStyle.Stone, terrainV2Textures[4].GetPixels32());                                                                              // stone
        terrainV2.SetStyleTextures((int)BlockStyle.Space, terrainV2Textures[1].GetPixels32());                                                                              // metal
        terrainV2.SetStyleTextures((int)BlockStyle.Grass, terrainV2Textures[8].GetPixels32(), terrainV2Textures[7].GetPixels32(), terrainV2Textures[6].GetPixels32());      // grass
        terrainV2.SetStyleTextures((int)BlockStyle.SnowRock, terrainV2Textures[11].GetPixels32(), terrainV2Textures[10].GetPixels32(), terrainV2Textures[9].GetPixels32()); // snow

        foreach (object obj in Enum.GetValues(typeof(BlockStyle)))
        {
            BlockStyle style = (BlockStyle)obj;
            if ((int)style <= (int)BlockStyle.SnowRock)
            {
                // We hard code this above for now.
                continue;
            }
            Color32[] topOrAtlas = null;
            Color32[] side       = null;
            Color32[] overflow   = null;
            foreach (var tex in terrainV2Textures)
            {
                if (tex == null)
                {
                    continue;
                }
                if (!tex.name.StartsWith(style.ToString().ToLowerInvariant()))
                {
                    continue;
                }

                if (tex.name.EndsWith("-top") || tex.name == style.ToString().ToLowerInvariant())
                {
                    topOrAtlas = tex.GetPixels32();
                }
                else if (tex.name.EndsWith("-side-ceiling"))
                {
                    side = tex.GetPixels32();
                }
                else if (tex.name.EndsWith("-overflow"))
                {
                    overflow = tex.GetPixels32();
                }
            }

            if (topOrAtlas == null)
            {
                Util.LogWarning($"Had to use fallback texture for terrain style {style}. side={side}, overflow={overflow}");
                topOrAtlas = fallbackTexture;
            }

            if (side != null)
            {
#if UNITY_EDITOR
                Debug.Assert(overflow != null, $"{style.ToString()} style has a side texture but not an overflow?");
#endif
            }
            else
            {
                if (overflow != null)
                {
                    Util.LogWarning($"Style {style} had an overflow texture but not a side? IGNORING overflow.");
                    overflow = null;
                }
            }

            terrainV2.SetStyleTextures((int)style, topOrAtlas, side, overflow);
        }

        // Custom styles
        this.customStyleWorkshopIds.Clear();
        if (customStyleWorkshopIds != null)
        {
            this.customStyleWorkshopIds.AddRange(customStyleWorkshopIds);
        }
        UpdateCustomStyleWorkshopIds();

        if (restoreData != null)
        {
            terrainV2.Deserialize(restoreData, (newDims / 2 - restoreDims / 2));
        }

        if (legacyData != null)
        {
            LoadLegacyTerrainData(legacyData);

            // But move all the blocks to our new system.
            using (Util.Profile("legacySync"))
            {
                foreach (var args in database.EnumerateBlocks())
                {
                    terrainV2.SetCell(args.cell.ToInt3() + GetV2Offset(), (int)args.value.style, (int)args.value.blockType - 1, (int)args.value.direction);
                }
            }
        }

        if (terrainV2Data != null)
        {
            Util.Log($"loading v2 data of {terrainV2Data.Length} bytes");
            using (Util.Profile("terrainV2 Deserialize"))
                terrainV2.Deserialize(terrainV2Data);

            // Legacy upgrade
            if (loadingDataFromBeforeDigging)
            {
                // The serialized data was before digging. We need to move it up, effectively.
                Debug.Assert(BlocksYStart < 0);
                // Copy...
                byte[] temp = terrainV2.Serialize(
                    Int3.zero(),
                    newDims.WithY(newDims.y + BlocksYStart));
                // Move up..
                terrainV2.Deserialize(
                    temp,
                    Int3.zero().WithY(-BlocksYStart));

                // At this point, we actually have 2 copies of the terrain, offset by
                // some Y! heh. But the SetSlices call below will deal with that.
            }
        }

        if (loadingDataFromBeforeDigging)
        {
            // Fill in the ground.
            BlockStyle style = BlockStyle.Grass;
            switch (stage.GetGroundType())
            {
            case GameBuilderStage.GroundType.Snow:
                style = BlockStyle.SnowRock;
                break;

            case GameBuilderStage.GroundType.SolidColor:
            case GameBuilderStage.GroundType.Space:
            case GameBuilderStage.GroundType.Grass:
            default:
                style = BlockStyle.Grass;
                break;
            }
            terrainV2.SetSlices(0, (0 - BlocksYStart), (int)style, 0, 0);
        }

        if (!simpleData.IsNullOrEmpty())
        {
            byte[] zippedBytes = System.Convert.FromBase64String(simpleData);
            using (var zippedStream = new System.IO.MemoryStream(zippedBytes, 0, zippedBytes.Length))
                using (var unzipped = new System.IO.Compression.GZipStream(zippedStream, System.IO.Compression.CompressionMode.Decompress))
                    using (System.IO.BinaryReader reader = new System.IO.BinaryReader(unzipped))
                    {
                        int version = reader.ReadUInt16(); // Unused.
                        Debug.Assert(version == 0, $"Unknown simpleData version: {version}");
                        uint numBlocks = reader.ReadUInt32();
                        Util.Log($"reading in {numBlocks} from simpleData");
                        for (int i = 0; i < numBlocks; i++)
                        {
                            short  x         = reader.ReadInt16();
                            short  y         = reader.ReadInt16();
                            short  z         = reader.ReadInt16();
                            byte   shape     = reader.ReadByte();
                            byte   direction = reader.ReadByte();
                            ushort style     = reader.ReadUInt16();
                            this.SetCellValue(
                                new Cell(x, y, z),
                                new CellValue
                            {
                                blockType = (BlockShape)shape,
                                direction = (BlockDirection)direction,
                                style     = (BlockStyle)style
                            });
                        }
                    }
        }

        // Now mark chunks with actors in them as important
        foreach (var actor in engine.EnumerateActors())
        {
            // Non-dynamic-physics actors don't need terrain to exist...well, less so.
            if (!actor.GetEnablePhysics())
            {
                continue;
            }
            var  pos  = actor.GetSpawnPosition();
            Int3 cell = GetContainingCell(pos).ToInt3();
            terrainV2.ReportRigidbodyAt((cell + GetV2Offset()));
        }
    }
Exemplo n.º 17
0
 public void SetColor(Color color, TerrainSystem terrainSystem)
 {
     terrainSystem.colorMap[index] = color;
 }
Exemplo n.º 18
0
 public Color GetColor(TerrainSystem terrainSystem)
 {
     return(terrainSystem.colorMap[index]);
 }
        protected override void OnLoad(EventArgs e)
        {
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();

            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            _keyboardInputObservable.SubscribeKey(KeyCombination.LeftAlt && KeyCombination.Enter, CombinationDirection.Down, ToggleFullScren);

            _keyboardInputObservable.SubscribeKey(KeyCombination.Esc, CombinationDirection.Down, Exit);
            _keyboardInputObservable.SubscribeKey(KeyCombination.P, CombinationDirection.Down, () => _camera.Projection = ProjectionMode.Perspective);
            _keyboardInputObservable.SubscribeKey(KeyCombination.O, CombinationDirection.Down, () => _camera.Projection = ProjectionMode.Orthographic);
            _keyboardInputObservable.SubscribeKey(KeyCombination.F, CombinationDirection.Down, () => _synchronizeCameras = !_synchronizeCameras);

            _entityManager = new EntityManager();

            var terrainSystem = new TerrainSystem(FractalBrownianMotionSettings.Default);
            _systems = new List<IEntitySystem>
            {
                terrainSystem,
                new FreeCameraSystem(_keyboardInputProcessor, _mouseInputProcessor,_camera),
                new LightMoverSystem(),
                new OceanSystem(),
                new CubeMeshSystem(),
                new InputSystem(_keyboardInputProcessor)
                //new ChunkedLODSystem(_lodCamera),
                //new RenderSystem(_camera),
            };

            var light = new Entity(Guid.NewGuid().ToString());
            _entityManager.Add(light);
            _entityManager.AddComponentToEntity(light, new PositionalLightComponent { Position = new Vector3d(0, 20, 0) });
            _entityManager.AddComponentToEntity(light, new InputComponent(Key.J, Key.L, Key.M, Key.N, Key.U, Key.I));

            const int numberOfChunksX = 20;
            const int numberOfChunksY = 20;
            for (var i = 0; i < numberOfChunksX; i++)
            {
                for (var j = 0; j < numberOfChunksY; j++)
                {
                    var entity = new Entity(Guid.NewGuid().ToString());
                    _entityManager.Add(entity);
                    _entityManager.AddComponentToEntity(entity, new ChunkComponent(i, j));
                    _entityManager.AddComponentToEntity(entity, new StaticMesh());
                }
            }

            var settingsViewModel = new SettingsViewModel(new NoiseFactory.NoiseParameters());
            settingsViewModel.SettingsChanged += () =>
            {
                var settings = settingsViewModel.Assemble();
                terrainSystem.SetTerrainSettings(new NoiseFactory.RidgedMultiFractal().Create(settings));
            };

            _terrain = new Terrain(new ChunkedLod());
            _cube = new Cube();
        }
        protected override void OnLoad(EventArgs e)
        {
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();

            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            _keyboardInputObservable.SubscribeKey(KeyCombination.LeftAlt && KeyCombination.Enter, CombinationDirection.Down, ToggleFullScren);

            _keyboardInputObservable.SubscribeKey(KeyCombination.Esc, CombinationDirection.Down, Exit);
            _keyboardInputObservable.SubscribeKey(KeyCombination.P, CombinationDirection.Down, () => _camera.Projection  = ProjectionMode.Perspective);
            _keyboardInputObservable.SubscribeKey(KeyCombination.O, CombinationDirection.Down, () => _camera.Projection  = ProjectionMode.Orthographic);
            _keyboardInputObservable.SubscribeKey(KeyCombination.F, CombinationDirection.Down, () => _synchronizeCameras = !_synchronizeCameras);

            _entityManager = new EntityManager();

            var terrainSystem = new TerrainSystem(FractalBrownianMotionSettings.Default);

            _systems = new List <IEntitySystem>
            {
                terrainSystem,
                new FreeCameraSystem(_keyboardInputProcessor, _mouseInputProcessor, _camera),
                new LightMoverSystem(),
                new OceanSystem(),
                new CubeMeshSystem(),
                new InputSystem(_keyboardInputProcessor)
                //new ChunkedLODSystem(_lodCamera),
                //new RenderSystem(_camera),
            };

            var light = new Entity(Guid.NewGuid().ToString());

            _entityManager.Add(light);
            _entityManager.AddComponentToEntity(light, new PositionalLightComponent {
                Position = new Vector3d(0, 20, 0)
            });
            _entityManager.AddComponentToEntity(light, new InputComponent(Key.J, Key.L, Key.M, Key.N, Key.U, Key.I));

            const int numberOfChunksX = 20;
            const int numberOfChunksY = 20;

            for (var i = 0; i < numberOfChunksX; i++)
            {
                for (var j = 0; j < numberOfChunksY; j++)
                {
                    var entity = new Entity(Guid.NewGuid().ToString());
                    _entityManager.Add(entity);
                    _entityManager.AddComponentToEntity(entity, new ChunkComponent(i, j));
                    _entityManager.AddComponentToEntity(entity, new StaticMesh());
                }
            }

            var settingsViewModel = new SettingsViewModel(new NoiseFactory.NoiseParameters());

            settingsViewModel.SettingsChanged += () =>
            {
                var settings = settingsViewModel.Assemble();
                terrainSystem.SetTerrainSettings(new NoiseFactory.RidgedMultiFractal().Create(settings));
            };

            _terrain = new Terrain(new ChunkedLod());
            _cube    = new Cube();
        }