/// <summary>
		/// Method to serialize a configuration file.
		/// </summary>
		/// <param name="definitions">The definition to serialize.</param>
		public void Serialize(MyObjectBuilder_Definitions definitions)
		{
			var settings = new XmlWriterSettings()
			{
				CloseOutput = true,
				Indent = true,
				ConformanceLevel = ConformanceLevel.Auto,
				NewLineHandling = NewLineHandling.Entitize
			};
			var writer = XmlWriter.Create(m_configFileInfo.FullName, settings);
			var serializer = (MyObjectBuilder_DefinitionsSerializer)Activator.CreateInstance(typeof(MyObjectBuilder_DefinitionsSerializer));
			serializer.Serialize(writer,definitions);
			writer.Close();
		}
        public static bool CopyBlueprintPrefabToClipboard(MyObjectBuilder_Definitions prefab, MyGridClipboard clipboard, bool setOwner = true)
        {
            if (prefab.ShipBlueprints == null)
                return false;

            var cubeGrids = prefab.ShipBlueprints[0].CubeGrids;

            if (cubeGrids == null || cubeGrids.Count() == 0)
                return false;

            var localBB = MyCubeGridExtensions.CalculateBoundingSphere(cubeGrids[0]);

            var posAndOrient = cubeGrids[0].PositionAndOrientation.Value;
            var worldMatrix = MatrixD.CreateWorld(posAndOrient.Position, posAndOrient.Forward, posAndOrient.Up);
            var invertedNormalizedWorld = Matrix.Normalize(Matrix.Invert(worldMatrix));

            var worldBB = localBB.Transform(worldMatrix);

            var dragVector = Vector3.TransformNormal((Vector3)(Vector3D)posAndOrient.Position - worldBB.Center, invertedNormalizedWorld);
            var dragDistance = localBB.Radius + 10f;

            //Reset ownership to local player
            if (setOwner)
            {
                foreach (var gridBuilder in cubeGrids)
                {
                    foreach (var block in gridBuilder.CubeBlocks)
                    {
                        if (block.Owner != 0)
                        {
                            block.Owner = MySession.LocalPlayerId;
                        }
                    }
                }
            }

            clipboard.SetGridFromBuilders(cubeGrids, dragVector, dragDistance);
            clipboard.Deactivate();
            return true;
        }
        void OnSave(MyGuiControlButton button)
        {
            var ob = new MyObjectBuilder_Definitions();

            var sounds = MyDefinitionManager.Static.GetSoundDefinitions();
            ob.Sounds = new MyObjectBuilder_AudioDefinition[sounds.Count];
            int i = 0;
            foreach (var sound in sounds)
            {
                ob.Sounds[i++] = (MyObjectBuilder_AudioDefinition)sound.GetObjectBuilder();
            }

            var path = Path.Combine(MyFileSystem.ContentPath, @"Data\Audio.sbc");
            MyObjectBuilderSerializer.SerializeXML(path, false, ob);
        }
        public static void Publish(MyObjectBuilder_Definitions prefab, string blueprintName, Action<ulong> publishCallback = null)
        {
            string file = Path.Combine(m_localBlueprintFolder, blueprintName);
            string title = prefab.ShipBlueprints[0].CubeGrids[0].DisplayName;
            string description = prefab.ShipBlueprints[0].Description;
            ulong publishId = prefab.ShipBlueprints[0].WorkshopId;
            MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                styleEnum: MyMessageBoxStyleEnum.Info,
                buttonType: MyMessageBoxButtonsType.YES_NO,
                messageCaption: new StringBuilder("Publish"),
                messageText: new StringBuilder("Do you want to publish this blueprint?"),
                callback: delegate(MyGuiScreenMessageBox.ResultEnum val)
                {
                    if (val == MyGuiScreenMessageBox.ResultEnum.YES)
                    {
                        Action<MyGuiScreenMessageBox.ResultEnum, string[]> onTagsChosen = delegate(MyGuiScreenMessageBox.ResultEnum tagsResult, string[] outTags)
                        {
                            if (tagsResult == MyGuiScreenMessageBox.ResultEnum.YES)
                            {
                                MySteamWorkshop.PublishBlueprintAsync(file, title, description, publishId, outTags, SteamSDK.PublishedFileVisibility.Public,
                                    callbackOnFinished: delegate(bool success, Result result, ulong publishedFileId)
                                    {
                                        if (success)
                                        {
                                            if (publishCallback != null)
                                                publishCallback(publishedFileId);

                                            prefab.ShipBlueprints[0].WorkshopId = publishedFileId;
                                            SavePrefabToFile(prefab, blueprintName, true);
                                            MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                styleEnum: MyMessageBoxStyleEnum.Info,
                                                messageText: MyTexts.Get(MySpaceTexts.MessageBoxTextWorldPublished),
                                                messageCaption: new StringBuilder("BLUEPRINT PUBLISHED"),
                                                callback: (a) =>
                                                {
                                                    MySteam.API.OpenOverlayUrl(string.Format("http://steamcommunity.com/sharedfiles/filedetails/?id={0}", publishedFileId));
                                                }));
                                        }
                                        else
                                        {
                                            MyStringId error;
                                            switch (result)
                                            {
                                                case Result.AccessDenied:
                                                    error = MySpaceTexts.MessageBoxTextPublishFailed_AccessDenied;
                                                    break;
                                                default:
                                                    error = MySpaceTexts.MessageBoxTextWorldPublishFailed;
                                                    break;
                                            }

                                            MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                messageText: MyTexts.Get(error),
                                                messageCaption: MyTexts.Get(MySpaceTexts.MessageBoxCaptionWorldPublishFailed)));
                                        }
                                    });
                            }
                        };

                        if (MySteamWorkshop.BlueprintCategories.Length > 0)
                            MyGuiSandbox.AddScreen(new MyGuiScreenWorkshopTags(MySteamWorkshop.WORKSHOP_BLUEPRINT_TAG, MySteamWorkshop.BlueprintCategories, null, onTagsChosen));
                        else
                            onTagsChosen(MyGuiScreenMessageBox.ResultEnum.YES, new string[] { MySteamWorkshop.WORKSHOP_BLUEPRINT_TAG });
                    }
                }));

        }
        protected static void SavePrefabToFile(MyObjectBuilder_Definitions prefab, string name = null, bool replace = false, MyBlueprintTypeEnum type = MyBlueprintTypeEnum.LOCAL)
        { 
            if (name == null)
            {
                name = MyUtils.StripInvalidChars(MyCubeBuilder.Static.Clipboard.CopiedGridsName);
            }

            string file = "";
            if (type == MyBlueprintTypeEnum.LOCAL)
            {
                file = Path.Combine(m_localBlueprintFolder, name);
            }
            else 
            {
                file = Path.Combine(m_workshopBlueprintFolder, "temp", name);
            }
            string filePath = "";
            int index = 1;

            try
            {
                if (!replace)
                {
                    while (MyFileSystem.DirectoryExists(file))
                    {
                        file = Path.Combine(m_localBlueprintFolder, name + "_" + index);
                        index++;
                    }
                    if (index > 1)
                    {
                        name += new StringBuilder("_" + (index - 1));
                    }
                }
                filePath = file + "\\bp.sbc";
                var success = MyObjectBuilderSerializer.SerializeXML(filePath, false, prefab);

                Debug.Assert(success, "falied to write blueprint to file");
                if (!success)
                {
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                        buttonType: MyMessageBoxButtonsType.OK,
                        styleEnum: MyMessageBoxStyleEnum.Error,
                        messageCaption: new StringBuilder("Error"),
                        messageText: new StringBuilder("There was a problem with saving blueprint")
                        ));
                    if (Directory.Exists(file))
                        Directory.Delete(file, true);
                }

            }
            catch (Exception e)
            {
                MySandboxGame.Log.WriteLine(String.Format("Failed to write prefab at file {0}, message: {1}, stack:{2}", filePath, e.Message, e.StackTrace));
            }
        }
 public virtual void CheckAndFixPrefab(MyObjectBuilder_Definitions prefab)
 { }
        public void ExportPrefabObjectToFile(bool blankOwnerAndMedBays, params IStructureViewBase[] viewModels)
        {
            var saveFileDialog = _saveFileDialogFactory();
            saveFileDialog.Filter = Res.DialogExportPrefabObjectFilter;
            saveFileDialog.Title = Res.DialogExportSandboxObjectTitle;
            saveFileDialog.FileName = "export prefab.sbc";
            saveFileDialog.OverwritePrompt = true;

            if (_dialogService.ShowSaveFileDialog(this, saveFileDialog) == DialogResult.OK)
            {
                var definition = new MyObjectBuilder_Definitions();
                definition.Prefabs = new MyObjectBuilder_PrefabDefinition[1];
                MyObjectBuilder_PrefabDefinition prefab;
                prefab = new MyObjectBuilder_PrefabDefinition();
                prefab.Id.TypeId = new MyObjectBuilderType(typeof(MyObjectBuilder_PrefabDefinition));
                prefab.Id.SubtypeId = Path.GetFileNameWithoutExtension(saveFileDialog.FileName);

                var grids = new List<MyObjectBuilder_CubeGrid>();

                foreach (var viewModel in viewModels)
                {
                    if (viewModel is StructureCubeGridViewModel)
                    {
                        var cloneEntity = (MyObjectBuilder_CubeGrid)viewModel.DataModel.EntityBase.Clone();

                        if (blankOwnerAndMedBays)
                        {
                            // Call to ToArray() to force Linq to update the value.

                            // Clear Medical room SteamId.
                            cloneEntity.CubeBlocks.Where(c => c.TypeId == SpaceEngineersTypes.MedicalRoom).Select(c => { ((MyObjectBuilder_MedicalRoom)c).SteamUserId = 0; return c; }).ToArray();

                            // Clear Owners.
                            cloneEntity.CubeBlocks.Select(c => { c.Owner = 0; c.ShareMode = MyOwnershipShareModeEnum.None; return c; }).ToArray();
                        }

                        // Remove any pilots.
                        cloneEntity.CubeBlocks.Where(c => c.TypeId == SpaceEngineersTypes.Cockpit).Select(c =>
                        {
                            ((MyObjectBuilder_Cockpit)c).ClearPilotAndAutopilot();
                            ((MyObjectBuilder_Cockpit)c).PilotRelativeWorld = null;
                            return c;
                        }).ToArray();

                        grids.Add(cloneEntity);
                    }
                }

                prefab.CubeGrids = grids.ToArray();
                definition.Prefabs[0] = prefab;

                SpaceEngineersApi.WriteSpaceEngineersFile(definition, saveFileDialog.FileName);
            }
        }
		/// <summary>
		/// Method to Deserialize the current inner Configuration File
		/// </summary>
		public void Deserialize()
		{
			m_definitions = m_configFileSerializer.Deserialize();
			FillOverLayerContainers(m_definitions.CubeBlocks);
		}