Exemplo n.º 1
0
    private IEnumerator SaveMap(string filename)
    {
        WorldSerialization blob = new WorldSerialization();

        ActionProgressBar.UpdateProgress("Saving Terrain", 0f);
        yield return(null);

        yield return(null);

        terrainManager.Save(ref blob);

        ActionProgressBar.UpdateProgress("Saving Prefabs", 0.33f);
        yield return(null);

        yield return(null);

        prefabManager.Save(ref blob);

        ActionProgressBar.UpdateProgress("Saving Paths", 0.66f);
        yield return(null);

        yield return(null);

        pathManager.Save(ref blob);

        ActionProgressBar.UpdateProgress("Saving File", 0.95f);
        yield return(null);

        yield return(null);

        blob.Save(filename);

        ActionProgressBar.Close();
    }
Exemplo n.º 2
0
    public void Load(WorldSerialization blob)
    {
        var terrainSize     = new Vector3(blob.world.size, 1000, blob.world.size);
        var terrainPosition = 0.5f * terrainSize;

        Terrain land  = GameObject.FindGameObjectWithTag("Land").GetComponent <Terrain>();
        Terrain water = GameObject.FindGameObjectWithTag("Water").GetComponent <Terrain>();

        WorldConverter.MapInfo terrains = WorldConverter.worldToTerrain(blob);

        land.terrainData.heightmapResolution = terrains.resolution;
        land.terrainData.size = terrains.size;

        water.terrainData.heightmapResolution = terrains.resolution;
        water.terrainData.size = terrains.size;

        land.terrainData.SetHeights(0, 0, terrains.land.heights);
        water.terrainData.SetHeights(0, 0, terrains.water.heights);


        land.terrainData.alphamapResolution = terrains.resolution;
        land.terrainData.size            = terrains.size;
        land.terrainData.splatPrototypes = getTextures();
        land.terrainData.SetAlphamaps(0, 0, terrains.splatMap);

        GameObject defaultObj = Resources.Load <GameObject>("Prefabs/DefaultPrefab");

        for (int i = 0; i < terrains.prefabData.Length; i++)
        {
            Vector3    pos      = new Vector3(terrains.prefabData[i].position.x, terrains.prefabData[i].position.y, terrains.prefabData[i].position.z);
            Vector3    scale    = new Vector3(terrains.prefabData[i].scale.x, terrains.prefabData[i].scale.y, terrains.prefabData[i].scale.z);
            Quaternion rotation = Quaternion.Euler(new Vector3(terrains.prefabData[i].rotation.x, terrains.prefabData[i].rotation.y, terrains.prefabData[i].rotation.z));

            GameObject g = FileSystem.Load <GameObject>(StringPool.Get((blob.world.prefabs[i].id)));

            GameObject newObject = Instantiate(g, pos + terrainPosition, rotation);
            newObject.transform.localScale = scale;
            PrefabDataHolder pdh = newObject.GetComponent <PrefabDataHolder>();
            if (pdh == null)
            {
                newObject.AddComponent <PrefabDataHolder>();
            }
            pdh.prefabData = terrains.prefabData[i];
        }

        GameObject pathObj = Resources.Load <GameObject>("Paths/Path");

        for (int i = 0; i < terrains.pathData.Length; i++)
        {
            Vector3 averageLocation = Vector3.zero;
            for (int j = 0; j < terrains.pathData[i].nodes.Length; j++)
            {
                averageLocation += terrains.pathData[i].nodes[j];
            }
            averageLocation /= terrains.pathData[i].nodes.Length;
            GameObject newObject = Instantiate(pathObj, averageLocation + terrainPosition, Quaternion.identity);
            newObject.GetComponent <PathDataHolder>().pathData = terrains.pathData[i];
            newObject.GetComponent <PathDataHolder>().offset   = terrainPosition;
        }
    }
Exemplo n.º 3
0
    /// <summary>Parses World Serialization and converts into MapInfo struct.</summary>
    /// <param name="world">Serialization of the map file to parse.</param>
    public static MapInfo WorldToTerrain(WorldSerialization world)
    {
        MapInfo terrains = new MapInfo();

        var terrainSize = new Vector3(world.world.size, 1000, world.world.size);
        var terrainMap  = new TerrainMap <short>(world.GetMap("terrain").data, 1);
        var heightMap   = new TerrainMap <short>(world.GetMap("height").data, 1);
        var waterMap    = new TerrainMap <short>(world.GetMap("water").data, 1);
        var splatMap    = new TerrainMap <byte>(world.GetMap("splat").data, 8);
        var topologyMap = new TerrainMap <int>(world.GetMap("topology").data, 1);
        var biomeMap    = new TerrainMap <byte>(world.GetMap("biome").data, 4);
        var alphaMap    = new TerrainMap <byte>(world.GetMap("alpha").data, 1);

        terrains.topology = topologyMap;

        terrains.pathData   = world.world.paths.ToArray();
        terrains.prefabData = world.world.prefabs.ToArray();

        terrains.terrainRes = heightMap.res;
        terrains.splatRes   = Mathf.Clamp(Mathf.NextPowerOfTwo((int)(world.world.size * 0.5f)), 16, 2048);
        terrains.size       = terrainSize;

        var heightTask = Task.Run(() => ShortMapToFloatArray(heightMap));
        var waterTask  = Task.Run(() => ShortMapToFloatArray(waterMap));

        terrains = ConvertMaps(terrains, splatMap, biomeMap, alphaMap);

        Task.WaitAll(heightTask, waterTask);
        terrains.land.heights  = heightTask.Result;
        terrains.water.heights = waterTask.Result;
        return(terrains);
    }
Exemplo n.º 4
0
    void Awake()
    {
        if (gm == null)
        {
            gm = this;
        }
        else if (gm != this)
        {
            if (isMain)
            {
                Destroy(gm);
                gm = this;
            }
            else
            {
                Destroy(gameObject);
            }
        }

        isMain = true;

        nm = GetComponent <NetworkManager> ();
        pm = GetComponent <PlantManager> ();
        wd = GetComponent <WorldSerialization> ();
        zd = GetComponent <ZoneAndDoorManager> ();
        gc = GetComponent <GeneticCrossing> ();
    }
Exemplo n.º 5
0
    public static Data WorldToTerrain(WorldSerialization blob)
    {
        Data worldData = new Data();

        Vector3 terrainSize = new Vector3(blob.world.size, 1000, blob.world.size);

        worldData.terrainMap = new TerrainMap <short>(blob.GetMap("terrain").data, 1);

        TerrainMap <short> heightMap = new TerrainMap <short>(blob.GetMap("height").data, 1);

        worldData.splatMap    = new TerrainMap <byte>(blob.GetMap("splat").data, 8);
        worldData.alphaMap    = new TerrainMap <byte>(blob.GetMap("alpha").data, 1);
        worldData.biomeMap    = new TerrainMap <byte>(blob.GetMap("biome").data, 4);
        worldData.topologyMap = new TerrainMap <int>(blob.GetMap("topology").data, 1);
        worldData.waterMap    = new TerrainMap <short>(blob.GetMap("water").data, 1);

        worldData.pathData   = new List <ProtoBuf.PathData>(blob.world.paths);
        worldData.prefabData = new List <ProtoBuf.PrefabData>(blob.world.prefabs);

        worldData.resolution = heightMap.res;
        worldData.size       = terrainSize;

        Debug.Log($"Load : World Size {terrainSize.x} Heightmap Res {heightMap.res} Texture Res {worldData.splatMap.res}");

        worldData.landHeightMap = ArrayUtils.ShortToFloatArray(worldData.terrainMap);

        blob.Clear();

        return(worldData);
    }
Exemplo n.º 6
0
    private WorldSerialization LoadWorld(string filename)
    {
        var blob = new WorldSerialization();

        blob.Load(filename);

        return(blob);
    }
Exemplo n.º 7
0
    private WorldSerialization LoadWorld(string filename)
    {
        var blob = new WorldSerialization();

        blob.Load(filename);
        GameObject.FindGameObjectWithTag("MapLoader").GetComponent <MapLoader>().Load(blob);
        return(blob);
    }
Exemplo n.º 8
0
    private void SpawnPrefabs(WorldSerialization blob, PrefabLookup prefabs)
    {
        foreach (var prefab in blob.world.prefabs)
        {
            var go = GameObject.Instantiate(prefabs[prefab.id], prefab.position, prefab.rotation);

            if (go)
            {
                go.transform.localScale = prefab.scale;
                go.SetActive(true);
            }
        }
    }
Exemplo n.º 9
0
    protected void OnGUI()
    {
        const float padding = 10;

        GUILayout.BeginArea(new Rect(padding, padding, Screen.width - padding - padding, Screen.height - padding - padding));
        GUILayout.BeginVertical();

        GUILayout.BeginHorizontal();
        GUILayout.Label("Map File");
        filename = GUILayout.TextField(filename, GUILayout.MinWidth(100));
        #if UNITY_EDITOR
        if (GUILayout.Button("Browse"))
        {
            filename = UnityEditor.EditorUtility.OpenFilePanel("Select Map File", filename, "map");
        }
#endif
        if (GUILayout.Button("Load"))
        {
            var blob = new WorldSerialization();
            Debug.Log("Loading");

            //

            //
            //StringPool


            blob.Load(filename);
            Load(blob);
        }
        if (GUILayout.Button("Save"))
        {
            Terrain            terrain = GameObject.FindGameObjectWithTag("Land").GetComponent <Terrain>();
            Terrain            water   = GameObject.FindGameObjectWithTag("Water").GetComponent <Terrain>();
            WorldSerialization world   = WorldConverter.terrainToWorld(terrain, water);

            Debug.Log("Out: " + world.world.maps.Count);
            Debug.Log("Out: " + world.world.prefabs.Count);
            Debug.Log("Out: " + world.world.paths.Count);

            world.Save(@"C:\Users\Jason\rust test\test.map");
            Debug.Log(world.Checksum);
        }
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();

        //GUILayout.TextArea(result);

        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
Exemplo n.º 10
0
        public static void LoadMapPanel()
        {
            string loadFile = "";

            loadFile = EditorUtility.OpenFilePanel("Import Map File", loadFile, "map");
            if (string.IsNullOrEmpty(loadFile))
            {
                return;
            }
            var world = new WorldSerialization();

            world.Load(loadFile);
            MapManager.Load(WorldConverter.WorldToTerrain(world), loadFile);
            ReloadTreeViews();
        }
Exemplo n.º 11
0
    public void Save(ref WorldSerialization blob)
    {
        if (!HasValidTerrain())
        {
            return;
        }

        blob.world.size = (uint)Terrain.terrainData.size.x;

        byte[] byteArray = ArrayUtils.FloatToByteArray(Terrain.terrainData.GetHeights(0, 0, Terrain.terrainData.heightmapWidth, Terrain.terrainData.heightmapHeight));

        blob.AddMap("terrain", byteArray);
        blob.AddMap("height", byteArray);
        blob.AddMap("water", Water.GetBytes());
        blob.AddMap("splat", Splat.GetBytes());
        blob.AddMap("alpha", Alpha.GetBytes());
        blob.AddMap("biome", Biome.GetBytes());
        blob.AddMap("topology", Topology.GetBytes());
    }
Exemplo n.º 12
0
    private IEnumerator LoadMap(string filename)
    {
        yield return(EditorCoroutineUtility.StartCoroutine(Cleanup(), this));

        WorldSerialization blob = new WorldSerialization();

        ActionProgressBar.UpdateProgress("Loading Map...", 0f);
        yield return(null);

        yield return(null);

        blob.Load(filename);

        world = World.WorldToTerrain(blob);

        yield return(EditorCoroutineUtility.StartCoroutine(LoadMap(world), this));

        ActionProgressBar.Close();

        Debug.Log("World Loaded!");
    }
Exemplo n.º 13
0
    public void Save(ref WorldSerialization blob)
    {
        List <ProtoBuf.PathData> pathList = new List <ProtoBuf.PathData>();

        PathData[] pathData = UnityEngine.Object.FindObjectsOfType <PathData>();
        if (pathData?.Length > 0)
        {
            for (int i = 0; i < pathData.Length; i++)
            {
                PathData data = pathData[i];
                if (data == null)
                {
                    continue;
                }

                pathList.Add(data.GetPathData());
            }
        }

        blob.world.paths = pathList;
    }
Exemplo n.º 14
0
    private void SpawnPrefabs(WorldSerialization blob, PrefabLookup prefabs)
    {
        foreach (var prefab in blob.world.prefabs)
        {
            var prefabGameObject = prefabs[prefab.id];

            if (!prefabGameObject)
            {
                continue;
            }

            var instanceGameObject = GameObject.Instantiate(prefabGameObject, prefab.position, prefab.rotation);

            if (!instanceGameObject)
            {
                continue;
            }

            instanceGameObject.transform.localScale = prefab.scale;
            instanceGameObject.SetActive(true);
        }
    }
Exemplo n.º 15
0
    public static MapInfo worldToTerrain(WorldSerialization blob)
    {
        MapInfo terrains = new MapInfo();

        var terrainSize = new Vector3(blob.world.size, 1000, blob.world.size);
        var terrainMap  = new TerrainMap <short>(blob.GetMap("terrain").data, 1);
        var heightMap   = new TerrainMap <short>(blob.GetMap("height").data, 1);
        var waterMap    = new TerrainMap <short>(blob.GetMap("water").data, 1);
        var splatMap    = new TerrainMap <byte>(blob.GetMap("splat").data, 8);

        terrains.pathData   = blob.world.paths.ToArray();
        terrains.prefabData = blob.world.prefabs.ToArray();

        terrains.resolution = heightMap.res;
        terrains.size       = terrainSize;

        //heightmap has monuments imprinted
        //terrainmap is whats generated and then deformed to create heightmap?

        terrains.terrain.heights = shortMapToFloatArray(terrainMap);
        terrains.land.heights    = shortMapToFloatArray(terrainMap);
        terrains.water.heights   = shortMapToFloatArray(waterMap);

        terrains.splatMap = new float[splatMap.res, splatMap.res, 8];


        for (int i = 0; i < terrains.splatMap.GetLength(0); i++)
        {
            for (int j = 0; j < terrains.splatMap.GetLength(1); j++)
            {
                for (int k = 0; k < 8; k++)
                {
                    terrains.splatMap[i, j, k] = BitUtility.Byte2Float(splatMap[k, i, j]);
                }
            }
        }

        return(terrains);
    }
Exemplo n.º 16
0
    private void LoadFromPNG(string path, Terrain ter1, Terrain ter2_1, WorldSerialization blob)
    {
        var       data1   = ter1.terrainData;
        var       data2_1 = ter2_1.terrainData;
        WWW       www     = new WWW("file://" + path);
        Texture2D tex     = www.texture;

        data1.heightmapResolution   = Mathf.NextPowerOfTwo((int)(tex.height * 0.50f)) + 1;
        data2_1.heightmapResolution = Mathf.NextPowerOfTwo((int)(tex.height * 0.50f)) + 1;
        float[,] height             = new float[Mathf.NextPowerOfTwo((int)(tex.height * 0.50f)) + 1, Mathf.NextPowerOfTwo((int)(tex.height * 0.50f)) + 1];
        data1.size                = new Vector3(tex.height, 1000, tex.height);
        data2_1.size              = new Vector3(tex.height, 1000, tex.height);
        ter1.transform.position   = -0.5f * data1.size;
        ter2_1.transform.position = -0.5f * data2_1.size;
        blob.world.size           = (uint)data1.size.x;
        for (int y = 0; y < Mathf.NextPowerOfTwo((int)(tex.height * 0.50f)) + 1; y++)
        {
            for (int x = 0; x < Mathf.NextPowerOfTwo((int)(tex.height * 0.50f)) + 1; x++)
            {
                height[y, x] = tex.GetPixel(x, y).grayscale;
            }
        }
        data1.SetHeights(0, 0, height);
    }
Exemplo n.º 17
0
    public void Save(ref WorldSerialization blob)
    {
        ActionProgressBar.UpdateProgress("Saving Prefabs", 0f);

        List <ProtoBuf.PrefabData> prefabList = new List <ProtoBuf.PrefabData>();

        PrefabData[] prefabData = UnityEngine.Object.FindObjectsOfType <PrefabData>();
        if (prefabData?.Length > 0)
        {
            for (int i = 0; i < prefabData.Length; i++)
            {
                PrefabData data = prefabData[i];

                if (prefabData == null || data.gameObject == null)
                {
                    continue;
                }

                prefabList.Add(data.GetPrefabData());
            }
        }

        blob.world.prefabs = prefabList;
    }
Exemplo n.º 18
0
    public void Save(string path)
    {
        if (selectedLandLayer != null)
        {
            selectedLandLayer.save();
        }
        saveTopologyLayer();
        Terrain terrain = GameObject.FindGameObjectWithTag("Land").GetComponent <Terrain>();
        Terrain water   = GameObject.FindGameObjectWithTag("Water").GetComponent <Terrain>();

        if (water == null)
        {
            Debug.LogError("Water object is not enabled");
        }
        if (terrain == null)
        {
            Debug.LogError("Land object is not enabled");
        }

        WorldSerialization world = WorldConverter.terrainToWorld(terrain, water);

        world.Save(path);
        //Debug.Log("Map hash: " + world.Checksum);
    }
Exemplo n.º 19
0
Arquivo: World.cs Projeto: Bycob/world
        public World(WorldDef worldDef)
        {
            string jsonStr = WorldSerialization.ToJson(worldDef);

            _handle = createWorldFromJson(jsonStr);
        }
Exemplo n.º 20
0
    private string GetInfo(WorldSerialization blob)
    {
        // Resolution of the terrain height and water maps
        var meshResolution = Mathf.NextPowerOfTwo((int)(blob.World.size * 0.50f)) + 1;

        // Resolution of the terrain splat, topology, biome and alpha maps
        var textureResolution = Mathf.NextPowerOfTwo((int)(blob.World.size * 0.50f));

        // The dimensions of the terrain object, Y always goes from -500 to +500, X and Z from -extents to +extents
        var terrainSize = new Vector3(blob.World.size, 1000, blob.World.size);

        // The position of the terrain object, chosen so world origin is always at the center of the terrain bounds
        var terrainPosition = -0.5f * terrainSize;

        // Terrain mesh height values (16 bit)
        // Indexed [z, x]
        var terrainMap = new TerrainMap <short>(blob.GetMap("terrain").data, 1);

        // World height values (16 bit)
        // Indexed [z, x]
        // Used to sample the height at which to spawn grass and decor at
        // Can include both terrain and other meshes like for example cliffs
        var heightMap = new TerrainMap <short>(blob.GetMap("height").data, 1);

        // Water map (16 bit)
        // Indexed [z, x]
        // Includes both the ocean plane at zero level and any rivers
        var waterMap = new TerrainMap <short>(blob.GetMap("water").data, 1);

        // Alpha map (8 bit)
        // Indexed [z, x]
        // Zero to render parts of the terrain invisible
        var alphaMap = new TerrainMap <byte>(blob.GetMap("alpha").data, 1);

        // Splat map (8 bit, 8 channels)
        // Indexed [c, z, x] (see TerrainSplat class)
        // Sum of all channels should be normalized to 255
        var splatMap = new TerrainMap <byte>(blob.GetMap("splat").data, 8);

        // Biome map (8 bit, 4 channels)
        // Indexed [c, z, x] (see TerrainBiome class)
        // Sum of all channels should be normalized to 255
        var biomeMap = new TerrainMap <byte>(blob.GetMap("biome").data, 4);

        // Topology map (32 bit)
        // Indexed [z, x] (see TerrainTopology class)
        // Used as a bit mask, multiple topologies can be set in one location
        var topologyMap = new TerrainMap <int>(blob.GetMap("topology").data, 1);

        int x = 0;
        int z = 0;

        var sb = new StringBuilder();

        sb.AppendLine("Info");
        sb.Append("\tPosition: ");
        sb.AppendLine(terrainPosition.ToString());
        sb.Append("\tSize: ");
        sb.AppendLine(terrainSize.ToString());
        sb.Append("\tMesh Resolution: ");
        sb.AppendLine(meshResolution.ToString());
        sb.Append("\tTexture Resolution: ");
        sb.AppendLine(textureResolution.ToString());

        sb.AppendLine();

        sb.AppendLine("Terrain Map");
        sb.Append("\t");
        sb.AppendLine(BitUtility.Short2Float(terrainMap[z, x]).ToString());

        sb.AppendLine();

        sb.AppendLine("Height Map");
        sb.Append("\t");
        sb.AppendLine(BitUtility.Short2Float(heightMap[z, x]).ToString());

        sb.AppendLine();

        sb.AppendLine("Water Map");
        sb.Append("\t");
        sb.AppendLine(BitUtility.Short2Float(waterMap[z, x]).ToString());

        sb.AppendLine();

        sb.AppendLine("Alpha Map");
        sb.Append("\t");
        sb.AppendLine(BitUtility.Byte2Float(alphaMap[z, x]).ToString());

        sb.AppendLine();

        sb.AppendLine("Splat Map");
        sb.Append("\tDirt: ");
        sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.DIRT_IDX, z, x]).ToString());
        sb.Append("\tSnow: ");
        sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.SNOW_IDX, z, x]).ToString());
        sb.Append("\tSand: ");
        sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.SAND_IDX, z, x]).ToString());
        sb.Append("\tRock: ");
        sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.ROCK_IDX, z, x]).ToString());
        sb.Append("\tGrass: ");
        sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.GRASS_IDX, z, x]).ToString());
        sb.Append("\tForest: ");
        sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.FOREST_IDX, z, x]).ToString());
        sb.Append("\tStones: ");
        sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.STONES_IDX, z, x]).ToString());
        sb.Append("\tGravel: ");
        sb.AppendLine(BitUtility.Byte2Float(splatMap[TerrainSplat.GRAVEL_IDX, z, x]).ToString());

        sb.AppendLine();

        sb.AppendLine("Biome Map");
        sb.Append("\tArid: ");
        sb.AppendLine(BitUtility.Byte2Float(biomeMap[TerrainBiome.ARID_IDX, z, x]).ToString());
        sb.Append("\tTemperate: ");
        sb.AppendLine(BitUtility.Byte2Float(biomeMap[TerrainBiome.TEMPERATE_IDX, z, x]).ToString());
        sb.Append("\tTundra: ");
        sb.AppendLine(BitUtility.Byte2Float(biomeMap[TerrainBiome.TUNDRA_IDX, z, x]).ToString());
        sb.Append("\tArctic: ");
        sb.AppendLine(BitUtility.Byte2Float(biomeMap[TerrainBiome.ARCTIC_IDX, z, x]).ToString());

        sb.AppendLine();

        sb.AppendLine("Topology Map");
        sb.Append("\tField: ");
        sb.AppendLine((topologyMap[z, x] & TerrainTopology.FIELD) != 0 ? "yes" : "no");
        sb.Append("\tBeach: ");
        sb.AppendLine((topologyMap[z, x] & TerrainTopology.BEACH) != 0 ? "yes" : "no");
        sb.Append("\tForest: ");
        sb.AppendLine((topologyMap[z, x] & TerrainTopology.FOREST) != 0 ? "yes" : "no");
        sb.Append("\tOcean: ");
        sb.AppendLine((topologyMap[z, x] & TerrainTopology.OCEAN) != 0 ? "yes" : "no");
        sb.Append("\tLake: ");
        sb.AppendLine((topologyMap[z, x] & TerrainTopology.LAKE) != 0 ? "yes" : "no");

        sb.AppendLine();
        sb.AppendLine("Paths");
        sb.Append("\t");
        sb.Append(blob.World.paths.Count);

        return(sb.ToString());
    }
Exemplo n.º 21
0
    protected void OnGUI()
    {
        if (norustbundles)
        {
            GUIStyle skin = new GUISkin().button;
            skin.wordWrap = true;
            if (GUI.Button(new Rect(Vector2.zero, new Vector2(Screen.width, Screen.height)), "enter bundles path, e.g. \"<path to steamlibrary>/steamapps/common/Rust/Bundles/Bundles\" in \"<path to _Data folder on Win/Linux, Content on Mac>/editor.config\" (click for unity documentation)", skin))
            {
                Application.OpenURL("https://docs.unity3d.com/ScriptReference/Application-dataPath.html");
            }
        }
        else
        {
            const float padding = 10;

            GUILayout.BeginArea(new Rect(padding, padding, Screen.width - padding - padding, Screen.height - padding - padding));
            GUILayout.BeginVertical();

            GUILayout.BeginHorizontal();
            if (world == null)
            {
                GUILayout.Label("Map File");
                filename = GUILayout.TextField(filename, GUILayout.MinWidth(100));
#if UNITY_EDITOR
                if (GUILayout.Button("Browse"))
                {
                    filename = UnityEditor.EditorUtility.OpenFilePanel("Select Map File", filename, "map");
                }
#endif
                winrect  = GUI.Window(0, winrect, BrowseFiles, "File Browser");
                winrect2 = GUI.Window(1, winrect2, Credits, "Credits");
                if (GUILayout.Button("Load"))
                {
                    world  = LoadWorld(filename);
                    result = GetInfo(world);
                    //StartCoroutine(GetPrefabs(world));
                    SpawnMap(world);
                }
            }
            else
            {
            }
            if (GUILayout.Button("Save"))
            {
                SaveMap(world);
            }
            restart = GUILayout.Toggle(restart, "Restart?");
            if (GUILayout.Button("Restart") && restart)
            {
                SceneManager.LoadScene("SampleScene");
            }

            /*if (GUILayout.Button("Add Prefab 84019840 (debug)")) {
             *  world.AddPrefab("Decor", 84019840, new Vector3(0, 0, 0), Quaternion.Euler(Vector3.zero), Vector3.one);
             *  world.Save(filename + ".new");
             * }*/
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            modeSelected = GUILayout.SelectionGrid(modeSelected, new string[] { "Object", "Terrain" }, 2);
            Camera.main.GetComponent <MainCamera>().mode = (MainCamera.EditorMode)modeSelected;
            GUILayout.EndHorizontal();
            if (Camera.main.GetComponent <MainCamera>().mode == MainCamera.EditorMode.Object)
            {
                GUILayout.BeginHorizontal();
                oModeSelected = GUILayout.SelectionGrid(oModeSelected, new string[] { "Position", "Rotation", "Scale" }, 3);
                Camera.main.GetComponent <MainCamera>().oMode = (MainCamera.ObjectMode)oModeSelected;
                GUILayout.EndHorizontal();
            }
            if (Camera.main.GetComponent <MainCamera>().mode == MainCamera.EditorMode.Terrain)
            {
                GUILayout.BeginHorizontal();
                tModeSelected = GUILayout.SelectionGrid(tModeSelected, new string[] { "Height Map", "Water Map", "Alpha Map" }, 3);
                Camera.main.GetComponent <MainCamera>().tMode = (MainCamera.TerrainMode)tModeSelected;
                GUILayout.EndHorizontal();
            }
            if (Camera.main.GetComponent <MainCamera>().mode == MainCamera.EditorMode.Terrain)
            {
                GUILayout.BeginHorizontal();
                tToolSelected = GUILayout.SelectionGrid(tToolSelected, new string[] { "Raise", "Lower", "Smooth", "Flatten" }, 4);
                Camera.main.GetComponent <MainCamera>().tTool = (MainCamera.TerrainTool)tToolSelected;
                GUILayout.EndHorizontal();
            }
            if (Camera.main.GetComponent <MainCamera>().mode == MainCamera.EditorMode.Terrain && (Camera.main.GetComponent <MainCamera>().tTool == MainCamera.TerrainTool.Raise || Camera.main.GetComponent <MainCamera>().tTool == MainCamera.TerrainTool.Lower || Camera.main.GetComponent <MainCamera>().tTool == MainCamera.TerrainTool.Smooth))
            {
                GUILayout.BeginHorizontal();
                Camera.main.GetComponent <MainCamera>().tRadius = (int)GUILayout.HorizontalSlider(Camera.main.GetComponent <MainCamera>().tRadius, 1, 100, GUILayout.MinWidth(100));
                GUILayout.Label("Radius: " + Camera.main.GetComponent <MainCamera>().tRadius);
                Camera.main.GetComponent <MainCamera>().tChange = GUILayout.HorizontalSlider(Camera.main.GetComponent <MainCamera>().tChange, 0, 0.01f, GUILayout.MinWidth(100));
                GUILayout.Label("Amount of change: " + Camera.main.GetComponent <MainCamera>().tChange);
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
                GUILayout.BeginHorizontal();
                GUILayout.Label(".png file path");
                png = GUILayout.TextField(png, GUILayout.MaxWidth(100));
                if (GUILayout.Button("Load from .png"))
                {
                    /*if (File.Exists(png))
                     *  LoadFromPNG(png, data, world);
                     * else if (File.Exists("\\" + png))*/
                    LoadFromPNG("\\" + png, ter, ter2, world);
                }
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
            }
            GUILayout.BeginHorizontal();
            if (loading)
            {
                GUILayout.Label("Loading...");
            }
            //GUILayout.TextArea(result);
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
            GUILayout.EndArea();
        }
    }
Exemplo n.º 22
0
    public override void OnInspectorGUI()
    {
        MapIO script = (MapIO)target;

        GUILayout.Label("Load Map", EditorStyles.boldLabel);
        if (GUILayout.Button("Import .map file"))
        {
            loadFile = UnityEditor.EditorUtility.OpenFilePanel("Import Map File", loadFile, "map");

            var blob = new WorldSerialization();
            Debug.Log("Importing map " + loadFile);
            blob.Load(loadFile);
            script.Load(blob);
        }

        GUILayout.Label("Save Map", EditorStyles.boldLabel);
        if (GUILayout.Button("Export .map file"))
        {
            saveFile = UnityEditor.EditorUtility.SaveFilePanel("Export Map File", saveFile, mapName, "map");
            Debug.Log("Exported map " + saveFile);
            script.Save(saveFile);
        }

/*
 *      GUILayout.Label("Select Bundle file", EditorStyles.boldLabel);
 *
 *      bundleFile = GUILayout.TextField(bundleFile);
 *      if (GUILayout.Button("Select Bundle file (Rust\\Bundles\\Bundles)"))
 *      {
 *          bundleFile = UnityEditor.EditorUtility.OpenFilePanel("Select Bundle file (Rust\\Bundles\\Bundles)", bundleFile, "map");
 *      }
 */

        GUILayout.Label("Land Option", EditorStyles.boldLabel);

        GUILayout.Label("Land Heightmap Offset");
        script.offset = float.Parse(GUILayout.TextField(script.offset + ""));
        script.offset = GUILayout.HorizontalSlider(script.offset, -500, 500);
        if (GUILayout.Button("Offset Map"))
        {
            script.offsetHeightmap();
            script.offset = 0;
        }

        string oldLandLayer = script.landLayer;

        string[] options = { "Ground", "Biome", "Alpha", "Topology" };
        script.landSelectIndex = EditorGUILayout.Popup("Select Land Layer:", script.landSelectIndex, options);
        script.landLayer       = options[script.landSelectIndex];
        if (script.landLayer != oldLandLayer)
        {
            script.changeLandLayer();
            Repaint();
        }
        if (script.landLayer.Equals("Topology"))
        {
            GUILayout.Label("Topology Option", EditorStyles.boldLabel);
            script.oldTopologyLayer = script.topologyLayer;
            script.topologyLayer    = (TerrainTopology.Enum)EditorGUILayout.EnumPopup("Select Topology Layer:", script.topologyLayer);
            if (script.topologyLayer != script.oldTopologyLayer)
            {
                //script.saveTopologyLayer();
                script.changeLandLayer();
                Repaint();
            }
        }
    }
Exemplo n.º 23
0
    /*private IEnumerator GetPrefabs(WorldSerialization blob)
     * {
     *  for (int i = 0; i < blob.world.prefabs.Count; i++) {
     *      yield return null;
     *      if ((blob.world.prefabs[i].category.ToLower().Contains("monument") || blob.world.prefabs[i].category.ToLower().Contains("river")) || blob.world.prefabs[i].category.ToLower().Contains("decor")) {
     *          Debug.Log(blob.world.prefabs[i].id + "-" + blob.world.prefabs[i].category);
     *          FileSystem.Operation g2 = FileSystem.LoadAsync(StringPool.Get((blob.world.prefabs[i].id)));
     *          /*yield return new WaitUntil(() => {
     *              return g2.isDone;
     *          });*
     *          while (!g2.isDone) {
     *              yield return null;
     *          }
     *
     *          GameObject g3 = g2.Load<GameObject>();
     *
     *          GameObject g = Instantiate(g3, blob.world.prefabs[i].position, blob.world.prefabs[i].rotation);
     *          g.transform.localScale = blob.world.prefabs[i].scale;
     *          g.SetActive(true);
     *          g.AddComponent<EditableObject>();
     *          g.AddComponent<BoxCollider>();
     *          yield return null;
     *          Debug.Log("Loaded " + i + "/" + blob.world.prefabs.Count);
     *      }
     *      else
     *      {
     *          yield return null;
     *          Debug.Log("Skipping " + i + "/" + blob.world.prefabs.Count);
     *      }
     *  }
     * }*/

    private void SaveMap(WorldSerialization blob)
    {
        // Resolution of the terrain height and water maps
        var meshResolution = Mathf.NextPowerOfTwo((int)(blob.world.size * 0.50f)) + 1;

        // Resolution of the terrain splat, topology, biome and alpha maps
        var textureResolution = Mathf.NextPowerOfTwo((int)(blob.world.size * 0.50f));

        // The dimensions of the terrain object, Y always goes from -500 to +500, X and Z from -extents to +extents
        var terrainSize = new Vector3(blob.world.size, 1000, blob.world.size);

        // The position of the terrain object, chosen so world origin is always at the center of the terrain bounds
        var terrainPosition = -0.5f * terrainSize;

        // Terrain mesh height values (16 bit)
        // Indexed [z, x]
        var terrainMap = new TerrainMap <short>(blob.GetMap("terrain").data, 1);

        // World height values (16 bit)
        // Indexed [z, x]
        // Used to sample the height at which to spawn grass and decor at
        // Can include both terrain and other meshes like for example cliffs
        var heightMap = new TerrainMap <short>(blob.GetMap("height").data, 1);

        // Water map (16 bit)
        // Indexed [z, x]
        // Includes both the ocean plane at zero level and any rivers
        var waterMap = new TerrainMap <short>(blob.GetMap("water").data, 1);

        // Alpha map (8 bit)
        // Indexed [z, x]
        // Zero to render parts of the terrain invisible
        var alphaMap = new TerrainMap <byte>(blob.GetMap("alpha").data, 1);

        // Splat map (8 bit, 8 channels)
        // Indexed [c, z, x] (see TerrainSplat class)
        // Sum of all channels should be normalized to 255
        var splatMap = new TerrainMap <byte>(blob.GetMap("splat").data, 8);

        // Biome map (8 bit, 4 channels)
        // Indexed [c, z, x] (see TerrainBiome class)
        // Sum of all channels should be normalized to 255
        var biomeMap = new TerrainMap <byte>(blob.GetMap("biome").data, 4);

        // Topology map (32 bit)
        // Indexed [z, x] (see TerrainTopology class)
        // Used as a bit mask, multiple topologies can be set in one location
        var topologyMap = new TerrainMap <int>(blob.GetMap("topology").data, 1);

        float[,] terrainMap2 = data.GetHeights(0, 0, meshResolution, meshResolution);
        for (int y = 0; y < meshResolution; y++)
        {
            for (int x = 0; x < meshResolution; x++)
            {
                terrainMap[y, x] = BitUtility.Float2Short(terrainMap2[y, x]);
            }
        }
        int t = 0;

        for (; t < blob.world.maps.Count; t++)
        {
            if (blob.world.maps[t].name == "terrain")
            {
                break;
            }
        }
        blob.world.maps[t].data = terrainMap.ToByteArray();

        int wh = 0;

        for (; wh < blob.world.maps.Count; wh++)
        {
            if (blob.world.maps[wh].name == "height")
            {
                break;
            }
        }
        blob.world.maps[wh].data = terrainMap.ToByteArray();

        float[,,] splatMap2 = data.GetAlphamaps(0, 0, textureResolution, textureResolution);
        for (int y = 0; y < textureResolution; y++)
        {
            for (int x = 0; x < textureResolution; x++)
            {
                splatMap[0, y, x] = BitUtility.Float2Byte(splatMap2[y, x, 0]);
                splatMap[1, y, x] = BitUtility.Float2Byte(splatMap2[y, x, 1]);
                splatMap[2, y, x] = BitUtility.Float2Byte(splatMap2[y, x, 2]);
                splatMap[3, y, x] = BitUtility.Float2Byte(splatMap2[y, x, 3]);
                splatMap[4, y, x] = BitUtility.Float2Byte(splatMap2[y, x, 4]);
                splatMap[5, y, x] = BitUtility.Float2Byte(splatMap2[y, x, 5]);
                splatMap[6, y, x] = BitUtility.Float2Byte(splatMap2[y, x, 6]);
                splatMap[7, y, x] = BitUtility.Float2Byte(splatMap2[y, x, 7]);
            }
        }
        int s = 0;

        for (; s < blob.world.maps.Count; s++)
        {
            if (blob.world.maps[s].name == "splat")
            {
                break;
            }
        }
        blob.world.maps[s].data = splatMap.ToByteArray();

        float[,] waterMap2 = data2.GetHeights(0, 0, meshResolution, meshResolution);
        for (int y = 0; y < meshResolution; y++)
        {
            for (int x = 0; x < meshResolution; x++)
            {
                waterMap[y, x] = BitUtility.Float2Short(waterMap2[y, x]);
            }
        }
        int w = 0;

        for (; w < blob.world.maps.Count; w++)
        {
            if (blob.world.maps[w].name == "water")
            {
                break;
            }
        }
        blob.world.maps[w].data = waterMap.ToByteArray();

        //blob.world.prefabs.Clear();
        for (int i = 0; i < blob.world.prefabs.Count; i++)
        {
            for (int j = 0; j < spawnedPrefabs.Count; j++)
            {
                if (spawnedPrefabs[j].GetComponent <PrefabData>().idInList == i)
                {
                    blob.world.prefabs[i].position = spawnedPrefabs[j].transform.position;
                    blob.world.prefabs[i].rotation = spawnedPrefabs[j].transform.rotation.eulerAngles;
                    blob.world.prefabs[i].scale    = spawnedPrefabs[j].transform.localScale;
                }
            }
        }


        blob.Save(filename + ".new");
    }
Exemplo n.º 24
0
    public void Load(WorldSerialization blob)
    {
        if (topology == null)
        {
            topology = GameObject.FindGameObjectWithTag("Topology").GetComponent <TopologyMesh>();
        }

        Debug.Log("Map hash: " + blob.Checksum);
        cleanUpMap();
        var terrainSize     = new Vector3(blob.world.size, 1000, blob.world.size);
        var terrainPosition = 0.5f * terrainSize;

        LandData groundLandData   = GameObject.FindGameObjectWithTag("Land").transform.Find("Ground").GetComponent <LandData>();
        LandData biomeLandData    = GameObject.FindGameObjectWithTag("Land").transform.Find("Biome").GetComponent <LandData>();
        LandData alphaLandData    = GameObject.FindGameObjectWithTag("Land").transform.Find("Alpha").GetComponent <LandData>();
        LandData topologyLandData = GameObject.FindGameObjectWithTag("Land").transform.Find("Topology").GetComponent <LandData>();

        Terrain land  = GameObject.FindGameObjectWithTag("Land").GetComponent <Terrain>();
        Terrain water = GameObject.FindGameObjectWithTag("Water").GetComponent <Terrain>();

        TopologyMesh topography = GameObject.FindGameObjectWithTag("Topology").GetComponent <TopologyMesh>();

        WorldConverter.MapInfo terrains = WorldConverter.worldToTerrain(blob);

        topography.InitMesh(terrains.topology);

        land.terrainData.heightmapResolution = terrains.resolution;
        land.terrainData.size = terrains.size;

        water.terrainData.heightmapResolution = terrains.resolution;
        water.terrainData.size = terrains.size;

        land.terrainData.SetHeights(0, 0, terrains.land.heights);
        water.terrainData.SetHeights(0, 0, terrains.water.heights);

        land.terrainData.alphamapResolution = terrains.resolution;
        //land.terrainData.baseMapResolution = terrains.resolution;
        //land.terrainData.SetDetailResolution(terrains.resolution,8);

        land.terrainData.size = terrains.size;

        groundLandData.setData(terrains.splatMap, "ground");

        biomeLandData.setData(terrains.biomeMap, "biome");

        alphaLandData.setData(terrains.alphaMap, "alpha");

        topologyLandData.setData(topology.getSplatMap((int)topologyLayer), "topology");
        changeLandLayer();

        Transform  prefabsParent = GameObject.FindGameObjectWithTag("Prefabs").transform;
        GameObject defaultObj    = Resources.Load <GameObject>("Prefabs/DefaultPrefab");

        for (int i = 0; i < terrains.prefabData.Length; i++)
        {
            GameObject newObj = spawnPrefab(defaultObj, terrains.prefabData[i], prefabsParent);
            newObj.GetComponent <PrefabDataHolder>().prefabData = terrains.prefabData[i];
        }


        Transform  pathsParent = GameObject.FindGameObjectWithTag("Paths").transform;
        GameObject pathObj     = Resources.Load <GameObject>("Paths/Path");

        for (int i = 0; i < terrains.pathData.Length; i++)
        {
            Vector3 averageLocation = Vector3.zero;
            for (int j = 0; j < terrains.pathData[i].nodes.Length; j++)
            {
                averageLocation += terrains.pathData[i].nodes[j];
            }
            averageLocation /= terrains.pathData[i].nodes.Length;
            GameObject newObject = Instantiate(pathObj, averageLocation + terrainPosition, Quaternion.identity, pathsParent);
            newObject.GetComponent <PathDataHolder>().pathData = terrains.pathData[i];
            newObject.GetComponent <PathDataHolder>().offset   = terrainPosition;
        }
    }
Exemplo n.º 25
0
    public static WorldSerialization terrainToWorld(Terrain land, Terrain water)
    {
        WorldSerialization world = new WorldSerialization();

        world.world.size = (uint)land.terrainData.size.x;

        byte[] landHeightBytes  = floatArrayToByteArray(land.terrainData.GetHeights(0, 0, land.terrainData.heightmapWidth, land.terrainData.heightmapHeight));
        byte[] waterHeightBytes = floatArrayToByteArray(water.terrainData.GetHeights(0, 0, water.terrainData.heightmapWidth, water.terrainData.heightmapHeight));


        float[,,] splatMapValues = land.terrainData.GetAlphamaps(0, 0, land.terrainData.alphamapWidth, land.terrainData.alphamapHeight);

        var textureResolution = Mathf.NextPowerOfTwo((int)(world.world.size * 0.50f));

        byte[] splatBytes = new byte[textureResolution * textureResolution * 8];
        var    splatMap   = new TerrainMap <byte>(splatBytes, 8);

        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < textureResolution; j++)
            {
                for (int k = 0; k < textureResolution; k++)
                {
                    splatMap[i, j, k] =
                        BitUtility.Float2Byte(splatMapValues[j, k, i]);
                }
            }
        }

        byte[] biomeBytes = new byte[textureResolution * textureResolution * 4];
        var    biomeMap   = new TerrainMap <byte>(biomeBytes, 4);


        for (int j = 0; j < textureResolution; j++)
        {
            for (int k = 0; k < textureResolution; k++)
            {
                biomeMap[TerrainBiome.ARID_IDX, j, k]      = BitUtility.Float2Byte(1f);
                biomeMap[TerrainBiome.ARCTIC_IDX, j, k]    = BitUtility.Float2Byte(0f);
                biomeMap[TerrainBiome.TEMPERATE_IDX, j, k] = BitUtility.Float2Byte(0f);
                biomeMap[TerrainBiome.TUNDRA_IDX, j, k]    = BitUtility.Float2Byte(0f);
            }
        }

        byte[] alphaBytes = new byte[textureResolution * textureResolution];
        var    alphaMap   = new TerrainMap <byte>(alphaBytes, 1);

        for (int k = 0; k < alphaBytes.Length; k++)
        {
            alphaBytes[k] = 255;
        }
        byte[] topologyBytes = new byte[textureResolution * textureResolution * 4];
        var    topologyMap   = new TerrainMap <int>(topologyBytes, 1);

        for (int k = 0; k < topologyBytes.Length; k++)
        {
            topologyBytes[k] = 0x0;
        }

        Debug.Log(alphaMap.res);



        world.AddMap("terrain", landHeightBytes);
        world.AddMap("height", landHeightBytes);
        world.AddMap("splat", splatMap.ToByteArray());
        world.AddMap("biome", biomeMap.ToByteArray());
        world.AddMap("topology", topologyMap.ToByteArray());
        world.AddMap("alpha", alphaMap.ToByteArray());
        world.AddMap("water", waterHeightBytes);

        PrefabDataHolder[] prefabs = GameObject.FindObjectsOfType <PrefabDataHolder>();

        foreach (PrefabDataHolder p in prefabs)
        {
            if (p.prefabData != null)
            {
                world.world.prefabs.Insert(0, p.prefabData);
            }
        }

        PathDataHolder[] paths = GameObject.FindObjectsOfType <PathDataHolder>();

        foreach (PathDataHolder p in paths)
        {
            if (p.pathData != null)
            {
                world.world.paths.Insert(0, p.pathData);
            }
        }


        /*
         *
         * byte[] emptyBiome = new byte[16777216];
         * byte[] emptyAlpha = new byte[4194304];
         *
         *
         * world.AddMap("terrain", landHeightBytes);
         * world.AddMap("height", landHeightBytes);
         * world.AddMap("splat", splatMap.ToByteArray());
         * world.AddMap("biome", emptyBiome);
         * world.AddMap("topology", emptyBiome);
         * world.AddMap("alpha", emptyAlpha);
         * world.AddMap("water", waterHeightBytes);*/
        return(world);
    }
Exemplo n.º 26
0
    private void SpawnMap(WorldSerialization blob)
    {
        // Resolution of the terrain height and water maps
        var meshResolution = Mathf.NextPowerOfTwo((int)(blob.world.size * 0.50f)) + 1;

        // Resolution of the terrain splat, topology, biome and alpha maps
        var textureResolution = Mathf.NextPowerOfTwo((int)(blob.world.size * 0.50f));

        // The dimensions of the terrain object, Y always goes from -500 to +500, X and Z from -extents to +extents
        var terrainSize = new Vector3(blob.world.size, 1000, blob.world.size);

        // The position of the terrain object, chosen so world origin is always at the center of the terrain bounds
        var terrainPosition = -0.5f * terrainSize;

        // Terrain mesh height values (16 bit)
        // Indexed [z, x]
        var terrainMap = new TerrainMap <short>(blob.GetMap("terrain").data, 1);

        // World height values (16 bit)
        // Indexed [z, x]
        // Used to sample the height at which to spawn grass and decor at
        // Can include both terrain and other meshes like for example cliffs
        var heightMap = new TerrainMap <short>(blob.GetMap("height").data, 1);

        // Water map (16 bit)
        // Indexed [z, x]
        // Includes both the ocean plane at zero level and any rivers
        var waterMap = new TerrainMap <short>(blob.GetMap("water").data, 1);

        // Alpha map (8 bit)
        // Indexed [z, x]
        // Zero to render parts of the terrain invisible
        var alphaMap = new TerrainMap <byte>(blob.GetMap("alpha").data, 1);

        // Splat map (8 bit, 8 channels)
        // Indexed [c, z, x] (see TerrainSplat class)
        // Sum of all channels should be normalized to 255
        var splatMap = new TerrainMap <byte>(blob.GetMap("splat").data, 8);

        // Biome map (8 bit, 4 channels)
        // Indexed [c, z, x] (see TerrainBiome class)
        // Sum of all channels should be normalized to 255
        var biomeMap = new TerrainMap <byte>(blob.GetMap("biome").data, 4);

        // Topology map (32 bit)
        // Indexed [z, x] (see TerrainTopology class)
        // Used as a bit mask, multiple topologies can be set in one location
        var topologyMap = new TerrainMap <int>(blob.GetMap("topology").data, 1);

        GameObject obj = Instantiate(terrain);

        obj.layer = 10;
        ter       = obj.GetComponent <Terrain>();
        Camera.main.GetComponent <MainCamera>().height = ter.gameObject;
        data = obj.GetComponent <Terrain>().terrainData;
        GameObject obj2 = Instantiate(water);

        obj2.layer = 10;
        ter2       = obj2.GetComponent <Terrain>();
        Camera.main.GetComponent <MainCamera>().water = ter2.gameObject;
        data2 = obj2.GetComponent <Terrain>().terrainData;
        //data.heightmapResolution = meshResolution;
        obj.transform.position   = terrainPosition;
        data.heightmapResolution = (int)meshResolution;
        data.alphamapResolution  = textureResolution;
        data.size = terrainSize;
        obj2.transform.position   = terrainPosition;
        data2.heightmapResolution = (int)meshResolution;
        data2.alphamapResolution  = textureResolution;
        data2.size = terrainSize;

        float[,] terrainMap2 = new float[(int)meshResolution, (int)meshResolution];
        for (int y = 0; y < meshResolution; y++)
        {
            for (int x = 0; x < meshResolution; x++)
            {
                terrainMap2[y, x] = BitUtility.Short2Float(terrainMap[y, x]);
            }
        }
        data.SetHeights(0, 0, terrainMap2);
        float[,,] splatMap2 = new float[(int)textureResolution, (int)textureResolution, 8];
        for (int y = 0; y < textureResolution; y++)
        {
            for (int x = 0; x < textureResolution; x++)
            {
                splatMap2[y, x, 0] = BitUtility.Byte2Float(splatMap[0, y, x]);
                splatMap2[y, x, 1] = BitUtility.Byte2Float(splatMap[1, y, x]);
                splatMap2[y, x, 2] = BitUtility.Byte2Float(splatMap[2, y, x]);
                splatMap2[y, x, 3] = BitUtility.Byte2Float(splatMap[3, y, x]);
                splatMap2[y, x, 4] = BitUtility.Byte2Float(splatMap[4, y, x]);
                splatMap2[y, x, 5] = BitUtility.Byte2Float(splatMap[5, y, x]);
                splatMap2[y, x, 6] = BitUtility.Byte2Float(splatMap[6, y, x]);
                splatMap2[y, x, 7] = BitUtility.Byte2Float(splatMap[7, y, x]);
            }
        }
        data.SetAlphamaps(0, 0, splatMap2);
        float[,] waterMap2 = new float[(int)meshResolution, (int)meshResolution];
        for (int y = 0; y < meshResolution; y++)
        {
            for (int x = 0; x < meshResolution; x++)
            {
                waterMap2[y, x] = BitUtility.Short2Float(waterMap[y, x]);
            }
        }
        data2.SetHeights(0, 0, waterMap2);
        float[,,] waterMap3 = new float[(int)textureResolution, (int)textureResolution, 1];
        for (int y = 0; y < textureResolution; y++)
        {
            for (int x = 0; x < textureResolution; x++)
            {
                waterMap3[y, x, 0] = 1;
            }
        }
        data2.SetAlphamaps(0, 0, waterMap3);

        for (int i = 0; i < blob.world.prefabs.Count; i++)
        {
            var        prefab = blob.world.prefabs[i];
            GameObject g      = GameObject.CreatePrimitive(PrimitiveType.Cube);
            g.transform.position   = prefab.position;
            g.transform.rotation   = prefab.rotation;
            g.transform.localScale = prefab.scale;
            g.name  = prefab.category.ToString();
            g.layer = 9;
            g.AddComponent <EditableObject>();
            g.AddComponent <LineRenderer>().material      = Rainbow.material;
            g.GetComponent <LineRenderer>().useWorldSpace = false;
            string[] pool = StringPool.Get(prefab.id).Split('/');
            g.AddComponent <PrefabData>().prefabName = pool[pool.Length - 1];
            g.GetComponent <PrefabData>().idInList   = i;
            Vector3[] poss = new Vector3[] { new Vector3(0, 1, 0), new Vector3(0, -1, 0) };
            g.GetComponent <LineRenderer>().SetPositions(poss);
            preSpawnedPrefabs.Add(g);
        }

        Camera.main.GetComponent <MainCamera>().isOpen = true;

        //StartCoroutine(GetPrefabs(blob));

        /*foreach (var prefab in blob.world.prefabs)
         * {
         *  GameObject obj3 = Instantiate((GameObject)bundles[prefabsListUint[prefab.id]].mainAsset, prefabs);
         *  obj3.transform.name = bundles[prefabsListUint[prefab.id]].name + " - " + prefab.id + " - " + prefab.category;
         *  obj3.transform.position = prefab.position;
         *  obj3.transform.rotation = prefab.rotation;
         *  obj3.transform.localScale = prefab.scale;
         * }*/
    }
Exemplo n.º 27
0
    /// <summary>Converts Unity terrains to WorldSerialization.</summary>
    public static WorldSerialization TerrainToWorld(Terrain land, Terrain water)
    {
        WorldSerialization world = new WorldSerialization();

        world.world.size = (uint)land.terrainData.size.x;

        var textureResolution = Mathf.Clamp(Mathf.NextPowerOfTwo((int)(world.world.size * 0.50f)), 16, 2048);

        byte[] splatBytes = new byte[textureResolution * textureResolution * 8];
        var    splatMap   = new TerrainMap <byte>(splatBytes, 8);
        var    splatTask  = Task.Run(() =>
        {
            Parallel.For(0, 8, i =>
            {
                for (int j = 0; j < textureResolution; j++)
                {
                    for (int k = 0; k < textureResolution; k++)
                    {
                        splatMap[i, j, k] = BitUtility.Float2Byte(GroundArray[j, k, i]);
                    }
                }
            });
            splatBytes = splatMap.ToByteArray();
        });

        byte[] biomeBytes = new byte[textureResolution * textureResolution * 4];
        var    biomeMap   = new TerrainMap <byte>(biomeBytes, 4);
        var    biomeTask  = Task.Run(() =>
        {
            Parallel.For(0, 4, i =>
            {
                for (int j = 0; j < textureResolution; j++)
                {
                    for (int k = 0; k < textureResolution; k++)
                    {
                        biomeMap[i, j, k] = BitUtility.Float2Byte(BiomeArray[j, k, i]);
                    }
                }
            });
            biomeBytes = biomeMap.ToByteArray();
        });

        byte[] alphaBytes = new byte[textureResolution * textureResolution * 1];
        var    alphaMap   = new TerrainMap <byte>(alphaBytes, 1);

        bool[,] terrainHoles = GetAlphaMap();
        var alphaTask = Task.Run(() =>
        {
            Parallel.For(0, textureResolution, i =>
            {
                for (int j = 0; j < textureResolution; j++)
                {
                    alphaMap[0, i, j] = BitUtility.Bool2Byte(terrainHoles[i, j]);
                }
            });
            alphaBytes = alphaMap.ToByteArray();
        });

        var topologyTask = Task.Run(() => TopologyData.SaveTopologyLayers());

        PrefabDataHolder[] prefabs = GameObject.FindGameObjectWithTag("Prefabs").GetComponentsInChildren <PrefabDataHolder>(false);
        foreach (PrefabDataHolder p in prefabs)
        {
            if (p.prefabData != null)
            {
                p.UpdatePrefabData(); // Updates the prefabdata before saving.
                world.world.prefabs.Insert(0, p.prefabData);
            }
        }

        PathDataHolder[] paths = GameObject.FindObjectsOfType <PathDataHolder>();
        foreach (PathDataHolder p in paths)
        {
            if (p.pathData != null)
            {
                p.pathData.nodes = new VectorData[p.transform.childCount];
                for (int i = 0; i < p.transform.childCount; i++)
                {
                    Transform g = p.transform.GetChild(i);
                    p.pathData.nodes[i] = g.position - (0.5f * land.terrainData.size);
                }
                world.world.paths.Insert(0, p.pathData);
            }
        }

        byte[] landHeightBytes  = FloatArrayToByteArray(land.terrainData.GetHeights(0, 0, land.terrainData.heightmapResolution, land.terrainData.heightmapResolution));
        byte[] waterHeightBytes = FloatArrayToByteArray(water.terrainData.GetHeights(0, 0, water.terrainData.heightmapResolution, water.terrainData.heightmapResolution));

        Task.WaitAll(splatTask, biomeTask, alphaTask, topologyTask);

        world.AddMap("terrain", landHeightBytes);
        world.AddMap("height", landHeightBytes);
        world.AddMap("water", waterHeightBytes);
        world.AddMap("splat", splatBytes);
        world.AddMap("biome", biomeBytes);
        world.AddMap("alpha", alphaBytes);
        world.AddMap("topology", TopologyData.GetTerrainMap().ToByteArray());
        return(world);
    }
Exemplo n.º 28
0
    public static WorldSerialization terrainToWorld(Terrain land, Terrain water)
    {
        WorldSerialization world = new WorldSerialization();

        world.world.size = (uint)land.terrainData.size.x;


        byte[] landHeightBytes  = TypeConverter.floatArrayToByteArray(land.terrainData.GetHeights(0, 0, land.terrainData.heightmapWidth, land.terrainData.heightmapHeight));
        byte[] waterHeightBytes = TypeConverter.floatArrayToByteArray(water.terrainData.GetHeights(0, 0, water.terrainData.heightmapWidth, water.terrainData.heightmapHeight));

        var textureResolution = Mathf.NextPowerOfTwo((int)(world.world.size * 0.50f));


        float[,,] splatMapValues = TypeConverter.singleToMulti(GameObject.FindGameObjectWithTag("Land").transform.Find("Ground").GetComponent <LandData>().splatMap, 8);
        byte[] splatBytes = new byte[textureResolution * textureResolution * 8];
        var    splatMap   = new TerrainMap <byte>(splatBytes, 8);

        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < textureResolution; j++)
            {
                for (int k = 0; k < textureResolution; k++)
                {
                    splatMap[i, j, k] = BitUtility.Float2Byte(splatMapValues[j, k, i]);
                }
            }
        }

        byte[] biomeBytes = new byte[textureResolution * textureResolution * 4];
        var    biomeMap   = new TerrainMap <byte>(biomeBytes, 4);

        float[,,] biomeArray = TypeConverter.singleToMulti(GameObject.FindGameObjectWithTag("Land").transform.Find("Biome").GetComponent <LandData>().splatMap, 4);

        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < textureResolution; j++)
            {
                for (int k = 0; k < textureResolution; k++)
                {
                    biomeMap[i, j, k] = BitUtility.Float2Byte(biomeArray[j, k, i]);
                }
            }
        }


        byte[] alphaBytes = new byte[textureResolution * textureResolution * 1];
        var    alphaMap   = new TerrainMap <byte>(alphaBytes, 1);

        float[,,] alphaArray = TypeConverter.singleToMulti(GameObject.FindGameObjectWithTag("Land").transform.Find("Alpha").GetComponent <LandData>().splatMap, 2);
        for (int j = 0; j < textureResolution; j++)
        {
            for (int k = 0; k < textureResolution; k++)
            {
                alphaMap[0, j, k] = BitUtility.Float2Byte(alphaArray[j, k, 0]);
            }
        }

        var topologyMap = GameObject.FindGameObjectWithTag("Topology").GetComponent <TopologyMesh>().getTerrainMap();


        world.AddMap("terrain", landHeightBytes);
        world.AddMap("height", landHeightBytes);
        world.AddMap("splat", splatMap.ToByteArray());
        world.AddMap("biome", biomeMap.ToByteArray());
        world.AddMap("topology", topologyMap.ToByteArray());
        world.AddMap("alpha", alphaMap.ToByteArray());
        world.AddMap("water", waterHeightBytes);

        PrefabDataHolder[] prefabs = GameObject.FindObjectsOfType <PrefabDataHolder>();

        foreach (PrefabDataHolder p in prefabs)
        {
            if (p.prefabData != null)
            {
                world.world.prefabs.Insert(0, p.prefabData);
            }
        }

        PathDataHolder[] paths = GameObject.FindObjectsOfType <PathDataHolder>();

        foreach (PathDataHolder p in paths)
        {
            if (p.pathData != null)
            {
                world.world.paths.Insert(0, p.pathData);
            }
        }


        return(world);
    }
Exemplo n.º 29
0
    public static MapInfo worldToTerrain(WorldSerialization blob)
    {
        MapInfo terrains = new MapInfo();

        var terrainSize = new Vector3(blob.world.size, 1000, blob.world.size);
        var terrainMap  = new TerrainMap <short>(blob.GetMap("terrain").data, 1);
        var heightMap   = new TerrainMap <short>(blob.GetMap("height").data, 1);
        var waterMap    = new TerrainMap <short>(blob.GetMap("water").data, 1);
        var splatMap    = new TerrainMap <byte>(blob.GetMap("splat").data, 8);
        var topologyMap = new TerrainMap <int>(blob.GetMap("topology").data, 1);
        var biomeMap    = new TerrainMap <byte>(blob.GetMap("biome").data, 4);
        var alphaMap    = new TerrainMap <byte>(blob.GetMap("alpha").data, 1);

        terrains.topology = topologyMap;

        terrains.pathData   = blob.world.paths.ToArray();
        terrains.prefabData = blob.world.prefabs.ToArray();

        terrains.resolution = heightMap.res;
        terrains.size       = terrainSize;

        terrains.terrain.heights = TypeConverter.shortMapToFloatArray(terrainMap);
        terrains.land.heights    = TypeConverter.shortMapToFloatArray(terrainMap);
        terrains.water.heights   = TypeConverter.shortMapToFloatArray(waterMap);

        terrains.splatMap = new float[splatMap.res, splatMap.res, 8];
        for (int i = 0; i < terrains.splatMap.GetLength(0); i++)
        {
            for (int j = 0; j < terrains.splatMap.GetLength(1); j++)
            {
                for (int k = 0; k < 8; k++)
                {
                    terrains.splatMap[i, j, k] = BitUtility.Byte2Float(splatMap[k, i, j]);
                }
            }
        }

        terrains.biomeMap = new float[biomeMap.res, biomeMap.res, 4];
        for (int i = 0; i < terrains.biomeMap.GetLength(0); i++)
        {
            for (int j = 0; j < terrains.biomeMap.GetLength(1); j++)
            {
                for (int k = 0; k < 4; k++)
                {
                    terrains.biomeMap[i, j, k] = BitUtility.Byte2Float(biomeMap[k, i, j]);
                }
            }
        }
        terrains.alphaMap = new float[alphaMap.res, alphaMap.res, 2];
        for (int i = 0; i < terrains.alphaMap.GetLength(0); i++)
        {
            for (int j = 0; j < terrains.alphaMap.GetLength(1); j++)
            {
                if (alphaMap[0, i, j] > 0)
                {
                    terrains.alphaMap[i, j, 0] = BitUtility.Byte2Float(alphaMap[0, i, j]);
                }
                else
                {
                    terrains.alphaMap[i, j, 1] = 0xFF;
                }
            }
        }

        /*
         * for (int i = 0; i < terrains.alphaMap.GetLength(0)/4; i++)
         * {
         *  for (int j = 0; j < terrains.alphaMap.GetLength(1)/4; j++)
         *  {
         *      for (int k = 0; k < 1; k++)
         *      {
         *          //if (BitUtility.Byte2Float(alphaMap[k, i, j]) > 0)
         *              //Debug.Log(alphaMap[k, i, j]);
         *      }
         *  }
         * }
         */


        return(terrains);
    }
Exemplo n.º 30
0
    protected void OnGUI()
    {
        const float padding = 10;

        GUILayout.BeginArea(new Rect(padding, padding, Screen.width - padding - padding, Screen.height - padding - padding));
        GUILayout.BeginVertical();

        GUILayout.BeginHorizontal();
        {
            GUILayout.Label("Map File");

            filename = GUILayout.TextField(filename, GUILayout.MinWidth(100));

                        #if UNITY_EDITOR
            if (GUILayout.Button("Browse"))
            {
                filename = UnityEditor.EditorUtility.OpenFilePanel("Select Map File", filename, "map");
                world    = LoadWorld(filename);
            }
                        #endif

            if (GUILayout.Button("Load"))
            {
                world = LoadWorld(filename);
            }

            GUILayout.FlexibleSpace();
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        if (world != null)
        {
            GUILayout.Label("Bundle File");

            bundlename = GUILayout.TextField(bundlename, GUILayout.MinWidth(100));

                        #if UNITY_EDITOR
            if (GUILayout.Button("Browse"))
            {
                bundlename = UnityEditor.EditorUtility.OpenFilePanel("Select Bundle File", bundlename, "");

                if (prefabs != null)
                {
                    prefabs.Dispose();
                    prefabs = null;
                }

                prefabs = new PrefabLookup(bundlename);
            }
                        #endif

            if (GUILayout.Button("Load"))
            {
                if (prefabs != null)
                {
                    prefabs.Dispose();
                    prefabs = null;
                }

                prefabs = new PrefabLookup(bundlename);
            }

            GUILayout.FlexibleSpace();
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        if (world != null && prefabs != null)
        {
            if (prefabs.isLoaded)
            {
                GUILayout.Label("Tools");

                if (GUILayout.Button("Print Map Info"))
                {
                    result = GetInfo(world);
                }
                if (GUILayout.Button("Clear Map Info"))
                {
                    result = string.Empty;
                }
                if (GUILayout.Button("Spawn Map Prefabs"))
                {
                    SpawnPrefabs(world, prefabs);
                }
            }
            else
            {
                GUILayout.Label("Loading Prefabs...");
            }

            GUILayout.FlexibleSpace();
        }
        GUILayout.EndHorizontal();

        if (!string.IsNullOrEmpty(result))
        {
            GUILayout.TextArea(result);
        }

        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
Exemplo n.º 31
0
 void Start() {
     _worldSerial = WorldSerialization.GetInstance();
     ActionButton.onClick.AddListener(DraftAction);
 }