Exemple #1
0
        internal CommandLineRunner(ConsoleIO console, CommonCompiler compiler, ScriptCompiler scriptCompiler, ObjectFormatter objectFormatter)
        {
            Debug.Assert(console != null);
            Debug.Assert(compiler != null);
            Debug.Assert(scriptCompiler != null);
            Debug.Assert(objectFormatter != null);

            _console = console;
            _compiler = compiler;
            _scriptCompiler = scriptCompiler;
            _objectFormatter = objectFormatter;
        }
        /// <summary>
        /// Builds and returns a requirer to include with an engine.
        /// </summary>
        /// <param name="compiler">Compiles the required scripts if needed.</param>
        /// <param name="engine">The engine that will run the required script.</param>
        /// <returns></returns>
        internal static Requirer BuildRequirer(ScriptCompiler compiler, V8ScriptEngine engine)
        {
            var requirer = new Requirer
            {
                Compiler = compiler,
                Engine = engine
            };

            //Need to add this as a host object to the script
            requirer.Engine.AddHostObject("require", new Func<string, object>(requirer.Require));
            requirer.Engine.AddHostObject("requireNamed", new Func<string, string, object>(requirer.Require));

            return requirer;
        }
        static void Main()
        {
            CmdArgs cmdArgs = new CmdArgs(Environment.GetCommandLineArgs());

             if (cmdArgs.Options.Count <= 0 && cmdArgs.Parameters.Count <= 0 && cmdArgs.Arguments.Count <= 1)
             {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
            return;
             }

             AttachConsole(ATTACH_PARENT_PROCESS);

             if (cmdArgs.HasParameter("sc"))
             {
            ScriptCompiler script = new ScriptCompiler();

            if (!script.Run(new FileName(cmdArgs.Parameter("s")), cmdArgs))
               Console.WriteLine("The run failed.");
            else
               Console.WriteLine("The run was ok.");
             }
             else if (cmdArgs.HasParameter("sv"))
             {
            Console.WriteLine("Run VB.NET script is not implemented yet.");
             }
             else if (cmdArgs.HasParameter("l"))
             {
            Console.WriteLine("Run from DLL is not implemented yet.");
             }
             else
             {
            Console.WriteLine("");
            Console.WriteLine("To launch visual interface: MohidToolBox");
            Console.WriteLine("To use command line:        MohidToolbox [[--sc][--sv] scriptfilename] [--l dllfilename]");
            Console.WriteLine("");
            Console.WriteLine("       --sc : Used to indicate a CSharp script file name");
            Console.WriteLine("       --sv : Used to indicate a VB.NET script file name (not implemented)");
            Console.WriteLine("       --l  : Used to indicate a DLL script file name (not implemented)");
            Console.WriteLine("");
            Console.WriteLine("If no options are present, the visual interface will be launched.");
            Console.WriteLine("ATTENTION: Only ONE of the above options can be used at a time");
            Console.WriteLine("");
            Console.WriteLine("Press a key...");
             }

             return;
        }
Exemple #4
0
        public void UpdateSpawnObjects(RelayInfo info, Mobile from)
        {
            TextRelay tr = info.GetTextEntry(500);

            if (tr != null && tr.Text.Length > 0)
            {
                Spawner.MaxCount = Math.Max(0, Utility.ToInt32(tr.Text));
            }

            for (int i = 0; i < MaxEntries; i++)
            {
                TextRelay te  = info.GetTextEntry(i);
                TextRelay te2 = info.GetTextEntry(i + 20);

                SpawnObject so = i < Spawner.SpawnObjects.Count ? Spawner.SpawnObjects[i] : null;

                if (te != null)
                {
                    string name     = te.Text;
                    string maxCount = te2 != null ? te2.Text : null;
                    int    max      = 0;

                    if (name.Length > 0)
                    {
                        name = name.Trim();

                        if (!string.IsNullOrEmpty(maxCount))
                        {
                            max = Utility.ToInt32(maxCount);
                        }

                        max = Math.Max(0, max);

                        string t    = Spawner.ParseType(name);
                        Type   type = ScriptCompiler.FindTypeByName(t);

                        if (type == null)
                        {
                            from.SendMessage("{0} is not a valid type name.", t);
                            continue;
                        }

                        if (so != null)
                        {
                            if (so.SpawnName != name)
                            {
                                so.SpawnName = name;
                            }

                            if (so.MaxCount != max)
                            {
                                so.MaxCount = max;
                            }
                        }
                        else
                        {
                            Spawner.AddSpawnObject(new SpawnObject(name, max));
                        }
                    }
                }
            }
        }
Exemple #5
0
        public override void Deserialize(GenericReader reader)
        {
            base.Deserialize(reader);

            int version = reader.ReadInt();

            switch (version)
            {
            case 6:
            {
                m_MobilesSeekHome = reader.ReadBool();
                m_UsesSpawnerHome = reader.ReadBool();
                goto case 5;
            }

            case 5:
            {
                m_SpawnArea       = reader.ReadRect2D();
                m_UsesSpawnerHome = reader.ReadBool();

                goto case 4;
            }

            case 4:
            {
                m_WalkingRange = reader.ReadInt();

                goto case 3;
            }

            case 3:
            case 2:
            {
                m_WayPoint = reader.ReadItem() as WayPoint;

                goto case 1;
            }

            case 1:
            {
                m_Group = reader.ReadBool();

                goto case 0;
            }

            case 0:
            {
                m_MinDelay  = reader.ReadTimeSpan();
                m_MaxDelay  = reader.ReadTimeSpan();
                m_Count     = reader.ReadInt();
                m_Team      = reader.ReadInt();
                m_HomeRange = reader.ReadInt();
                m_Running   = reader.ReadBool();

                TimeSpan ts = TimeSpan.Zero;

                if (m_Running)
                {
                    ts = reader.ReadDeltaTime() - DateTime.Now;
                }

                int size = reader.ReadInt();

                m_SpawnNames = new List <string>(size);

                for (int i = 0; i < size; ++i)
                {
                    string creatureString = reader.ReadString();

                    m_SpawnNames.Add(creatureString);
                    string typeName = ParseType(creatureString);

                    if (ScriptCompiler.FindTypeByName(typeName) == null)
                    {
                        if (m_WarnTimer == null)
                        {
                            m_WarnTimer = new WarnTimer();
                        }

                        m_WarnTimer.Add(Location, Map, typeName);
                    }
                }

                int count = reader.ReadInt();

                m_Spawned = new List <ISpawnable>(count);

                for (int i = 0; i < count; ++i)
                {
                    ISpawnable e = World.FindEntity(reader.ReadInt()) as ISpawnable;

                    if (e != null)
                    {
                        e.Spawner = this;
                        m_Spawned.Add(e);
                    }
                }

                if (m_Running)
                {
                    DoTimer(ts);
                }

                break;
            }
            }

            if (version < 3 && Weight == 0)
            {
                Weight = -1;
            }
        }
Exemple #6
0
        public static DecorationListMag Read(StreamReader ip)
        {
            string line;

            while ((line = ip.ReadLine()) != null)
            {
                line = line.Trim();

                if (line.Length > 0 && !line.StartsWith("#"))
                {
                    break;
                }
            }

            if (string.IsNullOrEmpty(line))
            {
                return(null);
            }

            DecorationListMag list = new DecorationListMag();

            int indexOf = line.IndexOf(' ');

            list.m_Type = ScriptCompiler.FindTypeByName(line.Substring(0, indexOf++), true);

            if (list.m_Type == null)
            {
                throw new ArgumentException(String.Format("Type not found for header: '{0}'", line));
            }

            line    = line.Substring(indexOf);
            indexOf = line.IndexOf('(');
            if (indexOf >= 0)
            {
                list.m_ItemID = Utility.ToInt32(line.Substring(0, indexOf - 1));

                string parms = line.Substring(++indexOf);

                if (line.EndsWith(")"))
                {
                    parms = parms.Substring(0, parms.Length - 1);
                }

                list.m_Params = parms.Split(';');

                for (int i = 0; i < list.m_Params.Length; ++i)
                {
                    list.m_Params[i] = list.m_Params[i].Trim();
                }
            }
            else
            {
                list.m_ItemID = Utility.ToInt32(line);
                list.m_Params = m_EmptyParams;
            }

            list.m_Entries = new ArrayList();

            while ((line = ip.ReadLine()) != null)
            {
                line = line.Trim();

                if (line.Length == 0)
                {
                    break;
                }

                if (line.StartsWith("#"))
                {
                    continue;
                }

                list.m_Entries.Add(new DecorationEntryMag(line));
            }

            return(list);
        }
Exemple #7
0
        public static void CheckRestart()
        {
            string[] files = ScriptCompiler.GetScripts("*.cs");

            if (files.Length == 0)
            {
                m_Mobile.SendMessage("No scripts found to compile!");
                return;
            }

            if (AlreadyCached(files))
            {
                m_Mobile.SendMessage("Scripts are already cached. Restarting...");
                DoRestart(new object[] { false });
                return;
            }

            using (CSharpCodeProvider provider = new CSharpCodeProvider())
            {
                string path = GetUnusedPath("Scripts.CS");

                CompilerParameters parms = new CompilerParameters(ScriptCompiler.GetReferenceAssemblies(), path, m_Debug);

                string defines = ScriptCompiler.GetDefines();

                if (defines != null)
                {
                    parms.CompilerOptions = string.Format("/D:{0}", defines);
                }

                m_Mobile.SendMessage("Compiling C# scripts, please wait...");
                World.Broadcast(1154, true, "[ATTENTION]:The server is restarting shortly...");

                CompilerResults results = provider.CompileAssemblyFromFile(parms, files);

                if (results.Errors.Count > 0)
                {
                    m_Mobile.SendMessage("There were errors in compiling the scripts. QuickRestart can NOT restart.");
                    World.Broadcast(1154, true, "[ATTENTION]:Server restart has been aborted.");
                    m_Restarting = false;
                    return;
                }

                if (Path.GetFileName(path) == "Scripts.CS.dll.new")
                {
                    try
                    {
                        byte[] hashCode = GetHashCode(path, files, false);

                        using (FileStream fs = new FileStream("Scripts/Output/Scripts.CS.hash.new", FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            using (BinaryWriter bin = new BinaryWriter(fs))
                            {
                                bin.Write(hashCode, 0, hashCode.Length);
                            }
                        }
                    }
                    catch { }
                }

                m_Mobile.SendMessage("Compilation successful. Restarting in 15 seconds.");
                World.Broadcast(1154, true, "[ATTENTION]:The server will restart in 15 seconds.");
                Timer.DelayCall(TimeSpan.FromSeconds(15.0), new TimerStateCallback(DoRestart), new object[] { true });
            }
        }
Exemple #8
0
        public static string ConstructFromString(Type type, object obj, string value, ref object constructed)
        {
            object toSet;
            bool   isSerial = IsSerial(type);

            if (isSerial)               // mutate into int32
            {
                type = m_NumericTypes[4];
            }

            if (value == "(-null-)" && !type.IsValueType)
            {
                value = null;
            }

            if (IsEnum(type))
            {
                try
                {
                    toSet = Enum.Parse(type, value, true);
                }
                catch
                {
                    return("That is not a valid enumeration member.");
                }
            }
            else if (IsType(type))
            {
                try
                {
                    toSet = ScriptCompiler.FindTypeByName(value);

                    if (toSet == null)
                    {
                        return("No type with that name was found.");
                    }
                }
                catch
                {
                    return("No type with that name was found.");
                }
            }
            else if (IsParsable(type))
            {
                try
                {
                    toSet = Parse(obj, type, value);
                }
                catch
                {
                    return("That is not properly formatted.");
                }
            }
            else if (value == null)
            {
                toSet = null;
            }
            else if (value.StartsWith("0x") && IsNumeric(type))
            {
                try
                {
                    toSet = Convert.ChangeType(Convert.ToUInt64(value.Substring(2), 16), type);
                }
                catch
                {
                    return("That is not properly formatted.");
                }
            }
            else
            {
                try
                {
                    toSet = Convert.ChangeType(value, type);
                }
                catch
                {
                    return("That is not properly formatted.");
                }
            }

            if (isSerial)               // mutate back
            {
                toSet = (Serial)((Int32)toSet);
            }

            constructed = toSet;
            return(null);
        }
        private bool Compile() {
            CompilerOptions options = new CompilerOptions();
            options.DebugFlavor = DebugFlavor;
            if (DebugFlavor) {
                options.IncludeTests = IncludeTests;
            }
            else {
                options.Minimize = Minimize;
            }
            options.Defines = GetDefines();
            options.References = GetReferences();
            options.Sources = GetSources(_sources);
            options.Resources = GetResources(_resources);
            if (_template != null) {
                options.TemplateFile = new TaskItemInputStreamSource(_template, "Template");
            }
            if (_docCommentFile != null) {
                options.DocCommentFile = new TaskItemInputStreamSource(_docCommentFile, "DocComment");
            }

            ITaskItem scriptTaskItem = new TaskItem(OutputPath);
            options.ScriptFile = new TaskItemOutputStreamSource(scriptTaskItem);

            string errorMessage = String.Empty;
            if (options.Validate(out errorMessage) == false) {
                Log.LogError(errorMessage);
                return false;
            }

            ScriptCompiler compiler = new ScriptCompiler(this);
            compiler.Compile(options);
            if (_hasErrors == false) {
                _script = scriptTaskItem;

                string projectName = (_projectPath != null) ? Path.GetFileNameWithoutExtension(_projectPath) : String.Empty;
                string scriptFileName = Path.GetFileName(scriptTaskItem.ItemSpec);
                string scriptPath = Path.GetFullPath(scriptTaskItem.ItemSpec);

                Log.LogMessage(MessageImportance.High, "{0} -> {1} ({2})", projectName, scriptFileName, scriptPath);
            }
            else {
                return false;
            }

            return true;
        }
 /// <summary>
 /// Allows vetoing of continued compilation after the entire AST conversion process finishes
 /// </summary>
 /// <remarks>
 /// Once the script is turned completely into an AST, including import
 /// and override handling, this function allows a listener to exit
 /// the compilation process.
 ///</remarks>
 /// <param name="compiler">A reference to the compiler</param>
 /// <param name="nodes"></param>
 /// <returns>True continues compilation, false aborts</returns>
 public virtual bool PostConversion(ScriptCompiler compiler, IList <AbstractNode> nodes)
 {
     return(true);
 }
 /// <summary>
 /// Allows for responding to and overriding behavior before a CST is translated into an AST
 /// </summary>
 /// <param name="compiler">A reference to the compiler</param>
 /// <param name="nodes"></param>
 public virtual void PreConversion(ScriptCompiler compiler, IList <ConcreteNode> nodes)
 {
 }
 /// <summary>
 /// Returns the concrete node list from the given file
 /// </summary>
 /// <param name="compiler">A reference to the compiler</param>
 /// <param name="name"></param>
 /// <returns></returns>
 public virtual IList <ConcreteNode> ImportFile(ScriptCompiler compiler, String name)
 {
     return(null);
 }
 /// <summary>
 /// Called when an event occurs during translation, return true if handled
 /// </summary>
 /// <remarks>
 /// This function is called from the translators when an event occurs that
 /// that can be responded to. Often this is overriding names, or it can be a request for
 ///	custom resource creation.
 /// </remarks>
 /// <param name="compiler">A reference to the compiler</param>
 /// <param name="evt">The event object holding information about the event to be processed</param>
 /// <param name="retVal">A possible return value from handlers</param>
 /// <returns>True if the handler processed the event</returns>
 public virtual bool HandleEvent(ScriptCompiler compiler, ref ScriptCompilerEvent evt, out object retVal)
 {
     retVal = null;
     return(false);
 }
        public bool Execute()
        {
            _output = new CompilationOutput(_test.TestContext.TestName);

            _options.References = _references;
            _options.Sources = _sources.Cast<IStreamSource>().ToList();
            _options.Resources = _resources.Cast<IStreamSource>().ToList();
            _options.DocCommentFile = _comments;
            _options.ScriptFile = _output;
            _options.IncludeResolver = _includeResolver;

            ScriptCompiler compiler = new ScriptCompiler(this);
            return compiler.Compile(_options);
        }
Exemple #15
0
        public static void Invoke(Mobile from, Point3D start, Point3D end, string[] args, List <Container> packs, bool outline, bool mapAvg)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("{0} {1} building ", from.AccessLevel, CommandLogging.Format(from));

            if (start == end)
            {
                sb.AppendFormat("at {0} in {1}", start, from.Map);
            }
            else
            {
                sb.AppendFormat("from {0} to {1} in {2}", start, end, from.Map);
            }

            sb.Append(":");

            for (int i = 0; i < args.Length; ++i)
            {
                sb.AppendFormat(" \"{0}\"", args[i]);
            }

            CommandLogging.WriteLine(from, sb.ToString());

            string name = args[0];

            FixArgs(ref args);

            string[,] props = null;

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "set"))
                {
                    int remains = args.Length - i - 1;

                    if (remains >= 2)
                    {
                        props = new string[remains / 2, 2];

                        remains /= 2;

                        for (int j = 0; j < remains; ++j)
                        {
                            props[j, 0] = args[i + (j * 2) + 1];
                            props[j, 1] = args[i + (j * 2) + 2];
                        }

                        FixSetString(ref args, i);
                    }

                    break;
                }
            }

            Type type = ScriptCompiler.FindTypeByName(name);

            if (!IsEntity(type))
            {
                from.SendMessage("No type with that name was found.");
                return;
            }

            DateTime time = DateTime.Now;

            int built = BuildObjects(from, type, start, end, args, props, packs, outline, mapAvg);

            if (built > 0)
            {
                from.SendMessage("{0} object{1} generated in {2:F1} seconds.", built, built != 1 ? "s" : "", (DateTime.Now - time).TotalSeconds);
            }
            else
            {
                SendUsage(type, from);
            }
        }
 /// <summary>
 /// Called when an error occurred
 /// </summary>
 /// <param name="compiler">A reference to the compiler</param>
 /// <param name="err"></param>
 public virtual void HandleError(ScriptCompiler compiler, ScriptCompiler.CompileError err)
 {
 }
Exemple #17
0
            /// <see cref="Translator.Translate"/>
            public override void Translate(ScriptCompiler compiler, AbstractNode node)
            {
                var obj = (ObjectAbstractNode)node;

                // Must have a type as the first value
                if (obj.Values.Count == 0)
                {
                    compiler.AddError(CompileErrorCode.StringExpected, obj.File, obj.Line);
                    return;
                }

                var type = string.Empty;

                if (!getString(obj.Values[0], out type))
                {
                    compiler.AddError(CompileErrorCode.InvalidParameters, obj.File, obj.Line);
                    return;
                }

                var system = (ParticleSystem)obj.Parent.Context;

                this._Affector = system.AddAffector(type);

                foreach (var i in obj.Children)
                {
                    if (i is PropertyAbstractNode)
                    {
                        var prop  = (PropertyAbstractNode)i;
                        var value = string.Empty;

                        // Glob the values together
                        foreach (var it in prop.Values)
                        {
                            if (it is AtomAbstractNode)
                            {
                                if (string.IsNullOrEmpty(value))
                                {
                                    value = ((AtomAbstractNode)it).Value;
                                }
                                else
                                {
                                    value = value + " " + ((AtomAbstractNode)it).Value;
                                }
                            }
                            else
                            {
                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line);
                                break;
                            }
                        }

                        if (!this._Affector.SetParam(prop.Name, value))
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line);
                        }
                    }
                    else
                    {
                        processNode(compiler, i);
                    }
                }
            }
        private bool Compile(string name, IEnumerable<ITaskItem> sourceItems, IEnumerable<ITaskItem> resourceItems, string locale)
        {
            ITaskItem scriptTaskItem;

            CompilerOptions debugOptions =
                CreateOptions(name, sourceItems, resourceItems, locale,
                              /* debug */ true, /* includeTests */ false, /* minimize */ false,
                              out scriptTaskItem);

            string errorMessage = String.Empty;
            if (debugOptions.Validate(out errorMessage) == false) {
                Log.LogError(errorMessage);
                return false;
            }

            ScriptCompiler debugCompiler = new ScriptCompiler(this);
            debugCompiler.Compile(debugOptions);
            if (_hasErrors == false) {
                // Only copy references once (when building language neutral scripts)
                bool copyReferences = String.IsNullOrEmpty(locale) && CopyReferences;

                OnScriptFileGenerated(scriptTaskItem, debugOptions, copyReferences);
                if (_hasErrors) {
                    return false;
                }
            }
            else {
                return false;
            }

            if (debugOptions.HasTestTypes) {
                CompilerOptions testOptions =
                    CreateOptions(name, sourceItems, resourceItems, locale,
                                  /* debug */ true, /* includeTests */ true, /* minimize */ false,
                                  out scriptTaskItem);
                ScriptCompiler testCompiler = new ScriptCompiler(this);
                testCompiler.Compile(testOptions);
                if (_hasErrors == false) {
                    OnScriptFileGenerated(scriptTaskItem, testOptions, /* copyReferences */ false);
                }
                else {
                    return false;
                }
            }

            CompilerOptions releaseOptions =
                CreateOptions(name, sourceItems, resourceItems, locale,
                              /* debug */ false, /* includeTests */ false, /* minimize */ true,
                              out scriptTaskItem);
            ScriptCompiler releaseCompiler = new ScriptCompiler(this);
            releaseCompiler.Compile(releaseOptions);
            if (_hasErrors == false) {
                OnScriptFileGenerated(scriptTaskItem, releaseOptions, /* copyReferences */ false);
            }
            else {
                return false;
            }

            return true;
        }
Exemple #19
0
        public static void FindItemByType_OnCommand(CommandEventArgs e)
        {
            try
            {
                if (e == null || e.Mobile == null || e.Mobile is PlayerMobile == false)
                {
                    return;
                }

                string name = null;

                if (e.Length >= 1)
                {
                    name = e.GetString(0);

                    // if you are a GM the world needs to be in 'Build' mode to access this comand
                    if (e.Mobile.AccessLevel < AccessLevel.Administrator && Core.Building == false)
                    {
                        e.Mobile.SendMessage("The server must be in build mode for you to access this command.");
                        return;
                    }

                    PlayerMobile pm     = e.Mobile as PlayerMobile;
                    LogHelper    Logger = new LogHelper("FindNPCResourceByType.log", e.Mobile, false);

                    // reset jump table
                    pm.JumpIndex = 0;
                    pm.JumpList  = new ArrayList();
                    Type tx = ScriptCompiler.FindTypeByName(name);

                    if (tx != null)
                    {
                        foreach (Mobile mob in World.Mobiles.Values)
                        {
                            if (mob is BaseVendor == false)
                            {
                                continue;
                            }

                            BaseVendor vendor = mob as BaseVendor;

                            if (vendor.Inventory == null || vendor.Inventory.Count == 0)
                            {
                                continue;
                            }

                            foreach (object ox in vendor.Inventory)
                            {
                                if (ox is SBInfo == false)
                                {
                                    continue;
                                }

                                SBInfo sbi = ox as SBInfo;

                                if (sbi.BuyInfo == null || sbi.BuyInfo.Count == 0)
                                {
                                    continue;
                                }

                                ArrayList bi = sbi.BuyInfo;

                                foreach (GenericBuyInfo gbi in bi)
                                {
                                    if (tx.IsAssignableFrom(gbi.Type))
                                    {
                                        pm.JumpList.Add(vendor);
                                        Logger.Log(LogType.Mobile, vendor);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        e.Mobile.SendMessage("{0} is not a recognized type.", name);
                    }
                    Logger.Finish();
                }
                else
                {
                    e.Mobile.SendMessage("Format: FindNPCResourceByType <type>");
                }
            }
            catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }
        }
            protected IMohidSim LoadUserInterface(CmdArgs args)
            {
                try
                {
                   FileName interfaceName;
                   data.sim.PreProcessing = OnPreProcessing;

                   if (args.HasParameter("script"))
                  interfaceName = new FileName(args.Parameters["script"]);
                   else
                  return null;

                   if (interfaceName.Extension.ToLower() == "dll") //it's a library
                   {
                  if (!args.HasParameter("class"))
                     return null;

                  string class_name = args.Parameter("class");

                  Assembly ass = Assembly.LoadFrom(interfaceName.FullPath);
                  data.userInterface = (IMohidSim)Activator.CreateInstance(ass.GetType("Mohid." + class_name));
                  return data.userInterface;
                   }
                   else //it's a script
                   {
                  ScriptCompiler sc = new ScriptCompiler();
                  Assembly ass = sc.Compile(interfaceName);
                  data.userInterface = (IMohidSim)sc.FindScriptInterface("IMohidSim", ass);
                  return data.userInterface;
                   }
                }
                catch (Exception ex)
                {
                   throw new Exception("MohidRunEngine.LoadUserInterface", ex);
                }
            }
            public static void TranslateProgramParameters(ScriptCompiler compiler, GpuProgramParameters parameters,
                                                          ObjectAbstractNode obj)
            {
                var animParametricsCount = 0;

                foreach (var i in obj.Children)
                {
                    if (!(i is PropertyAbstractNode))
                    {
                        continue;
                    }

                    var prop = (PropertyAbstractNode)i;
                    switch ((Keywords)prop.Id)
                    {
                        #region ID_SHARED_PARAMS_REF

                    case Keywords.ID_SHARED_PARAMS_REF:
                    {
                        if (prop.Values.Count != 1)
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                              "shared_params_ref requires a single parameter");
                            continue;
                        }

                        var i0 = getNodeAt(prop.Values, 0);
                        if (!(i0 is AtomAbstractNode))
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                              "shared parameter set name expected");
                            continue;
                        }
                        var atom0 = (AtomAbstractNode)i0;

                        try
                        {
                            parameters.AddSharedParameters(atom0.Value);
                        }
                        catch (AxiomException e)
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, e.Message);
                        }
                    }
                    break;

                        #endregion ID_SHARED_PARAMS_REF

                        #region ID_PARAM_INDEXED || ID_PARAM_NAMED

                    case Keywords.ID_PARAM_INDEXED:
                    case Keywords.ID_PARAM_NAMED:
                    {
                        if (prop.Values.Count >= 3)
                        {
                            var named = (prop.Id == (uint)Keywords.ID_PARAM_NAMED);
                            var i0    = getNodeAt(prop.Values, 0);
                            var i1    = getNodeAt(prop.Values, 1);
                            var k     = getNodeAt(prop.Values, 2);

                            if (!(i0 is AtomAbstractNode) || !(i1 is AtomAbstractNode))
                            {
                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                  "name or index and parameter type expected");
                                return;
                            }

                            var atom0 = (AtomAbstractNode)i0;
                            var atom1 = (AtomAbstractNode)i1;
                            if (!named && !atom0.IsNumber)
                            {
                                compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line, "parameter index expected");
                                return;
                            }

                            var name  = string.Empty;
                            var index = 0;
                            // Assign the name/index
                            if (named)
                            {
                                name = atom0.Value;
                            }
                            else
                            {
                                index = (int)atom0.Number;
                            }

                            // Determine the type
                            if (atom1.Value == "matrix4x4")
                            {
                                Matrix4 m;
                                if (getMatrix4(prop.Values, 2, out m))
                                {
                                    try
                                    {
                                        if (named)
                                        {
                                            parameters.SetNamedConstant(name, m);
                                        }
                                        else
                                        {
                                            parameters.SetConstant(index, m);
                                        }
                                    }
                                    catch
                                    {
                                        compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                          "setting matrix4x4 parameter failed");
                                    }
                                }
                                else
                                {
                                    compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line, "incorrect matrix4x4 declaration");
                                }
                            }
                            else
                            {
                                // Find the number of parameters
                                var isValid = true;
                                var type    = GpuProgramParameters.ElementType.Real;
                                var count   = 0;
                                if (atom1.Value.Contains("float"))
                                {
                                    type = GpuProgramParameters.ElementType.Real;
                                    if (atom1.Value.Length >= 6)
                                    {
                                        count = int.Parse(atom1.Value.Substring(5));
                                    }
                                    else
                                    {
                                        count = 1;
                                    }
                                }
                                else if (atom1.Value.Contains("int"))
                                {
                                    type = GpuProgramParameters.ElementType.Int;
                                    if (atom1.Value.Length >= 4)
                                    {
                                        count = int.Parse(atom1.Value.Substring(3));
                                    }
                                    else
                                    {
                                        count = 1;
                                    }
                                }
                                else
                                {
                                    compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                      "incorrect type specified; only variants of int and float allowed");
                                    isValid = false;
                                }

                                if (isValid)
                                {
                                    // First, clear out any offending auto constants
                                    if (named)
                                    {
                                        parameters.ClearNamedAutoConstant(name);
                                    }
                                    else
                                    {
                                        parameters.ClearAutoConstant(index);
                                    }

                                    var roundedCount = count % 4 != 0 ? count + 4 - (count % 4) : count;
                                    if (type == GpuProgramParameters.ElementType.Int)
                                    {
                                        var vals = new int[roundedCount];
                                        if (getInts(prop.Values, 2, out vals, roundedCount))
                                        {
                                            try
                                            {
                                                if (named)
                                                {
                                                    parameters.SetNamedConstant(name, vals, count, 1);
                                                }
                                                else
                                                {
                                                    parameters.SetConstant(index, vals, roundedCount / 4);
                                                }
                                            }
                                            catch
                                            {
                                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                            }
                                        }
                                        else
                                        {
                                            compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line,
                                                              "incorrect integer constant declaration");
                                        }
                                    }
                                    else
                                    {
                                        var vals = new float[roundedCount];
                                        if (getFloats(prop.Values, 2, out vals, roundedCount))
                                        {
                                            try
                                            {
                                                if (named)
                                                {
                                                    parameters.SetNamedConstant(name, vals, count, 1);
                                                }
                                                else
                                                {
                                                    parameters.SetConstant(index, vals, roundedCount / 4);
                                                }
                                            }
                                            catch
                                            {
                                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                            }
                                        }
                                        else
                                        {
                                            compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line,
                                                              "incorrect float constant declaration");
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                              "param_named and param_indexed properties requires at least 3 arguments");
                        }
                    }
                    break;

                        #endregion ID_PARAM_INDEXED || ID_PARAM_NAMED

                        #region ID_PARAM_INDEXED_AUTO || ID_PARAM_NAMED_AUTO

                    case Keywords.ID_PARAM_INDEXED_AUTO:
                    case Keywords.ID_PARAM_NAMED_AUTO:
                    {
                        var named = (prop.Id == (uint)Keywords.ID_PARAM_NAMED_AUTO);
                        var name  = string.Empty;
                        var index = 0;

                        if (prop.Values.Count >= 2)
                        {
                            var i0 = getNodeAt(prop.Values, 0);
                            var i1 = getNodeAt(prop.Values, 1);
                            var i2 = getNodeAt(prop.Values, 2);
                            var i3 = getNodeAt(prop.Values, 3);

                            if (!(i0 is AtomAbstractNode) || !(i1 is AtomAbstractNode))
                            {
                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                  "name or index and auto constant type expected");
                                return;
                            }
                            var atom0 = (AtomAbstractNode)i0;
                            var atom1 = (AtomAbstractNode)i1;

                            if (!named && !atom0.IsNumber)
                            {
                                compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line, "parameter index expected");
                                return;
                            }

                            if (named)
                            {
                                name = atom0.Value;
                            }
                            else
                            {
                                index = int.Parse(atom0.Value);
                            }

                            // Look up the auto constant
                            atom1.Value = atom1.Value.ToLower();

                            GpuProgramParameters.AutoConstantDefinition def;
                            var defFound = GpuProgramParameters.GetAutoConstantDefinition(atom1.Value, out def);

                            if (defFound)
                            {
                                switch (def.DataType)
                                {
                                    #region None

                                case GpuProgramParameters.AutoConstantDataType.None:
                                    // Set the auto constant
                                    try
                                    {
                                        if (named)
                                        {
                                            parameters.SetNamedAutoConstant(name, def.AutoConstantType);
                                        }
                                        else
                                        {
                                            parameters.SetAutoConstant(index, def.AutoConstantType);
                                        }
                                    }
                                    catch
                                    {
                                        compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                    }
                                    break;

                                    #endregion None

                                    #region Int

                                case GpuProgramParameters.AutoConstantDataType.Int:
                                    if (def.AutoConstantType == GpuProgramParameters.AutoConstantType.AnimationParametric)
                                    {
                                        try
                                        {
                                            if (named)
                                            {
                                                parameters.SetNamedAutoConstant(name, def.AutoConstantType, animParametricsCount++);
                                            }
                                            else
                                            {
                                                parameters.SetAutoConstant(index, def.AutoConstantType, animParametricsCount++);
                                            }
                                        }
                                        catch
                                        {
                                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                        }
                                    }
                                    else
                                    {
                                        // Only certain texture projection auto params will assume 0
                                        // Otherwise we will expect that 3rd parameter
                                        if (i2 == null)
                                        {
                                            if (def.AutoConstantType == GpuProgramParameters.AutoConstantType.TextureViewProjMatrix ||
                                                def.AutoConstantType == GpuProgramParameters.AutoConstantType.TextureWorldViewProjMatrix ||
                                                def.AutoConstantType == GpuProgramParameters.AutoConstantType.SpotLightViewProjMatrix ||
                                                def.AutoConstantType == GpuProgramParameters.AutoConstantType.SpotLightWorldViewProjMatrix)
                                            {
                                                try
                                                {
                                                    if (named)
                                                    {
                                                        parameters.SetNamedAutoConstant(name, def.AutoConstantType, 0);
                                                    }
                                                    else
                                                    {
                                                        parameters.SetAutoConstant(index, def.AutoConstantType, 0);
                                                    }
                                                }
                                                catch
                                                {
                                                    compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                                }
                                            }
                                            else
                                            {
                                                compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line,
                                                                  "extra parameters required by constant definition " + atom1.Value);
                                            }
                                        }
                                        else
                                        {
                                            var success   = false;
                                            var extraInfo = 0;
                                            if (i3 == null)
                                            {
                                                // Handle only one extra value
                                                if (getInt(i2, out extraInfo))
                                                {
                                                    success = true;
                                                }
                                            }
                                            else
                                            {
                                                // Handle two extra values
                                                var extraInfo1 = 0;
                                                var extraInfo2 = 0;
                                                if (getInt(i2, out extraInfo1) && getInt(i3, out extraInfo2))
                                                {
                                                    extraInfo = extraInfo1 | (extraInfo2 << 16);
                                                    success   = true;
                                                }
                                            }

                                            if (success)
                                            {
                                                try
                                                {
                                                    if (named)
                                                    {
                                                        parameters.SetNamedAutoConstant(name, def.AutoConstantType, extraInfo);
                                                    }
                                                    else
                                                    {
                                                        parameters.SetAutoConstant(index, def.AutoConstantType, extraInfo);
                                                    }
                                                }
                                                catch
                                                {
                                                    compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                                }
                                            }
                                            else
                                            {
                                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                                  "invalid auto constant extra info parameter");
                                            }
                                        }
                                    }
                                    break;

                                    #endregion Int

                                    #region Real

                                case GpuProgramParameters.AutoConstantDataType.Real:
                                    if (def.AutoConstantType == GpuProgramParameters.AutoConstantType.Time ||
                                        def.AutoConstantType == GpuProgramParameters.AutoConstantType.FrameTime)
                                    {
                                        Real f = 1.0f;
                                        if (i2 != null)
                                        {
                                            getReal(i2, out f);
                                        }

                                        try
                                        {
                                            if (named)
                                            {
                                                parameters.SetNamedAutoConstantReal(name, def.AutoConstantType, f);
                                            }
                                            else
                                            {
                                                parameters.SetAutoConstantReal(index, def.AutoConstantType, f);
                                            }
                                        }
                                        catch
                                        {
                                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                        }
                                    }
                                    else
                                    {
                                        if (i2 != null)
                                        {
                                            Real extraInfo = 0.0f;
                                            if (getReal(i2, out extraInfo))
                                            {
                                                try
                                                {
                                                    if (named)
                                                    {
                                                        parameters.SetNamedAutoConstantReal(name, def.AutoConstantType, extraInfo);
                                                    }
                                                    else
                                                    {
                                                        parameters.SetAutoConstantReal(index, def.AutoConstantType, extraInfo);
                                                    }
                                                }
                                                catch
                                                {
                                                    compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                                }
                                            }
                                            else
                                            {
                                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                                  "incorrect float argument definition in extra parameters");
                                            }
                                        }
                                        else
                                        {
                                            compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line,
                                                              "extra parameters required by constant definition " + atom1.Value);
                                        }
                                    }
                                    break;

                                    #endregion Real
                                }
                            }
                            else
                            {
                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line);
                            }
                        }
                        else
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line);
                        }
                    }
                    break;

                        #endregion ID_PARAM_INDEXED_AUTO || ID_PARAM_NAMED_AUTO

                    default:
                        compiler.AddError(CompileErrorCode.UnexpectedToken, prop.File, prop.Line,
                                          "token \"" + prop.Name + "\" is not recognized");
                        break;
                    }
                }
            }
Exemple #22
0
        public static void Find_OnCommand(CommandEventArgs e)
        {
            Mobile        from    = e.Mobile;
            string        arg     = "";
            Type          type    = null;
            List <Item>   items   = new List <Item>();
            List <Mobile> mobiles = new List <Mobile>();

            if (e.Arguments.Length > 0)
            {
                arg = e.Arguments[0];

                type = ScriptCompiler.FindTypeByName(arg);
            }

            if (type != null)
            {
                if (type.IsSubclassOf(typeof(Item)) || type.Equals(typeof(Item)))
                {
                    Dictionary <Serial, Item> .Enumerator its = World.Items.GetEnumerator();
                    List <Item> alItems = new List <Item>();
                    while (its.MoveNext())
                    {
                        alItems.Add(its.Current.Value);
                    }
                    its.Dispose();

                    for (int k = 0; k < alItems.Count; ++k)
                    {
                        Item it = alItems[k] as Item;

                        if (it.GetType().Equals(type))
                        {
                            items.Add(it);
                        }
                    }
                }
                else if (type.IsSubclassOf(typeof(Mobile)) || type.Equals(typeof(Mobile)))
                {
                    Dictionary <Serial, Mobile> .Enumerator mobs = World.Mobiles.GetEnumerator();
                    List <Mobile> alMobiles = new List <Mobile>();
                    while (mobs.MoveNext())
                    {
                        alMobiles.Add(mobs.Current.Value);
                    }
                    mobs.Dispose();

                    for (int k = 0; k < alMobiles.Count; ++k)
                    {
                        Mobile mob = alMobiles[k] as Mobile;

                        if (mob.GetType().Equals(type))
                        {
                            mobiles.Add(mob);
                        }
                    }
                }

                if (items.Count > 0)
                {
                    from.SendGump(new FindGump(from, items, 0, arg, e));
                }
                else if (mobiles.Count > 0)
                {
                    from.SendGump(new FindGump(from, mobiles, 0, arg, e));
                }
            }
            else
            {
                from.SendMessage(arg + " n'est pas un type valide.");
            }
        }
            protected void _translateGpuProgram(ScriptCompiler compiler, ObjectAbstractNode obj)
            {
                var          customParameters = new NameValuePairList();
                string       syntax = string.Empty, source = string.Empty;
                AbstractNode parameters = null;

                foreach (var i in obj.Children)
                {
                    if (i is PropertyAbstractNode)
                    {
                        var prop = (PropertyAbstractNode)i;
                        if (prop.Id == (uint)Keywords.ID_SOURCE)
                        {
                            if (prop.Values.Count != 0)
                            {
                                if (prop.Values[0] is AtomAbstractNode)
                                {
                                    source = ((AtomAbstractNode)prop.Values[0]).Value;
                                }
                                else
                                {
                                    compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "source file expected");
                                }
                            }
                            else
                            {
                                compiler.AddError(CompileErrorCode.StringExpected, prop.File, prop.Line, "source file expected");
                            }
                        }
                        else if (prop.Id == (uint)Keywords.ID_SYNTAX)
                        {
                            if (prop.Values.Count != 0)
                            {
                                if (prop.Values[0] is AtomAbstractNode)
                                {
                                    syntax = ((AtomAbstractNode)prop.Values[0]).Value;
                                }
                                else
                                {
                                    compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "syntax string expected");
                                }
                            }
                            else
                            {
                                compiler.AddError(CompileErrorCode.StringExpected, prop.File, prop.Line, "syntax string expected");
                            }
                        }
                        else
                        {
                            string name = prop.Name, value = string.Empty;
                            var    first = true;
                            foreach (var it in prop.Values)
                            {
                                if (it is AtomAbstractNode)
                                {
                                    if (!first)
                                    {
                                        value += " ";
                                    }
                                    else
                                    {
                                        first = false;
                                    }

                                    value += ((AtomAbstractNode)it).Value;
                                }
                            }
                            customParameters.Add(name, value);
                        }
                    }
                    else if (i is ObjectAbstractNode)
                    {
                        if (((ObjectAbstractNode)i).Id == (uint)Keywords.ID_DEFAULT_PARAMS)
                        {
                            parameters = i;
                        }
                        else
                        {
                            processNode(compiler, i);
                        }
                    }
                }

                if (!GpuProgramManager.Instance.IsSyntaxSupported(syntax))
                {
                    compiler.AddError(CompileErrorCode.UnsupportedByRenderSystem, obj.File, obj.Line);
                    //Register the unsupported program so that materials that use it know that
                    //it exists but is unsupported
                    var unsupportedProg = GpuProgramManager.Instance.Create(obj.Name, compiler.ResourceGroup,
                                                                            _translateIDToGpuProgramType(obj.Id), syntax);

                    return;
                }

                // Allocate the program
                object     progObj;
                GpuProgram prog = null;

                ScriptCompilerEvent evt = new CreateGpuProgramScriptCompilerEvent(obj.File, obj.Name, compiler.ResourceGroup,
                                                                                  source, syntax,
                                                                                  _translateIDToGpuProgramType(obj.Id));

                var processed = compiler._fireEvent(ref evt, out progObj);

                if (!processed)
                {
                    prog =
                        (GpuProgram)
                        GpuProgramManager.Instance.CreateProgram(obj.Name, compiler.ResourceGroup, source,
                                                                 _translateIDToGpuProgramType(obj.Id), syntax);
                }
                else
                {
                    prog = (GpuProgram)progObj;
                }

                // Check that allocation worked
                if (prog == null)
                {
                    compiler.AddError(CompileErrorCode.ObjectAllocationError, obj.File, obj.Line,
                                      "gpu program \"" + obj.Name + "\" could not be created");
                    return;
                }

                obj.Context = prog;

                prog.IsMorphAnimationIncluded     = false;
                prog.PoseAnimationCount           = 0;
                prog.IsSkeletalAnimationIncluded  = false;
                prog.IsVertexTextureFetchRequired = false;
                prog.Origin = obj.File;

                // Set the custom parameters
                prog.SetParameters(customParameters);

                // Set up default parameters
                if (prog.IsSupported && parameters != null)
                {
                    var ptr = prog.DefaultParameters;
                    GpuProgramTranslator.TranslateProgramParameters(compiler, ptr, (ObjectAbstractNode)parameters);
                }
            }
Exemple #24
0
        public static void Load()
        {
            if (!Directory.Exists("Saves/ACC"))
            {
                return;
            }

            string   filename  = "acc.sav";
            string   path      = @"Saves/ACC/";
            string   pathNfile = path + filename;
            DateTime start     = DateTime.Now;

            Console.WriteLine();
            Console.WriteLine("----------");
            Console.WriteLine("Loading ACC...");

            try
            {
                using (FileStream m_FileStream = new FileStream(pathNfile, FileMode.Open, FileAccess.Read))
                {
                    BinaryReader     m_BinaryReader = new BinaryReader(m_FileStream);
                    BinaryFileReader reader         = new BinaryFileReader(m_BinaryReader);

                    if (m_RegSystems == null)
                    {
                        m_RegSystems = new Dictionary <string, bool>();
                    }

                    int Count = reader.ReadInt();
                    for (int i = 0; i < Count; i++)
                    {
                        string system  = reader.ReadString();
                        Type   t       = ScriptCompiler.FindTypeByFullName(system);
                        bool   enabled = reader.ReadBool();

                        if (t != null)
                        {
                            m_RegSystems[system] = enabled;

                            if (m_RegSystems[system])
                            {
                                ACCSystem sys = (ACCSystem)Activator.CreateInstance(t);
                                if (sys != null)
                                {
                                    sys.StartLoad(path);
                                }
                            }
                        }
                    }

                    reader.Close();
                    m_FileStream.Close();
                }

                Console.WriteLine("Done in {0:F1} seconds.", (DateTime.Now - start).TotalSeconds);
                Console.WriteLine("----------");
                Console.WriteLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed. Exception: " + e);
            }
        }
            protected void _translateUnifiedGpuProgram(ScriptCompiler compiler, ObjectAbstractNode obj)
            {
                var          customParameters = new NameValuePairList();
                AbstractNode parameters       = null;

                foreach (var i in obj.Children)
                {
                    if (i is PropertyAbstractNode)
                    {
                        var prop = (PropertyAbstractNode)i;
                        if (prop.Name == "delegate")
                        {
                            var value = string.Empty;
                            if (prop.Values.Count != 0 && prop.Values[0] is AtomAbstractNode)
                            {
                                value = ((AtomAbstractNode)prop.Values[0]).Value;
                            }

                            ScriptCompilerEvent evt =
                                new ProcessResourceNameScriptCompilerEvent(ProcessResourceNameScriptCompilerEvent.ResourceType.GpuProgram,
                                                                           value);

                            compiler._fireEvent(ref evt);
                            customParameters["delegate"] = ((ProcessResourceNameScriptCompilerEvent)evt).Name;
                        }
                        else
                        {
                            var name  = prop.Name;
                            var value = string.Empty;
                            var first = true;
                            foreach (var it in prop.Values)
                            {
                                if (it is AtomAbstractNode)
                                {
                                    if (!first)
                                    {
                                        value += " ";
                                    }
                                    else
                                    {
                                        first = false;
                                    }
                                    value += ((AtomAbstractNode)it).Value;
                                }
                            }
                            customParameters.Add(name, value);
                        }
                    }
                    else if (i is ObjectAbstractNode)
                    {
                        if (((ObjectAbstractNode)i).Id == (uint)Keywords.ID_DEFAULT_PARAMS)
                        {
                            parameters = i;
                        }
                        else
                        {
                            processNode(compiler, i);
                        }
                    }
                }

                // Allocate the program
                Object progObj;
                HighLevelGpuProgram prog = null;

                ScriptCompilerEvent evnt = new CreateHighLevelGpuProgramScriptCompilerEvent(obj.File, obj.Name,
                                                                                            compiler.ResourceGroup, string.Empty,
                                                                                            "unified",
                                                                                            _translateIDToGpuProgramType(obj.Id));

                var processed = compiler._fireEvent(ref evnt, out progObj);

                if (!processed)
                {
                    prog =
                        (HighLevelGpuProgram)
                        (HighLevelGpuProgramManager.Instance.CreateProgram(obj.Name, compiler.ResourceGroup, "unified",
                                                                           _translateIDToGpuProgramType(obj.Id)));
                }
                else
                {
                    prog = (HighLevelGpuProgram)progObj;
                }

                // Check that allocation worked
                if (prog == null)
                {
                    compiler.AddError(CompileErrorCode.ObjectAllocationError, obj.File, obj.Line,
                                      "gpu program \"" + obj.Name + "\" could not be created");
                    return;
                }

                obj.Context = prog;

                prog.IsMorphAnimationIncluded     = false;
                prog.PoseAnimationCount           = 0;
                prog.IsSkeletalAnimationIncluded  = false;
                prog.IsVertexTextureFetchRequired = false;
                prog.Origin = obj.File;

                // Set the custom parameters
                prog.SetParameters(customParameters);

                // Set up default parameters
                if (prog.IsSupported && parameters != null)
                {
                    var ptr = prog.DefaultParameters;
                    GpuProgramTranslator.TranslateProgramParameters(compiler, ptr, (ObjectAbstractNode)parameters);
                }
            }
Exemple #26
0
        private bool Compile(string name, IEnumerable <ITaskItem> sourceItems, IEnumerable <ITaskItem> resourceItems, string locale)
        {
            ITaskItem scriptTaskItem;

            CompilerOptions debugOptions =
                CreateOptions(name, sourceItems, resourceItems, locale,
                              /* debug */ true, /* includeTests */ false, /* minimize */ false,
                              out scriptTaskItem);

            string errorMessage = String.Empty;

            if (debugOptions.Validate(out errorMessage) == false)
            {
                Log.LogError(errorMessage);
                return(false);
            }

            ScriptCompiler debugCompiler = new ScriptCompiler(this);

            debugCompiler.Compile(debugOptions);
            if (_hasErrors == false)
            {
                // Only copy references once (when building language neutral scripts)
                bool copyReferences = String.IsNullOrEmpty(locale) && CopyReferences;

                OnScriptFileGenerated(scriptTaskItem, debugOptions, copyReferences);
                if (_hasErrors)
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }

            if (debugOptions.HasTestTypes)
            {
                CompilerOptions testOptions =
                    CreateOptions(name, sourceItems, resourceItems, locale,
                                  /* debug */ true, /* includeTests */ true, /* minimize */ false,
                                  out scriptTaskItem);
                ScriptCompiler testCompiler = new ScriptCompiler(this);
                testCompiler.Compile(testOptions);
                if (_hasErrors == false)
                {
                    OnScriptFileGenerated(scriptTaskItem, testOptions, /* copyReferences */ false);
                }
                else
                {
                    return(false);
                }
            }

            CompilerOptions releaseOptions =
                CreateOptions(name, sourceItems, resourceItems, locale,
                              /* debug */ false, /* includeTests */ false, /* minimize */ true,
                              out scriptTaskItem);
            ScriptCompiler releaseCompiler = new ScriptCompiler(this);

            releaseCompiler.Compile(releaseOptions);
            if (_hasErrors == false)
            {
                OnScriptFileGenerated(scriptTaskItem, releaseOptions, /* copyReferences */ false);
            }
            else
            {
                return(false);
            }

            return(true);
        }
Exemple #27
0
        private void Form1_Load(object sender, EventArgs e)
        {
            taskbar.strip = toolStrip1; //this be a toolstrip reference to class taskbar
            string loc = Path.GetDirectoryName(Application.ExecutablePath);

            lang = new Languages(loc + "\\exec\\languages.xml", 0);
            lang.SetLang(this);
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length > 1)
            {
                AttachConsole(ATTACH_PARENT_PROCESS);
                if (args[1].Equals("-version-switch-from") && args.Length == 3)
                {
                    string version = Assembly.GetExecutingAssembly().GetName().Version.Build.ToString();
                    if (version.Equals(args[2]))
                    {
                        MessageBox.Show("Version switched to is the same as the one you had before the switch.");
                    }
                    else
                    {
                        MessageBox.Show("Version switched: " + args[2] + " => " + version);
                    }
                }
                else
                //automation
                if (args[1].Equals("-dlcinject") || args[1].Equals("-dlcextract") || args[1].Equals("-dlcaddfiles") || args[1].Equals("-dlcremovefiles") || args[1].Equals("-dlcunpack") || args[1].Equals("-dlcunpack-nodebug"))
                {
                    //autostart DLC editor 2 (used by FemShep's Mod Manager 3/3.1+)
                    //saves a little duplicate code
                    dLCEditor2ToolStripMenuItem.PerformClick();
                    return;
                }
                else
                if (args[1].Equals("-toceditorupdate"))
                {
                    //autostart the TOCEditor (used by FemShep's Mod Manager 3)
                    //saves a little duplicate code
                    tOCbinEditorToolStripMenuItem.PerformClick();
                    return;
                }
                if (args[1].Equals("-autotoc"))
                {
                    //autostart the AutoTOC Tool (uses a path) (used by FemShep's Mod Manager 3)
                    //saves a little duplicate code
                    autoTOCToolStripMenuItem.PerformClick();
                    return;
                }
                else
                if (args[1].Equals("-decompresspcc"))
                {
                    //autostart the TOCEditor (used by FemShep's Mod Manager 3.2)
                    //saves a little duplicate code
                    pCCRepackerToolStripMenuItem.PerformClick();
                    return;
                }
                else
                if (args[1].Equals("--help") || args[1].Equals("-h") || args[1].Equals("/?"))
                {
                    String[] version         = Assembly.GetExecutingAssembly().GetName().Version.ToString().Split('.');
                    String   commandLineHelp = "\nME3Explorer r" + version[2] + " Command Line Options\n";
                    commandLineHelp += " -decompresspcc pccPath.pcc decompressedPath.pcc\n";
                    commandLineHelp += "     Automates PCCRepacker to decompress a pcc to the new location.\n\n";
                    commandLineHelp += " -dlcinject DLC.sfar SearchTerm PathToNewFile [SearchTerm2 PathToNewFile2]...\n";
                    commandLineHelp += "     Automates injecting pairs of files into a .sfar file using DLCEditor2. SearchTerm is a value you would type into the searchbox with the first result being the file that will be replaced.\n\n";
                    commandLineHelp += " -dlcextract DLC.sfar SearchTerm ExtractionPath\n";
                    commandLineHelp += "     Automates DLCEditor2 to extract the specified SearchTerm. SearchTerm is a value you would type into the searchbox with the first result being the file that will be extracted. The file is extracted to the specied ExtractionPath.\n\n";
                    commandLineHelp += " -dlcaddfiles DLC.sfar InternalPath NewFile [InternalPath2 NewFile2]...\n";
                    commandLineHelp += "     Automates DLCEditor2 to add the specified new files. InternalPath is the internal path in the SFAR the file NewFile will be placed at.\n\n";
                    commandLineHelp += " -dlcremovefiles DLC.sfar SearchTerm [SearchTerm2]...\n";
                    commandLineHelp += "     Automates removing a file or list of files from a DLC. SearchTerm is a value you would type into the Searchbox with the first result being the file that will be removed.\n\n";
                    commandLineHelp += " -dlcunpack DLC.sfar Unpackpath\n";
                    commandLineHelp += "     Automates unpacking an SFAR file to the specified directory. Shows the debug interface to show progress. To unpack a game DLC for use by the game, unpack to the Mass Effect 3 directory. Unpacking Patch_001.sfar will cause the game to crash at startup.\n\n";
                    commandLineHelp += " -dlcunpack-nodebug DLC.sfar Unpackpath\n";
                    commandLineHelp += "     Same as -dlcunpack but does not show the debugging interface.\n\n";
                    commandLineHelp += " -toceditorupdate PCConsoleTOCFile.bin SearchTerm size\n";
                    commandLineHelp += "     Automates DLCEditor2 to extract the specified SearchTerm. SearchTerm is a value you would type into the searchbox with the first result being the file that will be extracted. The file is extracted to the specied ExtractionPath.\n\n";
                    System.Console.WriteLine(commandLineHelp);
                    Environment.Exit(0);
                    Application.Exit();
                    return;
                }

                string ending = Path.GetExtension(args[1]).ToLower();
                switch (ending)
                {
                case ".pcc":
                    PCCEditor2 editor = new PCCEditor2();
                    editor.MdiParent = this;
                    editor.Show();
                    editor.WindowState = FormWindowState.Maximized;
                    editor.LoadFile(args[1]);
                    break;

                case ".txt":
                    ScriptCompiler sc = new ScriptCompiler();
                    sc.MdiParent = this;
                    sc.rtb1.LoadFile(args[1]);
                    sc.Compile();
                    sc.Show();
                    sc.WindowState = FormWindowState.Maximized;
                    break;

                case ".mod":
                    ModMaker m = new ModMaker();
                    m.Show();
                    string[] s = new string[1];
                    s[0] = args[1];
                    //m.LoadMods(s);
                    m.WindowState = FormWindowState.Maximized;
                    break;
                }
            }

            if (!String.IsNullOrEmpty(Properties.Settings.Default.ME3InstallDir))
            {
                ME3Directory.GamePath(Properties.Settings.Default.ME3InstallDir);
            }
            if (!String.IsNullOrEmpty(Properties.Settings.Default.ME2InstallDir))
            {
                ME2Directory.GamePath(Properties.Settings.Default.ME2InstallDir);
            }
            if (!String.IsNullOrEmpty(Properties.Settings.Default.ME1InstallDir))
            {
                ME1Directory.GamePath(Properties.Settings.Default.ME1InstallDir);
            }

            var vers = Assembly.GetExecutingAssembly().GetName().Version.ToString().Split('.');

            versionToolStripMenuItem.Text += "0110 (r" + vers[2] + ")";
            versionToolStripMenuItem.Tag   = "versionItem";
            menuStrip1.Renderer            = new NoHighlightRenderer();
        }
Exemple #28
0
 private static Type FindType(string name, bool full = false, bool ignoreCase = true)
 {
     return(Type.GetType(name, false, ignoreCase) ??
            (full ? ScriptCompiler.FindTypeByFullName(name, ignoreCase) : ScriptCompiler.FindTypeByName(name, ignoreCase)));
 }
Exemple #29
0
        public override void Deserialize(GenericReader reader)
        {
            base.Deserialize(reader);

            int version = reader.ReadInt();

            switch (version)
            {
            case 7:
            {
                GuardImmune = reader.ReadBool();

                goto case 6;
            }

            case 6:
            {
                m_SpawnRange = reader.ReadInt();

                goto case 5;
            }

            case 5:
            case 4:
            {
                m_WalkingRange = reader.ReadInt();

                goto case 3;
            }

            case 3:
            case 2:
            {
                m_WayPoint = reader.ReadItem() as WayPoint;

                goto case 1;
            }

            case 1:
            {
                m_Group = reader.ReadBool();

                goto case 0;
            }

            case 0:
            {
                m_MinDelay  = reader.ReadTimeSpan();
                m_MaxDelay  = reader.ReadTimeSpan();
                m_MaxCount  = reader.ReadInt();
                m_Team      = reader.ReadInt();
                m_HomeRange = reader.ReadInt();
                m_Running   = reader.ReadBool();

                TimeSpan ts = TimeSpan.Zero;

                if (m_Running)
                {
                    ts = reader.ReadDeltaTime() - DateTime.UtcNow;
                }

                int size = reader.ReadInt();

                m_SpawnObjects = new List <SpawnObject>(size);

                for (int i = 0; i < size; ++i)
                {
                    if (version > 4)
                    {
                        SpawnObject so = new SpawnObject(reader);

                        if (AddSpawnObject(so))
                        {
                            string typeName = ParseType(so.SpawnName);

                            if (ScriptCompiler.FindTypeByName(typeName) == null)
                            {
                                if (m_WarnTimer == null)
                                {
                                    m_WarnTimer = new WarnTimer();
                                }

                                m_WarnTimer.Add(Location, Map, typeName);
                            }
                        }
                    }
                    else
                    {
                        string creatureString = reader.ReadString();

                        AddSpawnObject(new SpawnObject(creatureString));
                        string typeName = ParseType(creatureString);

                        if (ScriptCompiler.FindTypeByName(typeName) == null)
                        {
                            if (m_WarnTimer == null)
                            {
                                m_WarnTimer = new WarnTimer();
                            }

                            m_WarnTimer.Add(Location, Map, typeName);
                        }
                    }
                }

                if (version < 5)
                {
                    int count = reader.ReadInt();
                    for (int i = 0; i < count; ++i)
                    {
                        ISpawnable e = World.FindEntity(reader.ReadInt()) as ISpawnable;

                        if (e != null)
                        {
                            e.Delete();         // lets make this easy
                        }
                    }
                }

                if (m_Running)
                {
                    DoTimer(ts);
                }

                break;
            }
            }

            if (version < 3 && Weight == 0)
            {
                Weight = -1;
            }
        }
Exemple #30
0
        public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
        {
            Mobile from = sender.Mobile;

            string TypeName = string.Empty;
            int    GiveRule = 0;
            int    Access   = 0;

            foreach (int sw in info.Switches)
            {
                switch (sw)
                {
                case (int)Switches.GiveToCharacter:
                {
                    GiveRule = (int)Switches.GiveToCharacter;
                    break;
                }

                case (int)Switches.GiveToAccount:
                {
                    GiveRule = (int)Switches.GiveToAccount;
                    break;
                }

                case (int)Switches.GiveToAccessLevel:
                {
                    GiveRule = (int)Switches.GiveToAccessLevel;
                    break;
                }

                case (int)Switches.Administrator:
                case (int)Switches.GameMaster:
                case (int)Switches.Seer:
                case (int)Switches.Counselor:
                {
                    Access += sw;
                    break;
                }
                }
            }
            if (GiveRule == 0)
            {
                from.SendMessage("You must select the audience rule to receive the item.");
                from.SendGump(new AddToBankGump(GiveRule, Access, TypeName, m_Amount));
                return;
            }
            else if (GiveRule == (int)Switches.GiveToAccessLevel && Access == 0)
            {
                from.SendMessage("You must select the AccessLevel to receive the item.");
                from.SendGump(new AddToBankGump(GiveRule, Access, TypeName, m_Amount));
                return;
            }

            switch (info.ButtonID)
            {
            case (int)Buttons.GiveByTarget:
            {
                from.Target = new AddToBank.DupeTarget(false, m_Amount, GiveRule, Access);
                from.SendMessage("What do you wish to give out?");
                break;
            }

            case (int)Buttons.GiveByType:
            {
                if (info.TextEntries.Length > 0)
                {
                    TypeName = info.TextEntries[0].Text;
                }

                if (TypeName == string.Empty)
                {
                    from.SendMessage("You must specify a type");
                    from.SendGump(new AddToBankGump(GiveRule, Access, TypeName, m_Amount));
                }
                else
                {
                    Type type = ScriptCompiler.FindTypeByName(TypeName, true);
                    if (type == null)
                    {
                        from.SendMessage("{0} is not a valid type", type);
                        from.SendGump(new AddToBankGump(GiveRule, Access, string.Empty, m_Amount));
                        return;
                    }
                    else
                    {
                        object obj = Activator.CreateInstance(type);
                        if (obj is Item)
                        {
                            AddToBank.GiveItem(from, (Item)obj, m_Amount, GiveRule, Access);
                        }
                        else
                        {
                            from.SendMessage("You may only duplicate items.");
                        }
                    }
                }
                break;
            }

            case (int)Buttons.IncAmount:
            {
                from.SendGump(new AddToBankGump(GiveRule, Access, TypeName, ++m_Amount));
                break;
            }

            case (int)Buttons.DecAmount:
            {
                if (m_Amount > 1)
                {
                    m_Amount -= 1;
                }
                else
                {
                    from.SendMessage("You cannot give less than 1 item.");
                }
                from.SendGump(new AddToBankGump(GiveRule, Access, TypeName, m_Amount));
                break;
            }
            }
        }
        public static ObjectConditional Parse(Mobile from, ref string[] args)
        {
            string[] conditionArgs = null;

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "where"))
                {
                    string[] origArgs = args;

                    args = new string[i];

                    for (int j = 0; j < args.Length; ++j)
                    {
                        args[j] = origArgs[j];
                    }

                    conditionArgs = new string[origArgs.Length - i - 1];

                    for (int j = 0; j < conditionArgs.Length; ++j)
                    {
                        conditionArgs[j] = origArgs[i + j + 1];
                    }

                    break;
                }
            }

            if (conditionArgs == null || conditionArgs.Length == 0)
            {
                return(ObjectConditional.Empty);
            }

            int index = 0;

            Type type = ScriptCompiler.FindTypeByName(conditionArgs[index++], true);

            if (type == null)
            {
                throw new Exception(String.Format("No type with that name ({0}) was found.", conditionArgs[0]));
            }

            PropertyInfo[] props = type.GetProperties();

            ArrayList allConditions     = new ArrayList();
            ArrayList currentConditions = null;

            while (index < conditionArgs.Length)
            {
                string cur = conditionArgs[index];

                bool logicalNot = false;

                if (Insensitive.Equals(cur, "not") || cur == "!")
                {
                    logicalNot = true;
                    ++index;

                    if (index >= conditionArgs.Length)
                    {
                        throw new Exception("Improperly formatted object conditional.");
                    }
                }
                else if (Insensitive.Equals(cur, "or") || cur == "||")
                {
                    if (currentConditions != null)
                    {
                        allConditions.Add(currentConditions);
                        currentConditions = null;
                    }

                    ++index;

                    continue;
                }

                string prop = conditionArgs[index++];

                if (index >= conditionArgs.Length)
                {
                    throw new Exception("Improperly formatted object conditional.");
                }

                string oper = conditionArgs[index++];

                if (index >= conditionArgs.Length)
                {
                    throw new Exception("Improperly formatted object conditional.");
                }

                string arg = conditionArgs[index++];

                if (currentConditions == null)
                {
                    currentConditions = new ArrayList();
                }

                currentConditions.Add(new PropertyCondition(from, type, props, prop, oper, arg, logicalNot));
            }

            if (currentConditions != null)
            {
                allConditions.Add(currentConditions);
            }

            PropertyCondition[][] conditions = new PropertyCondition[allConditions.Count][];

            for (int i = 0; i < conditions.Length; ++i)
            {
                conditions[i] = (PropertyCondition[])(((ArrayList)allConditions[i]).ToArray(typeof(PropertyCondition)));
            }

            return(new ObjectConditional(type, conditions));
        }
 public static Type GetType(string name)
 {
     return(ScriptCompiler.FindTypeByName(name));
 }
Exemple #33
0
    static void Main(string[] args)
    {
#if DEBUG
        chdir("../../../");
#endif

        Window window = new Window();
        window.Create("application-02", (int)DisplayWidth, (int)DisplayHeight);

        GraphicsDevice.Instance.Create(window, FullScreen);

        SoundDevice.Instance.Create(window.Handle);

        if (ShowDebugInfo)
        {
            runner  = CommandRunner.Execute();
            monitor = GameSystemMonitor.Execute();
        }

        foreach (var file in Directory.GetFiles("res/mission/", "*.cs"))
        {
            var asm = ScriptCompiler.CompileAssemblyFromFile(new ScriptCompilerParameters()
            {
                BaseClassName      = "Script",
                BatchScriptStyle   = false,
                ClassName          = "Mission",
                GenerateExecutable = false,
                GenerateInMemory   = true,
                PythonScopeStyle   = false,
            }, file);
            Missions.MissionAssemblies.Add(Path.GetFileNameWithoutExtension(file), asm);
        }

        window.Updated += () =>
        {
            update();

            GraphicsDevice.Instance.Clear(ColorCode.Black);
#if true
            LoadingTask loadingTask = SceneManager.TryTransitScene();

            if (loadingTask.Finished)
            {
                Entity.BroadcastMessage(UpdateMessage);

                Entity.BroadcastMessage(RenderMessage);
                Entity.BroadcastMessage(TranslucentRenderMessage);
                Entity.BroadcastMessage(DrawMessage);
            }
            else
            {
                LoadingView.Draw(loadingTask);
            }
#endif
            GraphicsDevice.Instance.Present();

            if (pressed(KeyCode.Escape))
            {
                window.Close();
            }

            Entity.Update();
        };

        try
        {
            initialize();

            //SceneManager.FookScene(new MainScene());
            SceneManager.FookScene(new TitleScene());
            //SceneManager.FookScene(new MissionSelectScene());

            window.Start();
        }
        finally
        {
            Entity.Clear();

            ResourceManager.CleanUp();

            GC.Collect();

            finalize();

            GraphicsDevice.Instance.Dispose();
            SoundDevice.Instance.Dispose();

            if (ShowDebugInfo)
            {
                GameSystemMonitor.Shutdown(monitor);
                CommandRunner.Shutdown(runner);
            }
        }
    }
Exemple #34
0
        public static void ProfileWorld(string type, string opFile)
        {
            try
            {
                ArrayList types = new ArrayList();

                using (BinaryReader bin = new BinaryReader(new FileStream(String.Format("Saves/{0}/{0}.tdb", type), FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    int count = bin.ReadInt32();

                    for (int i = 0; i < count; ++i)
                    {
                        types.Add(ScriptCompiler.FindTypeByFullName(bin.ReadString()));
                    }
                }

                long total = 0;

                Hashtable table = new Hashtable();

                using (BinaryReader bin = new BinaryReader(new FileStream(String.Format("Saves/{0}/{0}.idx", type), FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    int count = bin.ReadInt32();

                    for (int i = 0; i < count; ++i)
                    {
                        int  typeID  = bin.ReadInt32();
                        int  serial  = bin.ReadInt32();
                        long pos     = bin.ReadInt64();
                        int  length  = bin.ReadInt32();
                        Type objType = (Type)types[typeID];

                        while (objType != null && objType != typeof(object))
                        {
                            object obj = table[objType];

                            if (obj == null)
                            {
                                table[objType] = length;
                            }
                            else
                            {
                                table[objType] = length + (int)obj;
                            }

                            objType = objType.BaseType;
                            total  += length;
                        }
                    }
                }

                ArrayList list = new ArrayList(table);

                list.Sort(new CountSorter());

                using (StreamWriter op = new StreamWriter(opFile))
                {
                    op.WriteLine("# Profile of world {0}", type);
                    op.WriteLine("# Generated on {0}", DateTime.UtcNow);
                    op.WriteLine();
                    op.WriteLine();

                    foreach (DictionaryEntry de in list)
                    {
                        op.WriteLine("{0}\t{1:F2}%\t{2}", de.Value, (100 * (int)de.Value) / (double)total, de.Key);
                    }
                }
            }
            catch
            {
            }
        }
        public override void Deserialize(GenericReader reader)
        {
            base.Deserialize(reader);

            short version = reader.ReadShort();

            switch (version)
            {
            case 1:
                goto case 0;

            case 0:
                m_Identified = reader.ReadBool();

                string sType = reader.ReadString();
                ItemType = ScriptCompiler.FindTypeByName(sType);

                // iProps
                iProps = new int[4];

                iProps[0] = (int)reader.ReadShort();
                iProps[1] = (int)reader.ReadShort();
                iProps[2] = (int)reader.ReadShort();
                iProps[3] = (int)reader.ReadShort();

                if (version < 1)
                {
                    reader.ReadString();                                                        // ID label
                }
                // Approx label
                sApproxLabel = reader.ReadString();

                // Skill stuff
                SkillReq = new int[52];

                iMajorSkill = (int)reader.ReadShort();

                if (version < 1)
                {
                    // Add new lines to name property
                    if (m_Identified)
                    {
                        this.Name = string.Format("an enchanted {0} scroll\n\n", sApproxLabel);
                    }

                    // Fix any BlackStaffs or Pitchforks
                    if (iMajorSkill == (int)SkillName.Blacksmith && (ItemType == typeof(BlackStaff) || ItemType == typeof(Pitchfork)))
                    {
                        iMajorSkill = (int)SkillName.Tinkering;
                    }
                }

                SkillReq[(int)SkillName.Magery] = 80;
                SkillReq[iMajorSkill]           = 90;

                // Determine skill required :
                if (ItemType.IsSubclassOf(typeof(BaseJewel)) ||
                    ItemType.IsSubclassOf(typeof(BaseClothing)))
                {
                    SkillReq[(int)SkillName.ItemID] = 80;
                }
                else
                {
                    SkillReq[(int)SkillName.ArmsLore] = 80;
                }

                break;
            }
        }
Exemple #36
0
 protected IMohidTask LoadScript(FileName script_file_path)
 {
     ScriptInfo si = scripts.Find(delegate(ScriptInfo info) { return info.ScriptFile.FullPath == script_file_path.FullPath;  });
      if (si != null)
      {
     si.Interface.Reset();
     return si.Interface;
      }
      else
      {
     ScriptCompiler sc = new ScriptCompiler();
     Assembly ass = sc.Compile(script_file_path);
     si = new ScriptInfo();
     si.ScriptFile = script_file_path;
     si.Interface = (IMohidTask)sc.FindScriptInterface("IMohidTask", ass);
     return si.Interface;
      }
 }
        public static void ImportXML(string path, string file)
        {
            using (var xml = new XmlDataStore <ConquestSerial, Conquest>(path, file))
            {
                xml.OnDeserialize = doc =>
                {
                    XmlElement root = doc.DocumentElement;

                    if (root == null)
                    {
                        return(true);
                    }

                    foreach (XmlElement conquestNode in root.ChildNodes.OfType <XmlElement>())
                    {
                        string typeAttr = conquestNode.GetAttribute("type");
                        var    type     = new TypeSelectProperty <Conquest>(typeAttr);

                        if (!type.IsNotNull)
                        {
                            continue;
                        }

                        var conquest = type.CreateInstance <Conquest>();
                        PropertyList <Conquest> pList = conquest.GetProperties(
                            BindingFlags.Instance | BindingFlags.Public,
                            p => p.CanWrite && p.Name != "Enabled" && p.Name != "InvokeReset" && p.Name != "InvokeClear");

                        foreach (XmlElement conquestPropNode in conquestNode.ChildNodes.OfType <XmlElement>())
                        {
                            string pName = conquestPropNode.Name;
                            string dType = conquestPropNode.GetAttribute("type");
                            string data  = conquestPropNode.GetAttribute("value");

                            switch (dType)
                            {
                            case "Type":
                            {
                                Type t = null;

                                if (!String.IsNullOrWhiteSpace(data))
                                {
                                    t = Type.GetType(data, false, true) ??
                                        ScriptCompiler.FindTypeByName(data, true) ??
                                        ScriptCompiler.FindTypeByFullName(data);
                                }

                                pList.Set(pName, t);
                            }
                            break;

                            default:
                            {
                                DataType dataType;

                                if (!Enum.TryParse(dType, out dataType))
                                {
                                    continue;
                                }

                                SimpleType sType;

                                if (SimpleType.TryParse(data, dataType, out sType) && sType.Flag != DataType.Null)
                                {
                                    pList.Set(pName, sType.Value);
                                }
                            }
                            break;
                            }
                        }

                        pList.Serialize(conquest);

                        xml.AddOrReplace(conquest.UID, conquest);
                    }

                    return(true);
                };

                if (xml.Import() == DataStoreResult.OK)
                {
                    xml.CopyTo(ConquestRegistry);

                    xml.Document.Delete();
                }

                foreach (Exception e in xml.Errors)
                {
                    e.ToConsole();
                }
            }
        }
Exemple #38
0
        protected IMohidTask LoadScript(FileName script_file_path)
        {
            ScriptInfo si = scripts.Find(delegate(ScriptInfo info) { return info.ScriptFile.FullPath == script_file_path.FullPath;  });
             if (si != null)
             {
            si.Interface.Reset();
            return si.Interface;
             }
             else
             {
            ScriptCompiler sc = new ScriptCompiler();
            Assembly ass;
            try
            {
               ass = sc.Compile(script_file_path);
            }
            catch (Exception ex)
            {
               throw new Exception("Error when trying to compile " + script_file_path.FullPath + ". The message returned was " + ex.Message);
            }

            si = new ScriptInfo();
            si.ScriptFile = script_file_path;
            si.Interface = (IMohidTask)sc.FindScriptInterface("IMohidTask", ass);

            scripts.Add(si);

            return si.Interface;
             }
        }
Exemple #39
0
        public StorageEntry(GenericReader reader)
        {
            int version = reader.ReadInt();

            switch (version)
            {
            case 1:
                m_Funds   = reader.ReadInt();
                m_Expires = reader.ReadDateTime();

                int count = reader.ReadInt();
                for (int i = 0; i < count; i++)
                {
                    Type cType  = ScriptCompiler.FindTypeByName(reader.ReadString());
                    int  amount = reader.ReadInt();

                    if (cType != null)
                    {
                        m_CommodityTypes[cType] = amount;
                    }
                }

                count = reader.ReadInt();
                for (int i = 0; i < count; i++)
                {
                    BaseCreature bc = reader.ReadMobile() as BaseCreature;

                    if (bc != null)
                    {
                        m_Creatures.Add(bc);
                    }
                }
                break;

            case 0:
                int type = reader.ReadInt();
                m_Funds   = reader.ReadInt();
                m_Expires = reader.ReadDateTime();

                switch (type)
                {
                case 0: break;

                case 1:
                {
                    int c1 = reader.ReadInt();
                    for (int i = 0; i < c1; i++)
                    {
                        Type cType  = ScriptCompiler.FindTypeByName(reader.ReadString());
                        int  amount = reader.ReadInt();

                        if (cType != null)
                        {
                            m_CommodityTypes[cType] = amount;
                        }
                    }
                    break;
                }

                case 2:
                {
                    int c2 = reader.ReadInt();
                    for (int i = 0; i < c2; i++)
                    {
                        BaseCreature bc = reader.ReadMobile() as BaseCreature;

                        if (bc != null)
                        {
                            m_Creatures.Add(bc);
                        }
                    }
                    break;
                }
                }
                break;
            }
        }
Exemple #40
0
        static void Main(string[] args)
        {
            string appName = AppDomain.CurrentDomain.FriendlyName;
            string outputDirectory = Environment.CurrentDirectory;
            bool helpRequested = false;
            bool verboseOutputRequested = false;

            var optionSet = new OptionSet()
            {
                string.Format("Usage: {0} [OPTIONS] filename [filename ...]", appName),
                "",
                "Compile jumpman scripting language files (.jms files).",
                "",
                "  filename                   the path to a source file(s) to compile.",
                "",
                "Options:",
                { "o|out=", "the {DIRECTORY} to place compiler output.", value => outputDirectory = value },
                { "v|verbose", "write out extended runtime debug information.", value => verboseOutputRequested = value != null },
                { "h|help", "show this help message and exit.", value => helpRequested = value != null },
            };

            List<string> extra;
            try
            {
                extra = optionSet.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine("{0}:", appName);
                Console.WriteLine(e.ToString());
                Console.WriteLine("Try '{0} --help' for more information.", appName);
                return;
            }

            Action writeUsage = () => optionSet.WriteOptionDescriptions(Console.Out);
            var filenames = extra.Select(filename => Path.GetFullPath(filename)).ToList<string>();
            var invalidFilenames = filenames.Where(filename => !File.Exists(filename)).ToList<string>();

            if (helpRequested)
            {
                writeUsage();
                return;
            }

            if (filenames.Count < 1)
            {
                Console.WriteLine("Must specify at least one filename.");
                Console.WriteLine();
                writeUsage();
                return;
            }

            if (invalidFilenames.Any())
            {
                Console.WriteLine("Cannot find file(s):");
                foreach (string invalidFilename in invalidFilenames)
                {
                    Console.WriteLine(invalidFilename);
                }
                Console.WriteLine();

                writeUsage();
                return;
            }

            Action<string, string> logDebugMessage = (formatString, param0) =>
                {
                    if (verboseOutputRequested)
                    {
                        Console.WriteLine(formatString, param0);
                    }
                };

            var scriptCompiler = new ScriptCompiler();
            foreach (string filenameToCompile in filenames)
            {
                string scriptBaseName = Path.GetFileNameWithoutExtension(filenameToCompile);
                string sourceDirectory = Path.GetDirectoryName(filenameToCompile);
                string includeDirectory = sourceDirectory;
                string binaryOutputFilename = Path.Combine(outputDirectory, scriptBaseName + ".bin");
                string constantsOutputFilename = Path.Combine(sourceDirectory, "ref" + scriptBaseName + ".jms");

                using (FileStream fileToCompileStream = File.OpenRead(filenameToCompile))
                using (StreamReader streamReader = new StreamReader(fileToCompileStream))
                {
                    logDebugMessage("Compiling file: {0}", filenameToCompile);
                    scriptCompiler.Compile(includeDirectory, streamReader.ReadToEnd());
                    logDebugMessage("Finished compiling file: {0}", filenameToCompile);

                    logDebugMessage("Writing output binary file: {0}", binaryOutputFilename);
                    scriptCompiler.WriteBinary(binaryOutputFilename);
                    logDebugMessage("Finished writing output binary file: {0}", binaryOutputFilename);

                    logDebugMessage("Writing output constants file: {0}", constantsOutputFilename);
                    scriptCompiler.WriteConstants(constantsOutputFilename, scriptBaseName);
                    logDebugMessage("Finished writing output constants file: {0}", constantsOutputFilename);
                }
            }
        }
        private bool Compile(IEnumerable<ITaskItem> sourceItems, IEnumerable<ITaskItem> resourceItems, string locale)
        {
            ITaskItem scriptTaskItem;

            CompilerOptions options =
                CreateOptions(sourceItems, resourceItems, locale,
                              /* includeTests */ false, /* minimize */ false,
                              out scriptTaskItem);

            string errorMessage = String.Empty;
            if (options.Validate(out errorMessage) == false) {
                Log.LogError(errorMessage);
                return false;
            }

            ScriptCompiler compiler = new ScriptCompiler(this);
            compiler.Compile(options);
            if (_hasErrors == false) {
                // Only copy references once (when building language neutral scripts)
                bool copyReferences = String.IsNullOrEmpty(locale) && CopyReferences;

                OnScriptFileGenerated(scriptTaskItem, options, copyReferences);
                if (_hasErrors) {
                    return false;
                }
            }
            else {
                return false;
            }

            if (options.HasTestTypes) {
                CompilerOptions testOptions =
                    CreateOptions(sourceItems, resourceItems, locale,
                                  /* includeTests */ true, /* minimize */ false,
                                  out scriptTaskItem);
                ScriptCompiler testCompiler = new ScriptCompiler(this);
                testCompiler.Compile(testOptions);
                if (_hasErrors == false) {
                    OnScriptFileGenerated(scriptTaskItem, testOptions, /* copyReferences */ false);
                }
                else {
                    return false;
                }
            }

            if (_minimize) {
                CompilerOptions minimizeOptions =
                    CreateOptions(sourceItems, resourceItems, locale,
                                  /* includeTests */ false, /* minimize */ true,
                                  out scriptTaskItem);
                ScriptCompiler minimizingCompiler = new ScriptCompiler(this);
                minimizingCompiler.Compile(minimizeOptions);
                if (_hasErrors == false) {
                    if (Crunch) {
                        ExecuteCruncher(scriptTaskItem);
                    }

                    OnScriptFileGenerated(scriptTaskItem, minimizeOptions, /* copyReferences */ false);
                }
                else {
                    return false;
                }
            }

            return true;
        }