Ejemplo n.º 1
0
 public ExperienceInit(TraitInfo info, int value)
     : base(info, value)
 {
 }
Ejemplo n.º 2
0
 public TraitSetter(TraitInfo parent)
     : base(parent)
 {
 }
Ejemplo n.º 3
0
        public U GetValue <T, U>(TraitInfo info, U fallback) where T : ValueActorInit <U>
        {
            var init = GetOrDefault <T>(info);

            return(init != null ? init.Value : fallback);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
#if DEBUG
            DateTime start = DateTime.Now;
#endif
            try
            {
                #region Initialization

                try
                {
                    bool hasMethod = false;

                    if (args.Length < 1)
                    {
                        WriteInfo();
                        Console.WriteLine("[?] Use -help for some instructions.");
                        return;
                    }

                    for (int i = 0, n = args.Length; i < n; ++i)
                    {
                        switch (args[i])
                        {
                        case "-h":
                        case "-help":
                        case "-?":
                        case "/?":
                        case "/help":
                            WriteInfo();
                            Usage();
                            return;

                        // OPTIONS /////////////////////////////////////////////////////////////////////

                        case "-o":
                        case "-output":
                            _pathOutput = args[++i];
                            break;

                        case "-q":
                        case "-quiet":
                            _isQuiet = true;
                            break;

                        // REPLACE ////////////////////////////////////////////////////////////////////

                        case "-r":
                        case "-replace":
                            _action = Action.Replace;
                            break;

                        // REPLACE PROPERTIES ////////////////////////////////////////////////////////

                        case "-sm":
                        case "-static-method":
                            if (hasMethod)
                            {
                                throw new Exception("Two methods defined.");
                            }
                            _isMethodStatic = true;
                            _methodName     = args[++i];
                            break;

                        case "-m":
                        case "-method":
                            if (hasMethod)
                            {
                                throw new Exception("Two methods defined.");
                            }
                            _isMethodStatic = false;
                            _methodName     = args[++i];
                            break;

                        case "-co":
                        case "-constructor":
                            if (hasMethod)
                            {
                                throw new Exception("Two methods defined.");
                            }
                            _isConstructor  = true;
                            _isMethodStatic = false;
                            break;

                        case "-sc":
                        case "-static-constructor":
                            if (hasMethod)
                            {
                                throw new Exception("Two methods defined.");
                            }
                            _isConstructor  = true;
                            _isMethodStatic = true;
                            break;

                        case "-c":
                        case "-class":
                            _className = args[++i];
                            break;

                        case "-n":
                        case "-namespace":
                            _namespace = args[++i];
                            break;

                        // INLINE ///////////////////////////////////////////////////////////////////

                        case "-i":
                        case "-inline":
                            _action  = Action.Inline;
                            _pathSwf = args[++i];
                            break;

                        // PATCH ///////////////////////////////////////////////////////////////////
                        case "-optimize":
                            _action  = Action.Optimize;
                            _pathSwf = args[++i];
                            break;

                        // DASM ////////////////////////////////////////////////////////////////////

                        case "-d":
                        case "-dasm":
                            _action = Action.Dasm;
                            break;

                        // DASM PROPERTIES ////////////////////////////////////////////////////////

                        case "-a":
                        case "-as3c":
                            _dasmType = Dasm.As3c;
                            break;

                        case "-p":
                        case "-plain":
                            _dasmType = Dasm.Plain;
                            break;

                        default:
                            if (File.Exists(args[i]))
                            {
                                try
                                {
                                    BinaryReader fileHead = new BinaryReader(File.Open(args[i], FileMode.Open, FileAccess.Read));

                                    if (fileHead.BaseStream.Length < 3)
                                    {
                                        throw new Exception("Invalid file given.");
                                    }

                                    byte[] head = fileHead.ReadBytes(3);

                                    fileHead.Close();

                                    //TODO fix this ugly part...
                                    if ((head[0] == (byte)'C' || head[0] == (byte)'F') && head[1] == (byte)'W' && head[2] == (byte)'S')
                                    {
                                        if (_pathSwf != "")
                                        {
                                            throw new Exception("Two SWF files given.");
                                        }

                                        _pathSwf = args[i];
                                    }
                                    else
                                    {
                                        if ("" != _pathAsm)
                                        {
                                            throw new Exception("Two ASM files given.");
                                        }

                                        _pathAsm = args[i];
                                    }
                                }
                                catch (IOException io)
                                {
                                    WriteInfo();
                                    Console.Error.WriteLine("[-] Error: Can not open file {0}", args[i]);
#if DEBUG
                                    Console.Error.WriteLine("[-] {0}", io.Message);
#endif
                                    return;
                                }
                                catch (Exception e)
                                {
                                    WriteInfo();
                                    Console.Error.WriteLine("[-] Error: {0}", e.Message);
#if DEBUG
                                    Console.Error.WriteLine("[-] {0}", e.StackTrace);
#endif
                                    return;
                                }
                            }
                            else
                            {
                                if (args[i].IndexOf(".") != -1)
                                {
                                    WriteInfo();
                                    Console.Error.WriteLine("[-] File {0} does not exist.", args[i]);
                                    return;
                                }
                                else
                                {
                                    throw new Exception("Invalid argument given.");
                                }
                            }
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    WriteInfo();
                    Console.Error.WriteLine("[-] Error: Invalid arguments. Use -help for help ...");
#if DEBUG
                    Console.Error.WriteLine("[-] {0}", e.Message);
                    Console.Error.WriteLine("[-] {0}", e.StackTrace);
#endif
                    return;
                }

                if (!_isQuiet)
                {
                    Console.WriteLine("[i] As3c - ActionScript3 ASM compiler");
                }

                Translator.InitTable();

                #endregion

                #region Integrity scan for the Translator class (DEBUG only)

#if DEBUG
                if (Translator.CheckIntegrity())
                {
                    if (!_isQuiet)
                    {
                        Console.WriteLine("[+] Integrity scan passed!");
                    }
                }
                else
                {
                    Console.WriteLine("[-] Integrity scan failed...!");
                }
#endif

                #endregion

                FileStream fileInput;
                FileStream fileOutput;
                SwfFormat  swf;

                switch (_action)
                {
                case Action.Dasm:

                    #region Disassemble file

                    swf       = new SwfFormat();
                    fileInput = File.Open(_pathSwf, FileMode.Open, FileAccess.Read);

                    swf.Read(fileInput);

                    fileInput.Close();
                    fileInput.Dispose();

                    DisassemblerBase dasm;

                    switch (_dasmType)
                    {
                    case Dasm.As3c:
                        dasm = new DisassemblerAs3c();
                        break;

                    case Dasm.Plain:
                        dasm = new DisassemblerPlain();
                        break;

                    default:
                        throw new Exception();
                    }

                    dasm.Parse(swf);

                    if ("" == _pathOutput)
                    {
                        dasm.EmitToConsole();
                    }
                    else
                    {
                        fileOutput = File.Open(_pathOutput, FileMode.OpenOrCreate, FileAccess.Write);
                        dasm.EmitToStream(fileOutput);

                        fileOutput.Close();
                        fileOutput.Dispose();
                    }

                    #endregion

                    break;

                case Action.Optimize:

                    #region Optimize SWF

                    swf       = new SwfFormat();
                    fileInput = File.Open(_pathSwf, FileMode.Open, FileAccess.Read);

                    swf.Read(fileInput);

                    fileInput.Close();
                    fileInput.Dispose();

                    CompilerOptimize compOptimize = new CompilerOptimize(swf);

                    compOptimize.Compile();

                    fileOutput = File.Open((_pathOutput != "") ? _pathOutput : _pathSwf, FileMode.OpenOrCreate, FileAccess.Write);

                    swf.Write(fileOutput);

                    fileOutput.Close();
                    fileOutput.Dispose();

                    #endregion

                    break;

                case Action.Inline:

                    #region Compile inline instructions

                    swf       = new SwfFormat();
                    fileInput = File.Open(_pathSwf, FileMode.Open, FileAccess.Read);

                    swf.Read(fileInput);

                    fileInput.Close();
                    fileInput.Dispose();

                    CompilerInline compInline = new CompilerInline(swf);
                    compInline.Compile();

                    fileOutput = File.Open((_pathOutput != "") ? _pathOutput : _pathSwf, FileMode.OpenOrCreate, FileAccess.Write);

                    swf.Write(fileOutput);

                    fileOutput.Close();
                    fileOutput.Dispose();

                    #endregion

                    break;

                case Action.Replace:

                    #region Replace method body

                    #region Simple pre-check

                    if ("" == _pathAsm || !File.Exists(_pathAsm))
                    {
                        Console.Error.WriteLine("[-] No valid ASM input given.");
                        return;
                    }

                    if ("" == _pathSwf || !File.Exists(_pathSwf))
                    {
                        Console.Error.WriteLine("[-] No valid SWF target given.");
                        return;
                    }

                    if ("" == _className)
                    {
                        Console.Error.WriteLine("[-] No class given.");
                        return;
                    }

                    if (!_isConstructor)
                    {
                        if ("" == _methodName)
                        {
                            Console.Error.WriteLine("[-] Need method name or constructor to replace");
                            return;
                        }
                    }

                    #endregion

                    swf       = new SwfFormat();
                    fileInput = File.Open(_pathSwf, FileMode.Open, FileAccess.Read);

                    swf.Read(fileInput);

                    fileInput.Close();
                    fileInput.Dispose();

                    #region Body lookup

                    Abc46 abc = null;
                    SwfLibrary.Abc.MethodInfo method = null;
                    MethodBodyInfo            body   = null;
                    bool  instanceFound = false;
                    Abc46 currentAbc    = null;

                    string classFormat;

                    if (_className.IndexOf(".") != -1)
                    {
                        classFormat = "public::" + _className.Substring(0, _className.LastIndexOf(".")) + "::" + _className.Substring(_className.LastIndexOf(".") + 1, _className.Length - _className.LastIndexOf(".") - 1);
                    }
                    else
                    {
                        classFormat = "public::" + _className;
                    }

                    string methodFormat = _namespace + "::" + _methodName;

                    // Parse for all possibilities
                    for (int i = 0, n = swf.AbcCount; i < n; ++i)
                    {
                        currentAbc = swf.GetAbcAt(i);

                        for (int j = 0, m = currentAbc.Scripts.Count; j < m; ++j)
                        {
                            ScriptInfo script = (ScriptInfo)currentAbc.Scripts[j];

                            for (int k = 0, o = script.Traits.Count; k < o; ++k)
                            {
                                TraitInfo scriptTrait = (TraitInfo)script.Traits[k];

                                if (!(scriptTrait.Body is TraitClass))
                                {
                                    continue;
                                }

                                TraitClass   classBody    = (TraitClass)scriptTrait.Body;
                                ClassInfo    classInfo    = (ClassInfo)currentAbc.Classes[(int)classBody.ClassI];
                                InstanceInfo instanceInfo = (InstanceInfo)currentAbc.Instances[(int)classBody.ClassI];

                                string instanceName = NameUtil.ResolveMultiname(currentAbc, instanceInfo.Name);

                                if (classFormat == instanceName)
                                {
                                    instanceFound = true;

                                    if (!_isQuiet)
                                    {
                                        Console.WriteLine("[+] Found class {0}", instanceName);
                                    }

                                    if (_isMethodStatic)
                                    {
                                        if (_isConstructor)
                                        {
                                            if (null != body)
                                            {
                                                Console.Error.WriteLine("[-] Can not explicitly determine method body.");
                                                return;
                                            }

                                            method = (SwfLibrary.Abc.MethodInfo)currentAbc.Methods[(int)classInfo.CInit];

                                            body = FindBody(currentAbc, classInfo.CInit);

                                            abc = currentAbc;

                                            if (null != body)
                                            {
                                                if (!_isQuiet)
                                                {
                                                    Console.WriteLine("[+] Found static class initializer.");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Console.Error.WriteLine("[-] Sorry, static methods do not work yet ...");
                                            return;
                                            //TODO support static methods...
                                        }
                                    }
                                    else
                                    {
                                        if (_isConstructor)
                                        {
                                            if (null != body)
                                            {
                                                Console.Error.WriteLine("[-] Can not explicitly determine method body.");
                                                return;
                                            }

                                            method = (SwfLibrary.Abc.MethodInfo)currentAbc.Methods[(int)instanceInfo.IInit];

                                            body = FindBody(currentAbc, instanceInfo.IInit);

                                            abc = currentAbc;

                                            if (null != body)
                                            {
                                                if (!_isQuiet)
                                                {
                                                    Console.WriteLine("[+] Found class initializer.");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            // here begins the ugly part ...
                                            for (int l = 0, p = instanceInfo.Traits.Count; l < p; ++l)
                                            {
                                                TraitInfo instanceTrait = (TraitInfo)instanceInfo.Traits[l];

                                                if (!(instanceTrait.Body is TraitMethod))
                                                {
                                                    continue;
                                                }

                                                string methodName = NameUtil.ResolveMultiname(currentAbc, instanceTrait.Name);

                                                if ("" == _namespace)
                                                {
                                                    if ("public::" + _methodName != methodName &&
                                                        "private::" + _methodName != methodName &&
                                                        "protected::" + _methodName != methodName &&
                                                        "protected$::" + _methodName != methodName &&
                                                        "internal::" + _methodName != methodName)
                                                    {
                                                        continue;
                                                    }
                                                }
                                                else
                                                {
                                                    if (methodName != methodFormat)
                                                    {
                                                        continue;
                                                    }
                                                }

                                                if (null != body)
                                                {
                                                    Console.Error.WriteLine("[-] Can not explicitly determine method body.");
                                                    return;
                                                }

                                                TraitMethod methodBody = (TraitMethod)instanceTrait.Body;

                                                method = (SwfLibrary.Abc.MethodInfo)currentAbc.Methods[(int)methodBody.Method];

                                                body = FindBody(currentAbc, methodBody.Method);

                                                abc = currentAbc;

                                                if (null != body)
                                                {
                                                    if (!_isQuiet)
                                                    {
                                                        Console.WriteLine("[+] Found method {0}", methodName);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (null == body)
                    {
                        Console.Error.WriteLine("[-] Could not find {0}.", (instanceFound) ? "method" : "class");
                        return;
                    }

                    #endregion

                    //
                    // We have valid body to replace. Start the parser.
                    //

                    ParserAs3c parser = new ParserAs3c();
                    parser.Parse(_pathAsm);

                    //
                    // Convert the parser instructions to actual bytecode for the AVM2.
                    //

                    CompilerAs3c compAs3c = new CompilerAs3c();
                    compAs3c.Compile(currentAbc, parser.Instructions, parser.Labels, false);

                    //
                    // Get body information (maxstack, localcount, maxscopedepth, initscopedepth)
                    // We keep compiler directives in respect here ...
                    //

                    #region MethodBody information

                    U30 maxStack;
                    U30 maxScopeDepth;
                    U30 localCount;
                    U30 initScopeDepth = new U30();

                    if (parser.HasMaxStack)
                    {
                        maxStack       = new U30();
                        maxStack.Value = parser.MaxStack;
                    }
                    else
                    {
                        maxStack = ByteCodeAnalyzer.CalcMaxStack(compAs3c.Code);

                        if (maxStack.Value < method.ParameterCount.Value)
                        {
                            maxStack.Value = method.ParameterCount.Value;
                        }
                    }

                    if (parser.HasLocalCount)
                    {
                        localCount       = new U30();
                        localCount.Value = parser.LocalCount;
                    }
                    else
                    {
                        localCount = ByteCodeAnalyzer.CalcLocalCount(compAs3c.Code);
                    }

                    if (parser.HasInitScopeDepth)
                    {
                        initScopeDepth.Value = parser.InitScopeDepth;
                    }
                    else
                    {
                        initScopeDepth.Value = 1;
                    }

                    if (parser.HasMaxScopeDepth)
                    {
                        maxScopeDepth       = new U30();
                        maxScopeDepth.Value = parser.MaxScopeDepth;
                    }
                    else
                    {
                        maxScopeDepth        = ByteCodeAnalyzer.CalcScopeDepth(compAs3c.Code);
                        maxScopeDepth.Value += initScopeDepth.Value;
                    }

                    if (!_isQuiet)
                    {
                        Console.WriteLine("[i] InitScopeDepth: {0}", (int)initScopeDepth);
                        Console.WriteLine("[i] MaxScopeDepth: {0}", (int)maxScopeDepth);
                        Console.WriteLine("[i] MaxStack: {0}", (int)maxStack);
                        Console.WriteLine("[i] LocalCount: {0}", (int)localCount);
                    }

                    #endregion

                    //
                    // Replace the code of the body.
                    //

                    body.Code = compAs3c.Code;

                    //
                    // Update body information
                    //

                    body.MaxStack       = maxStack;
                    body.MaxScopeDepth  = maxScopeDepth;
                    body.InitScopeDepth = initScopeDepth;
                    body.LocalCount     = localCount;

                    #region Write output

                    if ("" == _pathOutput)
                    {
                        fileOutput = File.Open(_pathSwf, FileMode.OpenOrCreate, FileAccess.Write);
                    }
                    else
                    {
                        fileOutput = File.Open(_pathOutput, FileMode.OpenOrCreate, FileAccess.Write);
                    }

                    swf.Write(fileOutput);

                    fileOutput.Close();
                    fileOutput.Dispose();

                    #endregion

                    #endregion

                    break;

                case Action.Usage:
                    Usage();
                    break;
                }

                #region Program end

                if (!_isQuiet)
                {
                    Console.WriteLine("[i] Done.");
                }
                #endregion
            }
            catch (IOException ioex)
            {
                Console.Error.WriteLine("[-] Error: {0}", ioex.Message);
            }
            catch (InstructionException iex)
            {
                #region Parser errors

                string message;

                switch (iex.ErrorType)
                {
                case InstructionException.Type.InvalidSyntax:
                    message = "Error while parsing";
                    break;

                case InstructionException.Type.NotEnoughArguments:
                    message = "Not enough arguments";
                    break;

                case InstructionException.Type.TooManyArguments:
                    message = "Too many arguments";
                    break;

                case InstructionException.Type.UnknownType:
                    message = "Unknown type";
                    break;

                case InstructionException.Type.LabelRedefined:
                    message = "Label has already been defined";
                    break;

                case InstructionException.Type.LabelMissing:
                    message = "Label has never been defined";
                    break;

                default:
                    message = "Unknown error at";
                    break;
                }

                Console.Error.WriteLine("[-] " + message + ":");

                if (null != iex.ParserInfo)
                {
                    Console.Error.WriteLine("{0}({1}): {2}", iex.ParserInfo.FilePath, iex.ParserInfo.LineNumber, iex.ParserInfo.Line);
                }

                #endregion
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("[-] Unexpected error: {0}", ex.Message);
#if DEBUG
                Console.Error.WriteLine("[-] Stacktrace: {0}", ex.StackTrace);
#endif
            }

#if DEBUG
            DateTime end   = DateTime.Now;
            TimeSpan delta = end - start;

            Console.WriteLine("[i] Total: {0}sec {1}ms", delta.Seconds, delta.Milliseconds);
#endif
        }
Ejemplo n.º 5
0
 public TurretFacingInit(TraitInfo info, WAngle value)
     : base(info, value)
 {
 }
Ejemplo n.º 6
0
 protected CompositeActorInit(TraitInfo info)
     : base(info.InstanceName)
 {
 }
Ejemplo n.º 7
0
 public bool Contains <T>(TraitInfo info) where T : ActorInit
 {
     return(reference.Contains <T>(info));
 }
Ejemplo n.º 8
0
 public TraitGetter(TraitInfo parent) : base(parent)
 {
 }
Ejemplo n.º 9
0
 public TraitBody(TraitInfo parent)
 {
     _parent = parent;
 }
Ejemplo n.º 10
0
 public RuntimeCargoInit(TraitInfo info, Actor[] value)
     : base(info, value)
 {
 }
Ejemplo n.º 11
0
 public CargoInit(TraitInfo info, string[] value)
     : base(info, value)
 {
 }
Ejemplo n.º 12
0
 public ProductionSpawnLocationInit(TraitInfo info, CPos value)
     : base(info, value)
 {
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets all the mods and patches them.
        /// </summary>
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            _errorLevel = ErrorLevel.NoError;

            //Gets the list of mods
            ItemCollection modCollection = null;
            string         lolLocation   = null;

            //Get the data from the UI thread
            Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                modCollection = ModsListBox.Items;
                lolLocation   = LocationTextbox.Text;
            }));

            SetStatusLabelAsync("Gathering mods...");

            //Gets the list of mods that have been checked.
            List <LessMod> modsToPatch = new List <LessMod>();

            foreach (var x in modCollection)
            {
                CheckBox box          = (CheckBox)x;
                bool     isBoxChecked = false;
                Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    isBoxChecked = box.IsChecked ?? false;
                }));

                if (isBoxChecked)
                {
                    modsToPatch.Add(_lessMods[box]);
                }
            }

            //Create a new dictionary to hold the SWF definitions in. This stops opening and closing the same SWF file if it's going to be modified more than once.
            Dictionary <string, SwfFile> swfs = new Dictionary <string, SwfFile>();

            //Start the stopwatch to see how long it took to patch (aiming for ~5 sec or less on test machine)
            timer = Stopwatch.StartNew();

            //Go through each modification
            foreach (var lessMod in modsToPatch)
            {
                SetStatusLabelAsync("Patching mod: " + lessMod.Name);

                //Go through each patch within the mod
                foreach (var patch in lessMod.Patches)
                {
                    //If the swf hasn't been loaded, load it into the dictionary.
                    if (!swfs.ContainsKey(patch.Swf))
                    {
                        string fullPath = Path.Combine(lolLocation, patch.Swf);

                        //Backup the SWF
                        string   CurrentLocation = "";
                        string[] FileLocation    = patch.Swf.Split('/', '\\');
                        foreach (string s in FileLocation.Take(FileLocation.Length - 1))
                        {
                            CurrentLocation = Path.Combine(CurrentLocation, s);
                            if (!Directory.Exists(Path.Combine(lolLocation, "LESsBackup", BackupVersion, CurrentLocation)))
                            {
                                Directory.CreateDirectory(Path.Combine(lolLocation, "LESsBackup", BackupVersion, CurrentLocation));
                            }
                        }
                        if (!File.Exists(Path.Combine(lolLocation, "LESsBackup", BackupVersion, patch.Swf)))
                        {
                            File.Copy(Path.Combine(lolLocation, patch.Swf), Path.Combine(lolLocation, "LESsBackup", BackupVersion, patch.Swf));
                        }

                        swfs.Add(patch.Swf, SwfFile.ReadFile(fullPath));
                    }

                    //Get the SWF file that is being modified
                    SwfFile swf = swfs[patch.Swf];

                    if (patch.Action == "replace_swf_character")// replace an swf-character (buttons, sprites, fonts etc.)
                    {
                        ushort charId;
                        if (ushort.TryParse(patch.Class, out charId) && swf.CharacterTags.ContainsKey(charId))
                        {
                            swf.CharacterTags[charId].SetData(File.ReadAllBytes(Path.Combine(lessMod.Directory, patch.Code)));
                        }
                        else
                        {
                            _errorLevel = ErrorLevel.UnableToPatch;
                            throw new TraitNotFoundException($"<{patch.Class}> is not a valid Character ID.");
                        }
                    }
                    else
                    {
                        //Get the ABC tags (containing the code) from the swf file.
                        List <DoAbcTag> tags       = swf.GetDoAbcTags();
                        bool            classFound = false;
                        foreach (var tag in tags)
                        {
                            //check if this tag contains our script
                            ScriptInfo si = tag.GetScriptByClassName(patch.Class);

                            //check next tag if it doesn't
                            if (si == null)
                            {
                                continue;
                            }

                            ClassInfo cls = si.FindClass(patch.Class);
                            classFound = true;

                            Assembler asm;
                            //Perform the action based on what the patch defines
                            switch (patch.Action)
                            {
                            case "replace_trait":     //replace trait (method)
                                                      //Load the code from the patch and assemble it to be inserted into the code
                                asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                                TraitInfo newTrait = asm.Assemble() as TraitInfo;

                                int  traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name, Scope.Instance);
                                bool classTrait = false;
                                if (traitIndex < 0)
                                {
                                    traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name, Scope.Class);
                                    classTrait = true;
                                }
                                if (traitIndex < 0)
                                {
                                    throw new TraitNotFoundException(String.Format("Can't find trait \"{0}\" in class \"{1}\"", newTrait.Name.Name, patch.Class));
                                }

                                //Modified the found trait
                                if (classTrait)
                                {
                                    cls.ClassTraits[traitIndex] = newTrait;
                                }
                                else
                                {
                                    cls.InstanceTraits[traitIndex] = newTrait;
                                }
                                break;

                            case "replace_cinit":    //replace class constructor
                                                     //Load the code from the patch and assemble it to be inserted into the code
                                asm           = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                                cls.ClassInit = asm.Assemble() as MethodInfo;
                                break;

                            case "replace_iinit":    //replace instance constructor
                                                     //Load the code from the patch and assemble it to be inserted into the code
                                asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                                cls.InstanceInit = asm.Assemble() as MethodInfo;
                                break;

                            case "add_class_trait":     //add new class trait (method)
                                                        //Load the code from the patch and assemble it to be inserted into the code
                                asm        = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                                newTrait   = asm.Assemble() as TraitInfo;
                                traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name, Scope.Class);
                                if (traitIndex < 0)
                                {
                                    cls.ClassTraits.Add(newTrait);
                                }
                                else
                                {
                                    cls.ClassTraits[traitIndex] = newTrait;
                                }
                                break;

                            case "add_instance_trait":     //add new instance trait (method)
                                                           //Load the code from the patch and assemble it to be inserted into the code
                                asm        = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                                newTrait   = asm.Assemble() as TraitInfo;
                                traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name, Scope.Instance);
                                if (traitIndex < 0)
                                {
                                    cls.InstanceTraits.Add(newTrait);
                                }
                                else
                                {
                                    cls.InstanceTraits[traitIndex] = newTrait;
                                }
                                break;

                            case "remove_class_trait":
                                throw new NotImplementedException();

                            case "remove_instance_trait":
                                throw new NotImplementedException();

                            default:
                                throw new NotSupportedException($"Unknown Action \"{patch.Action}\" in mod {lessMod.Name}");
                            }
                        }
                        if (!classFound)
                        {
                            _errorLevel = ErrorLevel.UnableToPatch;
                            throw new ClassNotFoundException($"Class {patch.Class} not found in file {patch.Swf}");
                        }
                    }
                }
            }

            //Save the modified SWFS to their original location
            foreach (var patchedSwf in swfs)
            {
                try
                {
                    SetStatusLabelAsync("Applying mods: " + patchedSwf.Key);
                    string swfLoc = Path.Combine(lolLocation, patchedSwf.Key);
                    SwfFile.WriteFile(patchedSwf.Value, swfLoc);
                }
                catch
                {
                    _errorLevel = ErrorLevel.GoodJobYourInstallationIsProbablyCorruptedNow;
                    if (Debugger.IsAttached)
                    {
                        throw;
                    }
                }
            }
            timer.Stop();
        }
Ejemplo n.º 14
0
 public TraitConst(TraitInfo parent)
     : base(parent)
 {
 }
Ejemplo n.º 15
0
 public T GetInitOrDefault <T>(TraitInfo info) where T : ActorInit
 {
     return(reference.GetOrDefault <T>(info));
 }
Ejemplo n.º 16
0
 public TraitClass(TraitInfo parent)
     : base(parent)
 {
 }
Ejemplo n.º 17
0
 /// <summary>
 ///   <para>Initializes a new instance of the <see cref="TraitBuilder"/> class with the specified <paramref name="info"/>.</para>
 /// </summary>
 /// <param name="info">The trait metadata to use.</param>
 public TraitBuilder(TraitInfo info) => Info = info;
Ejemplo n.º 18
0
 public TraitMethod(TraitInfo parent)
     : base(parent)
 {
 }
Ejemplo n.º 19
0
 public U GetValue <T, U>(TraitInfo info, U fallback) where T : ValueActorInit <U>
 {
     return(reference.GetValue <T, U>(info, fallback));
 }
Ejemplo n.º 20
0
 public TraitSlot(TraitInfo parent) : base(parent)
 {
 }
Ejemplo n.º 21
0
        void CheckDefinitions(string image, SequenceReferenceAttribute sequenceReference,
                              KeyValuePair <string, ActorInfo> actorInfo, string sequence, string faction, FieldInfo field, TraitInfo traitInfo)
        {
            var definitions = sequenceDefinitions.FirstOrDefault(n => n.Key == image.ToLowerInvariant());

            if (definitions != null)
            {
                if (sequenceReference != null && sequenceReference.Prefix)
                {
                    if (!definitions.Value.Nodes.Any(n => n.Key.StartsWith(sequence)))
                    {
                        emitError("Sprite image {0} from actor {1} of faction {2} does not define sequence prefix {3} from field {4} of {5}"
                                  .F(image, actorInfo.Value.Name, faction, sequence, field.Name, traitInfo));
                    }
                }
                else if (definitions.Value.Nodes.All(n => n.Key != sequence))
                {
                    emitError("Sprite image {0} from actor {1} of faction {2} does not define sequence {3} from field {4} of {5}"
                              .F(image, actorInfo.Value.Name, faction, sequence, field.Name, traitInfo));
                }
            }
        }
Ejemplo n.º 22
0
 public PlugInit(TraitInfo info, string value)
     : base(info, value)
 {
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Gets all the mods and patches them.
        /// </summary>
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            _errorLevel = ErrorLevel.NoError;

            //Gets the list of mods
            ItemCollection modCollection = null;

            Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                modCollection = ModsListBox.Items;
            }));

            SetStatusLabelAsync("Gathering mods...");
            //Gets the list of mods that have been checked.
            List <LessMod> modsToPatch = new List <LessMod>();

            foreach (var x in modCollection)
            {
                CheckBox box          = (CheckBox)x;
                bool     isBoxChecked = false;
                Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() =>
                {
                    isBoxChecked = box.IsChecked ?? false;
                }));

                if (isBoxChecked)
                {
                    modsToPatch.Add(_lessMods[box]);
                }
            }

            string lolLocation = null;
            bool   overwrite   = true;

            Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                lolLocation = LocationTextbox.Text;
            }));
            if (IsGarena)
            {
                MessageBox.Show("Garena detected! Please note that you must uninstall LESs before patching your LoL with Garena." + Environment.NewLine + "Otherwise, your Garena LoL patcher will complain hard and we are not responsible for it ;).");
                Uri lolRootLocation = new Uri(lolLocation);
                lolRootLocation = new Uri(lolRootLocation.LocalPath.Replace(lolRootLocation.Segments.Last(), String.Empty));
                // Get LoL latest patched date
                String versionLocation = Path.Combine(lolRootLocation.LocalPath, "lol.version");
                if (File.Exists(versionLocation))
                {
                    // Store the date in another file. It will be used in LESs removing.
                    File.Copy(versionLocation, Path.Combine(lolRootLocation.LocalPath, "LESs_recent.version"), true);
                }
                if (Directory.Exists(Path.Combine(lolLocation, "LESsBackup")))
                {
                    MessageBoxResult diagRst = MessageBox.Show("We found that you already have backup files. Overwriting it may result in you losing your original files." + Environment.NewLine + "Would you like to overwrite your old files?", "You already have backup files", MessageBoxButton.YesNo);
                    if (diagRst == MessageBoxResult.No)
                    {
                        overwrite = false;
                    }
                }
            }
            Dictionary <string, SwfFile> swfs = new Dictionary <string, SwfFile>();

            Stahpwatch = Stopwatch.StartNew();
            foreach (var lessMod in modsToPatch)
            {
                Debug.Assert(lessMod.Patches.Length > 0);
                SetStatusLabelAsync("Patching mod: " + lessMod.Name);
                foreach (var patch in lessMod.Patches)
                {
                    if (!swfs.ContainsKey(patch.Swf))
                    {
                        string fullPath = Path.Combine(lolLocation, patch.Swf);

                        //Backup the SWF
                        string   CurrentLocation = "";
                        string[] FileLocation    = patch.Swf.Split('/', '\\');
                        foreach (string s in FileLocation.Take(FileLocation.Length - 1))
                        {
                            CurrentLocation = Path.Combine(CurrentLocation, s);
                            if (IsGarena)
                            {
                                if (!Directory.Exists(Path.Combine(lolLocation, "LESsBackup", CurrentLocation)))
                                {
                                    Directory.CreateDirectory(Path.Combine(lolLocation, "LESsBackup", CurrentLocation));
                                }
                                if (!File.Exists(Path.Combine(lolLocation, "LESsBackup", patch.Swf)))
                                {
                                    if (overwrite)
                                    {
                                        File.Copy(Path.Combine(lolLocation, patch.Swf), Path.Combine(lolLocation, "LESsBackup", patch.Swf));
                                    }
                                }
                            }
                            else
                            {
                                if (!Directory.Exists(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, CurrentLocation)))
                                {
                                    Directory.CreateDirectory(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, CurrentLocation));
                                }
                                if (!File.Exists(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, patch.Swf)))
                                {
                                    File.Copy(Path.Combine(lolLocation, patch.Swf), Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, patch.Swf));
                                }
                            }
                        }

                        swfs.Add(patch.Swf, SwfFile.ReadFile(fullPath));
                    }

                    SwfFile         swf        = swfs[patch.Swf];
                    List <DoAbcTag> tags       = swf.GetDoAbcTags();
                    bool            classFound = false;
                    foreach (var tag in tags)
                    {
                        //check if this tag contains our script
                        ScriptInfo si = tag.GetScriptByClassName(patch.Class);

                        //check next tag if it doesn't
                        if (si == null)
                        {
                            continue;
                        }

                        ClassInfo cls = si.GetClassByClassName(patch.Class);
                        classFound = true;

                        Assembler asm;
                        switch (patch.Action)
                        {
                        case "replace_trait":     //replace trait (method)
                            asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                            TraitInfo newTrait = asm.Assemble() as TraitInfo;

                            int  traitIndex = cls.Instance.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name);
                            bool classTrait = false;
                            if (traitIndex < 0)
                            {
                                traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name);
                                classTrait = true;
                            }
                            if (traitIndex < 0)
                            {
                                throw new TraitNotFoundException(String.Format("Can't find trait \"{0}\" in class \"{1}\"", newTrait.Name.Name, patch.Class));
                            }

                            if (classTrait)
                            {
                                cls.Traits[traitIndex] = newTrait;
                            }
                            else
                            {
                                cls.Instance.Traits[traitIndex] = newTrait;
                            }
                            break;

                        case "replace_cinit":    //replace class constructor
                            asm           = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                            cls.ClassInit = asm.Assemble() as MethodInfo;
                            break;

                        case "replace_iinit":    //replace instance constructor
                            asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                            cls.Instance.InstanceInit = asm.Assemble() as MethodInfo;
                            break;

                        case "add_class_trait":     //add new class trait (method)
                            asm        = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                            newTrait   = asm.Assemble() as TraitInfo;
                            traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name);
                            if (traitIndex < 0)
                            {
                                cls.Traits.Add(newTrait);
                            }
                            else
                            {
                                cls.Traits[traitIndex] = newTrait;
                            }
                            break;

                        case "add_instance_trait":     //add new instance trait (method)
                            asm        = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code)));
                            newTrait   = asm.Assemble() as TraitInfo;
                            traitIndex = cls.Instance.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name);
                            if (traitIndex < 0)
                            {
                                cls.Instance.Traits.Add(newTrait);
                            }
                            else
                            {
                                cls.Instance.Traits[traitIndex] = newTrait;
                            }
                            break;

                        case "remove_class_trait":
                            throw new NotImplementedException();

                        case "remove_instance_trait":
                            throw new NotImplementedException();

                        default:
                            throw new NotSupportedException("Unknown Action \"" + patch.Action + "\" in mod " + lessMod.Name);
                        }
                    }

                    if (!classFound)
                    {
                        _errorLevel = ErrorLevel.UnableToPatch;
                        throw new ClassNotFoundException(string.Format("Class {0} not found in file {1}", patch.Class, patch.Swf));
                    }
                }
            }
            //return;

            foreach (var patchedSwf in swfs)
            {
                try
                {
                    SetStatusLabelAsync("Applying mods: " + patchedSwf.Key);
                    string swfLoc = Path.Combine(lolLocation, patchedSwf.Key);
                    SwfFile.WriteFile(patchedSwf.Value, swfLoc);
                }
                catch
                {
                    _errorLevel = ErrorLevel.GoodJobYourInstallationIsProbablyCorruptedNow;
                    if (Debugger.IsAttached)
                    {
                        throw;
                    }
                }
            }
            Stahpwatch.Stop();
        }
Ejemplo n.º 24
0
 public TraitFunction(TraitInfo parent) : base(parent)
 {
 }
Ejemplo n.º 25
0
 public DynamicTurretFacingInit(TraitInfo info, Func <WAngle> value)
     : base(info, value)
 {
 }
Ejemplo n.º 26
0
 public TurretFacingInit(TraitInfo info, int value)
     : base(info, value)
 {
 }
Ejemplo n.º 27
0
 public U GetValue <T, U>(TraitInfo info) where T : ValueActorInit <U>
 {
     return(Get <T>(info).Value);
 }
Ejemplo n.º 28
0
 public TraitMethod(TraitInfo parent) : base(parent)
 {
 }
Ejemplo n.º 29
0
 public bool Contains <T>(TraitInfo info) where T : ActorInit
 {
     return(GetOrDefault <T>(info) != null);
 }
Ejemplo n.º 30
0
 public FreeActorInit(TraitInfo info, bool value)
     : base(info, value)
 {
 }
Ejemplo n.º 31
0
 public StanceInit(TraitInfo info, UnitStance value)
     : base(info, value)
 {
 }
Ejemplo n.º 32
0
 protected ValueActorInit(TraitInfo info, T value)
     : base(info.InstanceName)
 {
     this.value = value;
 }
Ejemplo n.º 33
0
 public TraitSlot(TraitInfo parent)
     : base(parent)
 {
 }
Ejemplo n.º 34
0
 public TraitFunction(TraitInfo parent)
     : base(parent)
 {
 }