public SpaceEngineersCore() { var contentPath = ToolboxUpdater.GetApplicationContentPath(); string userDataPath = SpaceEngineersConsts.BaseLocalPath.DataPath; MyFileSystem.Reset(); MyFileSystem.Init(contentPath, userDataPath); MyLog.Default = MySandboxGame.Log; MySandboxGame.Config = new MyConfig("SpaceEngineers.cfg"); // TODO: Is specific to SE, not configurable to ME. MySandboxGame.Config.Load(); MyFileSystem.InitUserSpecific(null); SpaceEngineersGame.SetupPerGameSettings(); VRageRender.MyRenderProxy.Initialize(new MyNullRender()); // We create a whole instance of MySandboxGame! MySandboxGame gameTemp = new MySandboxGame(null); // creating MySandboxGame will reset the CurrentUICulture, so I have to reapply it. Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(GlobalSettings.Default.LanguageCode); SpaceEngineersApi.LoadLocalization(); _stockDefinitions = new SpaceEngineersResources(); _stockDefinitions.LoadDefinitions(); _manageDeleteVoxelList = new List <string>(); }
public void InitMyFileSystem(string instanceName = "", bool reset = true) { string contentPath = Path.Combine(new FileInfo(MyFileSystem.ExePath).Directory.FullName, "Content"); string userDataPath = Instance.GetUserDataPath(instanceName); if (reset) { MyFileSystem.Reset( ); } else { try { if (!string.IsNullOrWhiteSpace(MyFileSystem.ContentPath)) { return; } if (!string.IsNullOrWhiteSpace(MyFileSystem.UserDataPath)) { return; } } catch (Exception) { //Do nothing } } MyFileSystem.Init(contentPath, userDataPath); MyFileSystem.InitUserSpecific(null); m_instanceName = instanceName; }
/// <inheritdoc /> public override void Attach() { MyFileSystem.ExePath = Path.Combine(_filesystemManager.TorchDirectory, "DedicatedServer64"); MyFileSystem.Init("Content", Torch.Config.InstancePath); //Initializes saves path. Why this isn't in Init() we may never know. MyFileSystem.InitUserSpecific(null); }
private static void SetPaths() { string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string sepath = Path.Combine(appdata, "SpaceEngineers"); MyFileSystem.Init(sepath, sepath); }
public SpaceEngineersCore() { var contentPath = ToolboxUpdater.GetApplicationContentPath(); string userDataPath = SpaceEngineersConsts.BaseLocalPath.DataPath; MyFileSystem.Reset(); MyFileSystem.Init(contentPath, userDataPath); MyLog.Default = MySandboxGame.Log; MySandboxGame.Config = new MyConfig("SpaceEngineers.cfg"); // TODO: Is specific to SE, not configurable to ME. MySandboxGame.Config.Load(); MyFileSystem.InitUserSpecific(null); SpaceEngineersGame.SetupPerGameSettings(); VRageRender.MyRenderProxy.Initialize(new MyNullRender()); // We create a whole instance of MySandboxGame! // If this is causing an exception, then there is a missing dependency. MySandboxGame gameTemp = new MySandboxGame(new string[] { "-skipintro" }); // creating MySandboxGame will reset the CurrentUICulture, so I have to reapply it. Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(GlobalSettings.Default.LanguageCode); SpaceEngineersApi.LoadLocalization(); MyStorageBase.UseStorageCache = false; #region MySession creation // Replace the private constructor on MySession, so we can create it without getting involed with Havok and other depdancies. var keenStart = typeof(Sandbox.Game.World.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null); var ourStart = typeof(SEToolbox.Interop.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null); ReflectionUtil.ReplaceMethod(ourStart, keenStart); // Create an empty instance of MySession for use by low level code. Sandbox.Game.World.MySession mySession = ReflectionUtil.ConstructPrivateClass <Sandbox.Game.World.MySession>(new Type[0], new object[0]); ReflectionUtil.ConstructField(mySession, "m_sessionComponents"); // Required as the above code doesn't populate it during ctor of MySession. mySession.Settings = new MyObjectBuilder_SessionSettings { EnableVoxelDestruction = true }; VRage.MyVRage.Init(new ToolboxPlatform()); // change for the Clone() method to use XML cloning instead of Protobuf because of issues with MyObjectBuilder_CubeGrid.Clone() ReflectionUtil.SetFieldValue(typeof(VRage.ObjectBuilders.MyObjectBuilderSerializer), "ENABLE_PROTOBUFFERS_CLONING", false); // Assign the instance back to the static. Sandbox.Game.World.MySession.Static = mySession; Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static = new MyHeightMapLoadingSystem(); Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static.LoadData(); #endregion _stockDefinitions = new SpaceEngineersResources(); _stockDefinitions.LoadDefinitions(); _manageDeleteVoxelList = new List <string>(); }
public void LoadInstance(string path, bool validate = true) { Log.Info($"Loading instance {path}"); if (validate) { ValidateInstance(path); } MyFileSystem.Reset(); MyFileSystem.Init("Content", path); //Initializes saves path. Why this isn't in Init() we may never know. MyFileSystem.InitUserSpecific(null); var configPath = Path.Combine(path, CONFIG_NAME); if (!File.Exists(configPath)) { Log.Error($"Failed to load dedicated config at {path}"); return; } var config = new MyConfigDedicated <MyObjectBuilder_SessionSettings>(configPath); config.Load(configPath); DedicatedConfig = new ConfigDedicatedViewModel(config); var worldFolders = Directory.EnumerateDirectories(Path.Combine(Torch.Config.InstancePath, "Saves")); foreach (var f in worldFolders) { try { if (!string.IsNullOrEmpty(f) && File.Exists(Path.Combine(f, "Sandbox.sbc"))) { DedicatedConfig.Worlds.Add(new WorldViewModel(f)); } } catch (Exception ex) { Log.Error("Failed to load world at path: " + f); continue; } } if (DedicatedConfig.Worlds.Count == 0) { Log.Warn($"No worlds found in the current instance {path}."); return; } SelectWorld(DedicatedConfig.LoadWorld ?? DedicatedConfig.Worlds.First().WorldPath, false); InstanceLoaded?.Invoke(DedicatedConfig); }
public void InitMyFileSystem(string instanceName = "") { string contentPath = Path.Combine(new FileInfo(MyFileSystem.ExePath).Directory.FullName, "Content"); string userDataPath = SandboxGameAssemblyWrapper.Instance.GetUserDataPath(instanceName); MyFileSystem.Reset(); MyFileSystem.Init(contentPath, userDataPath); MyFileSystem.InitUserSpecific((string)null); string debugContentPath = MyFileSystem.ContentPath; string debugUserDataPath = MyFileSystem.UserDataPath; }
//internal static readonly string AppName = "SpaceEngineersDedicated"; /// <summary> /// The main entry point for the application. /// </summary> //[STAThread] public static void Start <T>() where T : MyObjectBuilder_SessionSettings, new() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); SelectInstanceForm selectionForm; ConfigForm <T> configForm; var isService = false; var serviceName = ""; var serviceData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), MyPerServerSettings.GameDSName); var contentPath = Path.Combine(new FileInfo(MyFileSystem.ExePath).Directory.FullName, "Content"); do { selectionForm = new SelectInstanceForm(serviceData, MyPerServerSettings.GameDSName + ".exe"); Application.Run(selectionForm); if (selectionForm.DialogResult == DialogResult.OK) { if (selectionForm.SelectedInstance != null) { isService = true; serviceName = selectionForm.SelectedInstance.InstanceName; MyFileSystem.Init(contentPath, Path.Combine(serviceData, serviceName)); MyFileSystem.InitUserSpecific(null); } else { isService = false; serviceName = ""; MyFileSystem.Init(contentPath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), MyPerServerSettings.GameDSName)); MyFileSystem.InitUserSpecific(null); } } else { break; } MySandboxGame.Config = new MyConfig(MyPerServerSettings.GameNameSafe + ".cfg"); MySandboxGame.ConfigDedicated = new MyConfigDedicated <T>(MyPerServerSettings.GameNameSafe + "-Dedicated.cfg"); configForm = new ConfigForm <T>(isService, serviceName); Application.Run(configForm); }while (configForm.HasToExit); }
public void LoadInstance(string path, bool validate = true) { if (validate) { ValidateInstance(path); } MyFileSystem.Reset(); MyFileSystem.ExePath = Path.Combine(_filesystemManager.TorchDirectory, "DedicatedServer64"); MyFileSystem.Init("Content", path); //Initializes saves path. Why this isn't in Init() we may never know. MyFileSystem.InitUserSpecific(null); var configPath = Path.Combine(path, CONFIG_NAME); if (!File.Exists(configPath)) { Log.Error($"Failed to load dedicated config at {path}"); return; } var config = new MyConfigDedicated <MyObjectBuilder_SessionSettings>(configPath); config.Load(configPath); DedicatedConfig = new ConfigDedicatedViewModel(config); var worldFolders = Directory.EnumerateDirectories(Path.Combine(Torch.Config.InstancePath, "Saves")); foreach (var f in worldFolders) { DedicatedConfig.WorldPaths.Add(f); } if (DedicatedConfig.WorldPaths.Count == 0) { Log.Warn($"No worlds found in the current instance {path}."); return; } ImportWorldConfig(); /* * if (string.IsNullOrEmpty(DedicatedConfig.LoadWorld)) * { * Log.Warn("No world specified, importing first available world."); * SelectWorld(DedicatedConfig.WorldPaths[0], false); * }*/ }
public SpaceEngineersCore() { var contentPath = ToolboxUpdater.GetApplicationContentPath(); string userDataPath = SpaceEngineersConsts.BaseLocalPath.DataPath; MyFileSystem.ExePath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(FastResourceLock)).Location); MyLog.Default = MySandboxGame.Log; SpaceEngineersGame.SetupBasicGameInfo(); _startup = new MyCommonProgramStartup(new string[] { }); //var appDataPath = _startup.GetAppDataPath(); //MyInitializer.InvokeBeforeRun(AppId, MyPerGameSettings.BasicGameInfo.ApplicationName + "SEToolbox", appDataPath); //MyInitializer.InitCheckSum(); MyFileSystem.Reset(); MyFileSystem.Init(contentPath, userDataPath); // This will start the Steam Service, and Steam will think SE is running. // TODO: we don't want to be doing this all the while SEToolbox is running, // perhaps a once off during load to fetch of mods then disconnect/Dispose. _steamService = MySteamGameService.Create(MySandboxGame.IsDedicated, AppId); MyServiceManager.Instance.AddService(_steamService); IMyUGCService serviceInstance = MySteamUgcService.Create(AppId, _steamService); MyServiceManager.Instance.AddService(serviceInstance); MyFileSystem.InitUserSpecific(_steamService.UserId.ToString()); // This sets the save file/path to load games from. //MyFileSystem.InitUserSpecific(null); //SpaceEngineersWorkshop.MySteam.Dispose(); MySandboxGame.Config = new MyConfig("SpaceEngineers.cfg"); // TODO: Is specific to SE, not configurable to ME. MySandboxGame.Config.Load(); SpaceEngineersGame.SetupPerGameSettings(); VRage.MyVRage.Init(new ToolboxPlatform()); VRage.MyVRage.Platform.Init(); MySandboxGame.InitMultithreading(); VRageRender.MyRenderProxy.Initialize(new MyNullRender()); // We create a whole instance of MySandboxGame! // If this is causing an exception, then there is a missing dependency. MySandboxGame gameTemp = new DerivedGame(new string[] { "-skipintro" }); // creating MySandboxGame will reset the CurrentUICulture, so I have to reapply it. Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(GlobalSettings.Default.LanguageCode); SpaceEngineersApi.LoadLocalization(); MyStorageBase.UseStorageCache = false; // Create an empty instance of MySession for use by low level code. var mySession = (Sandbox.Game.World.MySession)FormatterServices.GetUninitializedObject(typeof(Sandbox.Game.World.MySession)); // Required as the above code doesn't populate it during ctor of MySession. ReflectionUtil.ConstructField(mySession, "m_creativeTools"); ReflectionUtil.ConstructField(mySession, "m_sessionComponents"); ReflectionUtil.ConstructField(mySession, "m_sessionComponentsForUpdate"); mySession.Settings = new MyObjectBuilder_SessionSettings { EnableVoxelDestruction = true }; // change for the Clone() method to use XML cloning instead of Protobuf because of issues with MyObjectBuilder_CubeGrid.Clone() ReflectionUtil.SetFieldValue(typeof(VRage.ObjectBuilders.MyObjectBuilderSerializer), "ENABLE_PROTOBUFFERS_CLONING", false); // Assign the instance back to the static. Sandbox.Game.World.MySession.Static = mySession; var heightMapLoadingSystem = new MyHeightMapLoadingSystem(); mySession.RegisterComponent(heightMapLoadingSystem, heightMapLoadingSystem.UpdateOrder, heightMapLoadingSystem.Priority); heightMapLoadingSystem.LoadData(); _stockDefinitions = new SpaceEngineersResources(); _stockDefinitions.LoadDefinitions(); _manageDeleteVoxelList = new List <string>(); }
public void FindType() { Type ivms = typeof(VRage.Game.ModAPI.IMyVoxelMaps); var binPath = @"D:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin"; var assemblyFiles = Directory.GetFiles(binPath /*GlobalSettings.Default.SEBinPath*/, "*.dll"); _spaceEngineersAssemblies = assemblyFiles.Select(f => Path.GetFileName(f)).ToList(); Type baseType = typeof(Sandbox.Definitions.MyDefinitionManager); AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += currentDomain_AssemblyResolve; currentDomain.ReflectionOnlyAssemblyResolve += currentDomain_ReflectionOnlyAssemblyResolve; currentDomain.TypeResolve += currentDomain_TypeResolve; try { MyFileSystem.Reset(); MyFileSystem.Init(@"C:\Program Files (x86)\Steam\SteamApps\common\SpaceEngineers\Content", Environment.ExpandEnvironmentVariables(@"%AppData%\SpaceEngineers")); MyFileSystem.InitUserSpecific((string)null); // ######################### // MySandboxGame (obsfcated) has to be created in memory to be able to load Voxel Material Definitions. // Without the Voxel Material Definitions, you cannot use the IMyStorage to load an asteroid. // So, this is a pointless waste of effort to try and use the in game code. // ######################### Sandbox.Definitions.MyDefinitionManager.Static.LoadData(new List <MyObjectBuilder_Checkpoint.ModItem>()); var materials = Sandbox.Definitions.MyDefinitionManager.Static.GetVoxelMaterialDefinitions(); //DictionaryValuesReader<string, MyVoxelMaterialDefinition>; //var dict = materials as Dictionary<string, MyVoxelMaterialDefinition>; //var matx = Sandbox.Definitions.MyDefinitionManager.Static.m_definitions.m_voxelMaterialsByName; var xz = Sandbox.Definitions.MyDefinitionManager.Static.GetDefaultVoxelMaterialDefinition(); //var tt = ass2.GetType("Sandbox.ModAPI.IMyVoxelMaps"); //var ass = System.Reflection.Assembly.ReflectionOnlyLoad("Sandbox.Game"); var ass = baseType.Assembly; // ass.GetType(); //var modules = ass.GetModules(false); //var types = modules[0].GetTypes(); var types = ass.GetTypes(); var myVoxelMapsType = types.Where(p => ivms.IsAssignableFrom(p)).First(); var myVoxelMaps = Activator.CreateInstance(myVoxelMapsType) as VRage.Game.ModAPI.IMyVoxelMaps; //5BCAC68007431E61367F5B2CF24E2D6F.5217D2CFAB7CCD6299A3F53DAEE1DEB1 //public static 6922E99EC72C10627AA239B8167BF7DC A109856086C45CF523B23AFCDDB82F43(byte[] 06D95B424FC4150954FF019440A547AE) var filename = @"C:\Program Files (x86)\Steam\SteamApps\common\SpaceEngineers\Content\VoxelMaps\Arabian_Border_7.vx2"; byte[] buffer = File.ReadAllBytes(filename); var storage = myVoxelMaps.CreateStorage(buffer); } catch (Exception) { throw; } }
public static void InvokeBeforeRun(uint appId, string appName, string userDataPath, bool addDateToLog = false) { m_appName = appName; var logName = new StringBuilder(m_appName); if (addDateToLog) { logName.Append("_"); logName.Append(new StringBuilder().GetFormatedDateTimeForFilename(DateTime.Now)); } logName.Append(".log"); var rootPath = new FileInfo(MyFileSystem.ExePath).Directory.FullName; var contentPath = Path.Combine(rootPath, "Content"); MyFileSystem.Init(contentPath, userDataPath); bool isSteamPath = SteamHelpers.IsSteamPath(rootPath); bool manifestPresent = SteamHelpers.IsAppManifestPresent(rootPath, appId); MySandboxGame.IsPirated = !isSteamPath && !manifestPresent; MySandboxGame.Log.Init(logName.ToString(), MyFinalBuildConstants.APP_VERSION_STRING); MySandboxGame.Log.WriteLine("Steam build: Always true"); MySandboxGame.Log.WriteLine(string.Format("Is official: {0} {1}{2}{3}", MyFinalBuildConstants.IS_OFFICIAL, (MyObfuscation.Enabled ? "[O]" : "[NO]"), (isSteamPath ? "[IS]" : "[NIS]"), (manifestPresent ? "[AMP]" : "[NAMP]"))); MySandboxGame.Log.WriteLine("Environment.ProcessorCount: " + Environment.ProcessorCount); MySandboxGame.Log.WriteLine("Environment.OSVersion: " + Environment.OSVersion); MySandboxGame.Log.WriteLine("Environment.CommandLine: " + Environment.CommandLine); MySandboxGame.Log.WriteLine("Environment.Is64BitProcess: " + Environment.Is64BitProcess); MySandboxGame.Log.WriteLine("Environment.Is64BitOperatingSystem: " + Environment.Is64BitOperatingSystem); MySandboxGame.Log.WriteLine("Environment.Version: " + Environment.Version); MySandboxGame.Log.WriteLine("Environment.CurrentDirectory: " + Environment.CurrentDirectory); MySandboxGame.Log.WriteLine("MainAssembly.ProcessorArchitecture: " + Assembly.GetExecutingAssembly().GetArchitecture()); MySandboxGame.Log.WriteLine("ExecutingAssembly.ProcessorArchitecture: " + MyFileSystem.MainAssembly.GetArchitecture()); MySandboxGame.Log.WriteLine("IntPtr.Size: " + IntPtr.Size.ToString()); MySandboxGame.Log.WriteLine("Default Culture: " + CultureInfo.CurrentCulture.Name); MySandboxGame.Log.WriteLine("Default UI Culture: " + CultureInfo.CurrentUICulture.Name); MySandboxGame.Log.WriteLine("IsAdmin: " + new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)); MyLog.Default = MySandboxGame.Log; MyTrace.InitWinTrace(); MyEnumDuplicitiesTester.CheckEnumNotDuplicitiesInRunningApplication(); // About 300 ms Debug.WriteLine(string.Format("{0}: Started", m_appName)); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); Thread.CurrentThread.Name = "Main thread"; //Because we want exceptions from users to be in english Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; MySandboxGame.Config = new MyConfig(appName + ".cfg"); MySandboxGame.Config.Load(); //MySandboxGame.ConfigDedicated = new MyConfigDedicated("MedievalEngineers-Dedicated.cfg"); }
public SpaceEngineersCore() { var contentPath = ToolboxUpdater.GetApplicationContentPath(); string userDataPath = SpaceEngineersConsts.BaseLocalPath.DataPath; MyFileSystem.Reset(); MyFileSystem.Init(contentPath, userDataPath); MyLog.Default = MySandboxGame.Log; MySandboxGame.Config = new MyConfig("SpaceEngineers.cfg"); // TODO: Is specific to SE, not configurable to ME. MySandboxGame.Config.Load(); MyFileSystem.InitUserSpecific(null); MyFakes.ENABLE_INFINARIO = false; SpaceEngineersGame.SetupPerGameSettings(); VRageRender.MyRenderProxy.Initialize(new MyNullRender()); // We create a whole instance of MySandboxGame! MySandboxGame gameTemp = new MySandboxGame(null); // creating MySandboxGame will reset the CurrentUICulture, so I have to reapply it. Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(GlobalSettings.Default.LanguageCode); SpaceEngineersApi.LoadLocalization(); MyStorageBase.UseStorageCache = false; try { // Replace the private constructor on MySession, so we can create it without getting involed with Havok and other depdancies. var keenStart = typeof(Sandbox.Game.World.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null); var ourStart = typeof(SEToolbox.Interop.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null); ReflectionUtil.ReplaceMethod(ourStart, keenStart); // Create an empty instance of MySession for use by low level code. ConstructorInfo constructorInfo = typeof(Sandbox.Game.World.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null); object mySession = constructorInfo.Invoke(new object[0]); // Assign the instance back to the static. Sandbox.Game.World.MySession.Static = (Sandbox.Game.World.MySession)mySession; Sandbox.Game.World.MySession.Static.Settings = new MyObjectBuilder_SessionSettings { EnableVoxelDestruction = true }; } catch (Exception ex) { Debugger.Break(); } try { Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static = new MyHeightMapLoadingSystem(); Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static.LoadData(); } catch (Exception ex) { Debugger.Break(); } _stockDefinitions = new SpaceEngineersResources(); _stockDefinitions.LoadDefinitions(); _manageDeleteVoxelList = new List <string>(); }
public static void MainBootstrap(string[] args) { var rootContentPath = args[0]; MyLog.Default = new MyLog(); MyFileSystem.Init(rootContentPath, "./"); MyLanguage.Init(); MyRenderProxy.Initialize(new MyNullRender()); MyLog.Default.Init("converter.log", new StringBuilder()); Workers.Init(new WorkerConfigurationFactory() .AddGroup(new WorkerConfigurationFactory.Group { Id = WorkerGroup.Background, Min = 1, Priority = ThreadPriority.BelowNormal, Ratio = .1f }) .AddGroup(new WorkerConfigurationFactory.Group { Id = WorkerGroup.Logic, Min = 1, Priority = ThreadPriority.Normal, Ratio = .7f }) .AddGroup(new WorkerConfigurationFactory.Group { Id = WorkerGroup.Render, Min = 1, Priority = ThreadPriority.AboveNormal, Ratio = .2f }) .SetDefault(WorkerGroup.Logic) .Bake(32)); MyMetadataSystem.LoadAssemblies(new[] { "VRage", "VRage.Game", "Sandbox.Graphics", "Sandbox.Game", "MedievalEngineers.ObjectBuilders", "MedievalEngineers.Game" }.Select(Assembly.Load)); var config = (BlockVariantGeneratorConfig) new XmlSerializer(typeof(BlockVariantGeneratorConfig)).Deserialize(File.OpenText(args[1])); Console.WriteLine("Loading definitions..."); MyDefinitionManagerSandbox.Static.LoadData(new ListReader <MyModContext>(new List <MyModContext>(config.ContentRoots.Select(contentPath => new MyModContext(Path.GetFileNameWithoutExtension(contentPath), Path.GetFileNameWithoutExtension(contentPath), contentPath))))); MyFileSystem.SetAdditionalContentPaths(config.ContentRoots); Console.WriteLine("Processing definitions..."); DefinitionObLoader.LoadObjectBuilders(MyDefinitionManagerSandbox.Static.DefinitionSet); Console.WriteLine("Translating definitions..."); var translatedSet = new DefinitionObSet(); var modelTranslator = new ModelAssetTranslator(config.OutputDirectory, config.VariantName); Func <string, string> assetTranslator = (asset) => { if (string.IsNullOrWhiteSpace(asset)) { return(asset); } if (config.AssetTranslations.TryGetValue(asset, out var assetTranslation)) { return(assetTranslation); } if (asset.EndsWith(".mwm", StringComparison.OrdinalIgnoreCase) && config.Changes != null) { if (asset.Contains("GeneratedStoneEdge")) { Debugger.Break(); } var modelMaterials = modelTranslator.GetMaterialsForModel(asset); using (PoolManager.Get(out List <MyObjectBuilder_EquiModifierChangeMaterialDefinition.MaterialModifier> changes)) { foreach (var x in config.Changes) { if (modelMaterials.Contains(x.Name)) { changes.Add(x); } } if (changes.Count > 0) { Console.WriteLine("Translating model " + asset); using (var builder = MaterialEditsBuilder.Allocate()) { foreach (var k in changes) { var list = new List <MaterialEdit>(); k.GetChanges(list); builder.Add(k.Name, list); } return(modelTranslator.CreateModel(asset, builder)); } } } } return(asset); }; var translator = new DefinitionObTranslator( DefinitionObLoader.Loaded, translatedSet, assetTranslator, (displayName) => $"{displayName} ({config.VariantName})", "_" + config.VariantName, config.Translations); foreach (var id in config.DefinitionsToTranslate) { if (id.SubtypeName == "**any**") { // Find and translate ALL with the given type ID, not forcing foreach (var k in DefinitionObLoader.Loaded.AllDefinitions) { if (k.Id.TypeId == id.TypeId) { translator.Translate(k); } } } else if (id.SubtypeName == "**any_translated_model**") { var ids = new HashSet <MyDefinitionId>(); foreach (var k in DefinitionObLoader.Loaded.AllDefinitions) { if (k.Id.TypeId == id.TypeId && k is MyObjectBuilder_PhysicalModelDefinition physModel) { var originalModel = physModel.Model; var translatedModel = assetTranslator(originalModel); if (!originalModel.Equals(translatedModel)) { ids.Add(k.Id); } } } // Include variants that contain the blocks foreach (var k in DefinitionObLoader.Loaded.AllDefinitions.OfType <MyObjectBuilder_BlockVariantsDefinition>()) { var good = false; foreach (var e in k.Blocks) { if (ids.Contains(e)) { good = true; break; } } if (good) { ids.Add(k.Id); } } foreach (var sid in ids) { foreach (var def in DefinitionObLoader.Loaded.GetDefinitions(sid)) { translator.Translate(def, true); } } } else { var list = DefinitionObLoader.Loaded.GetDefinitions(id); if (list.Count == 0) { Console.WriteLine("Couldn't find any definitions with ID " + id); } foreach (var def in list) { translator.Translate(def, true); } } } var definitionSet = new MyObjectBuilder_Definitions { Definitions = new MySerializableList <MyObjectBuilder_DefinitionBase>(translatedSet.AllDefinitions.OrderBy(x => x.TypeId.ToString()) .ThenBy(x => x.SubtypeName)) }; XDocument doc; using (var baseWriter = new StringWriter()) { var serializer = new XmlSerializer(typeof(MyObjectBuilder_Definitions)); using (var writer = new XmlTextWriter(baseWriter)) serializer.Serialize(writer, definitionSet); doc = XDocument.Load(new StringReader(baseWriter.ToString())); } NullCleaner.Clean(doc); var translatedSbcPath = Path.Combine(config.OutputDirectory, "Data/Translated.sbc"); Directory.CreateDirectory(Path.GetDirectoryName(translatedSbcPath)); using (var writer = new XmlTextWriter(translatedSbcPath, Encoding.UTF8) { Formatting = Formatting.Indented, Indentation = 2 }) doc.WriteTo(writer); MyLog.Default.Dispose(); }
public bool LoadGame(string seBinPath, string userDataPath, string savePath) { if (!Directory.Exists(seBinPath)) { return(false); } if (!Directory.Exists(savePath)) { return(false); } if (!savePath.StartsWith(userDataPath, StringComparison.OrdinalIgnoreCase)) { return(false); } string contentPath = Path.GetFullPath(Path.Combine(seBinPath, @"..\Content")); MyFileSystem.Reset(); MyFileSystem.Init(contentPath, userDataPath); MyLog.Default = MySandboxGame.Log; MySandboxGame.Config = new MyConfig("SpaceEngineers.cfg"); // TODO: Is specific to SE, not configurable to ME. MySandboxGame.Config.Load(); MyFileSystem.InitUserSpecific(null); SpaceEngineersGame.SetupPerGameSettings(); VRageRender.MyRenderProxy.Initialize(new MyNullRender()); // We create a whole instance of MySandboxGame! // If this is causing an exception, then there is a missing dependency. MySandboxGame gameTemp = new MySandboxGame(null); #region Game Localization // creating MySandboxGame will reset the CurrentUICulture, so I have to reapply it. Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(GlobalSettings.Default.LanguageCode); var culture = System.Threading.Thread.CurrentThread.CurrentUICulture; var languageTag = culture.IetfLanguageTag; var localizationPath = Path.Combine(contentPath, @"Data\Localization"); var codes = languageTag.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); var maincode = codes.Length > 0 ? codes[0] : null; var subcode = codes.Length > 1 ? codes[1] : null; MyTexts.Clear(); MyTexts.LoadTexts(localizationPath, maincode, subcode); #endregion MyStorageBase.UseStorageCache = false; #region MySession creation // Replace the private constructor on MySession, so we can create it without getting involed with Havok and other depdancies. var keenStart = typeof(Sandbox.Game.World.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null); var ourStart = typeof(EconomyConfigurationEditor.Interop.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null); ReflectionUtil.ReplaceMethod(ourStart, keenStart); // Create an empty instance of MySession for use by low level code. Sandbox.Game.World.MySession mySession = ReflectionUtil.ConstructPrivateClass <Sandbox.Game.World.MySession>(new Type[0], new object[0]); ReflectionUtil.ConstructField(mySession, "m_sessionComponents"); // Required as the above code doesn't populate it during ctor of MySession. mySession.Settings = new MyObjectBuilder_SessionSettings { EnableVoxelDestruction = true }; // Assign the instance back to the static. Sandbox.Game.World.MySession.Static = mySession; Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static = new MyHeightMapLoadingSystem(); Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static.LoadData(); #endregion #region Load Sandbox var filename = Path.Combine(savePath, SpaceEngineersConsts.SandBoxCheckpointFilename); MyObjectBuilder_Checkpoint checkpoint; string errorInformation; bool compressedCheckpointFormat; bool snapshot = false; bool retVal = SpaceEngineersApi.TryReadSpaceEngineersFile <MyObjectBuilder_Checkpoint>(filename, out checkpoint, out compressedCheckpointFormat, out errorInformation, snapshot); if (!retVal) { return(false); } #endregion MyDefinitionManager.Static.PrepareBaseDefinitions(); MyDefinitionManager.Static.LoadData(checkpoint.Mods); var MaterialIndex = new Dictionary <string, byte>(); return(true); }