Ejemplo n.º 1
0
        public static void PopulateWithNewMod(ModContentPack rwmodInfo)
        {
            var    path       = new ComparablePath(rwmodInfo.PythonFolder()); //will throw ex if rwmodInfo is null, which is fine
            string scriptPath = Path.Combine(path.reconstructedPath, "main.py");

            if (!Directory.Exists(path.ToString()) || !File.Exists(scriptPath))
            {
                return;
            }

            ScriptSource mainScriptSource = Py.Engine.CreateScriptSourceFromFile(scriptPath);
            string       packageName      = PythonMod.MakeHiddenPackageName(rwmodInfo.Identifier);

            PythonModManager inst = Instance; //getting this after several potential points of failure, to avoid pointless instantiation

            if (!inst.ordered.TrueForAll(m => m.rwmodInfo != rwmodInfo))
            {
                throw new ArgumentException(
                          "The mod with that ModContentPack has already been added");
            }

            //create and import package
            var pkg      = IronPython.Modules.PythonImport.new_module(DefaultContext.Default, packageName);
            var pkg_dict = (PythonDictionary)typeof(IronPython.Runtime.PythonModule).InvokeMember("_dict",
                                                                                                  BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance,
                                                                                                  null, pkg, null);
            {
                var __path__ = new IronPython.Runtime.List();
                __path__.Add(path.reconstructedPath);
                pkg_dict["__path__"]       = __path__;
                pkg_dict["__file__"]       = scriptPath;
                SystemModules[packageName] = pkg;
            }

            //setup scope
            ScriptScope scope = Py.CreateScope();

            scope.SetVariable("__contentpack__", rwmodInfo);
            scope.GetModuleContext().AddExtensionType(typeof(StandardScriptingExtensions));

            // MAKE MOD OBJECT
            var mod = new PythonMod(rwmodInfo, packageName, scope, mainScriptSource);

            inst.ordered.Add(mod);

            //run main.py
            try
            {
                mainScriptSource.Execute(scope);
            }
            catch (Exception e)
            {
                string msg = "Exception while loading " + scriptPath + ": " + e.ToString() + "\n" + Py.GetFullErrorMessage(e);
                Verse.Log.Error(msg);
                pkg_dict["__error__"] = e;
            }
        }