/// <summary>
        /// Uses the PQS System to query the color of the undergound
        /// </summary>
        /// <param name="body"></param>
        /// <param name="lat"></param>
        /// <param name="lon"></param>
        /// <returns></returns>
        public static Color GetSurfaceColorPQS(CelestialBody body, Double lat, Double lon)
        {
            // Tell the PQS that our actions are not supposed to end up in the terrain
            body.pqsController.isBuildingMaps = true;
            body.pqsController.isFakeBuild    = true;

            // Create the vertex information
            PQS.VertexBuildData data = new PQS.VertexBuildData
            {
                directionFromCenter = body.GetRelSurfaceNVector(lat, lon).normalized,
                //vertHeight = body.pqsController.radius
                vertHeight = body.pqsController.GetSurfaceHeight(body.GetRelSurfaceNVector(lat, lon).normalized *body.Radius)
            };

            // Fetch all enabled Mods
            //PQSMod[] mods = body.GetComponentsInChildren<PQSMod>(true).Where(m => m.modEnabled && m.sphere == body.pqsController).ToArray();
            List <PQSMod> modsList = body.GetComponentsInChildren <PQSMod>(true).Where(m => m.modEnabled && m.sphere == body.pqsController).ToList();

            modsList.Sort(delegate(PQSMod first, PQSMod second)
            {
                return(first.order.CompareTo(second.order));
            });
            PQSMod[] mods = modsList.ToArray();


            // Iterate over them and build the height at this point
            // This is neccessary for mods that use the terrain height to
            // color the terrain (like HeightColorMap)
            foreach (PQSMod mod in mods)
            {
                mod.OnVertexBuildHeight(data);
            }

            // Iterate over the mods again, this time build the color component
            foreach (PQSMod mod in mods)
            {
                mod.OnVertexBuild(data);
            }

            // Reset the PQS
            body.pqsController.isBuildingMaps = false;
            body.pqsController.isFakeBuild    = false;

            Color vertColor = data.vertColor;

            vertColor  += new Color(0.01f, 0.01f, 0.02f);
            vertColor.a = 1;
            // The terrain color is now stored in data.vertColor.
            // For getting the height at this point you can use data.vertHeight
            return(vertColor);
        }
Example #2
0
        public PairIntDouble[] GetTerrainAndBiome(Coordinates[] coords)
        {
            DebugUtils.Assert(!ThreadDispatcher.IsMainThread);
            PairIntDouble[] ret = new PairIntDouble[coords.Length];

            ThreadDispatcher.QueueToMainThreadSync(() =>
            {
                for (int i = 0; i < coords.Length; i++)
                {
                    double lon = coords[i].Longitude;
                    double lat = coords[i].Latitude;

                    double alt = Body.pqsController.GetSurfaceHeight(Body.GetRelSurfaceNVector(lat * 180 / Math.PI, lon * 180 / Math.PI)) - Body.Radius;
                    int biome  = -1;

                    if (Body.BiomeMap)
                    {
                        var attr = Body.BiomeMap.GetAtt(lat, lon);
                        for (int k = 0, n = Body.BiomeMap.Attributes.Length; k < n; k++)
                        {
                            if (attr == Body.BiomeMap.Attributes[k])
                            {
                                biome = k;
                                break;
                            }
                        }
                    }

                    ret[i] = new PairIntDouble(biome, alt);
                }
            });


            return(ret);
        }
Example #3
0
        public static double TerrainAltitude(this CelestialBody body, double Lat, double Lon)
        {
            if (body.pqsController == null)
            {
                return(0);
            }
            var alt = body.pqsController.GetSurfaceHeight(body.GetRelSurfaceNVector(Lat, Lon)) - body.pqsController.radius;

            return(body.ocean && alt < 0 ? 0 : alt);
        }
Example #4
0
        public static double GetLocalTime(double lon, CelestialBody body, CelestialBody sun)
        {
            // latitude does not affect local time of day (it does affect sun visibility, though)
            Vector3d zenith_ra = body.GetRelSurfaceNVector(0, lon);
            Vector3d sunPos    = body.GetRelSurfacePosition(sun.position);

            sunPos.y = 0;               // not interested in declination
            Vector3d sunPos_ra = sunPos.normalized;
            double   sign      = Vector3d.Cross(zenith_ra, sunPos_ra).y >= 0 ? 1 : -1;

            return(sign * Angle(sunPos_ra, zenith_ra) / (2 * Math.PI) + 0.5);
        }
Example #5
0
        /// <summary>
        /// sets the latitude and lognitude from the deltas of north and east and creates a new reference vector
        /// </summary>
        /// <param name="north"></param>
        /// <param name="east"></param>
        internal void Setlatlng(double north, double east)
        {
            body = Planetarium.fetch.CurrentMainBody;
            double latOffset = north / (body.Radius * KKMath.deg2rad);

            selectedGroup.RefLatitude += latOffset;
            double lonOffset = east / (body.Radius * KKMath.deg2rad);

            selectedGroup.RefLongitude += lonOffset * Math.Cos(Mathf.Deg2Rad * selectedGroup.RefLatitude);

            selectedGroup.RadialPosition = body.GetRelSurfaceNVector(selectedGroup.RefLatitude, selectedGroup.RefLongitude).normalized *body.Radius;
            ApplySettings();
        }
Example #6
0
 public static PQS.VertexBuildData getBuildData(CelestialBody body, double lat, double lon)
 {
     if (lat > 90 || lat < -90 || lon > 180 || lon < -180)
         return new PQS.VertexBuildData ();
     PQS pqs = body.pqsController;
     Vector3d radialVector = body.GetRelSurfaceNVector (lat, lon);
     var buildData = new PQS.VertexBuildData ();
     buildData.directionFromCenter = radialVector.normalized;
     buildData.vertHeight = pqs.radius;
     typeof(PQS).InvokeMember ("Mod_OnVertexBuildHeight", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, pqs, new object[]{buildData});
     typeof(PQS).InvokeMember ("Mod_OnVertexBuild", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, pqs, new object[]{buildData});
     buildData.vertColor.a = 1.0f;
     return buildData;
 }
        //

        /// <summary>
        /// Updates the static instance with new settings
        /// </summary>
        public void Update(bool doUpdate = true)
        {
            mapDecal.heightMap = DecalsDatabase.GetHeightMapByName(HeightMapName).map;
            mapDecal.colorMap  = DecalsDatabase.GetColorMapByName(ColorMapName).map;

            if (mapDecal.heightMap == null && mapDecal.colorMap == null)
            {
                //DecalsDatabase.DeleteMapDecalInstance(this);
                return;
            }

            mapDecal.modEnabled       = true;
            mapDecal.requirements     = PQS.ModiferRequirements.MeshColorChannel | PQS.ModiferRequirements.MeshCustomNormals;
            mapDecal.order            = Order;
            mapDecal.sphere           = CelestialBody.pqsController;
            mapDecal.transform.parent = CelestialBody.pqsController.transform;

            mapDecal.position = CelestialBody.GetRelSurfaceNVector(Latitude, Longitude).normalized *CelestialBody.Radius;

            mapDecal.absolute       = UseAbsolut;
            mapDecal.absoluteOffset = AbsolutOffset;

            mapDecal.radius        = Radius;
            mapDecal.angle         = Angle;
            mapDecal.removeScatter = RemoveScatter;


            mapDecal.smoothHeight = SmoothHeight;

            mapDecal.heightMapDeformity      = HeightMapDeformity;
            mapDecal.useAlphaHeightSmoothing = UseAlphaHeightSmoothing;
            mapDecal.cullBlack = CullBlack;

            mapDecal.smoothColor = SmoothColor;

            //Log.Normal("MapDecal: heightmap: " + mapDecal.heightMap.name);
            //Log.Normal("MapDecal: Radius: "  + Radius.ToString());
            //Log.Normal("MapDecal: Vector:  " + mapDecal.position.ToString());
            //Log.Normal("MapDecal: Offset: " + AbsolutOffset);
            //Log.Normal("MapDecal: UseABS: " + UseAbsolut.ToString());


            mapDecal.OnSetup();
            // only rebuild the sphere when we use the editor
            if (doUpdate)
            {
                mapDecal.sphere.ForceStart();
            }
        }
        /// <summary>
        /// sets the latitude and lognitude from the deltas of north and east and creates a new reference vector
        /// </summary>
        /// <param name="north"></param>
        /// <param name="east"></param>
        internal void Setlatlng(double north, double east)
        {
            body = selectedDecal.CelestialBody;
            double latOffset = north / (body.Radius * KKMath.deg2rad);

            latitude += latOffset;
            double lonOffset = east / (body.Radius * KKMath.deg2rad);

            longitude += lonOffset * Math.Cos(Mathf.Deg2Rad * latitude);

            Vector3d newpos = body.GetWorldSurfacePosition(latitude, longitude, altitude);

            selectedDecal.mapDecal.transform.position = newpos;

            referenceVector = body.GetRelSurfaceNVector(latitude, longitude).normalized *body.Radius;
        }
Example #9
0
 public static Cell GetCellUnder(CelestialBody body, double latitude, double longitude)
 {
     return(Cell.Containing(body.GetRelSurfaceNVector(latitude, longitude), KethaneData.GridLevel));
 }
Example #10
0
        private Cell getKethaneCell(int ilon, int ilat)             //Find the Kethane cell corresponding to the current position
        {
            Vector3 pos = body.GetRelSurfaceNVector((double)ilat, (double)ilon);

            return(Cell.Containing(pos, 5));
        }
Example #11
0
        void GeneratePQSMaps()
        {
            // Textures
            Texture2D heightMap    = new Texture2D(tile, tile, TextureFormat.ARGB32, true);
            Texture2D normalMap    = new Texture2D(tile, tile, TextureFormat.ARGB32, true);
            Texture2D slopeMap     = new Texture2D(tile, tile, TextureFormat.RGB24, true);
            Texture2D colorMap     = new Texture2D(tile, tile, TextureFormat.ARGB32, true);
            Texture2D oceanMap     = new Texture2D(tile, tile, TextureFormat.ARGB32, true);
            Texture2D satelliteMap = new Texture2D(tile, tile, TextureFormat.RGB24, true);
            Texture2D biomeMap     = new Texture2D(tile, tile, TextureFormat.RGB24, true);

            // Arrays
            double[] terrainHeightValues = new double[(tile + 2) * (tile + 2)];
            Color[]  heightMapValues     = new Color[tile * tile];
            Color[]  colorMapValues      = new Color[tile * tile];
            Color[]  oceanMapValues      = new Color[tile * tile];
            Color[]  biomeMapValues      = new Color[tile * tile];

            // Edges
            int?firstY = null;
            int?lastY  = null;


            // reset current
            current = 0;

            // Get PQS
            PQS pqs = null;

            if (exportAny)
            {
                pqs = body.pqsController;
                pqs.isBuildingMaps = true;
                pqs.isFakeBuild    = true;
            }

            // Get the mods
            Action <PQS.VertexBuildData> modOnVertexBuildHeight = (Action <PQS.VertexBuildData>)Delegate.CreateDelegate(
                typeof(Action <PQS.VertexBuildData>),
                pqs,
                typeof(PQS).GetMethod("Mod_OnVertexBuildHeight", BindingFlags.Instance | BindingFlags.NonPublic));
            Action <PQS.VertexBuildData> modOnVertexBuild = (Action <PQS.VertexBuildData>)Delegate.CreateDelegate(
                typeof(Action <PQS.VertexBuildData>),
                pqs,
                typeof(PQS).GetMethod("Mod_OnVertexBuild", BindingFlags.Instance | BindingFlags.NonPublic));

            for (int j = width / 2 - tile; j >= 0; j -= tile)
            {
                for (int i = 0; i < width; i += tile)
                {
                    if (Print(current))
                    {
                        // Loop through the pixels
                        for (int y = -1; y < tile + 1; y++)
                        {
                            for (int x = -1; x < tile + 1; x++)
                            {
                                // Longitude
                                double lon = ((i + x) * 360d / width + LONoffset) % 360d - 180d;

                                // Latitude
                                double lat = ((j + y) * 360d / width - LAToffset) % 180d - 90d;
                                if (lat < -90)
                                {
                                    lat += 180;
                                }

                                // Export
                                if (exportAny)
                                {
                                    // Create a VertexBuildData
                                    PQS.VertexBuildData data = new PQS.VertexBuildData
                                    {
                                        directionFromCenter = body.GetRelSurfaceNVector(lat, lon).normalized,
                                        vertHeight          = pqs.radius
                                    };

                                    // Build from the Mods
                                    modOnVertexBuildHeight(data);

                                    if (exportHeightMap || exportNormalMap || exportSlopeMap || exportSatelliteMap)
                                    {
                                        // Adjust the height
                                        double height = (data.vertHeight - pqs.radiusMin) / pqs.radiusDelta;

                                        if (!oceanFloor & data.vertHeight < pqs.radius)
                                        {
                                            height = (pqs.radius - pqs.radiusMin) / pqs.radiusDelta;
                                        }

                                        if (height < 0)
                                        {
                                            height = 0;
                                        }
                                        else if (height > 1)
                                        {
                                            height = 1;
                                        }

                                        // Set the Pixels
                                        if (exportHeightMap && x > -1 && y > -1 && x < tile && y < tile)
                                        {
                                            Color color = Color.black;

                                            for (int k = 0; k < altitudeColor?.Count; k++)
                                            {
                                                KeyValuePair <double, Color> element1 = altitudeColor.ElementAt(k);

                                                if (k == altitudeColor?.Count - 1)
                                                {
                                                    color = element1.Value;
                                                }
                                                else
                                                {
                                                    KeyValuePair <double, Color> element2 = altitudeColor.ElementAt(k + 1);

                                                    if (element2.Key > height)
                                                    {
                                                        color = Color.Lerp(element1.Value, element2.Value, (float)((height - element1.Key) / (element2.Key - element1.Key)));
                                                        break;
                                                    }
                                                }
                                            }

                                            heightMapValues[(y * tile) + x] = color;
                                        }

                                        if (exportNormalMap || exportSlopeMap || exportSatelliteMap)
                                        {
                                            // Find First and last Latitude pixels
                                            double latN = ((j + y - 1) * 360d / width - LAToffset) % 180d - 90d;
                                            if (latN < -90)
                                            {
                                                latN += 180;
                                            }

                                            double latP = ((j + y + 1) * 360d / width - LAToffset) % 180d - 90d;
                                            if (latP < -90)
                                            {
                                                latP += 180;
                                            }

                                            if (latN - lat > 90)
                                            {
                                                firstY = y;
                                            }

                                            if (lat - latP > 90)
                                            {
                                                lastY = y;
                                            }

                                            terrainHeightValues[((y + 1) * (tile + 2)) + (x + 1)] = height * pqs.radiusDelta;
                                        }
                                    }

                                    if ((exportColorMap || exportSatelliteMap) && x > -1 && y > -1 && x < tile && y < tile)
                                    {
                                        modOnVertexBuild(data);

                                        // Adjust the Color
                                        Color color = data.vertColor.A(1f);
                                        if (!oceanFloor && data.vertHeight < pqs.radius)
                                        {
                                            color = oceanColor;
                                        }

                                        // Set the Pixels
                                        colorMapValues[(y * tile) + x] = color;
                                    }

                                    if (body.ocean && (exportOceanMap || exportSatelliteMap) && x > -1 && y > -1 && x < tile && y < tile)
                                    {
                                        // Adjust the Color
                                        Color color = data.vertHeight < pqs.radius ? oceanColor : new Color(0, 0, 0, 0);

                                        // Set the Pixels
                                        oceanMapValues[(y * tile) + x] = color;
                                    }
                                }

                                if (exportBiomeMap && x > -1 && y > -1 && x < tile && y < tile)
                                {
                                    CBAttributeMapSO.MapAttribute biome = body.BiomeMap.GetAtt(lat * Math.PI / 180d, lon * Math.PI / 180d);
                                    Color color = biome.mapColor;
                                    biomeMapValues[(y * tile) + x] = color;
                                }
                            }
                        }

                        // Apply the maps
                        if (exportHeightMap)
                        {
                            heightMap.SetPixels(heightMapValues);
                        }
                        if (exportNormalMap || exportSlopeMap || exportSatelliteMap)
                        {
                            CalculateSlope(terrainHeightValues, pqs, firstY, lastY, ref normalMap, ref slopeMap);
                        }
                        if (exportColorMap)
                        {
                            colorMap.SetPixels(colorMapValues);
                        }
                        if (exportOceanMap)
                        {
                            oceanMap.SetPixels(oceanMapValues);
                        }
                        if (exportSatelliteMap)
                        {
                            CreateSatelliteMap(colorMapValues, oceanMapValues, ref normalMap, ref satelliteMap);
                        }
                        if (exportBiomeMap)
                        {
                            biomeMap.SetPixels(biomeMapValues);
                        }

                        // Serialize them to disk
                        int    position = Flip(current);
                        string folder   = leaflet ? (position % (width / tile) + "/") : "";
                        string fileName = leaflet ? (position / (width / tile)) + ".png" : "Tile" + position.ToString("D4") + ".png";

                        if (exportHeightMap)
                        {
                            Directory.CreateDirectory(exportFolder + "HeightMap/" + folder);

                            if (flipH)
                            {
                                FlipH(ref heightMap);
                            }
                            if (flipV)
                            {
                                FlipV(ref heightMap);
                            }

                            File.WriteAllBytes(exportFolder + "HeightMap/" + folder + fileName, heightMap.EncodeToPNG());
                            File.WriteAllLines
                            (
                                exportFolder + "HeightMap/Info.txt",
                                new string[]
                            {
                                "HeightMap info",
                                "",
                                "Body = " + body.transform.name,
                                "deformity = " + pqs.radiusDelta,
                                "offset = " + (pqs.radiusMin - pqs.radius)
                            }
                            );
                        }

                        if (exportNormalMap)
                        {
                            Directory.CreateDirectory(exportFolder + "NormalMap/" + folder);

                            if (flipH)
                            {
                                FlipH(ref normalMap);
                            }
                            if (flipV)
                            {
                                FlipV(ref normalMap);
                            }

                            File.WriteAllBytes(exportFolder + "NormalMap/" + folder + fileName, normalMap.EncodeToPNG());
                        }

                        if (exportSlopeMap)
                        {
                            Directory.CreateDirectory(exportFolder + "SlopeMap/" + folder);

                            if (flipH)
                            {
                                FlipH(ref slopeMap);
                            }
                            if (flipV)
                            {
                                FlipV(ref slopeMap);
                            }

                            File.WriteAllBytes(exportFolder + "SlopeMap/" + folder + fileName, slopeMap.EncodeToPNG());
                        }

                        if (exportColorMap)
                        {
                            Directory.CreateDirectory(exportFolder + "ColorMap/" + folder);

                            if (flipH)
                            {
                                FlipH(ref colorMap);
                            }
                            if (flipV)
                            {
                                FlipV(ref colorMap);
                            }

                            File.WriteAllBytes(exportFolder + "ColorMap/" + folder + fileName, colorMap.EncodeToPNG());
                        }

                        if (exportOceanMap)
                        {
                            Directory.CreateDirectory(exportFolder + "OceanMap/" + folder);

                            if (flipH)
                            {
                                FlipH(ref oceanMap);
                            }
                            if (flipV)
                            {
                                FlipV(ref oceanMap);
                            }

                            File.WriteAllBytes(exportFolder + "OceanMap/" + folder + fileName, oceanMap.EncodeToPNG());
                        }

                        if (exportSatelliteMap)
                        {
                            Directory.CreateDirectory(exportFolder + "SatelliteMap/" + folder);

                            if (flipH)
                            {
                                FlipH(ref satelliteMap);
                            }
                            if (flipV)
                            {
                                FlipV(ref satelliteMap);
                            }

                            File.WriteAllBytes(exportFolder + "SatelliteMap/" + folder + fileName, satelliteMap.EncodeToPNG());
                        }

                        if (exportBiomeMap)
                        {
                            Directory.CreateDirectory(exportFolder + "BiomeMap/" + folder);

                            if (flipH)
                            {
                                FlipH(ref biomeMap);
                            }
                            if (flipV)
                            {
                                FlipV(ref biomeMap);
                            }

                            File.WriteAllBytes(exportFolder + "BiomeMap/" + folder + fileName, biomeMap.EncodeToPNG());

                            List <string> attributes = new string[] { "BiomeMap info", "", "Body = " + body.transform.name }.ToList();
                            foreach (var biome in body.BiomeMap.Attributes)
                            {
                                attributes.Add("Biome =\t" + biome.name + "\t" + biome.mapColor);
                            }

                            File.WriteAllLines(exportFolder + "BiomeMap/Info.txt", attributes.ToArray());
                        }
                    }
                    current++;
                }
            }

            // Close the Renderer
            pqs.isBuildingMaps = false;
            pqs.isFakeBuild    = false;

            // CleanUp
            DestroyImmediate(heightMap);
            DestroyImmediate(normalMap);
            DestroyImmediate(slopeMap);
            DestroyImmediate(colorMap);
            DestroyImmediate(oceanMap);
            DestroyImmediate(satelliteMap);
            DestroyImmediate(biomeMap);
        }
Example #12
0
 public static Vector3 GetRadiadFromLatLng(CelestialBody body, double lat, double lng)
 {
     return(body.GetRelSurfaceNVector(lat, lng).normalized *body.Radius);
 }
Example #13
0
 public static Vector3 GetRadiadFromLatLng(CelestialBody body, double lat, double lng)
 {
     //Log.Normal("Body Radius is: " +body.pqsController.radius);
     return(body.GetRelSurfaceNVector(lat, lng).normalized *body.pqsController.radius);
 }
Example #14
0
        internal static void GeneratePQSMaps(string subfolder = "", bool split = false)
        {
            // If no exports are required, end here
            if (!exportAny && !exportBiomeMap)
            {
                return;
            }

            // If normal maps should be kept separated
            if (split & satelliteAny)
            {
                exportNormalMap = true;

                if (exportSatelliteHeight)
                {
                    exportHeightMap = true;
                }
                if (exportSatelliteSlope)
                {
                    exportSlopeMap = true;
                }
                if (exportSatelliteMap)
                {
                    exportColorMap = true;
                }
                if (exportSatelliteBiome)
                {
                    exportBiomeMap = true;
                }

                satelliteAny = false;
            }

            // Textures
            try
            {
                heightMap    = new Texture2D(tile, Math.Min(tile, width / 2), TextureFormat.ARGB32, true);
                normalMap    = new Texture2D(tile, Math.Min(tile, width / 2), TextureFormat.ARGB32, true);
                slopeMap     = new Texture2D(tile, Math.Min(tile, width / 2), TextureFormat.RGB24, true);
                colorMap     = new Texture2D(tile, Math.Min(tile, width / 2), TextureFormat.ARGB32, true);
                oceanMap     = new Texture2D(tile, Math.Min(tile, width / 2), TextureFormat.ARGB32, true);
                biomeMap     = new Texture2D(tile, Math.Min(tile, width / 2), TextureFormat.RGB24, true);
                satelliteMap = new Texture2D(tile, Math.Min(tile, width / 2), TextureFormat.RGB24, true);
            }
            catch
            {
                Debug.LOG("MapGenerator", "ERROR - Failed to create new textures.");
                return;
            }

            // Create arrays
            double[] terrainHeightValues;
            Color[]  heightMapValues;
            Color[]  colorMapValues;
            Color[]  oceanMapValues;
            Color[]  biomeMapValues;
            // Define arrays
            try
            {
                terrainHeightValues = new double[(tile + 2) * (tile + 2)];
                heightMapValues     = new Color[tile * tile];
                colorMapValues      = new Color[tile * tile];
                oceanMapValues      = new Color[tile * tile];
                biomeMapValues      = new Color[tile * tile];
            }
            catch
            {
                Debug.LOG("MapGenerator", "ERROR - Failed to create new arrays.");
                return;
            }

            // Edges
            int?firstY = null;
            int?lastY  = null;


            // reset current
            current = 0;
            //generate folder & file names
            int position = Flip(current);
            //string folder = leaflet ? (position % (width / tile) + "/") : "";
            //string fileName = leaflet ? (position / (width / tile)) + ".png" : "Tile" + position.ToString("D4") + ".png";
            // Expanded statements for greater understandability. STH 2019-0831
            string folder;
            string fileName;

            if (leaflet)
            {
                folder   = (position % (width / tile) + "/");
                fileName = (position / (width / tile)) + ".png";
            }
            else
            {
                folder   = "";
                fileName = "Tile" + position.ToString("D4") + ".png";
            }

            //--------------------------
            //put checks for images here
            //STH 2019-0831
            string checkFile;

            checkFile = exportFolder + folder + "HeightMap/" + fileName;
            if (File.Exists(checkFile) && !overwriteHeightMap)
            {
                exportHeightMap = false;
                //UnityEngine.Debug.Log(Debug.Tag + " Overwrite of HeightMap skipped");
            }
            checkFile = exportFolder + folder + "NormalMap/" + fileName;
            if (File.Exists(checkFile) && !overwriteNormalMap)
            {
                exportNormalMap = false;
                //UnityEngine.Debug.Log(Debug.Tag + " Overwrite of NormalMap skipped");
            }
            checkFile = exportFolder + folder + "SlopeMap/" + fileName;
            if (File.Exists(checkFile) && !overwriteSlopeMap)
            {
                exportSlopeMap = false;
                //UnityEngine.Debug.Log(Debug.Tag + " Overwrite of SlopeMap skipped");
            }
            checkFile = exportFolder + folder + "ColorMap/" + fileName;
            if (File.Exists(checkFile) && !overwriteColorMap)
            {
                exportColorMap = false;
                //UnityEngine.Debug.Log(Debug.Tag + " Overwrite of ColorMap skipped");
            }
            checkFile = exportFolder + folder + "OceanMap/" + fileName;
            if (File.Exists(checkFile) && !overwriteOceanMap)
            {
                exportOceanMap = false;
                //UnityEngine.Debug.Log(Debug.Tag + " Overwrite of OceanMap skipped");
            }
            checkFile = exportFolder + folder + "BiomeMap/" + fileName;
            if (File.Exists(checkFile) && !overwriteBiomeMap)
            {
                exportBiomeMap = false;
                //UnityEngine.Debug.Log(Debug.Tag + " Overwrite of BiomeMap skipped");
            }
            //sat maps
            checkFile = exportFolder + folder + "SatelliteHeight/" + fileName;
            if (File.Exists(checkFile) && !overwriteSatelliteHeight)
            {
                exportSatelliteHeight = false;
                //UnityEngine.Debug.Log(Debug.Tag + " Overwrite of SatelliteHeight skipped");
            }
            checkFile = exportFolder + folder + "SatelliteSlope/" + fileName;
            if (File.Exists(checkFile) && !overwriteSatelliteSlope)
            {
                exportSatelliteSlope = false;
                //UnityEngine.Debug.Log(Debug.Tag + " Overwrite of SatelliteSlope skipped");
            }
            checkFile = exportFolder + folder + "SatelliteMap/" + fileName;
            if (File.Exists(checkFile) && !overwriteSatelliteMap)
            {
                exportSatelliteMap = false;
                //UnityEngine.Debug.Log(Debug.Tag + " Overwrite of SatelliteMap skipped");
            }
            checkFile = exportFolder + folder + "SatelliteBiome/" + fileName;
            if (File.Exists(checkFile) && !overwriteSatelliteBiome)
            {
                exportSatelliteBiome = false;
                //UnityEngine.Debug.Log(Debug.Tag + " Overwrite of SatelliteBiome skipped");
            }
            //--------------------------

            // Get PQS
            PQS pqs = null;

            if (exportAny)
            {
                pqs = body.pqsController;
                pqs.isBuildingMaps = true;
                pqs.isFakeBuild    = true;
            }

            // Get the mods
            Action <PQS.VertexBuildData, Boolean> modOnVertexBuildHeight = (Action <PQS.VertexBuildData, Boolean>)Delegate.CreateDelegate(
                typeof(Action <PQS.VertexBuildData, Boolean>),
                pqs,
                typeof(PQS).GetMethod("Mod_OnVertexBuildHeight", BindingFlags.Instance | BindingFlags.NonPublic));
            Action <PQS.VertexBuildData> modOnVertexBuild = (Action <PQS.VertexBuildData>)Delegate.CreateDelegate(
                typeof(Action <PQS.VertexBuildData>),
                pqs,
                typeof(PQS).GetMethod("Mod_OnVertexBuild", BindingFlags.Instance | BindingFlags.NonPublic));


            int count = width / 2 - tile;

            for (int j = count < 0 ? 0 : count; j >= 0; j -= tile)
            {
                for (int i = 0; i < width; i += tile)
                {
                    if (Print(current))
                    {
                        // Loop through the pixels
                        for (int y = -1; y < tile + 1; y++)
                        {
                            if (y > width / 2 + 1)
                            {
                                break;
                            }

                            for (int x = -1; x < tile + 1; x++)
                            {
                                // Longitude
                                double lon = ((i + x) * 360d / width + LONoffset) % 360d - 180d;
                                lon = ((lon % 360) + 360) % 360;
                                // Latitude
                                double lat = ((j + y) * 360d / width - LAToffset) % 180d - 90d;
                                if (lat < -90)
                                {
                                    lat += 180;
                                }

                                // Generate
                                try
                                {
                                    if (exportAny)
                                    {
                                        // Create a VertexBuildData
                                        PQS.VertexBuildData data = new PQS.VertexBuildData
                                        {
                                            directionFromCenter = body.GetRelSurfaceNVector(lat, lon).normalized,
                                            vertHeight          = pqs.radius
                                        };

                                        // Build from the Mods
                                        modOnVertexBuildHeight(data, true);

                                        if (exportHeightMap || exportNormalMap || exportSlopeMap || satelliteAny)
                                        {
                                            // Adjust the height
                                            double height = (data.vertHeight - pqs.radiusMin) / pqs.radiusDelta;

                                            if (!oceanFloor & data.vertHeight < pqs.radius)
                                            {
                                                height = (pqs.radius - pqs.radiusMin) / pqs.radiusDelta;
                                            }

                                            if (height < 0)
                                            {
                                                height = 0;
                                            }
                                            else if (height > 1)
                                            {
                                                height = 1;
                                            }

                                            // Set the Pixels
                                            if ((exportHeightMap || exportSatelliteHeight) && x > -1 && y > -1 && x < tile && y < tile)
                                            {
                                                Color color = Color.black;

                                                for (int k = 0; k < altitudeColor?.Count; k++)
                                                {
                                                    KeyValuePair <double, Color> element1 = altitudeColor.ElementAt(k);

                                                    if (k == altitudeColor?.Count - 1)
                                                    {
                                                        color = element1.Value;
                                                    }
                                                    else
                                                    {
                                                        KeyValuePair <double, Color> element2 = altitudeColor.ElementAt(k + 1);

                                                        if (element2.Key > height)
                                                        {
                                                            color = Color.Lerp(element1.Value, element2.Value, (float)((height - element1.Key) / (element2.Key - element1.Key)));
                                                            break;
                                                        }
                                                    }
                                                }

                                                heightMapValues[(y * tile) + x] = color;
                                            }

                                            if (exportNormalMap || exportSlopeMap || satelliteAny)
                                            {
                                                // Find First and last Latitude pixels
                                                double latN = ((j + y - 1) * 360d / width - LAToffset) % 180d - 90d;
                                                if (latN < -90)
                                                {
                                                    latN += 180;
                                                }

                                                double latP = ((j + y + 1) * 360d / width - LAToffset) % 180d - 90d;
                                                if (latP < -90)
                                                {
                                                    latP += 180;
                                                }

                                                if (latN - lat > 90)
                                                {
                                                    firstY = y;
                                                }

                                                if (lat - latP > 90)
                                                {
                                                    lastY = y;
                                                }

                                                terrainHeightValues[((y + 1) * (tile + 2)) + (x + 1)] = height * pqs.radiusDelta;
                                            }
                                        }

                                        if ((exportColorMap || exportSatelliteMap) && x > -1 && y > -1 && x < tile && y < tile)
                                        {
                                            try
                                            {
                                                modOnVertexBuild(data);

                                                // Adjust the Color
                                                Color color = data.vertColor.A(1);

                                                if (!oceanFloor)
                                                {
                                                    if (data.vertHeight > pqs.radius)
                                                    {
                                                        color.a = alpha ? 0 : 1;
                                                    }
                                                    else
                                                    {
                                                        color = oceanColor;
                                                    }
                                                }

                                                // Set the Pixels
                                                colorMapValues[(y * tile) + x] = color;
                                            }
                                            catch (Exception e)
                                            {
                                                Debug.LOG("MapGenerator", "ERROR - Failed to generate colors for colorMap/satelliteMap. \ncolorMapValues.length = " + colorMapValues.Length + "\n(y * tile) + x = " + x + ", y = " + y + ", tile = " + tile + "\n(y * tile) + x = " + ((y * tile) + x) + "\n\n" + e);
                                                return;
                                            }
                                        }

                                        if (body.ocean && exportOceanMap && x > -1 && y > -1 && x < tile && y < tile)
                                        {
                                            // Adjust the Color
                                            Color color = data.vertHeight < pqs.radius ? oceanColor : new Color(0, 0, 0, 0);

                                            // Set the Pixels
                                            oceanMapValues[(y * tile) + x] = color;
                                        }
                                    }

                                    if ((exportBiomeMap || exportSatelliteBiome) && x > -1 && y > -1 && x < tile && y < tile)
                                    {
                                        CBAttributeMapSO.MapAttribute biome = body.BiomeMap.GetAtt(lat * Math.PI / 180d, lon * Math.PI / 180d);
                                        Color color = biome.mapColor;
                                        biomeMapValues[(y * tile) + x] = color;
                                    }
                                }
                                catch (Exception e)
                                {
                                    Debug.LOG("MapGenerator", "ERROR - Failed to generate colors for tile " + current + ".\n\n" + e + "\n\n" + e.StackTrace + "\n\n" + e.Source + "\n\n" + e.TargetSite);
                                    return;
                                }
                            }
                        }

                        // Apply the maps
                        try
                        {
                            if (exportHeightMap || exportSatelliteHeight)
                            {
                                heightMap.SetPixels(heightMapValues);
                                heightMap.Apply();
                            }
                            if (exportNormalMap || exportSlopeMap || satelliteAny)
                            {
                                CalculateSlope(terrainHeightValues, pqs, firstY, lastY, ref normalMap, ref slopeMap);
                                normalMap.Apply();
                                slopeMap.Apply();
                            }
                            if (exportColorMap || exportSatelliteMap)
                            {
                                colorMap.SetPixels(colorMapValues);
                                colorMap.Apply();
                            }
                            if (exportOceanMap)
                            {
                                oceanMap.SetPixels(oceanMapValues);
                                oceanMap.Apply();
                            }
                            if (exportBiomeMap || exportSatelliteBiome)
                            {
                                biomeMap.SetPixels(biomeMapValues);
                                biomeMap.Apply();
                            }
                        }
                        catch
                        {
                            Debug.LOG("MapGenerator", "ERROR - Failed to apply colors for tile " + current + ".");
                            return;
                        }

                        // Serialize them to disk
                        //--------
                        //moved to before processing
                        //STH 2019-0831
                        //int position = Flip(current);
                        //string folder = leaflet ? (position % (width / tile) + "/") : "";
                        //string fileName = leaflet ? (position / (width / tile)) + ".png" : "Tile" + position.ToString("D4") + ".png";
                        //--------

                        // Export
                        try
                        {
                            if (exportHeightMap)
                            {
                                if (flipH)
                                {
                                    Utility.FlipH(ref heightMap);
                                }
                                if (flipV)
                                {
                                    Utility.FlipV(ref heightMap);
                                }

                                ExportPQSMap(ref heightMap, subfolder + "HeightMap/", folder + fileName);

                                File.WriteAllLines
                                (
                                    exportFolder + subfolder + "HeightMap/Info.txt",
                                    new string[]
                                {
                                    "HeightMap info",
                                    "",
                                    "Body = " + body.transform.name,
                                    "deformity = " + pqs.radiusDelta,
                                    "offset = " + (pqs.radiusMin - pqs.radius)
                                }
                                );
                            }

                            if (exportNormalMap)
                            {
                                if (flipH)
                                {
                                    Utility.FlipH(ref normalMap);
                                }
                                if (flipV)
                                {
                                    Utility.FlipV(ref normalMap);
                                }

                                ExportPQSMap(ref normalMap, subfolder + "NormalMap/", folder + fileName);
                            }

                            if (exportSlopeMap)
                            {
                                if (flipH)
                                {
                                    Utility.FlipH(ref slopeMap);
                                }
                                if (flipV)
                                {
                                    Utility.FlipV(ref slopeMap);
                                }

                                ExportPQSMap(ref slopeMap, subfolder + "SlopeMap/", folder + fileName);
                            }

                            if (exportColorMap)
                            {
                                if (flipH)
                                {
                                    Utility.FlipH(ref colorMap);
                                }
                                if (flipV)
                                {
                                    Utility.FlipV(ref colorMap);
                                }

                                ExportPQSMap(ref colorMap, subfolder + "ColorMap/", folder + fileName);
                            }

                            if (exportOceanMap)
                            {
                                if (flipH)
                                {
                                    Utility.FlipH(ref oceanMap);
                                }
                                if (flipV)
                                {
                                    Utility.FlipV(ref oceanMap);
                                }

                                ExportPQSMap(ref oceanMap, subfolder + "OceanMap/", folder + fileName);
                            }

                            if (exportBiomeMap)
                            {
                                if (flipH)
                                {
                                    Utility.FlipH(ref biomeMap);
                                }
                                if (flipV)
                                {
                                    Utility.FlipV(ref biomeMap);
                                }

                                ExportPQSMap(ref biomeMap, subfolder + "BiomeMap/", folder + fileName);

                                List <string> attributes = new string[] { "BiomeMap info", "", "Body = " + body.transform.name }.ToList();
                                foreach (var biome in body.BiomeMap.Attributes)
                                {
                                    attributes.Add("Biome =\t" + biome.name + "\t" + biome.mapColor);
                                }
                                File.WriteAllLines(exportFolder + subfolder + "BiomeMap/Info.txt", attributes.ToArray());
                            }

                            if (satelliteAny)
                            {
                                if (exportSatelliteHeight)
                                {
                                    CreateSatelliteMap(ref heightMap, ref normalMap, ref satelliteMap);
                                    ExportPQSMap(ref satelliteMap, subfolder + "SatelliteHeight/", fileName);
                                }

                                if (exportSatelliteSlope)
                                {
                                    CreateSatelliteMap(ref slopeMap, ref normalMap, ref satelliteMap);
                                    ExportPQSMap(ref satelliteMap, subfolder + "SatelliteSlope/", fileName);
                                }

                                if (exportSatelliteMap)
                                {
                                    CreateSatelliteMap(ref colorMap, ref normalMap, ref satelliteMap);
                                    ExportPQSMap(ref satelliteMap, subfolder + "SatelliteMap/", fileName);
                                }

                                if (exportSatelliteBiome)
                                {
                                    CreateSatelliteMap(ref biomeMap, ref normalMap, ref satelliteMap);
                                    ExportPQSMap(ref satelliteMap, subfolder + "SatelliteBiome/", fileName);
                                }
                            }
                        }
                        catch
                        {
                            Debug.LOG("MapGenerator", "ERROR - Failed to export tile " + current + ".");
                            return;
                        }
                    }
                    current++;
                }
            }

            // Close the Renderer
            pqs.isBuildingMaps = false;
            pqs.isFakeBuild    = false;
        }