Пример #1
0
        private static List <string> GetDepDlls(UnityPlugin plugin)
        {
            var dlls = new List <string>();

            if (plugin != null)
            {
                if (plugin.pluginState == UnityPlugin.PluginState.convert)
                {
                    if (plugin.convertedPath.convertedDLLPath != null && File.Exists(plugin.convertedPath.convertedDLLPath))
                    {
                        dlls.Add(plugin.convertedPath.convertedDLLPath);
                    }
                }
                else
                {
                    if (plugin.stubPath.stubDLLPath != null && File.Exists(plugin.stubPath.stubDLLPath))
                    {
                        dlls.Add(plugin.stubPath.stubDLLPath);
                    }
                    if (plugin.stubPath.stubRefDLLPath != null && File.Exists(plugin.stubPath.stubRefDLLPath))
                    {
                        dlls.Add(plugin.stubPath.stubRefDLLPath);
                    }
                }
            }

            var unityDllpath = UnityPluginUtil.GetUnityEngineStub().stubPath.stubDLLPath;

            if (File.Exists(unityDllpath))
            {
                dlls.Add(unityDllpath);
            }

            return(dlls);
        }
Пример #2
0
 public StubPath(UnityPlugin plugin)
 {
     stubCSPath     = PathUtil.GetPluginOutputPath(plugin, PathUtil.PluginOutputType.CS);
     stubRefCSPath  = PathUtil.GetPluginOutputPath(plugin, PathUtil.PluginOutputType.CS, "-ref.cs");
     stubRefDLLPath = PathUtil.GetPluginOutputPath(plugin, PathUtil.PluginOutputType.DLL, "-ref.dll");
     stubDLLPath    = PathUtil.GetPluginOutputPath(plugin, PathUtil.PluginOutputType.DLL, "-stub.dll");
     stubJSPath     = PathUtil.GetPluginOutputPath(plugin, PathUtil.PluginOutputType.JS);
 }
        private static void GeneratePluginRefStubCs(UnityPlugin plugin)
        {
            if (!plugin.enable)
            {
                return;
            }

            var refs = UnityPluginUtil.GetLib(plugin);

            if (refs == null || refs.Count == 0)
            {
                Debug.Log(plugin.pluginName + ": References C# generating... no references found");
                return;
            }

            // header
            var allRefContent = string.Format(topHeader, plugin.pluginName);

            for (var i = 0; i < refs.Count; i++)
            {
                var r = refs[i];

                var refName = Path.GetFileNameWithoutExtension(r);
                Debug.Log(refName);
                var assembly = Assembly.LoadFile(r);
                var output   = plugin.stubPath.stubRefCSPath;
                GeneratePluginRefStubCs(plugin.pluginName, output, assembly);

                var tmp = "";
                using (var sr = new StreamReader(output)) {
                    tmp = sr.ReadToEnd();
                }

                // remove #if UNITY_WAGAME
                //        using Bridge;
                //        using System;
                // at the begining of new ref stub content
                if (i > 0)
                {
                    tmp = String.Join("\n", tmp.Split('\n').Skip(4));
                }

                // remove #endif at last line
                tmp = tmp.Remove(tmp.TrimEnd().LastIndexOf(Environment.NewLine));

                // ref header
                allRefContent += string.Format(refHeader, i, refName);

                allRefContent += tmp;
                allRefContent += "\n\n";
            }
            // add #endif at the very last line
            allRefContent += "#endif";

            using (var sw = new StreamWriter(plugin.stubPath.stubRefCSPath, false)) {
                sw.Write(allRefContent);
            }
        }
        public static List <string> GetLib(UnityPlugin plugin)
        {
            if (!plugin.enable)
            {
                return(new List <string>());
            }

            return(GetPluginFilesFromConfig(plugin.pluginPath.libs, "/*.dll"));
        }
        public static List <string> GetSource(UnityPlugin plugin)
        {
            if (!plugin.enable)
            {
                return(new List <string>());
            }

            return(GetPluginFilesFromConfig(plugin.pluginPath.sources, "/*.cs"));
        }
        private static void GeneratePluginStubDLL(UnityPlugin config)
        {
            if (!config.enable)
            {
                return;
            }

            if (references == null)
            {
                references = DirectoryBuilder.RegisterDirectory("references", new DirectoryStructure("References~"));
            }

            var sources = new List <string>()
            {
                config.stubPath.stubCSPath
            };

            // Add refCS stub file
            var refCS = config.stubPath.stubRefCSPath;

            if (refCS != null && File.Exists(refCS))
            {
                sources.Add(refCS);
            }

            var os = File.Create(config.stubPath.stubDLLPath);

            // var refs = UnityPluginUtil.GetLib(config, true, true);
            var refs = new List <string>()
            {
                references["Bridge"]["Bridge.dll"], UnityPluginUtil.GetUnityEngineStub().stubPath.stubDLLPath
            };

            if (refs == null || refs.Count == 0)
            {
                return;
            }

            EmitResult result;

            try {
                result = DLLProc.BuildDLL(config.pluginName + "-stub", os, sources, config.defineMacros,
                                          refs, true);
            } finally {
                os.Close();
            }
            if (result == null || !result.Success)
            {
                throw new Exception();
            }
        }
        public static List <string> GetExclude(UnityPlugin plugin)
        {
            if (!plugin.enable)
            {
                return(new List <string>());
            }

            if (plugin.pluginState == UnityPlugin.PluginState.stub && plugin.stubConfig.generateJSTemplate)
            {
                return(new List <string>());
            }

            return(GetPluginFilesFromConfig(plugin.pluginPath.excludes));
        }
Пример #8
0
 // [MenuItem("WeChat/Export/Export Plugin")]
 public static void ExportPluginMenu(UnityPlugin single = null)
 {
     EditorUtility.DisplayProgressBar("Exporting", "...", 0.0f);
     try
     {
         ExportPreCheck();
         ExportPlugins(single);
     } catch (Exception e) {
         Debug.LogException(e);
     } finally {
         EditorUtility.DisplayProgressBar("Exporting", "finish.", 1.0f);
         ClearProgressBar();
     }
 }
        // public static void AttachPluginsToConfig() {
        //     var allPlugins = Resources.LoadAll<UnityPlugin>("configs/WXPlugins") as UnityPlugin[];
        //     // Debug.Log(allPlugins);
        //     if (allPlugins != null) {
        //         ConfigManager.configEntry.unityPluginConfig.unityPlugins = new List<UnityPlugin>(allPlugins);
        //     }
        // }

        // public static void RemoveAllPlugins() {
        //     var allPlugins = Resources.LoadAll<UnityPlugin>("configs/WXPlugins") as UnityPlugin[];
        //     foreach(var p in allPlugins) {
        //         AssetDatabase.DeleteAsset(p.PathAtAssets());
        //     }
        // }

        // public static void DeattachAllPlugins() {
        //     ConfigManager.configEntry.unityPluginConfig.unityPlugins.Clear();
        // }


        static UnityPluginUtil()
        {
            UnityEngineStub             = ScriptableObject.CreateInstance <UnityPlugin>();
            UnityEngineStub.enable      = true;
            UnityEngineStub.pluginName  = "UnityEngine";
            UnityEngineStub.type        = UnityPlugin.PluginType.Other;
            UnityEngineStub.pluginState = UnityPlugin.PluginState.stub;
            UnityEngineStub.stubConfig  = new UnityPlugin.StubConfig {
                generateJSTemplate = false,
                generateStub       = true
            };

            UnityEngineStub.stubPath = new UnityPlugin.StubPath(UnityEngineStub);
            InitXML();
        }
 public static void GeneratePluginStub(UnityPlugin plugin)
 {
     if (plugin.pluginState != UnityPlugin.PluginState.stub)
     {
         return;
     }
     // Debug.Log("1");
     // 生成插件依赖的外部DLL的桩C#
     GeneratePluginRefStubCs(plugin);
     // 用unitydll和systemdll编译插件代码dll(有实现)
     GeneratePluginDLL(plugin);
     // 用上述dll的类型信息进行反射编桩c#代码(空实现)
     GeneratePluginStubCs(plugin);
     // 用所有桩c#编译桩DLL
     GeneratePluginStubDLL(plugin);
 }
Пример #11
0
        public static string GetPluginOutputPath(UnityPlugin plugin, PluginOutputType outputType, string outputFile = null)
        {
            if (plugin == null)
            {
                return("");
            }

            string pathToPluginName = plugin.pluginName;

            switch (plugin.pluginState)
            {
            case UnityPlugin.PluginState.convert:
                pathToPluginName = Path.Combine("Convert", plugin.pluginName);
                break;

            case UnityPlugin.PluginState.stub:
                pathToPluginName = Path.Combine("Stub", plugin.pluginName);
                break;
            }

            switch (outputType)
            {
            case PluginOutputType.CS:
                if (outputFile == null)
                {
                    outputFile = ".cs";
                }
                return(build["Plugins"].GetFilePath(Path.Combine(pathToPluginName, csDist, plugin.pluginName + outputFile)));

            case PluginOutputType.JS:
                return(build["Plugins"].GetFilePath(Path.Combine(pathToPluginName, jsDist)));

            case PluginOutputType.DLL:
                if (outputFile == null)
                {
                    outputFile = ".dll";
                }
                return(build["Plugins"].GetFilePath(Path.Combine(pathToPluginName, dllDist, plugin.pluginName + outputFile)));
            }

            return("");
        }
        public static List <string> GetLib(UnityPlugin plugin, bool unity, bool system)
        {
            var lib = GetLib(plugin);

            if (lib == null)
            {
                lib = new List <string>();
            }

            if (unity)
            {
                lib.AddRange(GetUnityEngineLibs());
            }

            // if (system) {
            //     lib.AddRange(GetSystemLibs());
            // }

            return(lib);
        }
        private static void GeneratePluginDLL(UnityPlugin config)
        {
            if (!config.enable)
            {
                return;
            }
            var sources = UnityPluginUtil.GetSource(config);
            var exc     = UnityPluginUtil.GetExclude(config);

            sources = sources.Except(exc).ToList();
            if (sources == null || sources.Count == 0)
            {
                return;
            }

            var refs = UnityPluginUtil.GetLib(config, true, true);

            if (refs == null || refs.Count == 0)
            {
                return;
            }

            // rename dist dll
            var dist = config.stubPath.stubDLLPath.Replace("-stub.dll", "-internal.dll");
            var os   = File.Create(dist);

            EmitResult result;

            try {
                // comment this for TMP issue(internal visibility)
                result = DLLProc.BuildDLL(config.pluginName /* + "-internal" */, os, sources, config.defineMacros,
                                          refs, true);
            } finally {
                os.Close();
            }
            if (result == null || !result.Success)
            {
                throw new Exception();
            }
        }
Пример #14
0
        private static void ExportPlugins(UnityPlugin single = null)
        {
            var logger = new Bridge.Translator.Logging.Logger("plugins_export_logger", true,
                                                              LoggerLevel.None, false, new MyLoggerWriter(), new Bridge.Translator.Logging.FileLoggerWriter());


            var plugins = ConfigManager.configEntry.unityPluginConfig.unityPlugins;

            // 处理只转换一个插件的情况
            if (single != null)
            {
                // if (single.pluginState == UnityPlugin.PluginState.stub) {
                //     single.stubConfig.generateJSTemplate = true;
                // }
                plugins = new List <UnityPlugin>()
                {
                    single
                };
            }

            plugins
            .Where(p => p.enable)
            .ToList()
            .ForEach(plugin => {
                // clear temp
                RemoveTempCodeDir();

                var bridgeOptions = new BridgeOptions();
                if (plugin.pluginState == UnityPlugin.PluginState.convert)
                {
                    plugin.convertedPath = new UnityPlugin.ConvertedPath(plugin);
                    ConfigureBridgeOptionsForConvertPlugin(ref bridgeOptions, plugin);

                    ProcessBridge(bridgeOptions, logger,
                                  // Pre Process
                                  (processor) => {
                        // add plugin outside
                        logger.Info("Add Plugin...");
                        if (single != null)
                        {
                            processor.Translator.Plugins.AddPlugin(new BridgePlugin(single.pluginName));
                        }
                        else
                        {
                            processor.Translator.Plugins.AddPlugin(new BridgePlugin());
                        }
                        logger.Info("Add Plugin...[done]");

                        // clean js output
                        DirectoryUtil.DeleteDirectory(plugin.convertedPath.convertedJSPath);

                        {
                            // remove all dll2
                            var distDir = references["Bridge"].FullPath;
                            Directory.EnumerateFiles(distDir, "*.dll2", SearchOption.AllDirectories)
                            .ToList()
                            .ForEach(f => {
                                File.Delete(f);
                            });
                        }

                        {
                            // copy all plugins dlls into references path
                            var dlls    = GetDepDlls(plugin);
                            var distDir = references["Bridge"].FullPath;
                            dlls.ForEach(dll => {
                                var fileName = Path.GetFileNameWithoutExtension(dll);
                                File.Copy(dll, Path.Combine(distDir, fileName + ".dll2"), true);
                            });
                        }
                    },

                                  // Post Process
                                  (processor) => {
                        // caching binding scripts
                        var dir            = build["Temp"]["bindings"];
                        var bindingScripts = Directory.EnumerateFiles(dir, "*.js", SearchOption.AllDirectories);
                        var cacheDir       = build["BindingsCache"].FullPath;
                        if (!Directory.Exists(cacheDir))
                        {
                            Directory.CreateDirectory(cacheDir);
                        }
                        foreach (var bs in bindingScripts)
                        {
                            var fileName = Path.GetFileName(bs);
                            File.Copy(bs, Path.Combine(cacheDir, fileName), true);
                        }

                        // move files to plugin js output
                        var tmpPath = build["Temp"].FullPath;
                        var projDir = plugin.convertedPath.convertedJSPath;
                        DirectoryUtil.CopyDirectory(tmpPath, projDir);
                        DirectoryUtil.DeleteDirectory(tmpPath);

                        // move dll to plugin dll output
                        var projDllSrc  = build["Output"][plugin.pluginName + ".dll"];
                        var projDllDist = plugin.convertedPath.convertedDLLPath;
                        File.Copy(projDllSrc, projDllDist, true);

                        Debug.Log("<" + plugin.pluginName + "> convertion finish.");
                    }
                                  );
                }
                else if (plugin.pluginState == UnityPlugin.PluginState.stub)
                {
                    // generate cs stub
                    if (plugin.stubConfig.generateStub)
                    {
                        plugin.stubPath = new UnityPlugin.StubPath(plugin);
                        GenerateStubProc.GeneratePluginStub(plugin);
                        Debug.Log("Generate Stub <" + plugin.pluginName + ">");

                        // 自动生成桩代码只需要一次
                        plugin.stubConfig.generateStub = false;
                    }


                    // generate js stub template
                    if (plugin.stubConfig.generateJSTemplate)
                    {
                        ConfigureBridgeOptionsForStubPlugin(ref bridgeOptions, plugin);
                        ProcessBridge(bridgeOptions, logger,
                                      // Pre Process
                                      (processor) => {
                            // add plugin outside
                            if (single != null)
                            {
                                processor.Translator.Plugins.AddPlugin(new BridgePlugin(single.pluginName + "-stub"));
                            }
                            else
                            {
                                processor.Translator.Plugins.AddPlugin(new BridgePlugin());
                            }

                            // clean js output
                            DirectoryUtil.DeleteDirectory(plugin.stubPath.stubJSPath);

                            {
                                // remove all dll2
                                var distDir = references["Bridge"].FullPath;
                                Directory.EnumerateFiles(distDir, "*.dll2", SearchOption.AllDirectories)
                                .ToList()
                                .ForEach(f => {
                                    File.Delete(f);
                                });
                            }

                            {
                                // copy unity stub dll
                                var dll      = UnityPluginUtil.GetUnityEngineStub().stubPath.stubDLLPath;
                                var fileName = Path.GetFileNameWithoutExtension(dll);
                                var distDir  = references["Bridge"].FullPath;
                                File.Copy(dll, Path.Combine(distDir, fileName + ".dll2"), true);
                            }
                        },

                                      // Post Process
                                      (processor) => {
                            // caching binding scripts
                            var dir            = build["Temp"]["bindings"];
                            var bindingScripts = Directory.EnumerateFiles(dir, "*.js", SearchOption.AllDirectories);
                            var cacheDir       = build["BindingsCache"].FullPath;
                            if (!Directory.Exists(cacheDir))
                            {
                                Directory.CreateDirectory(cacheDir);
                            }
                            foreach (var bs in bindingScripts)
                            {
                                var fileName = Path.GetFileName(bs);
                                File.Copy(bs, Path.Combine(cacheDir, fileName), true);
                            }

                            if (single != null)
                            {
                                single.stubConfig.generateJSTemplate = false;
                            }
                            // move files to plugin js output
                            var tmpPath   = build["Temp"].FullPath;
                            var stubJSDir = plugin.stubPath.stubJSPath;
                            DirectoryUtil.CopyDirectory(tmpPath, stubJSDir);
                            DirectoryUtil.DeleteDirectory(tmpPath);
                            Debug.Log("<" + plugin.pluginName + "> stub template convertion finish.");
                        }
                                      );
                    }
                }

                EditorUtility.DisplayProgressBar("Exporting", "...", 0.0f);
            });
        }
Пример #15
0
        private static void ConfigureBridgeOptionsForStubPlugin(ref BridgeOptions bridgeOptions, UnityPlugin config)
        {
            bridgeOptions.ProjectProperties = new ProjectProperties();

            bridgeOptions.BridgeLocation = references["Bridge"]["Bridge.dll"];
            bridgeOptions.Lib            = build["Output"][config.pluginName + "-stub.dll"];
            bridgeOptions.ReferencesPath = references["Bridge"].FullPath;
            bridgeOptions.ProjectProperties.Configuration = configs["Text"]["bridge.json"].PathToAssets();

            bridgeOptions.Folder = Path.GetFullPath(".");

            var src = config.stubPath.stubCSPath.PathToAssets() + ";" + config.stubPath.stubRefCSPath.PathToAssets();

            bridgeOptions.Sources           = src;
            bridgeOptions.ExcludeSubFolders = "";

            bridgeOptions.Rebuild         = true;
            bridgeOptions.Recursive       = true;
            bridgeOptions.Name            = config.pluginName;
            bridgeOptions.OutputLocation  = bridgeOptions.Folder;
            bridgeOptions.DefaultFileName = Path.GetFileNameWithoutExtension(bridgeOptions.Lib);
            bridgeOptions.ProjectProperties.AssemblyName    = bridgeOptions.DefaultFileName;
            bridgeOptions.ProjectProperties.DefineConstants = config.defineMacros.Join(";");
        }
        private static void GeneratePluginStubCs(UnityPlugin plugin)
        {
            if (!plugin.enable)
            {
                return;
            }

            var output = plugin.stubPath.stubCSPath;
            var dll    = plugin.stubPath.stubDLLPath.Replace("-stub.dll", "-internal.dll");

            if (dll == null || dll == "")
            {
                return;
            }
            try {
                var assembly = Assembly.LoadFile(dll);
                StubBuilder.Build(new StubOptions {
                    stubName   = plugin.pluginName,
                    outputPath = output,
                    whiteList  = assembly.ExportedTypes,
                    filter     = t => {
                        if (t == null)
                        {
                            return(false);
                        }
                        if (assembly.ExportedTypes.Contains(t))
                        {
                            return(true);
                        }
                        return(assembly.ExportedTypes.Contains(t.DeclaringType));
                    },
                    namespaceInterceptor = type => {
                        // 不允许没有 Namespace
                        if (type == null)
                        {
                            return(Utils.NamespaceName);
                        }
                        var ns = type.Namespace;
                        if (string.IsNullOrEmpty(ns))
                        {
                            return(Utils.NamespaceName);
                        }
                        return(null);
                    }
                });
            } catch (FileNotFoundException e) {
                Debug.LogError(dll + " not exists");
            } catch (Exception ex) {
                Debug.LogError(ex);
            }

            // header
            var allRefContent = string.Format(topHeader, plugin.pluginName);

            string content = "";

            using (StreamReader sr = new StreamReader(output)) {
                content = sr.ReadToEnd();
            }
            if (content == null || content == "" || content.Length == 0)
            {
                return;
            }

            using (var sw = new StreamWriter(output, false)) {
                sw.Write(allRefContent);
                sw.Write(content);
            }
        }
Пример #17
0
 public ConvertedPath(UnityPlugin plugin)
 {
     convertedJSPath  = PathUtil.GetPluginOutputPath(plugin, PathUtil.PluginOutputType.JS);
     convertedDLLPath = PathUtil.GetPluginOutputPath(plugin, PathUtil.PluginOutputType.DLL);
 }