private void btProceed_Click(object sender, EventArgs e)
        {
            try {
                name = tBoxName.Text;
                double benchPressValue = double.Parse(tBoxInitBenchPress.Text);
                double squatValue      = double.Parse(tBoxInitSquat.Text);
                double deadliftValue   = double.Parse(tBoxInitDeadlift.Text);
                double ohpValue        = double.Parse(tBoxInitOHP.Text);

                benchPressInit = CalcLib.OrmCalc(benchPressValue, Convert.ToInt32(numInitBenchPress.Value));
                ohpInit        = CalcLib.OrmCalc(ohpValue, Convert.ToInt32(numInitBenchPress.Value));
                squatInit      = CalcLib.OrmCalc(squatValue, Convert.ToInt32(numInitBenchPress.Value));
                deadliftInit   = CalcLib.OrmCalc(deadliftValue, Convert.ToInt32(numInitBenchPress.Value));
                try {
                    FileLib.SaveIntoFile(name, benchPressInit, squatInit, deadliftInit, ohpInit);
                }
                catch { }

                this.Hide();
                MainForm mainForm = new MainForm(name);
                mainForm.Closed += (s, args) => this.Close();
                mainForm.ShowDialog();
            }
            catch (FormatException) {
                MessageBox.Show("Enter valid data", "Error");
            }
        }
    protected void btnImport_Click(object sender, EventArgs e)
    {
        String cAppDir  = Server.MapPath("~/");
        String cFileDir = cAppDir + "Upload\\";

        if (!Directory.Exists(cFileDir))
        {
            Directory.CreateDirectory(cFileDir);
        }
        cFileDir = cAppDir + "Upload\\temp\\";
        if (!Directory.Exists(cFileDir))
        {
            Directory.CreateDirectory(cFileDir);
        }
        String cFileName = cFileDir + "import.dat";

        if (File.Exists(cFileName))
        {
            File.Delete(cFileName);
        }
        String cFileText = null;
        int    iCode     = 0;

        try
        {
            this.Upload.PostedFile.SaveAs(cFileName);
            cFileText = FileLib.ReadTextFile(cFileName);
            List <ExportObject> rows = PackUtil.Explain(cFileText);
            iCode = PackUtil.UpdateDB(rows, cAppDir);
        }
        catch (Exception ex)
        {
        }
    }
Example #3
0
        public void TestScript()
        {
            GlobalTest.Init();

            using (var biopProEar = MEPackageHandler.OpenMEPackage(Path.Combine(GlobalTest.GetTestPackagesDirectory(), "PC", "ME3", "BioP_ProEar.pcc")))
            {
                var  biopProEarLib      = new FileLib(biopProEar);
                bool fileLibInitialized = biopProEarLib.Initialize().Result;
                Assert.IsTrue(fileLibInitialized, "ME3 Script failed to compile BioP_ProEar class definitions!");

                foreach (ExportEntry funcExport in biopProEar.Exports.Where(exp => exp.ClassName == "Function"))
                {
                    (ASTNode astNode, string text) = UnrealScriptCompiler.DecompileExport(funcExport, biopProEarLib);

                    Assert.IsInstanceOfType(astNode, typeof(Function), $"#{funcExport.UIndex} {funcExport.InstancedFullPath} in BioP_ProEar did not decompile!");

                    (_, MessageLog log) = UnrealScriptCompiler.CompileFunction(funcExport, text, biopProEarLib);

                    if (log.AllErrors.Any())
                    {
                        Assert.Fail($"#{funcExport.UIndex} {funcExport.InstancedFullPath} in BioP_ProEar did not recompile!");
                    }
                }
            }
        }
Example #4
0
        private void btDeleteUser_Click(object sender, EventArgs e)
        {
            //string name = listBoxUsers.SelectedItem.Va;
            string name = listBoxUsers.GetItemText(listBoxUsers.SelectedItem.ToString());

            FileLib.DeleteFile(name + ".xml");
            StartupForm_Load(sender, e);
        }
Example #5
0
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog vDialog = new OpenFileDialog();

            if (vDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                List <String> UrlList = FileLib.getFileLines(vDialog.FileName);
            }
        }
Example #6
0
 public ME3ByteCodeDecompiler(UStruct dataContainer, UClass containingClass, List <FunctionParameter> parameters = null, VariableType returnType = null, FileLib lib = null)
     : base(new byte[dataContainer.ScriptBytecodeSize])
 {
     Buffer.BlockCopy(dataContainer.ScriptBytes, 0, _data, 0, dataContainer.ScriptStorageSize);
     DataContainer   = dataContainer;
     ContainingClass = containingClass;
     Parameters      = parameters;
     ReturnType      = returnType;
     FileLib         = lib;
 }
Example #7
0
 private void StartupForm_Load(object sender, EventArgs e)
 {
     if (FileLib.ListBoxUsersUpdate().Count == 0)
     {
         btCreateUser_Click(sender, e);
     }
     else
     {
         listBoxUsers.DataSource = FileLib.ListBoxUsersUpdate();
     }
 }
Example #8
0
        public static GameModel StartNewGame()
        {
            var gameModel = new GameModel()
            {
                Id         = Guid.NewGuid(),
                StatusGame = StatusGameEnum.Iniciada
            };

            FileLib.CreateJsonFile(gameModel);

            return(gameModel);
        }
        public static LuaTable CreateGlobalEnviroment()
        {
            LuaTable global = new LuaTable();

            BaseLib.RegisterFunctions(global);
            StringLib.RegisterModule(global);
            TableLib.RegisterModule(global);
            IOLib.RegisterModule(global);
            FileLib.RegisterModule(global);
            MathLib.RegisterModule(global);
            OSLib.RegisterModule(global);

            global.SetNameValue("_G", global);

            return(global);
        }
Example #10
0
        public void save()
        {
            ActiveResult vret     = ActiveResult.Valid(AppConfig.SUCCESS);
            String       cKeyID   = StringEx.getString(request["ID"]);
            String       cORG_ID  = StringEx.getString(request["org_id"]);
            String       cAREA_ID = StringEx.getString(request["AREA_ID"]);

            cAREA_ID = cAREA_ID.Replace("00", "");

            S_ORG_INF vo = new S_ORG_INF();

            vo = (S_ORG_INF)RequestUtil.readFromRequest(request, vo);

            if (String.IsNullOrEmpty(cORG_ID))
            {
                vret = ActiveResult.Valid("单位编码不能为空!");
            }
            else if (!cORG_ID.StartsWith(cAREA_ID))
            {
                vret = ActiveResult.Valid("单位编码格式错误!");
            }
            else if (String.IsNullOrEmpty(vo.org_name))
            {
                vret = ActiveResult.Valid("单位简称不能为空!");
            }
            else if (String.IsNullOrEmpty(vo.org_full_name))
            {
                vret = ActiveResult.Valid("单位全称不能为空!");
            }

            String cPloygn = vo.ploygn;

            if (!String.IsNullOrEmpty(cPloygn))
            {
                String cWebRoot  = request.MapPath("/");
                String cFileName = cWebRoot + @"static\area_range\" + cORG_ID + ".js";
                FileLib.WriteTextFile(cFileName, cPloygn);
            }
            vo.org_type = cORG_ID.Length;
            if (vret.result == AppConfig.SUCCESS)
            {
                int iCode = dao.save(vo, cKeyID);
                vret = ActiveResult.Valid(iCode);
            }
            response.Write(vret.toJSONString());
        }
        public IComandoResposta Exec(ComandoExecutarMovimento comando, Guid id)
        {
            var result = new MovementMessageModel();

            try
            {
                //Recupera o jogo
                var gameModel = FileLib.GetJsonFile(id);


                //Executa as validações do movimento
                ValidaMovimento(comando, gameModel, result);
                if (result.Invalid)
                {
                    return(new ComandoGenericoResposta(false, "Erro ao executar movimento.", result));
                }


                //Executa o movimento
                GameEngine.ExecutarMovimento(gameModel, comando.Position.X.ToInt32(0), comando.Position.Y.ToInt32(0), comando.Player);


                //Verifica o Termino da partida
                GameEngine.VerificarStatusPartida(gameModel);

                //Atualiza o jsonFile
                FileLib.CreateJsonFile(gameModel);


                result.PlayerTurn = gameModel.PlayerTurn;
                result.Winner     = gameModel.Winner;
                result.Status     = gameModel.StatusGame.GetDescription();


                return(new ComandoGenericoResposta(true, "Movimento executado com sucesso.", result));
            }
            catch (Exception ex)
            {
                result.AddNotification("", ex.Message);
                return(new ComandoGenericoResposta(false, $@"Erro ao executar movimento.", result));
            }
        }
Example #12
0
        // 登入
        public static List <Solar_termsModel> GetSolar_terms()
        {
            var DataFile = FileLib.rootPath + "solar_terms.json";

            if (FileLib.IsFileExist(DataFile))
            {
                List <Solar_termsModel> Solar_terms = new List <Solar_termsModel>();

                string FileData = FileLib.ReadFile(DataFile);

                Solar_terms = JsonConvert.DeserializeObject <List <Solar_termsModel> >(FileData);
                Random rnd = new Random();
                foreach (var item in Solar_terms)
                {
                    item.randomWeek = rnd.Next(1, 4);
                }

                return(Solar_terms);
            }
            return(null);
        }
Example #13
0
        public bool ApplyUpdate(IMEPackage package, ExportEntry targetExport, MergeAssetCache1 assetsCache, Mod installingMod, GameTarget gameTarget)
        {
            FileLib fl;

            if (!assetsCache.FileLibs.TryGetValue(package.FilePath, out fl))
            {
                fl = new FileLib(package);
                bool initialized = fl.Initialize(new RelativePackageCache()
                {
                    RootPath = M3Directories.GetBioGamePath(gameTarget)
                }, gameTarget.TargetPath);
                if (!initialized)
                {
                    Log.Error($@"FileLib loading failed for package {targetExport.InstancedFullPath} ({targetExport.FileRef.FilePath}):");
                    foreach (var v in fl.InitializationLog.AllErrors)
                    {
                        Log.Error(v.Message);
                    }

                    throw new Exception(M3L.GetString(M3L.string_interp_fileLibInitMergeMod1Script, targetExport.InstancedFullPath, string.Join(Environment.NewLine, fl.InitializationLog.AllErrors)));
                }

                assetsCache.FileLibs[package.FilePath] = fl;
            }


            (_, MessageLog log) = UnrealScriptCompiler.CompileFunction(targetExport, ScriptText, fl);
            if (log.AllErrors.Any())
            {
                Log.Error($@"Error compiling function {targetExport.InstancedFullPath}:");
                foreach (var l in log.AllErrors)
                {
                    Log.Error(l.Message);
                }

                throw new Exception(M3L.GetString(M3L.string_interp_mergefile_errorCompilingFunction, targetExport, string.Join(Environment.NewLine, log.AllErrors)));
            }

            return(true);
        }
Example #14
0
        // 登入
        public static UserModel Login(string No, string Password)
        {
            var UserDataFile = FileLib.rootPath + "employee.json";

            if (FileLib.IsFileExist(UserDataFile))
            {
                List <UserProfileModel> users = new List <UserProfileModel>();
                string FileData = FileLib.ReadFile(UserDataFile);
                users = JsonConvert.DeserializeObject <List <UserProfileModel> >(FileData);
                var user = users.Where(p => p.No == No && p.Password == Password).FirstOrDefault();
                if (user != null)
                {
                    UserModel usermodel = new UserModel()
                    {
                        Name     = user.Name,
                        password = user.Password,
                        userNo   = user.No
                    };
                    return(usermodel);
                }
                else
                {
                    if (No.IndexOf("guest") > -1)
                    {
                        UserModel usermodel = new UserModel()
                        {
                            Name     = "訪客 " + No,
                            password = "",
                            userNo   = No
                        };
                        return(usermodel);
                    }
                }
            }
            return(null);
        }
Example #15
0
        /// <summary>
        /// パッケージをインストールします。
        /// ただし、既にインストール済みならインストールはしません。
        /// </summary>
        /// <param name="packageDir">パッケージ展開用ディレクトリ</param>
        /// <param name="packageName">パッケージ名</param>
        /// <param name="version">バージョン</param>
        /// <param name="pkgId">正式なパッケージ名(name(var))</param>
        /// <returns>dllリスト</returns>
        public static List <PackageInfo> install(string _packageDir, string packageName, string version, out string pkgId)
        {
            pkgId = "";
            string toolPath = Path.Combine(_packageDir, "nuget.exe");

            if (!File.Exists(toolPath))
            {
                string msg = Language.Instance["Help:NugetNotExist"];
                ControlTools.ShowErrorMessage(msg.Replace("<DIR>", _packageDir));
                return(null);
            }

            string packageVName = $"{packageName}.{version}";
            string packageDir   = Path.Combine(_packageDir, packageName);
            string packageRoot  = Path.Combine(packageDir, packageVName);

            if (!Directory.Exists(packageRoot))
            {
                // nugetファイルをダウンロード

                Console.WriteLine($"Get {packageVName}");

                ToolExec toolExec = new ToolExec(toolPath);
                toolExec.ParamList.Add("Install");
                toolExec.ParamList.Add(packageName);
                toolExec.ParamList.Add("-Version");
                toolExec.ParamList.Add(version);
                toolExec.ParamList.Add("-PackageSaveMode");
                toolExec.ParamList.Add("nuspec");
                toolExec.ParamList.Add("-OutputDirectory");
                toolExec.ParamList.Add(packageDir);
                int result = toolExec.Start(true);
                if (result == 0)
                {
                    Console.WriteLine("OK");
                    CommandCanvasList.OutPut.Flush();
                }
                else
                {
                    Console.WriteLine($"error({result})");
                    return(null);
                }
            }

            List <string> dllList     = new List <string>();
            List <string> libPathList = new List <string>(FileLib.GetDirectories(packageDir, true));

            libPathList.Sort((a, b) => b.CompareTo(a));
            foreach (var dir in libPathList)
            {
                if (dir.Contains(@"\ref\"))
                {
                    continue;
                }
                if (dir.Contains("netstandard"))
                {
                    ICollection <string> dll = FileLib.GetFiles(dir, "*.dll");
                    if (dll.Count != 0)
                    {
                        bool isHit = dllList.Any((n) => dir.StartsWith(n.Substring(0, n.IndexOf("netstandard"))));
                        if (isHit)
                        {
                            continue;
                        }
                        dllList.Add(dll.First());
                    }
                }
            }

            // dll をリストに登録
            var packageList = new List <PackageInfo>();

            if (dllList != null && dllList.Count != 0)
            {
                string basePass = System.IO.Path.GetDirectoryName(dllList[dllList.Count - 1]);
                foreach (var libPath in dllList)
                {
                    // 内部に複数のサブディレクトリを持っている場合、サブディレクトリ名を名前に残す
                    string name = Path.GetFileNameWithoutExtension(libPath);

                    if (loadedPackages.Contains(libPath))
                    {
                        // 一度取り込んでいるdllは無視する

                        continue;
                    }
                    loadedPackages.Add(libPath);
                    Match match = Regex.Match(libPath, @"\d+\.\d+\.\d+");
                    if (match.Success)  // バージョン情報が見つかった
                    {
                        packageList.Add(new PackageInfo(libPath, name.Replace(match.Value, ""), match.Value));
                    }
                    else
                    {
                        packageList.Add(new PackageInfo(libPath, name, ""));
                    }
                }
            }
            {
                Match match = Regex.Match(packageVName, @"\d+\.\d+\.\d+");
                if (match.Success)  // バージョン情報が見つかった
                {
                    pkgId = packageVName.Replace("." + match.Value, "");
                }
                else
                {
                    pkgId = packageVName;
                }
            }
            return(packageList);
        }
Example #16
0
        /// <summary>
        /// Creates a global environment with all the base modules registered and
        /// some default values set.
        /// </summary>
        /// <returns></returns>
        public static LuaTable CreateGlobalEnviroment(bool createBaseLib       = true,
                                                      bool createStringLib     = true,
                                                      bool createTableLib      = true,
                                                      bool createOSLib         = true,
                                                      bool createIOLib         = true,
                                                      bool createFileLib       = true,
                                                      bool createMathLib       = true,
                                                      bool createScriptLib     = true,
                                                      bool createWinFormsLib   = true,
                                                      bool createConsoleLib    = true,
                                                      bool createCoroutineLib  = true,
                                                      bool createPackageLib    = true,
                                                      bool createClassLib      = true,
                                                      bool createFileSystemLib = true)
        {
            LuaTable global = new LuaTable();

            // Register Lua Modules

            if (createBaseLib)
            {
                BaseLib.RegisterFunctions(global);
            }
            if (createStringLib)
            {
                StringLib.RegisterModule(global);
            }
            if (createTableLib)
            {
                TableLib.RegisterModule(global);
            }
            if (createIOLib)
            {
                IOLib.RegisterModule(global);
            }
            if (createFileLib)
            {
                FileLib.RegisterModule(global);
            }
            if (createMathLib)
            {
                MathLib.RegisterModule(global);
            }
            if (createOSLib)
            {
                OSLib.RegisterModule(global);
            }
            if (createScriptLib)
            {
                ScriptLib.RegisterModule(global);
            }
            //if (createWinFormsLib)
            //    WinFormLib.RegisterModule(global);
            if (createConsoleLib)
            {
                ConsoleLib.RegisterModule(global);
            }
            if (createCoroutineLib)
            {
                CoroutineLib.RegisterModule(global);
            }
            if (createPackageLib)
            {
                PackageLib.RegisterModule(global);
            }
            if (createClassLib)
            {
                ClassLib.RegisterModule(global);
            }
            if (createFileSystemLib)
            {
                FileSystemLib.RegisterModule(global);
            }

            //global.SetNameValue("_WORKDIR", new LuaString(Application.StartupPath + "\\"));
            global.SetNameValue("_VERSION", new LuaString("Sharp Lua 1.1"));
            global.SetNameValue("_G", global);

            if (createPackageLib)
            {
                // set package.preload table
                LuaTable preload = (LuaTable)(global.GetValue("package") as LuaTable).GetValue("preload");
                if (createStringLib)
                {
                    preload.SetNameValue("string", (LuaTable)global.GetValue("string"));
                }
                if (createTableLib)
                {
                    preload.SetNameValue("table", (LuaTable)global.GetValue("table"));
                }
                if (createIOLib)
                {
                    preload.SetNameValue("io", (LuaTable)global.GetValue("io"));
                }
                if (createFileLib)
                {
                    preload.SetNameValue("file", (LuaTable)global.GetValue("file"));
                }
                if (createMathLib)
                {
                    preload.SetNameValue("math", (LuaTable)global.GetValue("math"));
                }
                if (createOSLib)
                {
                    preload.SetNameValue("os", (LuaTable)global.GetValue("os"));
                }
                if (createScriptLib)
                {
                    preload.SetNameValue("script", (LuaTable)global.GetValue("script"));
                }
                //if (createWinFormsLib)
                //    preload.SetNameValue("WinForms", (LuaTable) global.GetValue("WinForms"));
                if (createConsoleLib)
                {
                    preload.SetNameValue("console", (LuaTable)global.GetValue("console"));
                }
                if (createCoroutineLib)
                {
                    preload.SetNameValue("coroutine", (LuaTable)global.GetValue("coroutine"));
                }
                if (createPackageLib) // wait a second...
                {
                    preload.SetNameValue("package", (LuaTable)global.GetValue("package"));
                }
                if (createClassLib)
                {
                    preload.SetNameValue("class", (LuaTable)global.GetValue("class"));
                }
                if (createFileSystemLib)
                {
                    preload.SetNameValue("filesystem", (LuaTable)global.GetValue("filesystem"));
                }
            }
            if (createFileSystemLib)
            {
                FileSystemLib.currentDir = global.GetValue("_WORKDIR").ToString();
            }

            GlobalEnvironment = global;
            return(global);
        }
Example #17
0
        public static void BuildBioPGlobal(GameTarget target)
        {
            M3MergeDLC.RemoveMergeDLC(target);
            var loadedFiles = MELoadedFiles.GetFilesLoadedInGame(target.Game, gameRootOverride: target.TargetPath);

            //var mergeFiles = loadedFiles.Where(x =>
            //    x.Key.StartsWith(@"BioH_") && x.Key.Contains(@"_DLC_MOD_") && x.Key.EndsWith(@".pcc") && !x.Key.Contains(@"_LOC_") && !x.Key.Contains(@"_Explore."));

            Log.Information($@"SQMMERGE: Building BioP_Global");
            var appearanceInfo = new CaseInsensitiveDictionary <List <SquadmateInfoSingle> >();

            int appearanceId       = 255; // starting
            int currentConditional = STARTING_OUTFIT_CONDITIONAL;

            // Scan squadmate merge files
            var sqmSupercedances = M3Directories.GetFileSupercedances(target, new[] { @".sqm" });

            if (sqmSupercedances.TryGetValue(SQUADMATE_MERGE_MANIFEST_FILE, out var infoList))
            {
                infoList.Reverse();
                foreach (var dlc in infoList)
                {
                    Log.Information($@"SQMMERGE: Processing {dlc}");

                    var jsonFile    = Path.Combine(M3Directories.GetDLCPath(target), dlc, target.Game.CookedDirName(), SQUADMATE_MERGE_MANIFEST_FILE);
                    var infoPackage = JsonConvert.DeserializeObject <SquadmateMergeInfo>(File.ReadAllText(jsonFile));
                    if (!infoPackage.Validate(dlc, target, loadedFiles))
                    {
                        continue; // skip this
                    }

                    // Enumerate all outfits listed for a single squadmate
                    foreach (var outfit in infoPackage.Outfits)
                    {
                        List <SquadmateInfoSingle> list;

                        // See if we already have an outfit list for this squadmate, maybe from another mod...
                        if (!appearanceInfo.TryGetValue(outfit.HenchName, out list))
                        {
                            list = new List <SquadmateInfoSingle>();
                            appearanceInfo[outfit.HenchName] = list;
                        }

                        outfit.ConditionalIndex = currentConditional++; // This is always incremented, so it might appear out of order in game files depending on how mod order is processed, that should be okay though.
                        outfit.AppearanceId     = appearanceId++;       // may need adjusted
                        outfit.DLCName          = dlc;
                        list.Add(outfit);
                        Log.Information($@"SQMMERGE: ConditionalIndex for {outfit.HenchName} appearanceid {outfit.AppearanceId}: {outfit.ConditionalIndex}");
                    }
                }
            }

            if (appearanceInfo.Any())
            {
                var biopGlobal      = MEPackageHandler.OpenMEPackage(loadedFiles[@"BioP_Global.pcc"]);
                var lsk             = biopGlobal.Exports.FirstOrDefault(x => x.ClassName == @"LevelStreamingKismet");
                var persistentLevel = biopGlobal.FindExport(@"TheWorld.PersistentLevel");

                // Clone LevelStreamingKismets
                foreach (var sqm in appearanceInfo.Values)
                {
                    foreach (var outfit in sqm)
                    {
                        var fName  = outfit.HenchPackage;
                        var newLSK = EntryCloner.CloneEntry(lsk);
                        newLSK.WriteProperty(new NameProperty(fName, @"PackageName"));

                        if (target.Game.IsGame3())
                        {
                            // Game 3 has _Explore files too
                            fName += @"_Explore";
                            newLSK = EntryCloner.CloneEntry(lsk);
                            newLSK.WriteProperty(new NameProperty(fName, @"PackageName"));
                        }
                    }
                }

                // Update BioWorldInfo
                // Doesn't have consistent number so we can't find it by instanced full path
                var bioWorldInfo = biopGlobal.Exports.FirstOrDefault(x => x.ClassName == @"BioWorldInfo");

                var props = bioWorldInfo.GetProperties();

                // Update Plot Streaming
                var plotStreaming = props.GetProp <ArrayProperty <StructProperty> >(@"PlotStreaming");
                foreach (var sqm in appearanceInfo.Values)
                {
                    foreach (var outfit in sqm)
                    {
                        // find item to add to
                        buildPlotElementObject(plotStreaming, outfit, target.Game, false);
                        if (target.Game.IsGame3())
                        {
                            buildPlotElementObject(plotStreaming, outfit, target.Game, true);
                        }
                    }
                }


                // Update StreamingLevels
                var streamingLevels = props.GetProp <ArrayProperty <ObjectProperty> >(@"StreamingLevels");
                streamingLevels.ReplaceAll(biopGlobal.Exports.Where(x => x.ClassName == @"LevelStreamingKismet").Select(x => new ObjectProperty(x)));

                bioWorldInfo.WriteProperties(props);


                M3MergeDLC.GenerateMergeDLC(target, Guid.NewGuid());

                // Save BioP_Global into DLC
                var cookedDir = Path.Combine(M3Directories.GetDLCPath(target), M3MergeDLC.MERGE_DLC_FOLDERNAME, target.Game.CookedDirName());
                var outP      = Path.Combine(cookedDir, @"BioP_Global.pcc");
                biopGlobal.Save(outP);

                // Generate conditionals file
                if (target.Game.IsGame3())
                {
                    CNDFile cnd = new CNDFile();
                    cnd.ConditionalEntries = new List <CNDFile.ConditionalEntry>();

                    foreach (var sqm in appearanceInfo.Values)
                    {
                        foreach (var outfit in sqm)
                        {
                            var scText   = $@"(plot.ints[{GetSquadmateOutfitInt(outfit.HenchName, target.Game)}] == i{outfit.MemberAppearanceValue})";
                            var compiled = ME3ConditionalsCompiler.Compile(scText);
                            cnd.ConditionalEntries.Add(new CNDFile.ConditionalEntry()
                            {
                                Data = compiled, ID = outfit.ConditionalIndex
                            });
                        }
                    }

                    cnd.ToFile(Path.Combine(cookedDir, $@"Conditionals{M3MergeDLC.MERGE_DLC_FOLDERNAME}.cnd"));
                }
                else if (target.Game.IsGame2())
                {
                    var startupF = Path.Combine(cookedDir, $@"Startup_{M3MergeDLC.MERGE_DLC_FOLDERNAME}.pcc");
                    var startup  = MEPackageHandler.OpenMEPackageFromStream(Utilities.GetResourceStream(
                                                                                $@"MassEffectModManagerCore.modmanager.mergedlc.{target.Game}.Startup_{M3MergeDLC.MERGE_DLC_FOLDERNAME}.pcc"));
                    var conditionalClass =
                        startup.FindExport($@"PlotManager{M3MergeDLC.MERGE_DLC_FOLDERNAME}.BioAutoConditionals");

                    // Add Conditional Functions
                    FileLib fl          = new FileLib(startup);
                    bool    initialized = fl.Initialize(new RelativePackageCache()
                    {
                        RootPath = M3Directories.GetBioGamePath(target)
                    });
                    if (!initialized)
                    {
                        throw new Exception(
                                  $@"FileLib for script update could not initialize, cannot install conditionals");
                    }


                    var funcToClone =
                        startup.FindExport($@"PlotManager{M3MergeDLC.MERGE_DLC_FOLDERNAME}.BioAutoConditionals.TemplateFunction");
                    foreach (var sqm in appearanceInfo.Values)
                    {
                        foreach (var outfit in sqm)
                        {
                            var func = EntryCloner.CloneEntry(funcToClone);
                            func.ObjectName = $@"F{outfit.ConditionalIndex}";
                            func.indexValue = 0;

                            var scText = new StreamReader(Utilities.GetResourceStream(
                                                              $@"MassEffectModManagerCore.modmanager.squadmates.{target.Game}.HasOutfitOnConditional.txt"))
                                         .ReadToEnd();

                            scText = scText.Replace(@"%CONDITIONALNUM%", outfit.ConditionalIndex.ToString());
                            scText = scText.Replace(@"%SQUADMATEOUTFITPLOTINT%", outfit.AppearanceId.ToString());
                            scText = scText.Replace(@"%OUTFITINDEX%", outfit.MemberAppearanceValue.ToString());

                            (_, MessageLog log) = UnrealScriptCompiler.CompileFunction(func, scText, fl);
                            if (log.AllErrors.Any())
                            {
                                Log.Error($@"Error compiling function {func.InstancedFullPath}:");
                                foreach (var l in log.AllErrors)
                                {
                                    Log.Error(l.Message);
                                }

                                throw new Exception(M3L.GetString(M3L.string_interp_errorCompilingConditionalFunction, func, string.Join('\n', log.AllErrors.Select(x => x.Message))));
                            }
                        }
                    }


                    // Relink the conditionals chain
                    UClass uc = ObjectBinary.From <UClass>(conditionalClass);
                    uc.UpdateLocalFunctions();
                    uc.UpdateChildrenChain();
                    conditionalClass.WriteBinary(uc);

                    startup.Save(startupF);
                }


                // Add startup package, member appearances
                if (target.Game.IsGame2())
                {
                    var bioEngine = Path.Combine(cookedDir, @"BIOEngine.ini");
                    var ini       = DuplicatingIni.LoadIni(bioEngine);

                    var startupSection = ini.GetOrAddSection(@"Engine.StartupPackages");

                    startupSection.Entries.Add(new DuplicatingIni.IniEntry(@"+DLCStartupPackage", $@"Startup_{M3MergeDLC.MERGE_DLC_FOLDERNAME}"));
                    startupSection.Entries.Add(new DuplicatingIni.IniEntry(@"+Package", $@"PlotManager{M3MergeDLC.MERGE_DLC_FOLDERNAME}"));

                    ini.WriteToFile(bioEngine);
                }
                else if (target.Game.IsGame3())
                {
                    var mergeCoalFile = Path.Combine(M3Directories.GetDLCPath(target), M3MergeDLC.MERGE_DLC_FOLDERNAME, target.Game.CookedDirName(), $@"Default_{M3MergeDLC.MERGE_DLC_FOLDERNAME}.bin");
                    var mergeCoal     = CoalescedConverter.DecompileGame3ToMemory(new MemoryStream(File.ReadAllBytes(mergeCoalFile)));

                    // Member appearances
                    var bioUiDoc = XDocument.Parse(mergeCoal[@"BIOUI.xml"]);

                    foreach (var sqm in appearanceInfo.Values)
                    {
                        foreach (var outfit in sqm)
                        {
                            var entry = new Game3CoalescedValueEntry()
                            {
                                Section = @"sfxgame.sfxguidata_teamselect",
                                Name    = @"selectappearances",
                                Type    = 3,
                                Value   = StringStructParser.BuildCommaSeparatedSplitValueList(outfit.ToPropertyDictionary(), @"AvailableImage", @"HighlightImage", @"DeadImage", @"SilhouetteImage")
                            };
                            Game3CoalescedHelper.AddArrayEntry(bioUiDoc, entry);
                        }
                    }

                    mergeCoal[@"BIOUI.xml"] = bioUiDoc.ToString();

                    // Dynamic load mapping
                    var bioEngineDoc = XDocument.Parse(mergeCoal[@"BIOEngine.xml"]);

                    foreach (var sqm in appearanceInfo.Values)
                    {
                        foreach (var outfit in sqm)
                        {
                            //
                            // * <Section name="sfxgame.sfxengine">
                            // <Property name="dynamicloadmapping">
                            // <Value type="3">(ObjectName="BIOG_GesturesConfigDLC.RuntimeData",SeekFreePackageName="GesturesConfigDLC")</Value>

                            var entry = new Game3CoalescedValueEntry()
                            {
                                Section = @"sfxgame.sfxengine",
                                Name    = @"dynamicloadmapping",
                                Type    = 3
                            };

                            entry.Values.Add($"(ObjectName=\"{outfit.AvailableImage}\",SeekFreePackageName=\"SFXHenchImages_{outfit.DLCName}\")"); // do not localize
                            entry.Values.Add($"(ObjectName=\"{outfit.HighlightImage}\",SeekFreePackageName=\"SFXHenchImages_{outfit.DLCName}\")"); // do not localize
                            Game3CoalescedHelper.AddArrayEntry(bioEngineDoc, entry);
                        }
                    }

                    mergeCoal[@"BIOEngine.xml"] = bioEngineDoc.ToString();


                    CoalescedConverter.CompileFromMemory(mergeCoal).WriteToFile(mergeCoalFile);
                }
            }
        }
Example #18
0
        public static Class ConvertClass(UClass uClass, bool decompileBytecode, FileLib lib = null)
        {
            IMEPackage pcc = uClass.Export.FileRef;

            VariableType parent = new VariableType(pcc.GetEntry(uClass.SuperClass)?.ObjectName.Instanced ?? "object");

            VariableType outer = new VariableType(pcc.GetEntry(uClass.OuterClass)?.ObjectName.Instanced ?? parent.Name);

            // TODO: components

            var interfaces = new List <VariableType>();

            foreach ((UIndex interfaceUIndex, UIndex _) in uClass.Interfaces)
            {
                interfaces.Add(new VariableType(pcc.GetEntry(interfaceUIndex)?.ObjectName.Instanced ?? "UNK_INTERFACE"));
            }

            var Types  = new List <VariableType>();
            var Vars   = new List <VariableDeclaration>();
            var Funcs  = new List <Function>();
            var States = new List <State>();

            var nextItem = uClass.Children;

            while (pcc.TryGetUExport(nextItem, out ExportEntry nextChild))
            {
                var objBin = ObjectBinary.From(nextChild);
                switch (objBin)
                {
                case UConst uConst:
                    Types.Add(new Const(uConst.Export.ObjectName.Instanced, uConst.Value)
                    {
                        Literal = new ClassOutlineParser(new TokenStream <string>(new StringLexer(uConst.Value))).ParseConstValue()
                    });
                    nextItem = uConst.Next;
                    break;

                case UEnum uEnum:
                    Types.Add(ConvertEnum(uEnum));
                    nextItem = uEnum.Next;
                    break;

                case UFunction uFunction:
                    Funcs.Add(ConvertFunction(uFunction, uClass, decompileBytecode));
                    nextItem = uFunction.Next;
                    break;

                case UProperty uProperty:
                    Vars.Add(ConvertVariable(uProperty));
                    nextItem = uProperty.Next;
                    break;

                case UScriptStruct uScriptStruct:
                    Types.Add(ConvertStruct(uScriptStruct));
                    nextItem = uScriptStruct.Next;
                    break;

                case UState uState:
                    nextItem = uState.Next;
                    States.Add(ConvertState(uState, uClass, decompileBytecode));
                    break;

                default:
                    nextItem = 0;
                    break;
                }
            }
            var propObject        = pcc.GetUExport(uClass.Defaults);
            var defaultProperties = ConvertDefaultProperties(propObject);

            Class AST = new Class(uClass.Export.ObjectName.Instanced, parent, outer, uClass.ClassFlags, interfaces, Types, Vars, Funcs, States, defaultProperties)
            {
                ConfigName = uClass.ClassConfigName,
                Package    = uClass.Export.Parent is null?Path.GetFileNameWithoutExtension(pcc.FilePath) : uClass.Export.ParentInstancedFullPath,
            };

            // Ugly quick fix:
            foreach (var member in Types)
            {
                member.Outer = AST;
            }
            foreach (var member in Vars)
            {
                member.Outer = AST;
            }
            foreach (var member in Funcs)
            {
                member.Outer = AST;
            }
            foreach (var member in States)
            {
                member.Outer = AST;
            }


            var virtFuncLookup = new CaseInsensitiveDictionary <ushort>();

            for (ushort i = 0; i < uClass.FullFunctionsList.Length; i++)
            {
                virtFuncLookup.Add(uClass.FullFunctionsList[i].GetEntry(pcc)?.ObjectName, i);
            }
            AST.VirtualFunctionLookup = virtFuncLookup;

            return(AST);
        }
Example #19
0
        public static State ConvertState(UState obj, UClass containingClass = null, bool decompileBytecode = true, FileLib lib = null)
        {
            if (containingClass is null)
            {
                ExportEntry classExport = obj.Export.Parent as ExportEntry;
                while (classExport != null && !classExport.IsClass)
                {
                    classExport = classExport.Parent as ExportEntry;
                }

                if (classExport == null)
                {
                    throw new Exception($"Could not get containing class for state {obj.Export.ObjectName}");
                }

                containingClass = classExport.GetBinaryData <UClass>();
            }
            // TODO: labels

            State parent = null;

            //if the parent is not from the same class, then it's overriden, not extended
            if (obj.SuperClass != 0 && obj.SuperClass.GetEntry(obj.Export.FileRef).Parent == obj.Export.Parent)
            {
                parent = new State(obj.SuperClass.GetEntry(obj.Export.FileRef).ObjectName.Instanced, null, default, null, null, null, null, null, null);
        public static bool RunPlotManagerUpdate(GameTarget target)
        {
            Log.Information($@"Updating PlotManager for game: {target.TargetPath}");
            var supercedances = M3Directories.GetFileSupercedances(target, new[] { @".pmu" });
            Dictionary <string, string> funcMap = new();
            List <string> combinedNames         = new List <string>();

            if (supercedances.TryGetValue(@"PlotManagerUpdate.pmu", out var supercedanes))
            {
                supercedanes.Reverse(); // list goes from highest to lowest. We want to build in lowest to highest
                StringBuilder sb             = null;
                string        currentFuncNum = null;
                var           metaMaps       = M3Directories.GetMetaMappedInstalledDLC(target, false);
                foreach (var pmuDLCName in supercedanes)
                {
                    var uiName = metaMaps[pmuDLCName]?.ModName ?? ThirdPartyServices.GetThirdPartyModInfo(pmuDLCName, target.Game)?.modname ?? pmuDLCName;
                    combinedNames.Add(uiName);
                    var text = File.ReadAllLines(Path.Combine(M3Directories.GetDLCPath(target), pmuDLCName, target.Game.CookedDirName(), @"PlotManagerUpdate.pmu"));
                    foreach (var line in text)
                    {
                        if (line.StartsWith(@"public function bool F"))
                        {
                            if (sb != null)
                            {
                                funcMap[currentFuncNum] = sb.ToString();
                                Log.Information($@"PlotSync: Adding function {currentFuncNum} from {pmuDLCName}");
                                currentFuncNum = null;
                            }

                            sb = new StringBuilder();
                            sb.AppendLine(line);

                            // Method name
                            currentFuncNum = line.Substring(22);
                            currentFuncNum = currentFuncNum.Substring(0, currentFuncNum.IndexOf('('));
                            if (int.TryParse(currentFuncNum, out var num))
                            {
                                if (num <= 0)
                                {
                                    Log.Error($@"Skipping plot manager update: Conditional {num} is not a valid number for use. Values must be greater than 0 and less than 2 billion.");
                                    Analytics.TrackEvent(@"Bad plot manager function", new Dictionary <string, string>()
                                    {
                                        { @"FunctionName", $@"F{currentFuncNum}" },
                                        { @"DLCName", pmuDLCName }
                                    });
                                    sb = null;
                                    return(false);
                                }
                                else if (num.ToString().Length != currentFuncNum.Length)
                                {
                                    Log.Error($@"Skipping plot manager update: Conditional {currentFuncNum} is not a valid number for use. Values must not contain leading zeros");
                                    Analytics.TrackEvent(@"Bad plot manager function", new Dictionary <string, string>()
                                    {
                                        { @"FunctionName", $@"F{currentFuncNum}" },
                                        { @"DLCName", pmuDLCName }
                                    });
                                    sb = null;
                                    return(false);
                                }
                            }
                            else
                            {
                                Log.Error($@"Skipping plot manager update: Conditional {currentFuncNum} is not a valid number for use. Values must be greater than 0 and less than 2 billion.");
                                Analytics.TrackEvent(@"Bad plot manager function", new Dictionary <string, string>()
                                {
                                    { @"FunctionName", $@"F{currentFuncNum}" },
                                    { @"DLCName", pmuDLCName }
                                });
                                sb = null;
                                return(false);
                            }
                        }
                        else
                        {
                            sb?.AppendLine(line);
                        }
                    }

                    // Add final, if any was found
                    if (sb != null)
                    {
                        funcMap[currentFuncNum] = sb.ToString();
                        Log.Information($@"PlotSync: Adding function {currentFuncNum} from {pmuDLCName}");
                    }
                }
            }

            var pmPath = GetPlotManagerPath(target);
            var vpm    = Utilities.ExtractInternalFileToStream($@"MassEffectModManagerCore.modmanager.plotmanager.{target.Game}.PlotManager.{(target.Game == MEGame.ME1 ? @"u" : @"pcc")}"); // do not localize

            if (funcMap.Any())
            {
                var plotManager      = MEPackageHandler.OpenMEPackageFromStream(vpm, $@"PlotManager.{(target.Game == MEGame.ME1 ? @"u" : @"pcc")}"); // do not localize
                var clonableFunction = plotManager.Exports.FirstOrDefault(x => x.ClassName == @"Function");

                // STEP 1: ADD ALL NEW FUNCTIONS BEFORE WE INITIALIZE THE FILELIB.
                foreach (var v in funcMap)
                {
                    var pmKey = $@"BioAutoConditionals.F{v.Key}";
                    var exp   = plotManager.FindExport(pmKey);
                    if (exp == null)
                    {
                        // Adding a new conditional
                        exp            = EntryCloner.CloneEntry(clonableFunction);
                        exp.ObjectName = new NameReference($@"F{v.Key}", 0);
                        exp.FileRef.InvalidateLookupTable(); // We changed the name.

                        // Reduces trash
                        UFunction uf = ObjectBinary.From <UFunction>(exp);
                        uf.Children    = 0;
                        uf.ScriptBytes = Array.Empty <byte>(); // No script data
                        exp.WriteBinary(uf);
                        Log.Information($@"Generated new blank conditional function export: {exp.UIndex} {exp.InstancedFullPath}", Settings.LogModInstallation);
                    }
                }

                // Relink child chain
                UClass uc = ObjectBinary.From <UClass>(plotManager.FindExport(@"BioAutoConditionals"));
                uc.UpdateChildrenChain();
                uc.UpdateLocalFunctions();
                uc.Export.WriteBinary(uc);


                // STEP 2: UPDATE FUNCTIONS
                Stopwatch sw          = Stopwatch.StartNew();
                var       fl          = new FileLib(plotManager);
                bool      initialized = fl.Initialize(new RelativePackageCache()
                {
                    RootPath = M3Directories.GetBioGamePath(target)
                }, target.TargetPath, canUseBinaryCache: false);
                if (!initialized)
                {
                    Log.Error(@"Error initializing FileLib for plot manager sync:");
                    foreach (var v in fl.InitializationLog.AllErrors)
                    {
                        Log.Error(v.Message);
                    }
                    throw new Exception(M3L.GetString(M3L.string_interp_fileLibInitFailedPlotManager, string.Join(Environment.NewLine, fl.InitializationLog.AllErrors.Select(x => x.Message)))); //force localize
                }
                sw.Stop();
                Debug.WriteLine($@"Took {sw.ElapsedMilliseconds}ms to load filelib");

                bool relinkChain = false;
                foreach (var v in funcMap)
                {
                    var pmKey = $@"BioAutoConditionals.F{v.Key}";
                    Log.Information($@"Updating conditional entry: {pmKey}", Settings.LogModInstallation);
                    var exp = plotManager.FindExport(pmKey);
                    (_, MessageLog log) = UnrealScriptCompiler.CompileFunction(exp, v.Value, fl);
                    if (log.AllErrors.Any())
                    {
                        Log.Error($@"Error compiling function {exp.InstancedFullPath}:");
                        foreach (var l in log.AllErrors)
                        {
                            Log.Error(l.Message);
                        }

                        throw new Exception(M3L.GetString(M3L.string_interp_errorCompilingFunctionReason, exp, string.Join('\n', log.AllErrors.Select(x => x.Message))));
                    }
                }

                if (plotManager.IsModified)
                {
                    plotManager.Save(pmPath, true);
                    // Update local file DB
                    var bgfe = new BasegameFileIdentificationService.BasegameCloudDBFile(pmPath.Substring(target.TargetPath.Length + 1), (int)new FileInfo(pmPath).Length, target.Game, M3L.GetString(M3L.string_interp_plotManagerSyncForX, string.Join(@", ", combinedNames)), Utilities.CalculateMD5(pmPath));
                    BasegameFileIdentificationService.AddLocalBasegameIdentificationEntries(new List <BasegameFileIdentificationService.BasegameCloudDBFile>(new[] { bgfe }));
                }
            }
            else
            {
                // Just write out vanilla.
                vpm.WriteToFile(pmPath);
            }

            return(true);
        }
Example #21
0
        public static void Main(string[] arg)
        {
            // *** Parse arguments.

            if (arg.Length == 0)
            {
                PrintUsage();
                return;
            }

            bool optRunTests        = false;
            bool optInteractiveMode = false;
            bool optVerbose         = false;
            bool optPause           = false;
            bool optDump            = false;

            List <string> optFiles        = new List <string>();
            List <string> passThroughArgs = null;

            for (int iArg = 0; iArg < arg.Length; ++iArg)
            {
                string ar = arg[iArg];
                if (ar[0] == '-' || ar[0] == '/')
                {
                    if (ar[1] == 't')
                    {
                        optRunTests = true;
                    }
                    else if (ar[1] == 'i')
                    {
                        optInteractiveMode = true;
                    }
                    else if (ar[1] == 'v')
                    {
                        Console.WriteLine("verbose enabled.");
                        optVerbose = true;
                    }
                    else if (ar[1] == 'p')
                    {
                        optPause = true;
                    }
                    else if (ar[1] == 'd')
                    {
                        optDump = true;
                    }
                    else if (ar[1] == 'a')
                    {
                        if (iArg == arg.Length - 1)
                        {
                            Console.WriteLine("Argument expected after -a option.");
                            PrintUsage();
                            return;
                        }
                        else
                        {
                            passThroughArgs = passThroughArgs ?? new List <string>();
                            passThroughArgs.Add(arg[++iArg]);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unrecognized option '" + ar[1] + "'.");
                        PrintUsage();
                        return;
                    }
                }
                else
                {
                    optFiles.Add(ar);
                }
            }


            // *** Initialize engine.

            // Create engine.
            Engine engine = new Engine();

            engine.LogError = (msg) => {
                ConsoleColor sav = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(msg);
                Console.ForegroundColor = sav;
            };

            // Register optional libraries.
            DebugLib.Register(engine);
            FileLib.Register(engine);
            DateTimeLib.Register(engine);
            ConsoleLib.Register(engine);

            List <ParseErrorInst> errors = new List <ParseErrorInst>();

            // Create pass-through args.
            if (null != passThroughArgs)
            {
                string initScript = "global List<string> CLIargs = new { ";
                foreach (string pta in passThroughArgs)
                {
                    initScript += "Add(\"" + pta + "\"); ";
                }
                initScript += "};";

                ScriptResult result = engine.RunScript(initScript, false);
                if (!result.success)
                {
                    Console.WriteLine("INTERNAL ERROR creating passthrough arguments array.");
                    return;
                }
                errors.Clear();
            }

            // *** Do tasks.

            // Tests...
            if (optRunTests)
            {
                UnitTests.RunTests(engine, optVerbose);
            }

            // Files...
            foreach (string filename in optFiles)
            {
                string fileContents;
                try {
                    fileContents = File.ReadAllText(filename);
                } catch (Exception e) {
                    Console.WriteLine("Error attempting to open '" + filename + "': " + e.Message);
                    break;
                }
                errors.Clear();

                ScriptResult result = engine.RunScript(fileContents, optVerbose, filename);
                if (result.success)
                {
                    Console.WriteLine("Returned: " + CoreLib.ValueToString(engine.defaultContext, result.value, true));
                }
                else
                {
                    // At time of writing, errors get printed (in red) when they are created, so don't need to do it again here.
                    //Console.WriteLine(result);
                    Console.WriteLine("  " + filename + " failed to compile or execute.");
                }
            }

            // Interactive mode...
            if (optInteractiveMode)
            {
                Console.WriteLine("Pebble Interpreter (C) 2021 Patrick Cyr");
                Console.WriteLine("Interactive mode. Enter 'exit' to exit, 'help' for help:");

                // Lines in interactive mode don't use their own scope. Instead, they
                // use one shared scope that is created here.
                engine.defaultContext.stack.PushTerminalScope("<interactive mode>", null);

                while (true)
                {
                    Console.Write("> ");
                    string line = Console.ReadLine();

                    line = line.Trim();
                    if (line.Equals("exit", StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }
                    if (line.Equals("help", StringComparison.OrdinalIgnoreCase))
                    {
                        line = "Debug::DumpClass(\"Debug\");";
                        Console.WriteLine(line);
                    }

                    ScriptResult result = engine.RunInteractiveScript(line, optVerbose);
                    if (result.success)
                    {
                        if (null == result.value)
                        {
                            Console.WriteLine("<null>");
                        }
                        else
                        {
                            Console.WriteLine(CoreLib.ValueToString(engine.defaultContext, result.value, true));
                        }
                    }
                }
            }

            // Dump memory...
            if (optDump)
            {
                Console.WriteLine();
                Console.WriteLine(engine.defaultContext);
            }

            // Pause before exiting...
            if (optPause)
            {
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
        }