Exemplo n.º 1
0
        /// <summary>
        ///     If diagnostic output is enabled, this method writes the log of a compilation.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="assemblyName"></param>
        /// <param name="messages"></param>
        /// <param name="success"></param>
        /// <returns></returns>
        async Task WriteDiagnostics(MyApiTarget target, string assemblyName, IEnumerable <Message> messages, bool success)
        {
            string outputPath;

            if (!GetDiagnosticsOutputPath(target, assemblyName, out outputPath))
            {
                return;
            }
            var fileName = Path.Combine(outputPath, "log.txt");
            var builder  = new StringBuilder();

            builder.AppendLine("Success: " + success);
            builder.AppendLine();
            foreach (var line in messages)
            {
                builder.AppendLine(line.Severity + " " + line.Text);
            }
            using (var stream = MyFileSystem.OpenWrite(fileName))
            {
                var writer = new StreamWriter(stream);
                await writer.WriteAsync(builder.ToString()).ConfigureAwait(false);

                await writer.FlushAsync().ConfigureAwait(false);
            }
        }
Exemplo n.º 2
0
 public void Save()
 {
     if (!Game.IsDedicated)
     {
         MySandboxGame.Log.WriteLine("MyConfig.Save() - START");
         MySandboxGame.Log.IncreaseIndent();
         try
         {
             MySandboxGame.Log.WriteLine("Path: " + this.m_path, LoggingOptions.CONFIG_ACCESS);
             try
             {
                 using (Stream stream = MyFileSystem.OpenWrite(this.m_path, FileMode.Create))
                 {
                     XmlWriterSettings settings = new XmlWriterSettings();
                     settings.Indent          = true;
                     settings.NewLineHandling = NewLineHandling.None;
                     using (XmlWriter writer = XmlWriter.Create(stream, settings))
                     {
                         Type[] extraTypes = new Type[] { typeof(SerializableDictionary <string, string>), typeof(List <string>), typeof(SerializableDictionary <string, MyConfig.MyDebugInputData>), typeof(MyConfig.MyDebugInputData), typeof(MyObjectBuilder_ServerFilterOptions) };
                         new XmlSerializer(this.m_values.GetType(), extraTypes).Serialize(writer, this.m_values);
                     }
                 }
             }
             catch (Exception exception)
             {
                 MySandboxGame.Log.WriteLine("Exception occured, but application is continuing. Exception: " + exception);
             }
         }
         finally
         {
             MySandboxGame.Log.DecreaseIndent();
             MySandboxGame.Log.WriteLine("MyConfig.Save() - END");
         }
     }
 }
Exemplo n.º 3
0
        public void Init(string logFileName, StringBuilder appVersionString)
        {
            lock (m_lock)
            {
                try
                {
                    m_filepath        = Path.IsPathRooted(logFileName) ? logFileName : Path.Combine(MyFileSystem.UserDataPath, logFileName);
                    m_stream          = MyFileSystem.OpenWrite(m_filepath);
                    m_streamWriter    = new StreamWriter(m_stream);
                    m_normalWriter    = new Action <string>(WriteLine);
                    m_closedLogWriter = new Action <string>((s) => File.AppendAllText(m_filepath, s + Environment.NewLine));
                    m_enabled         = true;
                }
                catch (Exception e)
                {
                    SystemTrace.Fail("Cannot create log file: " + e.ToString());
                }

                m_indentsByThread = new Dictionary <int, int>();
                m_indents         = new Dictionary <MyLogIndentKey, MyLogIndentValue>();

                int timezone = (int)Math.Round((DateTime.Now - DateTime.UtcNow).TotalHours);

                WriteLine("Log Started");
                WriteLine(String.Format("Timezone (local - UTC): {0}h", timezone));
                WriteLine("App Version: " + appVersionString);
            }
        }
Exemplo n.º 4
0
        private static void UpdateFileFormat(string originalVoxFile)
        {
            var newFile = Path.ChangeExtension(originalVoxFile, MyVoxelConstants.FILE_EXTENSION);

            if (!File.Exists(originalVoxFile))
            {
                MySandboxGame.Log.WriteLine(string.Format("ERROR: Voxel file '{0}' does not exists!", originalVoxFile));
            }
            if (Path.GetExtension(originalVoxFile) != "vox")
            {
                MySandboxGame.Log.WriteLine(string.Format("ERROR: Unexpected voxel file extensions in path: '{0}'", originalVoxFile));
            }

            using (var decompressFile = new MyCompressionFileLoad(originalVoxFile))
                using (var file = MyFileSystem.OpenWrite(newFile))
                    using (var gzip = new GZipStream(file, CompressionMode.Compress))
                        using (var buffer = new BufferedStream(gzip))
                        {
                            buffer.WriteNoAlloc(m_attributesByType[typeof(MyCellStorage)].SerializedTypeName);

                            // File version. New format will store it in 7bit encoded int right after the name of storage.
                            buffer.Write7BitEncodedInt(decompressFile.GetInt32());

                            // All remaining data is unchanged. Just copy it to new file.
                            byte[] tmp       = new byte[0x4000];
                            int    bytesRead = decompressFile.GetBytes(tmp.Length, tmp);
                            while (bytesRead != 0)
                            {
                                buffer.Write(tmp, 0, bytesRead);
                                bytesRead = decompressFile.GetBytes(tmp.Length, tmp);
                            }
                        }
        }
Exemplo n.º 5
0
        /// <summary>
        ///     If diagnostics is enabled, this method writes
        /// </summary>
        /// <param name="target"></param>
        /// <param name="assemblyName"></param>
        /// <param name="syntaxTrees"></param>
        /// <param name="suffix"></param>
        /// <returns></returns>
        async Task WriteDiagnostics(MyApiTarget target, string assemblyName, IEnumerable <SyntaxTree> syntaxTrees, string suffix = null)
        {
            string outputPath;

            if (!GetDiagnosticsOutputPath(target, assemblyName, out outputPath))
            {
                return;
            }
            suffix = suffix ?? "";
            foreach (var syntaxTree in syntaxTrees)
            {
                var root = await syntaxTree.GetRootAsync().ConfigureAwait(false);

                var normalizedTree = CSharpSyntaxTree.Create((CSharpSyntaxNode)root.NormalizeWhitespace(), path: syntaxTree.FilePath);
                var fileName       = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(syntaxTree.FilePath) + suffix + Path.GetExtension(syntaxTree.FilePath));
                if (!fileName.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))
                {
                    fileName += ".cs";
                }
                using (var stream = MyFileSystem.OpenWrite(fileName))
                {
                    var writer = new StreamWriter(stream);
                    await writer.WriteAsync(normalizedTree.ToString()).ConfigureAwait(false);

                    await writer.FlushAsync().ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 6
0
        private void Compile(IEnumerable <string> scriptFiles, string assemblyName, bool zipped, MyModContext context)
        {
#if XB1
            System.Diagnostics.Debug.Assert(false, "Unsupported runtime script compilation on XB1.");
#else
            Assembly assembly = null;
            bool     compiled = false;
            if (zipped)
            {
                var tmp = Path.GetTempPath();
                foreach (var file in scriptFiles)
                {
                    try
                    {
                        var newPath = string.Format("{0}{1}", tmp, Path.GetFileName(file));
                        var stream  = MyFileSystem.OpenRead(file);
                        using (var sr = new StreamReader(stream))
                        {
                            stream = MyFileSystem.OpenWrite(newPath);// (newPath);
                            using (var sw = new StreamWriter(stream))
                            {
                                sw.Write(sr.ReadToEnd()); //create file in tmp for debugging
                            }
                        }
                        m_cachedFiles.Add(newPath);
                    }
                    catch (Exception e)
                    {
                        MySandboxGame.Log.WriteLine(e);
                        MyDefinitionErrors.Add(context, string.Format("Cannot load {0}", Path.GetFileName(file)), TErrorSeverity.Error);
                        MyDefinitionErrors.Add(context, e.Message, TErrorSeverity.Error);
                    }
                }
                compiled = IlCompiler.CompileFileModAPI(assemblyName, m_cachedFiles.ToArray(), out assembly, m_errors);
            }
            else
            {
                compiled = IlCompiler.CompileFileModAPI(assemblyName, scriptFiles.ToArray(), out assembly, m_errors);
            }
            Debug.Assert(compiled == (assembly != null), "Compile results inconsistency!");
            if (assembly != null && compiled)
            {
                AddAssembly(context, MyStringId.GetOrCompute(assemblyName), assembly);
            }
            else
            {
                MyDefinitionErrors.Add(context, string.Format("Compilation of {0} failed:", assemblyName), TErrorSeverity.Error);
                MySandboxGame.Log.IncreaseIndent();
                foreach (var error in m_errors)
                {
                    MyDefinitionErrors.Add(context, error.ToString(), TErrorSeverity.Error);
                    Debug.Assert(false, error.ToString());
                }
                MySandboxGame.Log.DecreaseIndent();
                m_errors.Clear();
            }
            m_cachedFiles.Clear();
#endif
        }
Exemplo n.º 7
0
        private void Compile(IEnumerable <string> scriptFiles, string assemblyName, bool zipped)
        {
            Assembly assembly = null;
            var      c        = new MyModContext();

            c.Init(assemblyName, assemblyName);
            if (zipped)
            {
                var tmp = Path.GetTempPath();
                foreach (var file in scriptFiles)
                {
                    try
                    {
                        var newPath = string.Format("{0}{1}", tmp, Path.GetFileName(file));
                        var stream  = MyFileSystem.OpenRead(file);
                        using (var sr = new StreamReader(stream))
                        {
                            stream = MyFileSystem.OpenWrite(newPath);// (newPath);
                            using (var sw = new StreamWriter(stream))
                            {
                                sw.Write(sr.ReadToEnd()); //create file in tmp for debugging
                            }
                        }
                        m_cachedFiles.Add(newPath);
                    }
                    catch (Exception e)
                    {
                        MySandboxGame.Log.WriteLine(e);
                        MyDefinitionErrors.Add(c, string.Format("Cannot load {0}", Path.GetFileName(file)), ErrorSeverity.Error);
                        MyDefinitionErrors.Add(c, e.Message, ErrorSeverity.Error);
                    }
                }
                IlCompiler.CompileFileModAPI(assemblyName, m_cachedFiles.ToArray(), out assembly, m_errors);
            }
            else
            {
                IlCompiler.CompileFileModAPI(assemblyName, scriptFiles.ToArray(), out assembly, m_errors);
            }
            if (assembly != null)
            {
                AddAssembly(MyStringId.GetOrCompute(assemblyName), assembly);
            }
            else
            {
                MyDefinitionErrors.Add(c, string.Format("Compilation of {0} failed:", assemblyName), ErrorSeverity.Error);
                MySandboxGame.Log.IncreaseIndent();
                foreach (var error in m_errors)
                {
                    MyDefinitionErrors.Add(c, error.ToString(), ErrorSeverity.Error);
                    Debug.Assert(false, error.ToString());
                }
                MySandboxGame.Log.DecreaseIndent();
                m_errors.Clear();
            }
            m_cachedFiles.Clear();
        }
Exemplo n.º 8
0
            void ShrinkVMap()
            {
                Vector3I min, max;

                m_selectedVoxel.GetFilledStorageBounds(out min, out max);

                MyVoxelMapStorageDefinition def = null;

                if (m_selectedVoxel.AsteroidName != null)
                {
                    MyDefinitionManager.Static.TryGetVoxelMapStorageDefinition(m_selectedVoxel.AsteroidName, out def);
                }

                var origSize = m_selectedVoxel.Size;

                var tightSize = max - min + 1;

                var storage = new MyOctreeStorage(null, tightSize);

                var offset = (storage.Size - tightSize) / 2 + 1;

                MyStorageData data = new MyStorageData();

                data.Resize(tightSize);

                m_selectedVoxel.Storage.ReadRange(data, MyStorageDataTypeFlags.ContentAndMaterial, 0, min, max);

                min = offset;
                max = offset + tightSize - 1;
                storage.WriteRange(data, MyStorageDataTypeFlags.ContentAndMaterial, ref min, ref max);

                var newMap = MyWorldGenerator.AddVoxelMap(m_selectedVoxel.StorageName, storage, m_selectedVoxel.WorldMatrix);

                m_selectedVoxel.Close();

                newMap.Save = true;

                if (def == null)
                {
                    ShowAlert("Voxel map {0} does not have a definition, the shrunk voxel map will be saved with the world instead.", m_selectedVoxel.StorageName);
                }
                else
                {
                    byte[] cVmapData;
                    newMap.Storage.Save(out cVmapData);

                    using (var ostream = MyFileSystem.OpenWrite(Path.Combine(MyFileSystem.ContentPath, def.StorageFile), FileMode.Open))
                    {
                        ostream.Write(cVmapData, 0, cVmapData.Length);
                    }
                    var notification = new MyHudNotification(MyStringId.GetOrCompute("Voxel prefab {0} updated succesfuly (size changed from {1} to {2})."), 4000);
                    notification.SetTextFormatArguments(def.Id.SubtypeName, origSize, storage.Size);
                    MyHud.Notifications.Add(notification);
                }
            }
    BinaryWriter IMyUtilities.WriteBinaryFileInGlobalStorage(string file)
    {
        if (file.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
        {
            throw new FileNotFoundException();
        }
        Stream stream = MyFileSystem.OpenWrite(Path.Combine(MyFileSystem.UserDataPath, "Storage", file));

        if (stream != null)
        {
            return(new BinaryWriter(stream));
        }
        throw new FileNotFoundException();
    }
    BinaryWriter IMyUtilities.WriteBinaryFileInWorldStorage(string file, Type callingType)
    {
        if (file.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
        {
            throw new FileNotFoundException();
        }
        Stream stream = MyFileSystem.OpenWrite(Path.Combine(MySession.Static.CurrentPath, "Storage", StripDllExtIfNecessary(callingType.Assembly.ManifestModule.ScopeName), file));

        if (stream != null)
        {
            return(new BinaryWriter(stream));
        }
        throw new FileNotFoundException();
    }
Exemplo n.º 11
0
        BinaryWriter IMyUtilities.WriteBinaryFileInLocalStorage(string file, Type callingType)
        {
            if (file.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
            {
                throw new FileNotFoundException();
            }
            var path   = Path.Combine(MyFileSystem.UserDataPath, STORAGE_FOLDER, callingType.Assembly.ManifestModule.ScopeName, file);
            var stream = MyFileSystem.OpenWrite(path);

            if (stream != null)
            {
                return(new BinaryWriter(stream));
            }
            throw new FileNotFoundException();
        }
Exemplo n.º 12
0
        TextWriter IMyUtilities.WriteFileInGlobalStorage(string file)
        {
            if (file.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
            {
                throw new FileNotFoundException();
            }
            var path   = Path.Combine(MyFileSystem.UserDataPath, STORAGE_FOLDER, file);
            var stream = MyFileSystem.OpenWrite(path);

            if (stream != null)
            {
                return(new StreamWriter(stream));
            }
            throw new FileNotFoundException();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Writes to a file located in the storage folder at path. The calling type is used
        /// to get the assembly name to get the sub directory in the storage folder, where files for the dll are stored.
        /// </summary>
        /// <param name="path">Path to the storage folder</param>
        /// <param name="file">File name</param>
        /// <param name="callingType">Calling type</param>
        /// <returns>A TextWriter to write to the file</returns>
        public static TextWriter WriteFileInPath(string path, string file, Type callingType)
        {
            if (file.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
            {
                throw new FileNotFoundException();
            }

            var paths  = Path.Combine(path, STORAGE_FOLDER, StripDllExtIfNecessary(callingType.Assembly.ManifestModule.ScopeName), file);
            var stream = MyFileSystem.OpenWrite(paths);

            if (stream != null)
            {
                return(new StreamWriter(stream));
            }
            throw new FileNotFoundException();
        }
Exemplo n.º 14
0
        /// <summary>
        /// Writes to a file located in the storage folder at path.
        /// The subdirectoy for the file in the storage folder
        /// is the plugins storage folder, SEWorldGenPlugin
        /// </summary>
        /// <param name="path">Path to the storage folder</param>
        /// <param name="file">File name</param>
        /// <returns>A TextWriter to write to the file</returns>
        public static TextWriter WriteFileInPath(string path, string file)
        {
            if (file.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
            {
                throw new FileNotFoundException();
            }

            var paths  = Path.Combine(path, STORAGE_FOLDER, PLUGIN_FOLDER, file);
            var stream = MyFileSystem.OpenWrite(paths);

            if (stream != null)
            {
                return(new StreamWriter(stream));
            }
            throw new FileNotFoundException();
        }
        public static bool SerializeXML(string path, bool compress, MyObjectBuilder_Base objectBuilder, out ulong sizeInBytes, Type serializeAsType = null)
        {
            try
            {
                using (var fileStream = MyFileSystem.OpenWrite(path))
                    using (var writeStream = compress ? fileStream.WrapGZip() : fileStream)
                    {
                        long          startPos   = fileStream.Position;
                        XmlSerializer serializer = m_serializersByType[serializeAsType ?? objectBuilder.GetType()];
                        serializer.Serialize(writeStream, objectBuilder);
                        sizeInBytes = (ulong)(fileStream.Position - startPos); // Length of compressed stream
                    }
            }
            catch (Exception e)
            {
                MyLog.Default.WriteLine("Error: " + path + " failed to serialize.");
                MyLog.Default.WriteLine(e.ToString());

#if !XB1
#if DEBUG
                var io = e as IOException;
                if (io != null && io.IsFileLocked())
                {
                    MyLog.Default.WriteLine("Files is locked during saving.");
                    MyLog.Default.WriteLine("Xml file locks:");
                    try
                    {
                        foreach (var p in Win32Processes.GetProcessesLockingFile(path))
                        {
                            MyLog.Default.WriteLine(p.ProcessName);
                        }
                    }
                    catch (Exception e2)
                    {
                        MyLog.Default.WriteLine(e2);
                    }
                }
#endif
#endif // !XB1

                sizeInBytes = 0;

                return(false);
            }
            return(true);
        }
Exemplo n.º 16
0
        //  Save all values from config file
        public void Save()
        {
            if (MySandboxGame.IsDedicated)
            {
                return;
            }

            MySandboxGame.Log.WriteLine("MyConfig.Save() - START");
            MySandboxGame.Log.IncreaseIndent();
            ProfilerShort.Begin("MyConfig.Save");
            try
            {
                MySandboxGame.Log.WriteLine("Path: " + m_path, LoggingOptions.CONFIG_ACCESS);

                try
                {
                    using (var stream = MyFileSystem.OpenWrite(m_path))
                    {
                        XmlWriterSettings settings = new XmlWriterSettings()
                        {
                            Indent          = true,
                            NewLineHandling = NewLineHandling.None
                        };

                        using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
                        {
                            XmlSerializer xmlSerializer = new XmlSerializer(m_values.GetType(), new Type[] { typeof(SerializableDictionary <string, string>), typeof(List <string>), typeof(SerializableDictionary <string, MyConfig.MyDebugInputData>), typeof(MyConfig.MyDebugInputData) });
                            xmlSerializer.Serialize(xmlWriter, m_values);
                        }
                    }
                }
                catch (Exception exc)
                {
                    //  Write exception to log, but continue as if nothing wrong happened
                    MySandboxGame.Log.WriteLine("Exception occured, but application is continuing. Exception: " + exc);
                }
            }
            finally
            {
                ProfilerShort.End();
                MySandboxGame.Log.DecreaseIndent();
                MySandboxGame.Log.WriteLine("MyConfig.Save() - END");
            }
        }
Exemplo n.º 17
0
        private static void UpdateFileFormat(string originalVoxFile)
        {
            var newFile = Path.ChangeExtension(originalVoxFile, MyVoxelConstants.FILE_EXTENSION);

            if (!File.Exists(originalVoxFile))
            {
                MySandboxGame.Log.Error("Voxel file '{0}' does not exist!", originalVoxFile);
                return;
            }

            if (Path.GetExtension(originalVoxFile) != ".vox")
            {
                MySandboxGame.Log.Warning("Unexpected voxel file extensions in path: '{0}'", originalVoxFile);
            }

            try
            {
                using (var decompressFile = new MyCompressionFileLoad(originalVoxFile))
                    using (var file = MyFileSystem.OpenWrite(newFile))
                        using (var gzip = new GZipStream(file, CompressionMode.Compress))
                            using (var buffer = new BufferedStream(gzip))
                            {
                                buffer.WriteNoAlloc(STORAGE_TYPE_NAME_CELL);

                                // File version. New format will store it in 7bit encoded int right after the name of storage.
                                buffer.Write7BitEncodedInt(decompressFile.GetInt32());

                                // All remaining data is unchanged. Just copy it to new file.
                                byte[] tmp       = new byte[0x4000];
                                int    bytesRead = decompressFile.GetBytes(tmp.Length, tmp);
                                while (bytesRead != 0)
                                {
                                    buffer.Write(tmp, 0, bytesRead);
                                    bytesRead = decompressFile.GetBytes(tmp.Length, tmp);
                                }
                            }
            }
            catch (Exception e)
            {
                MySandboxGame.Log.Error("While updating voxel storage '{0}' to new format: {1}", originalVoxFile, e.Message);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Writes to a file in the current worlds storage folder.
        /// If the file does not exist, it will be created.
        /// The subdirectoy for the file in the storage folder
        /// is the plugins storage folder, SEWorldGenPlugin
        /// </summary>
        /// <param name="file">File name</param>
        /// <exception cref="FileNotFoundException">When no file cannot be created</exception>
        /// <returns>A TextWriter, to write to the file</returns>
        public static TextWriter WriteFileInWorldStorage(string file)
        {
            if (file.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
            {
                throw new FileNotFoundException();
            }
            if (!MySession.Static.CurrentPath.ToLower().Contains(MyFileSystem.UserDataPath.ToLower()))
            {
                return(null);
            }

            var path   = Path.Combine(MySession.Static.CurrentPath, STORAGE_FOLDER, PLUGIN_FOLDER, file);
            var stream = MyFileSystem.OpenWrite(path);

            if (stream != null)
            {
                return(new StreamWriter(stream));
            }
            throw new FileNotFoundException();
        }
Exemplo n.º 19
0
        /// <summary>
        /// Writes to a file in the current worlds storage folder.
        /// If the file does not exist, it will be created. The calling type is used
        /// to get the assembly name to get the sub directory in the storage folder,
        /// where files for the dll are stored.
        /// </summary>
        /// <param name="file">File name</param>
        /// <param name="callingType">Calling type</param>
        /// <exception cref="FileNotFoundException">When no file cannot be created</exception>
        /// <returns>A TextWriter, to write to the file</returns>
        public static TextWriter WriteFileInWorldStorage(string file, Type callingType)
        {
            if (file.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
            {
                throw new FileNotFoundException();
            }
            if (!MySession.Static.CurrentPath.ToLower().Contains(MyFileSystem.UserDataPath.ToLower()))
            {
                return(null);
            }

            var path   = Path.Combine(MySession.Static.CurrentPath, STORAGE_FOLDER, StripDllExtIfNecessary(callingType.Assembly.ManifestModule.ScopeName), file);
            var stream = MyFileSystem.OpenWrite(path);

            if (stream != null)
            {
                return(new StreamWriter(stream));
            }
            throw new FileNotFoundException();
        }
Exemplo n.º 20
0
 private void WriteScripts(string path)
 {
     try
     {
         var fsPath = Path.Combine(path, "Data", "Scripts");
         foreach (var file in m_scriptsToSave)
         {
             var newPath = string.Format("{0}\\{1}", fsPath, file.Key);
             var stream  = MyFileSystem.OpenWrite(newPath);
             using (var sw = new StreamWriter(stream))
             {
                 sw.Write(file.Value);
             }
         }
     }
     catch (Exception e)
     {
         MySandboxGame.Log.WriteLine(e);
     }
 }
Exemplo n.º 21
0
        private void ResavePrefabs(MyGuiControlButton sender)
        {
            var fileList = MyFileSystem.GetFiles(
                MyFileSystem.ContentPath,
                //Path.Combine(MyFileSystem.ContentPath, "VoxelMaps"),
                "*" + MyVoxelConstants.FILE_EXTENSION,
                SearchOption.AllDirectories).ToArray();

            for (int i = 0; i < fileList.Length; ++i)
            {
                var file = fileList[i];
                Debug.WriteLine(string.Format("Resaving [{0}/{1}] '{2}'", i + 1, fileList.Length, file));
                var    storage = MyStorageBase.LoadFromFile(file);
                byte[] savedData;
                storage.Save(out savedData);
                using (var stream = MyFileSystem.OpenWrite(file, System.IO.FileMode.Open))
                {
                    stream.Write(savedData, 0, savedData.Length);
                }
            }
            Debug.WriteLine("Saving prefabs finished.");
        }
Exemplo n.º 22
0
        private static StreamWriter GetFileStreamToStorage(string file)
        {
            Stream stream = MyFileSystem.OpenWrite(Path.Combine(MyFileSystem.UserDataPath, "Storage", "MorePPSettings", file), FileMode.Create);

            return(new StreamWriter(stream));
        }
Exemplo n.º 23
0
        public static string SaveScreenshot(Texture tex, string file)
        {
#if !XB1
            MyRender.Log.WriteLine("MyScreenshot.SaveTexture2D() - START");
            MyRender.Log.IncreaseIndent();

            string filename = null;

            using (Texture systemTex = new Texture(MyRender.GraphicsDevice, tex.GetLevelDescription(0).Width, tex.GetLevelDescription(0).Height, 1, Usage.None, Format.A8R8G8B8, Pool.SystemMemory))
            {
                string extension = Path.GetExtension(file);

                using (Surface sourceSurface = tex.GetSurfaceLevel(0))
                    using (Surface destSurface = systemTex.GetSurfaceLevel(0))
                    {
                        MyRender.GraphicsDevice.GetRenderTargetData(sourceSurface, destSurface);
                    }

                try
                {
                    MyRender.Log.WriteLine("File: " + file);

                    Stack <SharpDX.Rectangle> tiles = new Stack <SharpDX.Rectangle>();

                    int tileWidth  = systemTex.GetLevelDescription(0).Width;
                    int tileHeight = systemTex.GetLevelDescription(0).Height;

                    while (tileWidth > 3200)
                    {
                        tileWidth  /= 2;
                        tileHeight /= 2;
                    }

                    int widthOffset  = 0;
                    int heightOffset = 0;

                    while (widthOffset < systemTex.GetLevelDescription(0).Width)
                    {
                        while (heightOffset < systemTex.GetLevelDescription(0).Height)
                        {
                            tiles.Push(new SharpDX.Rectangle(widthOffset, heightOffset, widthOffset + tileWidth, heightOffset + tileHeight));
                            heightOffset += tileHeight;
                        }

                        heightOffset = 0;
                        widthOffset += tileWidth;
                    }

                    bool multipleTiles = tiles.Count > 1;

                    int    sc   = 0;
                    byte[] data = new byte[tileWidth * tileHeight * 4];

                    int sysTexWidth  = systemTex.GetLevelDescription(0).Width;
                    int sysTexHeight = systemTex.GetLevelDescription(0).Height;
                    while (tiles.Count > 0)
                    {
                        SharpDX.Rectangle rect = tiles.Pop();
                        //texture2D.GetData<byte>(0, rect2, data, 0, data.Length);
                        DataStream ds;
                        //DataRectangle dr = texture2D.LockRectangle(0, rect2, LockFlags.ReadOnly, out ds);
                        DataRectangle dr = systemTex.LockRectangle(0, LockFlags.ReadOnly, out ds);

                        //we have to go line by line..
                        ds.Seek(rect.Y * sysTexWidth * 4, SeekOrigin.Begin);
                        int targetOffset = 0;

                        int linesCount = tileHeight;

                        int pixelsBefore = rect.X;
                        int pixelsAfter  = sysTexWidth - tileWidth - rect.X;

                        while (linesCount-- > 0)
                        {
                            if (pixelsBefore > 0)
                            {
                                ds.Seek(pixelsBefore * 4, SeekOrigin.Current);
                            }

                            ds.Read(data, targetOffset, tileWidth * 4);
                            targetOffset += tileWidth * 4;

                            if (pixelsAfter > 0 && linesCount > 0)
                            {
                                ds.Seek(pixelsAfter * 4, SeekOrigin.Current);
                            }
                        }

                        systemTex.UnlockRectangle(0);
                        filename = file;

                        if (multipleTiles)
                        {
                            filename = file.Replace(extension, "_" + sc.ToString("##00") + extension);
                        }

                        using (var stream = MyFileSystem.OpenWrite(MyFileSystem.UserDataPath, filename))
                        {
                            using (System.Drawing.Bitmap image = new System.Drawing.Bitmap(tileWidth, tileHeight))
                            {
                                System.Drawing.Imaging.BitmapData imageData = image.LockBits(new System.Drawing.Rectangle(0, 0, tileWidth, tileHeight), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                                System.Runtime.InteropServices.Marshal.Copy(data, 0, imageData.Scan0, data.Length);

                                if (extension == ".png")
                                {
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                                }
                                else if (extension == ".jpg" || extension == ".jpeg")
                                {
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                                else if (extension == ".bmp")
                                {
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                                }
                                else
                                {
                                    throw new InvalidOperationException("Invalid file extension: " + extension + ", please use png, jpg or bmp");
                                }

                                image.UnlockBits(imageData);
                            }

                            //texture2D.SaveAsPng(stream, texture2D.Width, texture2D.Height);
                            //BaseTexture.ToStream(texture2D, ImageFileFormat.Png);
                        }

                        sc++;
                        GC.Collect();
                    }
                }
                catch (Exception exc)
                {
                    //  Write exception to log, but continue as if nothing wrong happened
                    MyRender.Log.WriteLine(exc);
                    filename = null;
                }
            }
            //BaseTexture.ToFile(texture2D, "c:\\test.png", ImageFileFormat.Png);

            MyRender.Log.DecreaseIndent();
            MyRender.Log.WriteLine("MyScreenshot.SaveTexture2D() - END");

            return(filename);
#else
            System.Diagnostics.Debug.Assert(false, "Not Screenshoot support on XB1 yet!");
            return(null);
#endif
        }