Example #1
0
        public static void WriteInt32(BinaryWriter binw, Microsoft.Scripting.Hosting.ScriptScope s, string pyVar, int value)
        {
            if (s.ContainsVariable(pyVar + "_OFFSET"))
            {
                binw.BaseStream.Seek(s.GetVariable(pyVar + "_OFFSET"), SeekOrigin.Begin);
            }
            if (s.ContainsVariable(pyVar + "_TYPE"))
            {
                string type = s.GetVariable(pyVar + "_TYPE");
                switch (type)
                {
                case "TRAILED_STRING":
                    char   trail  = char.Parse(s.GetVariable(pyVar + "_TRAIL"));
                    char[] value2 = value.ToString().ToCharArray();
                    binw.Write(value2);
                    binw.Write(trail);
                    break;

                case "INT16":
                    binw.Write((Int16)value);
                    break;

                default:
                    binw.Write(value);
                    break;
                }
            }
            else
            {
                binw.Write(value);
            }
        }
Example #2
0
        private void Start()
        {
            engine = Python.CreateEngine();
            engine.Runtime.LoadAssembly(typeof(GameObject).Assembly);

            engine.Runtime.LoadAssembly(typeof(Image).Assembly);
            //engine.ImportModule("");
            scope = engine.CreateScope();
            scope.SetVariable("pyConsole", pyConsole);
            engine.Execute(pythonScript, scope);
            //var scope = engine.ExecuteFile(path);
            int counter = scope.GetVariable <int>("counter");

            Debug.Log(counter);

            float timeBackup = scope.GetVariable <float>("timeBackup");

            Debug.Log(timeBackup);

            Debug.LogError("Error test");

            Debug.LogWarning("warning\nTest");

            //TestInstance();
            //TestInstance();


            //GameObject.Find("Player").transform.GetChild(0).GetComponent("MeshRenderer").sharedMaterial.color = Color.black;
            //GameObject.Find("Player").transform.localRotation = Quaternion.Euler(0, 0, 90);
            //Camera.main.transform.position = new Vector3(2,2,-5);

            //string variables = string.Join(",", scope.GetVariableNames().ToArray());
            //Debug.Log("variables: " + variables);
        }
Example #3
0
        //interface


        //constructor
        public Console(IConsoleTarget target)
        {
            if (target == null)
            {
                throw new ArgumentException("target cannot be null");
            }
            title       = target.ConsoleTitle;
            this.target = target;
            var targetScope = target.GetScope();
            var locals      = new IronPython.Runtime.PythonDictionary();

            foreach (var name in targetScope.GetVariableNames())
            {
                locals[name] = targetScope.GetVariable(name);
            }
            scope = Py.CreateScope();
            scope.SetVariable("_locals", locals);
            var    ops         = scope.Engine.Operations;
            string init_script = System.IO.File.ReadAllText(Util.ResourcePath("PythonScripts/initialize_new_console.py"));

            Py.Engine.Execute(init_script, scope);
            python_output_buffer    = scope.GetVariable <IronPython.Modules.PythonIOModule.StringIO>("output_buffer");
            python_compile_command  = scope.GetVariable <IronPython.Runtime.PythonFunction>("compile_command");
            python_console_run_code = scope.GetVariable <IronPython.Runtime.PythonFunction>("console_run_code");

            output             = new LineBuffer(new string[] { ">>> " });
            input              = new LineBuffer(new string[] { "" });
            editor             = new StringBuilder(500);
            multilineEditor    = new StringBuilder(500);
            _currentInputIndex = 0;
            _editorCursor      = 0;
        }
Example #4
0
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(
                "helloWorldString = 'Hello World!'\n" +
                "print helloWorldString\n" +
                "print externalString"
                );

            Microsoft.Scripting.Hosting.ScriptScope scope = pythonEngine.CreateScope();
            scope.SetVariable("externalString", "How do you do?");

            pythonScript.Execute(scope);

            System.Console.Out.WriteLine();
            System.Console.Out.WriteLine("List of variables in the scope:");
            foreach (string name in scope.GetVariableNames())
            {
                System.Console.Out.Write(name + " ");
            }
            System.Console.Out.WriteLine();

            System.Console.Out.WriteLine();
            System.Console.Out.WriteLine("Variable values:");
            System.Console.Out.WriteLine("helloWorldString: " + scope.GetVariable("helloWorldString"));
            System.Console.Out.WriteLine("externalString: " + scope.GetVariable("externalString"));
        }
        private void callPythonCode()
        {
            var options = new Dictionary <string, object>();

            options["Frames"]     = true;
            options["FullFrames"] = true;

            //create ironpython engine and scope
            Microsoft.Scripting.Hosting.ScriptEngine py    = Python.CreateEngine(options);
            Microsoft.Scripting.Hosting.ScriptScope  scope = py.CreateScope();

            //add python folder to pythonpath
            string pythonCodePath      = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/";
            string pyGDPPath           = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/pyGDP-master/";
            string OWSPath             = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/owslib/";
            string owslibPath          = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/OWS/OWSLib-0.8.6/owslib/";
            string libPath             = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/Lib/";
            ICollection <string> paths = py.GetSearchPaths();

            paths.Add(pythonCodePath);
            paths.Add(pyGDPPath);
            paths.Add(OWSPath);
            paths.Add(owslibPath);
            paths.Add(libPath);
            py.SetSearchPaths(paths);

            //store variables in scope
            scope.SetVariable("futOne", futOne);
            scope.SetVariable("futTwo", futTwo);
            scope.SetVariable("futThree", futThree);
            scope.SetVariable("futFour", futFour);
            scope.SetVariable("futFive", futFive);
            scope.SetVariable("futSix", futSix);
            scope.SetVariable("histOne", histOne);
            scope.SetVariable("histTwo", histTwo);
            scope.SetVariable("filePath", filePath);

            //run code
            py.ExecuteFile(Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/module1.py", scope);

            string outputPathF2 = scope.GetVariable("outputPathF2").ToString();
            string outputPathH1 = scope.GetVariable("outputPathH1").ToString();

            //retrieve climate data
            filePath = filePath.Remove(filePath.Length - 9);

            string    urlF2     = "http://cida.usgs.gov:80/gdp/process/RetrieveResultServlet?id=" + outputPathF2;
            WebClient webClient = new WebClient();

            webClient.DownloadFile(urlF2, @filePath + "FutureClimateData.csv");

            string    urlH1      = "http://cida.usgs.gov:80/gdp/process/RetrieveResultServlet?id=" + outputPathH1;
            WebClient webClient2 = new WebClient();

            webClient2.DownloadFile(urlH1, @filePath + "HistoricalClimateData.csv");

            return;
        }
Example #6
0
        /// <summary>
        /// 用户自定义Python脚本
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string RepairFun_PythonScript(string handler, string source)
        {
            if (source == "")
            {
                return("");
            }

            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(
                $"import textRepairPlugins.{handler} as customHandler\n" +
                "ResultStr = customHandler.process(SourceStr)\n"
                );
            Microsoft.Scripting.Hosting.ScriptScope scope = pythonEngine.CreateScope();
            scope.SetVariable("SourceStr", source);

            try
            {
                pythonScript.Execute(scope);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
            return((string)scope.GetVariable("ResultStr"));
        }
Example #7
0
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();

            ICollection <string> searchPaths = pythonEngine.GetSearchPaths();

            searchPaths.Add("..\\..");
            pythonEngine.SetSearchPaths(searchPaths);

            Microsoft.Scripting.Hosting.ScriptScope scope = IronPython.Hosting.Python.ImportModule(pythonEngine, "HelloWorldModule");

            dynamic printHelloWorldFunction = scope.GetVariable("PrintHelloWorld");

            printHelloWorldFunction();

            dynamic printMessageFunction = scope.GetVariable("PrintMessage");

            printMessageFunction("Goodbye!");

            dynamic addFunction = scope.GetVariable("Add");

            System.Console.Out.WriteLine("The sum of 1 and 2 is " + addFunction(1, 2));
        }
Example #8
0
 public object GetVar(string name)
 {
     return(_scope.GetVariable(name));
 }
        /// <summary>
        /// Export image to chosen format
        /// </summary>
        /// <param name="path">output path</param>
        /// <param name="scriptpath">script path</param>
        public void ExportImg(string path, string scriptpath)
        {
            py = Python.CreateEngine();
            s  = py.CreateScope();
            //py.ExecuteFile(scriptpath, s);
            if (scriptpath.Length > 100)
            {
                py.Execute(scriptpath, s);
            }
            else
            {
                py.ExecuteFile(scriptpath, s);
            }

            BinaryWriter binr;

            fs   = new FileStream(path, FileMode.Create);
            binr = new BinaryWriter(fs);

            pixelFormat = s.GetVariable("IMG_PIXEL_FORMAT");
            pixelFormat = pixelFormat.ToUpper();
            if (pixelFormat.Length < 4 && BPP == 32)
            {
                pixelFormat += "A";
            }

            int           w1    = 0;
            List <string> order = s.GetVariable("WRITE_ORDER");

            for (int i = 0; i < order.Count; i++)
            {
                switch (order[i])
                {
                case "FILE_MAGIC":
                    List <Byte> magic2 = s.GetVariable("FILE_MAGIC");
                    for (int j = 0; j < magic2.Count; j++)
                    {
                        binr.Write(magic2[j]);
                    }
                    break;

                case "FILE_SIZE":
                    /*if (img.Width % 2 > 0)
                     *  w1 = 1;
                     * binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                     * binr.Write(0x36 + ((img.Width + w1) * img.Height * bpp / 8));*/
                    break;

                case "IMG_PIXELS_LEN":
                    if (img.Width % 2 > 0)
                    {
                        w1 = 1;
                    }
                    binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                    binr.Write((img.Width + w1) * img.Height * BPP / 8);
                    break;

                /*case "FILE_HEADER_SIZE":
                 *  binr.Seek(s.GetVariable("FILE_HEADER_SIZE_OFFSET"), SeekOrigin.Begin);
                 *  binr.Write(s.GetVariable("FILE_HEADER_SIZE"));
                 *  break;*/
                case "IMG_WIDTH":
                    //binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                    //binr.Write(img.Width);
                    VarWriter.WriteInt32(binr, s, order[i], img.Width);
                    break;

                case "IMG_HEIGHT":
                    //binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                    //binr.Write(img.Height);
                    VarWriter.WriteInt32(binr, s, order[i], img.Height);
                    break;

                case "IMG_BPP":
                    binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                    binr.Write(BPP);
                    break;

                case "IMG_PIXELS":
                    if (s.ContainsVariable("IMG_PIXELS_OFFSET"))
                    {
                        binr.Seek(s.GetVariable("IMG_PIXELS_OFFSET"), SeekOrigin.Begin);
                    }
                    //int red = 0, green = 0, blue = 0;
                    w1 = 0;
                    if (s.ContainsVariable("IMG_UNEVEN_PADDING"))
                    {
                        if (s.GetVariable("IMG_UNEVEN_PADDING"))
                        {
                            if (img.Width % 2 > 0)
                            {
                                w1 = 1;
                            }
                        }
                    }
                    if (s.ContainsVariable("IMG_UPSIDE_DOWN"))
                    {
                        if (s.GetVariable("IMG_UPSIDE_DOWN"))
                        {
                            img = Operations.FlipVertical(img);
                        }
                    }

                    List <byte> rgb = new List <byte>();
                    if (s.ContainsVariable("IMG_PIXELS_HANDLER"))
                    {
                        if (s.GetVariable("IMG_PIXELS_HANDLER"))
                        {
                            for (int j = 0; j < img.Height; j++)
                            {
                                for (int q = 0; q < img.Width + w1; q++)
                                {
                                    if (q < img.Width)
                                    {
                                        for (int c = 0; c < pixelFormat.Length; c++)
                                        {
                                            if (pixelFormat[c] == 'B')
                                            {
                                                rgb.Add(img.GetPixel(q, j).B);
                                            }
                                            if (pixelFormat[c] == 'G')
                                            {
                                                rgb.Add(img.GetPixel(q, j).G);
                                            }
                                            if (pixelFormat[c] == 'R')
                                            {
                                                rgb.Add(img.GetPixel(q, j).R);
                                            }
                                            if (pixelFormat[c] == 'A')
                                            {
                                                rgb.Add(img.GetPixel(q, j).A);
                                            }
                                        }
                                    }
                                }
                            }
                            var            SavePixels = s.GetVariable("SavePixels");
                            IList <object> rgbp       = new List <object>();
                            for (int z = 0; z < rgb.Count; z++)
                            {
                                rgbp.Add(rgb[z]);
                            }
                            List <byte> rgbl = SavePixels(rgbp, img.Width, img.Height, BPP);
                            if (rgbl.Count < img.Width * img.Height)
                            {
                                binr.Write(rgb.ToArray());
                            }
                            else
                            {
                                binr.Write(rgbl.ToArray());
                            }
                        }
                    }
                    else
                    {
                        for (int j = 0; j < img.Height; j++)
                        {
                            for (int q = 0; q < img.Width + w1; q++)
                            {
                                if (q < img.Width)
                                {
                                    for (int c = 0; c < pixelFormat.Length; c++)
                                    {
                                        if (pixelFormat[c] == 'B')
                                        {
                                            binr.Write(img.GetPixel(q, j).B);
                                        }
                                        if (pixelFormat[c] == 'G')
                                        {
                                            binr.Write(img.GetPixel(q, j).G);
                                        }
                                        if (pixelFormat[c] == 'R')
                                        {
                                            binr.Write(img.GetPixel(q, j).R);
                                        }
                                        if (pixelFormat[c] == 'A')
                                        {
                                            binr.Write(img.GetPixel(q, j).A);
                                        }
                                    }
                                }
                                else
                                {
                                    for (int c = 0; c < pixelFormat.Length; c++)
                                    {
                                        binr.Write((byte)0);
                                    }
                                }
                            }
                        }
                    }
                    if (s.ContainsVariable("IMG_UPSIDE_DOWN"))
                    {
                        if (s.GetVariable("IMG_UPSIDE_DOWN"))
                        {
                            img = Operations.FlipVertical(img);
                        }
                    }
                    break;

                default:
                    //binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin);
                    //binr.Write(s.GetVariable(order[i]));
                    VarWriter.WriteScriptVar(binr, s, order[i]);
                    break;
                }
            }
            if (order.Contains("FILE_SIZE"))
            {
                int size = (int)binr.BaseStream.Position;
                binr.Seek(s.GetVariable("FILE_SIZE_OFFSET"), SeekOrigin.Begin);
                binr.Write(size);
            }
            binr.Close();
            fs.Close();
        }
        /// <summary>
        /// Loads the image
        /// </summary>
        public void LoadImg()
        {
            BinaryReader binr;

            fs   = new FileStream(path, FileMode.Open);
            binr = new BinaryReader(fs);
            int w = 0, h = 0;

            pixelFormat = s.GetVariable("IMG_PIXEL_FORMAT");
            pixelFormat = pixelFormat.ToUpper();
            BPP         = VarReader.ReadInt32(binr, s, "IMG_BPP");

            List <string> order = s.GetVariable("WRITE_ORDER");

            for (int q = 0; q < order.Count; q++)
            {
                switch (order[q])
                {
                case "FILE_MAGIC":
                    int         maglen = s.GetVariable("FILE_MAGIC_LEN");
                    List <Byte> magic  = binr.ReadBytes(maglen).ToList();
                    List <Byte> magic2 = s.GetVariable("FILE_MAGIC");
                    //if (magic.Equals(magic2))
                    //    return;
                    break;

                case "IMG_WIDTH":
                    w = VarReader.ReadInt32(binr, s, order[q]);
                    break;

                case "IMG_HEIGHT":
                    h = VarReader.ReadInt32(binr, s, order[q]);
                    break;

                case "IMG_BPP":
                    BPP = VarReader.ReadInt32(binr, s, order[q]);
                    break;

                case "IMG_PIXELS":
                    if (s.ContainsVariable("IMG_PIXEL_FORMAT"))
                    {
                        byte[] rgb;
                        int    size = 0;
                        if (s.ContainsVariable("IMG_UNEVEN_PADDING"))
                        {
                            if (s.GetVariable("IMG_UNEVEN_PADDING"))
                            {
                                int w1 = 0;
                                if (w % 2 > 0)
                                {
                                    w1 = 1;
                                }
                                size = (w + w1) * h * (bpc * pixelFormat.Length / 8);
                            }
                            else
                            {
                                size = w * h * (bpc * pixelFormat.Length / 8);
                            }
                        }
                        else
                        {
                            size = w * h * (bpc * pixelFormat.Length / 8);
                        }

                        if (s.ContainsVariable("IMG_PIXELS_LEN"))
                        {
                            size = s.GetVariable("IMG_PIXELS_LEN");
                        }

                        if (s.ContainsVariable("IMG_PIXELS_LEN_OFFSET"))
                        {
                            binr.BaseStream.Seek(s.GetVariable("IMG_PIXELS_LEN_OFFSET"), SeekOrigin.Begin);
                            size = VarReader.ReadInt32(binr, s, "IMG_PIXELS_LEN");
                        }

                        if (s.ContainsVariable(order[q] + "_OFFSET"))
                        {
                            binr.BaseStream.Seek(s.GetVariable(order[q] + "_OFFSET"), SeekOrigin.Begin);
                        }

                        rgb = binr.ReadBytes(size);

                        if (s.ContainsVariable("IMG_DEFLATE"))
                        {
                            if (s.GetVariable("IMG_DEFLATE"))
                            {
                                System.IO.FileStream inFile = new System.IO.FileStream("CompZ.bin", System.IO.FileMode.Create);
                                BinaryWriter         binZ   = new BinaryWriter(inFile);
                                binZ.Write(rgb);
                                //binZ.Flush();
                                binZ.Close();
                                inFile.Close();

                                System.IO.FileStream outFileStream = new System.IO.FileStream("DecompZ.bin", System.IO.FileMode.Create);
                                zlib.ZOutputStream   outZStream    = new zlib.ZOutputStream(outFileStream);
                                System.IO.FileStream inFileStream  = new System.IO.FileStream("CompZ.bin", System.IO.FileMode.Open);

                                try
                                {
                                    byte[] buffer = new byte[2000];
                                    int    len;
                                    while ((len = inFileStream.Read(buffer, 0, 2000)) > 0)
                                    {
                                        outZStream.Write(buffer, 0, len);
                                    }
                                    outZStream.Flush();
                                }
                                finally
                                {
                                    outZStream.Close();
                                    outFileStream.Close();
                                    inFileStream.Close();
                                }

                                System.IO.FileStream inFile2 = new System.IO.FileStream("DecompZ.bin", System.IO.FileMode.Open);
                                BinaryReader         binZ2   = new BinaryReader(inFile2);
                                //rgb = new byte[inFile2.Length];
                                //inFile2.Read(rgb, 0, (int)inFile2.Length);
                                rgb = binZ2.ReadBytes((int)inFile2.Length);
                                binZ2.Close();
                                inFile2.Close();
                            }
                        }

                        if (s.ContainsVariable("IMG_PIXELS_HANDLER"))
                        {
                            if (s.GetVariable("IMG_PIXELS_HANDLER"))
                            {
                                var            ProcessPixels = s.GetVariable("ProcessPixels");
                                IList <object> rgbp          = new List <object>();
                                for (int i = 0; i < rgb.Length; i++)
                                {
                                    rgbp.Add(rgb[i]);
                                }
                                List <byte> rgbl = ProcessPixels(rgbp, w, h, BPP);
                                rgb = rgbl.ToArray();
                            }
                        }

                        img             = new Bitmap(w, h);
                        Color[,] pixels = Render(rgb, h, w);
                        for (int j = 0; j < h; j++)
                        {
                            for (int i = 0; i < w; i++)
                            {
                                img.SetPixel(i, j, pixels[i, j]);
                            }
                        }
                    }
                    break;

                default:
                    VarReader.ReadInt32(binr, s, order[q]);
                    break;
                }
            }
            binr.Close();
            fs.Close();
        }
Example #11
0
        public static int ReadInt32(BinaryReader binr, Microsoft.Scripting.Hosting.ScriptScope s, string pyVar)
        {
            int  rVar = 0;
            bool skip = false;

            FileStream fs     = (FileStream)binr.BaseStream;
            string     script = Path.GetExtension(fs.Name).Remove(0, 1).ToUpper();

            if (script == pyVar.Split('_')[0])
            {
                skip = true;
            }

            if (s.ContainsVariable(pyVar + "_OFFSET"))
            {
                binr.BaseStream.Seek(s.GetVariable(pyVar + "_OFFSET"), SeekOrigin.Begin);
            }
            if (!skip && s.ContainsVariable(pyVar))
            {
                rVar = s.GetVariable(pyVar);
            }
            else
            {
                if (s.ContainsVariable(pyVar + "_TYPE"))
                {
                    string type = s.GetVariable(pyVar + "_TYPE");
                    switch (type)
                    {
                    case "TRAILED_STRING":
                        char trail = char.Parse(s.GetVariable(pyVar + "_TRAIL"));

                        string value = "";
                        char   add   = ' ';
                        while (true)
                        {
                            add = binr.ReadChar();
                            if (add != trail)
                            {
                                value += add;
                            }
                            else
                            {
                                if (!skip)
                                {
                                    rVar = int.Parse(value);
                                }
                                break;
                            }
                        }
                        break;

                    case "INT16":
                        rVar = binr.ReadInt16();
                        break;

                    case "BYTE":
                        rVar = binr.ReadByte();
                        break;

                    default:
                        rVar = 0;
                        break;
                    }
                }
                else
                {
                    rVar = binr.ReadInt32();
                }
            }
            if (skip)
            {
                return(0);
            }
            return(rVar);
        }