Exemple #1
0
 protected void SetProgress(ProgressHandler progress, string newTask)
 {
     if (progress == null)
         return;
     progress.Task = newTask;
 }
Exemple #2
0
        public void Create(ProgressHandler progress)
        {
            string modFilePath = GetFolderPath() + System.IO.Path.DirectorySeparatorChar + "Mod" + System.IO.Path.DirectorySeparatorChar + this.ID + ".dll";
            if (!System.IO.File.Exists(modFilePath))
            {
                Debug.Log("Mod: "+ID, "Couldn't find the compiled mod dll at \""+modFilePath+"\".", Debug.Type.ERROR);
                SetProgress(progress, "Error.FileNotFound");
                return;
            }

            string modInfoPath = GetFolderPath() + System.IO.Path.DirectorySeparatorChar + "ModInfo.xml";
            if (!System.IO.File.Exists(modInfoPath))
            {
                Debug.Log("Mod: "+ID, "Couldn't find the mod configuration at \""+modInfoPath+"\".", Debug.Type.ERROR);
                SetProgress(progress, "Error.FileNotFound");
                return;
            }

            string libraryFolder = Game.ModLibrary.GetLibraryFolder();
            string baseModLibPath = libraryFolder + System.IO.Path.DirectorySeparatorChar + "BaseModLib.dll";

            if (!System.IO.File.Exists(baseModLibPath))
            {
                Debug.Log("Mod: "+ID, "Couldn't find BaseModLib.dll at \""+baseModLibPath+"\".", Debug.Type.ERROR);
                SetProgress(progress, "Error.FileNotFound");
                return;
            }

            ModuleDefinition modModule;
            ModuleDefinition baseModLib;
            try
            {
                SetProgress(progress, 0f, "Preparing");
                baseModLib = ModuleDefinition.ReadModule(baseModLibPath);
                SetProgress(progress, 5f);
                modModule = ModuleDefinition.ReadModule(modFilePath);
                SetProgress(progress, 10f);
            }
            catch (Exception e)
            {
                Debug.Log("Mod: "+ID, "One of the assemblies is corrupted: "+e.ToString(), Debug.Type.ERROR);
                SetProgress(progress, "Error.CorruptAssembly");
                return;
            }

            Mod mod = new Mod(this.Game, "");
            mod.header = new Mod.Header(mod, System.IO.File.ReadAllText(modInfoPath));
            mod.module = modModule;
            MemoryStream stream = new MemoryStream();
            mod.module.Write(stream);
            stream.Position = 0;
            mod.originalModule = ModuleDefinition.ReadModule(stream);

            SetProgress(progress, 15f);

            try
            {
                Dictionary<MethodReference, MethodReference> baseModLibRemap = new Dictionary<MethodReference, MethodReference>();
                foreach (TypeDefinition baseModLibType in baseModLib.Types)
                {
                    foreach (MethodDefinition method in baseModLibType.Methods)
                    {
                        if (method.HasCustomAttributes && method.CustomAttributes[0].AttributeType.Name == "AddModname")
                        {
                            foreach (MethodDefinition method2 in baseModLibType.Methods)
                            {
                                if (!method2.HasCustomAttributes && method2.Name == method.Name && method2.Parameters.Count > method.Parameters.Count)
                                {
                                    bool add = true;
                                    for (int i = 0; i < method.Parameters.Count; i++)
                                    {
                                        ParameterDefinition param = method.Parameters[i];
                                        if (param.ParameterType.FullName != method2.Parameters[i].ParameterType.FullName)
                                            add = false;
                                    }
                                    if (add)
                                    {
                                        baseModLibRemap.Add(method, method2);
                                    }
                                }
                            }
                        }
                    }
                }
                SetProgress(progress, 20f, "FetchingTypes");

                Dictionary<string, string> injectableClasses = new Dictionary<string, string>();
                Dictionary<string, Dictionary<string, TypeDefinition>> assemblyTypes = new Dictionary<string, Dictionary<string, TypeDefinition>>();

                for (int i = 0; i < Game.GameConfiguration.IncludeAssemblies.Count; i++)
                {
                    string assembly = libraryFolder + System.IO.Path.DirectorySeparatorChar + Game.ParsePath(Game.GameConfiguration.IncludeAssemblies[i]);
                    ModuleDefinition module = ModuleDefinition.ReadModule(assembly);
                    string key = System.IO.Path.GetFileNameWithoutExtension(assembly);
                    assemblyTypes.Add(key, new Dictionary<string, TypeDefinition>());
                    foreach (TypeDefinition type in module.Types)
                    {
                        if (!ModLib.CheckName(type.Namespace, Game.GameConfiguration.ExcludeNamespaces) && !ModLib.CheckName(type.FullName, Game.GameConfiguration.ExcludeTypes) && !ModLib.CheckName(type.FullName, Game.GameConfiguration.NoFamily))
                        {
                            assemblyTypes[key].Add(type.FullName, type);
                            if (!injectableClasses.ContainsKey(type.FullName))
                            {
                                injectableClasses.Add(type.FullName, key);
                            }
                        }
                    }
                    SetProgress(progress, 20f + ((float)i / (float)Game.GameConfiguration.IncludeAssemblies.Count) * 30f);
                }

                SetProgress(progress, 50f, "ConvertingClasses");
                Dictionary<string, TypeDefinition> newClasses = new Dictionary<string, TypeDefinition>();
                for (int i = 0; i < modModule.Types.Count; i++)
                {
                    TypeDefinition type = modModule.Types[i];
                    if (type.FullName == "<Module>")
                        continue;

                    foreach (MethodDefinition method in type.Methods)
                    {
                        if (method != null && method.Body != null)
                        {
                            for (int j = 0; j < method.Body.Instructions.Count; j++)
                            {
                                ILProcessor methodIL = method.Body.GetILProcessor();

                                Instruction instruction = method.Body.Instructions[j];
                                if (instruction.OpCode == OpCodes.Call && instruction.Operand != null)
                                {
                                    foreach (KeyValuePair<MethodReference, MethodReference> map in baseModLibRemap)
                                    {
                                        if (((MethodReference)instruction.Operand).FullName == map.Key.FullName)
                                        {
                                            instruction.Operand = type.Module.Import(map.Value);
                                            Instruction newInstruction = methodIL.Create(OpCodes.Ldstr, ID);
                                            methodIL.InsertBefore(instruction, newInstruction);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    string assemblyName = "";
                    if (type.BaseType != null && injectableClasses.ContainsKey(type.BaseType.FullName))
                        assemblyName = injectableClasses[type.BaseType.FullName];
                    if (assemblyName == "" || !assemblyTypes[assemblyName].ContainsKey(type.BaseType.FullName))
                    {
                        Mod.Header.AddClass addClass = new Mod.Header.AddClass(mod);
                        addClass.Type = type;
                        mod.header.AddAddClass(addClass);
                    }
                    else
                    {
                        foreach (Mono.Cecil.FieldDefinition field in type.Fields)
                        {
                            Mod.Header.AddField addField = new Mod.Header.AddField(mod);
                            addField.Field = field;
                            addField.AssemblyName = assemblyName;
                            mod.header.AddAddField(addField);
                        }
                        foreach (MethodDefinition method in type.Methods)
                        {
                            if (method == null) continue;
                            int priority = int.MaxValue;

                            if (method.CustomAttributes != null)
                            {
                                foreach (CustomAttribute attribute in method.CustomAttributes)
                                {
                                    if (attribute.AttributeType.Name == "Priority")
                                    {
                                        priority = (int)attribute.ConstructorArguments[0].Value;
                                    }
                                }
                            }

                            bool inject = false;

                            if (method.IsVirtual || method.IsStatic || method.IsConstructor)
                            {
                                foreach (MethodDefinition _m in assemblyTypes[assemblyName][type.BaseType.FullName].Methods)
                                {
                                    if (_m.Name == method.Name)
                                    {
                                        if ((_m.IsStatic && method.IsStatic) || (_m.IsConstructor && method.IsConstructor))
                                        {
                                            if (method.Parameters.Count == _m.Parameters.Count)
                                            {
                                                bool ok = true;
                                                for (int pi = 0; pi < _m.Parameters.Count; pi++)
                                                {
                                                    ParameterDefinition param = _m.Parameters[pi];
                                                    if (param.ParameterType.FullName != method.Parameters[pi].ParameterType.FullName)
                                                    {
                                                        ok = false;
                                                        break;
                                                    }
                                                }
                                                if (ok)
                                                {
                                                    inject = true;
                                                }
                                            }
                                        }
                                        else if (!_m.IsStatic && !method.IsStatic)
                                            inject = true;
                                        break;
                                    }
                                }
                            }

                            if (inject)
                            {
                                Mod.Header.InjectInto injectInto = new Mod.Header.InjectInto(mod);
                                injectInto.Method = method;
                                injectInto.Priority = priority;
                                injectInto.AssemblyName = assemblyName;
                                mod.header.AddInjectInto(injectInto);
                            }
                            else
                            {
                                Mod.Header.AddMethod addMethod = new Mod.Header.AddMethod(mod);
                                addMethod.Method = method;
                                addMethod.AssemblyName = assemblyName;
                                mod.header.AddAddMethod(addMethod);
                            }
                        }
                    }
                    SetProgress(progress, 50f + ((float)i / (float)modModule.Types.Count) * 30f);
                }

                foreach (AssemblyNameReference aref in modModule.AssemblyReferences)
                {
                    if (aref.Name == "mscorlib" || aref.Name == "System")
                    {
                        aref.Version = new System.Version("2.0.0.0");
                        aref.PublicKeyToken = new byte[] { 0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89 };
                    }
                    if (aref.Name == "System.Core")
                    {
                        aref.Version = new System.Version("3.5.0.0");
                        aref.PublicKeyToken = new byte[] { 0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89 };
                    }
                    if (aref.Name == "System.Xml")
                    {
                        aref.Version = new System.Version("2.0.0.0");
                        aref.PublicKeyToken = new byte[] { 0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89 };
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Log("Mod: "+ID, "An unexpected error occured while parsing the assembly: "+e.ToString(), Debug.Type.ERROR);
                SetProgress(progress, "Error.UnexpectedError");
                return;
            }

            string modResourcesPath = GetFolderPath() + System.IO.Path.DirectorySeparatorChar + "Resources/";
            if (!System.IO.Directory.Exists(modResourcesPath))
            {
                System.IO.Directory.CreateDirectory(modResourcesPath);
            }
            if (System.IO.Directory.GetFiles(modResourcesPath).Length > 0 || System.IO.Directory.GetDirectories(modResourcesPath).Length > 0)
            {
                ZipFile newZipFile = new ZipFile();
                newZipFile.AddDirectory(modResourcesPath);
                newZipFile.Comment = "Automaticlly created resources zip file.";
                mod.Resources = newZipFile;
            }

            try
            {
                SetProgress(progress, 90f, "SavingMod");

                string modFolder = System.IO.Path.GetFullPath(Configuration.GetPath("mods") + System.IO.Path.DirectorySeparatorChar + Game.GameConfiguration.ID);

                if (!System.IO.Directory.Exists(modFolder))
                    System.IO.Directory.CreateDirectory(modFolder);

                mod.FileName = System.IO.Path.GetFullPath(modFolder + System.IO.Path.DirectorySeparatorChar + mod.UniqueID + ".mod");
                if (mod.Save())
                {
                    string key = mod.ID + "-" + mod.header.GetVersion();
                    if (Mod.Mods.ContainsKey(key))
                    {
                        if (Mod.Mods[key].FileName != mod.FileName)
                            Mod.Mods[key].Remove();
                        //Mod.Mods[key] = mod;
                    }
                    /*else
                    {
                        Mod.Mods.Add(key, mod);
                    }*/
                    SetProgress(progress, 100f, "Finish");
                }
                else
                {
                    Debug.Log("Mod: "+ID, "Could not save the mod.", Debug.Type.ERROR);
                    SetProgress(progress, "Error.Save");
                }
            }
            catch (Exception e)
            {
                Debug.Log("Mod: "+ID, "An error occured while saving the mod: "+e.ToString(), Debug.Type.ERROR);
                SetProgress(progress, "Error.Save");
            }
        }
Exemple #3
0
        private void StartGame(object sender, RoutedEventArgs e)
        {
            List<Data.Mod> mods = new List<Data.Mod>();
            foreach (ListViewItem i in Mods.Mods)
            {
                ModViewModel vm = (ModViewModel)i.DataContext;
                if (vm != null && vm.Selected)
                {
                    ModVersionViewModel vm2 = (ModVersionViewModel)vm.SelectedVersion.DataContext;
                    if (vm2 != null)
                    {
                        mods.Add(vm2.mod);
                    }
                }
            }
            ProgressHandler progressHandler = new ProgressHandler();
            progressHandler.OnComplete += (object o, EventArgs ex) => {
                if (Configuration.GetString("UseSteam") == "true" && App.Game.GameConfiguration.SteamAppID != "")
                {

                    Process p = new Process();
                    p.StartInfo.FileName = Configuration.GetPath("Steam") + System.IO.Path.DirectorySeparatorChar + "Steam.exe";
                    p.StartInfo.Arguments = "-applaunch "+App.Game.GameConfiguration.SteamAppID;
                    p.Start();
                }
                else
                {
                    Process p = new Process();
                    p.StartInfo.FileName = App.Game.GamePath + System.IO.Path.DirectorySeparatorChar + App.Game.GameConfiguration.SelectFile;
                    p.Start();
                }
            };

            Thread thread = new Thread(delegate()
            {
                App.Game.ApplyMods(mods, progressHandler);

            });
            ModAPI.Windows.SubWindows.OperationPending window = new ModAPI.Windows.SubWindows.OperationPending("Lang.Windows.OperationPending", "ApplyMods", progressHandler, null, true);
            if (!window.Completed)
            {
                window.ShowSubWindow();
                window.Show();
            }
            thread.Start();
        }
Exemple #4
0
 protected void SetProgress(ProgressHandler progress, float percentage, string newTask = "")
 {
     if (progress == null)
         return;
     if (newTask != "")
         progress.Task = newTask;
     progress.Progress = percentage;
 }
Exemple #5
0
 private void CreateMod(object sender, RoutedEventArgs e)
 {
     if (CurrentModProjectViewModel != null)
     {
         ProgressHandler progressHandler = new ProgressHandler();
         Thread thread = new Thread(delegate() {
             CurrentModProjectViewModel.Project.Create(progressHandler);
         });
         ModAPI.Windows.SubWindows.OperationPending window = new ModAPI.Windows.SubWindows.OperationPending("Lang.Windows.OperationPending", "CreateMod", progressHandler);
         if (!window.Completed)
         {
             window.ShowSubWindow();
             window.Show();
         }
         thread.Start();
     }
 }
Exemple #6
0
 public void Preload(ProgressHandler handler)
 {
     handler.OnComplete += delegate
     {
         Debug.Log("MainWindow", "GUI is ready.");
     };
     Debug.Log("MainWindow", "Preparing GUI.");
     Opacity = 0.0f;
     Tabs.Preload(handler);
 }
Exemple #7
0
 public Task(ProgressChain chain, float weight, ProgressChain.TaskMethod method)
 {
     this.Weight = weight;
     this.chain = chain;
     Progress = new ProgressHandler();
     Progress.OnChange += (s, e) =>
     {
         chain.ProgressChanged();
     };
     Progress.OnComplete += (s, e) =>
     {
         chain.Next();
     };
     Method = method;
 }
 public void GUITick(object sender, EventArgs e)
 {
     if (!loadingWindow && Progress >= 70f)
     {
         Debug.Log("SplashScreen", "Preparing and opening main window.");
         GUIProgress = new ProgressHandler();
         GUIProgress.OnChange += delegate
         {
             Progress = 70f + (GUIProgress.Progress / 100f * 30f);
         };
         GUIProgress.OnComplete += delegate
         {
             windowLoaded = true;
         };
         loadingWindow = true;
         MainWindowThread = new Thread(new ThreadStart(ShowWindow));
         MainWindowThread.SetApartmentState(ApartmentState.STA);
         //MainWindowThread.IsBackground = true;
         MainWindowThread.Start();
     }
     if (ShownProgress == 100f && Alpha > 0f)
     {
         if (windowLoaded)
         {
             MainWindow.BlendIn = true;
             Alpha -= 5f * GUIDeltaTime;
             if (Alpha <= 0f)
             {
                 Alpha = 0f;
                 Hide();
                 //Close();
             }
         }
     }
     Opacity = Alpha;
     if (ShownProgress < Progress)
     {
         ShownProgress += 200f * GUIDeltaTime;
         if (ShownProgress > Progress)
             ShownProgress = Progress;
     }
     ClipRect.Rect = new Rect(0, 0, (ShownProgress / 100f) * 620f, 180f);
 }
Exemple #9
0
        public static ResultCode Load(ProgressHandler progressHandler)
        {
            string fileName = Path.GetFullPath(Configuration.GetPath("GameConfigurations") + Path.DirectorySeparatorChar + Configuration.CurrentGame + Path.DirectorySeparatorChar + "DynamicClasses.xml");
            if (System.IO.File.Exists(fileName))
            {
                try
                {
                    XDocument DynamicClasses = XDocument.Load(fileName);
                    AssemblyName assemblyName = new AssemblyName("DynamicClasses");
                    assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
                    moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicClassesModule");
                    progressHandler.Progress = 10f;
                    IEnumerable<XElement> classes = DynamicClasses.Root.Elements("Class");
                    float count = classes.Count();
                    float done = 0f;
                    foreach (XElement el in classes)
                    {
                        ParseClass(el);
                        done += 1f;
                        progressHandler.Progress = 10f + (done / count) * 89f;
                    }

                    foreach (TypeBuilder builder in BuildingTypes.Values)
                    {
                        Type t = builder.CreateType();
                        Types.Add(t.FullName, t);
                        Debug.Log("DynamicTypes", "Successfully created dynamic type \"" + t.FullName + "\".");
                    }
                    progressHandler.Progress = 100f;
                }
                catch (System.Xml.XmlException e)
                {
                    Error = ErrorCode.MALFORMED_CONFIGURATION;
                    ErrorString = "The dynamic types configuration file is malformed. Exception: "+e.ToString();
                    Debug.Log("DynamicTypes", ErrorString, Debug.Type.ERROR);
                    return ResultCode.ERROR;
                }
                catch (Exception e)
                {
                    Error = ErrorCode.UNEXPECTED;
                    ErrorString = "Unexpected exception while parsing dynamic types: " + e.ToString();
                    Debug.Log("DynamicTypes", ErrorString, Debug.Type.ERROR);
                    return ResultCode.ERROR;
                }
                return ResultCode.OK;
            }
            else
            {
                Error = ErrorCode.FILE_NOT_FOUND;
                ErrorString = "The dynamic types configuration file \"" + fileName + "\" couldn't be found.";
                Debug.Log("DynamicTypes", ErrorString, Debug.Type.ERROR);
                return ResultCode.ERROR;
            }
        }