Initial commit: Client Doc docs Server Tools

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
ud18010
2026-07-10 10:24:29 +08:00
co-authored by Cursor
commit 7e35d8da31
3374 changed files with 680813 additions and 0 deletions
@@ -0,0 +1,29 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: e6914217da6edb34baad8872f8642df3, type: 3}
m_Name: GroundToolConfig
m_EditorClassIdentifier:
randOffset: 0
randJitter: 0.1
width: 128
length: 128
height: 30
perlinScale: 0.05
groundIncline: 0.01
matSplit1: 0.25
matSplit2: 0.5
matSplit3: 0.75
power: 2
texGround1: {fileID: 0}
texGround2: {fileID: 0}
texGround3: {fileID: 0}
texGround4: {fileID: 0}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1ffcafc0382981e4ea66da337163c171
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 55b10dbb5dfe31b41ad1150327f5c12d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,152 @@
using HybridCLR.Editor.Commands;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
namespace HybridCLR.Editor
{
public static class BuildAssetsCommand
{
public static string HybridCLRBuildCacheDir => Application.dataPath + "/HybridCLRBuildCache";
public static string AssetBundleOutputDir => $"{HybridCLRBuildCacheDir}/AssetBundleOutput";
public static string AssetBundleSourceDataTempDir => $"{HybridCLRBuildCacheDir}/AssetBundleSourceData";
public static string GetAssetBundleOutputDirByTarget(BuildTarget target)
{
return $"{AssetBundleOutputDir}/{target}";
}
public static string GetAssetBundleTempDirByTarget(BuildTarget target)
{
return $"{AssetBundleSourceDataTempDir}/{target}";
}
public static string ToRelativeAssetPath(string s)
{
return s.Substring(s.IndexOf("Assets/"));
}
/// <summary>
/// 将HotFix.dll和HotUpdatePrefab.prefab打入common包.
/// 将HotUpdateScene.unity打入scene包.
/// </summary>
/// <param name="tempDir"></param>
/// <param name="outputDir"></param>
/// <param name="target"></param>
private static void BuildAssetBundles(string tempDir, string outputDir, BuildTarget target)
{
Directory.CreateDirectory(tempDir);
Directory.CreateDirectory(outputDir);
List<AssetBundleBuild> abs = new List<AssetBundleBuild>();
{
var prefabAssets = new List<string>();
string testPrefab = $"{Application.dataPath}/Prefabs/HotUpdatePrefab.prefab";
prefabAssets.Add(testPrefab);
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
abs.Add(new AssetBundleBuild
{
assetBundleName = "prefabs",
assetNames = prefabAssets.Select(s => ToRelativeAssetPath(s)).ToArray(),
});
}
BuildPipeline.BuildAssetBundles(outputDir, abs.ToArray(), BuildAssetBundleOptions.None, target);
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
}
public static void BuildAssetBundleByTarget(BuildTarget target)
{
BuildAssetBundles(GetAssetBundleTempDirByTarget(target), GetAssetBundleOutputDirByTarget(target), target);
}
[MenuItem("HybridCLR/Build/BuildAssetsAndCopyToStreamingAssets")]
public static void BuildAndCopyABAOTHotUpdateDlls()
{
BuildAssetBundleByTarget(EditorUserBuildSettings.activeBuildTarget);
CopyAssetBundlesToStreamingAssets();
CompileDllCommand.CompileDllActiveBuildTarget();
CopyAOTAssembliesToStreamingAssets();
CopyHotUpdateAssembliesToStreamingAssets();
}
//[MenuItem("HybridCLR/Build/Copy_AB_AOT_HotUpdateDlls")]
public static void Copy_AB_AOT_HotUpdateDlls()
{
CopyAOTAssembliesToStreamingAssets();
CopyHotUpdateAssembliesToStreamingAssets();
CopyAssetBundlesToStreamingAssets();
}
//[MenuItem("HybridCLR/Build/BuildAssetbundle")]
public static void BuildSceneAssetBundleActiveBuildTargetExcludeAOT()
{
BuildAssetBundleByTarget(EditorUserBuildSettings.activeBuildTarget);
}
public static void CopyAOTAssembliesToStreamingAssets()
{
var target = EditorUserBuildSettings.activeBuildTarget;
string aotAssembliesSrcDir = SettingsUtil.GetAssembliesPostIl2CppStripDir(target);
string aotAssembliesDstDir = Application.streamingAssetsPath+"/xaot";//改为aot目录
if (!Directory.Exists(aotAssembliesDstDir))
Directory.CreateDirectory(aotAssembliesDstDir);
foreach (var dll in Packager.AOTMetaAssemblyNames)
{
string srcDllPath = $"{aotAssembliesSrcDir}/{dll}";
if (!File.Exists(srcDllPath))
{
Debug.LogError($"ab中添加AOT补充元数据dll:{srcDllPath} 时发生错误,文件不存在。裁剪后的AOT dll在BuildPlayer时才能生成,因此需要你先构建一次游戏App后再打包。");
continue;
}
string dllBytesPath = $"{aotAssembliesDstDir}/{dll}";
File.Copy(srcDllPath, dllBytesPath, true);
Debug.Log($"[CopyAOTAssembliesToStreamingAssets] copy AOT dll {srcDllPath} -> {dllBytesPath}");
}
}
public static void CopyHotUpdateAssembliesToStreamingAssets()
{
var target = EditorUserBuildSettings.activeBuildTarget;
string hotfixDllSrcDir = SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target);
string hotfixAssembliesDstDir = Application.streamingAssetsPath+"/xhotfix";//改为hotfix目录
if (!Directory.Exists(hotfixAssembliesDstDir))
Directory.CreateDirectory(hotfixAssembliesDstDir);
foreach (var dll in SettingsUtil.HotUpdateAssemblyFilesExcludePreserved)
{
string dllPath = $"{hotfixDllSrcDir}/{dll}";
string dllBytesPath = $"{hotfixAssembliesDstDir}/{dll}";
File.Copy(dllPath, dllBytesPath, true);
Debug.Log($"[CopyHotUpdateAssembliesToStreamingAssets] copy hotfix dll {dllPath} -> {dllBytesPath}");
}
}
public static void CopyAssetBundlesToStreamingAssets()
{
var target = EditorUserBuildSettings.activeBuildTarget;
string streamingAssetPathDst = Application.streamingAssetsPath;
Directory.CreateDirectory(streamingAssetPathDst);
string outputDir = GetAssetBundleOutputDirByTarget(target);
var abs = new string[] { "prefabs" };
foreach (var ab in abs)
{
string srcAb = ToRelativeAssetPath($"{outputDir}/{ab}");
string dstAb = ToRelativeAssetPath($"{streamingAssetPathDst}/{ab}");
Debug.Log($"[CopyAssetBundlesToStreamingAssets] copy assetbundle {srcAb} -> {dstAb}");
AssetDatabase.CopyAsset( srcAb, dstAb);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7417143702c594642ba8d9a138dbfa1d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,79 @@
#if EngineEditor
using HybridCLR.Editor.Commands;
using HybridCLR.Editor.Installer;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace HybridCLR.Editor
{
public class BuildPlayerCommand
{
public static void CopyAssets(string outputDir)
{
Directory.CreateDirectory(outputDir);
foreach(var srcFile in Directory.GetFiles(Application.streamingAssetsPath))
{
string dstFile = $"{outputDir}/{Path.GetFileName(srcFile)}";
File.Copy(srcFile, dstFile, true);
}
}
private static string[] FindEnabledEditorScenes()
{
List<string> EditorScenes = new List<string>();
foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
{
if (!scene.enabled) continue;
EditorScenes.Add(scene.path);
}
return EditorScenes.ToArray();
}
[MenuItem("HybridCLR/Build/Win64")]
public static void Build_Win64()
{
BuildTarget target = BuildTarget.StandaloneWindows64;
BuildTarget activeTarget = EditorUserBuildSettings.activeBuildTarget;
if (activeTarget != BuildTarget.StandaloneWindows64 && activeTarget != BuildTarget.StandaloneWindows)
{
Debug.LogError("请先切到Win平台再打包");
return;
}
// Get filename.
string outputPath = $"{SettingsUtil.ProjectDir}/Release-Win64";
var buildOptions = BuildOptions.CompressWithLz4;
string location = $"{outputPath}/HybridCLRTrial.exe";
PrebuildCommand.GenerateAll();
Debug.Log("====> Build App");
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions()
{
scenes = FindEnabledEditorScenes(),//new string[] { "Assets/Scenes/SimpleScene.unity" },
locationPathName = location,
options = buildOptions,
target = target,
targetGroup = BuildTargetGroup.Standalone,
};
var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
{
Debug.LogError("打包失败");
return;
}
Debug.Log("====> 复制热更新资源和代码");
BuildAssetsCommand.BuildAndCopyABAOTHotUpdateDlls();
BashUtil.CopyDir(Application.streamingAssetsPath, $"{outputPath}/HybridCLRTrial_Data/StreamingAssets", true);
#if UNITY_EDITOR
Application.OpenURL($"file:///{location}");
#endif
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9fc09201239ded843a793c9167e0ff6a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 227b11ce7187c9b4da274d4119b36597
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+136
View File
@@ -0,0 +1,136 @@
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace XGame.Editor
{
// publish.json 视图(JsonUtilityC# 字段名须与 json 键一致,故小写开头)
[Serializable]
public sealed class MiniGamePublishSpec
{
public string gameId;
public string serverSrcDir; // 相对 Server/games-src/
public string serverProject; // 相对 serverSrcDir
public string serverAssembly;
public string serverEntryType;
public string clientProject; // 相对仓库根
public string coreDll;
public string clientDll;
public string clientEntryType;
public int minFrameworkVersion = 1;
public int playerCount = 2;
public int tickRateHz = 10;
}
public static class MiniGamePublishMenu
{
[MenuItem("XWorld/生成小游戏更新", false, 802)]
public static void Open() => MiniGamePublishWindow.Open();
}
public sealed class MiniGamePublishWindow : EditorWindow
{
private string[] _gameDirs = Array.Empty<string>();
private string[] _gameNames = Array.Empty<string>();
private int _selected;
private int _version = 1;
private bool _pc, _android, _ios, _webgl;
private Vector2 _scroll;
public static void Open()
{
var w = GetWindow<MiniGamePublishWindow>("生成小游戏更新");
w.minSize = new Vector2(360, 320);
w.RefreshGames();
w.Show();
}
private void RefreshGames()
{
string root = Path.Combine(Application.dataPath, "MiniGames");
_gameDirs = Directory.Exists(root)
? Directory.GetDirectories(root).Where(d => File.Exists(Path.Combine(d, "publish.json"))).ToArray()
: Array.Empty<string>();
_gameNames = _gameDirs.Select(Path.GetFileName).ToArray();
_selected = Mathf.Clamp(_selected, 0, Mathf.Max(0, _gameDirs.Length - 1));
// 默认平台 = 当前激活 BuildTarget
_pc = _android = _ios = _webgl = false;
switch (EditorUserBuildSettings.activeBuildTarget)
{
case BuildTarget.Android: _android = true; break;
case BuildTarget.iOS: _ios = true; break;
case BuildTarget.WebGL: _webgl = true; break;
default: _pc = true; break;
}
RefreshDefaultVersion();
}
private void RefreshDefaultVersion()
{
if (_gameDirs.Length == 0) return;
var spec = LoadSpec(_gameDirs[_selected]);
_version = (spec == null || string.IsNullOrEmpty(spec.gameId))
? 1 : MiniGamePublishPipeline.NextVersion(spec.gameId);
}
private static MiniGamePublishSpec LoadSpec(string gameDir)
{
try { return JsonUtility.FromJson<MiniGamePublishSpec>(File.ReadAllText(Path.Combine(gameDir, "publish.json"))); }
catch (Exception e) { Debug.LogError("[MiniGamePublish] publish.json 解析失败: " + e.Message); return null; }
}
private void OnGUI()
{
if (_gameDirs.Length == 0)
{
EditorGUILayout.HelpBox("Assets/MiniGames 下没有含 publish.json 的小游戏目录。", MessageType.Warning);
if (GUILayout.Button("刷新")) RefreshGames();
return;
}
_scroll = EditorGUILayout.BeginScrollView(_scroll);
EditorGUILayout.LabelField("小游戏", EditorStyles.boldLabel);
int sel = GUILayout.SelectionGrid(_selected, _gameNames, 1, EditorStyles.radioButton);
if (sel != _selected) { _selected = sel; RefreshDefaultVersion(); }
EditorGUILayout.Space();
_version = Mathf.Max(1, EditorGUILayout.IntField("版本号", _version));
EditorGUILayout.Space();
EditorGUILayout.LabelField("平台(AB 按平台构建)", EditorStyles.boldLabel);
_pc = EditorGUILayout.ToggleLeft("PC (StandaloneWindows64)", _pc);
_android = EditorGUILayout.ToggleLeft("Android", _android);
_ios = EditorGUILayout.ToggleLeft("iOS", _ios);
_webgl = EditorGUILayout.ToggleLeft("WebGL", _webgl);
EditorGUILayout.EndScrollView();
EditorGUILayout.Space();
using (new EditorGUI.DisabledScope(!(_pc || _android || _ios || _webgl)))
{
if (GUILayout.Button("生成", GUILayout.Height(32)))
{
var spec = LoadSpec(_gameDirs[_selected]);
if (spec == null || string.IsNullOrEmpty(spec.gameId))
{
EditorUtility.DisplayDialog("生成小游戏更新", "publish.json 无效(缺 gameId", "OK");
}
else
{
var targets = new List<MiniGamePublishPipeline.PlatformChoice>();
if (_pc) targets.Add(new MiniGamePublishPipeline.PlatformChoice("pc", BuildTarget.StandaloneWindows64));
if (_android) targets.Add(new MiniGamePublishPipeline.PlatformChoice("android", BuildTarget.Android));
if (_ios) targets.Add(new MiniGamePublishPipeline.PlatformChoice("ios", BuildTarget.iOS));
if (_webgl) targets.Add(new MiniGamePublishPipeline.PlatformChoice("webgl", BuildTarget.WebGL));
MiniGamePublishPipeline.Run(spec, _gameDirs[_selected], _version, targets);
}
}
}
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0582fda2162516d46b2e207152dd6b35
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,299 @@
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace XGame.Editor
{
// 生成小游戏更新的流水线:dotnet build 两端 DLL → 打代码/资源 AB → PublishTool.Cli 落位。
// 产物:CDN/minigame/<id>/<ver>/<platform>/(客户端)、deploy/minigame/<id>/<ver>/(服务器)。
public static class MiniGamePublishPipeline
{
public struct PlatformChoice
{
public string Name; public BuildTarget Target;
public PlatformChoice(string name, BuildTarget target) { Name = name; Target = target; }
}
// resolved-spec.json(交给 PublishTool.Cli;字段小写对齐 GameSpecJson 大小写不敏感解析)
[Serializable]
private sealed class ResolvedSpecJson
{
public string gameId; public int version; public int minFrameworkVersion;
public int playerCount; public int tickRateHz;
public string serverAssembly; public string serverEntryType;
public string coreDll; public string clientDll; public string clientEntryType;
public string codeAb; public List<string> assets;
}
private const string CodeAbName = "code.unity3d";
private const string ResAbName = "res.unity3d";
// staging 不能用 '~' 隐藏目录:隐藏资产不入 AssetDatabase,进不了 AB
private const string StagingAssetDir = "Assets/MiniGameStaging";
private const string CliProject = "Server/PublishTool.Cli/PublishTool.Cli.csproj";
private const string CliDll = "Server/PublishTool.Cli/bin/Release/net10.0/XWorld.PublishTool.Cli.dll";
private const string PrivateKeyRel = "Tools/keys/minigame-private.pem";
private static string RepoRoot => Path.GetFullPath(Path.Combine(Application.dataPath, "../.."));
// 当前 Editor 安装目录(…/Editor),传给 RPS.Client.csproj 的 UnityEditorPath 以定位 UnityEngine dll
private static string UnityEditorDir => Path.GetDirectoryName(EditorApplication.applicationPath);
// 默认版本号 = CDN/minigame/<gameId>/ 下已有数字目录 max+1
public static int NextVersion(string gameId)
{
string dir = Path.Combine(RepoRoot, "CDN/minigame", gameId);
int max = 0;
if (Directory.Exists(dir))
foreach (var d in Directory.GetDirectories(dir))
if (int.TryParse(Path.GetFileName(d), out int v) && v > max) max = v;
return max + 1;
}
public static void Run(MiniGamePublishSpec spec, string gameDir, int version, List<PlatformChoice> platforms)
{
string cdnVerDir = Path.Combine(RepoRoot, "CDN/minigame", spec.gameId, version.ToString());
string deployVerDir = Path.Combine(RepoRoot, "deploy/minigame", spec.gameId, version.ToString());
if ((Directory.Exists(cdnVerDir) || Directory.Exists(deployVerDir)) &&
!EditorUtility.DisplayDialog("生成小游戏更新",
$"版本 {spec.gameId}/{version} 已存在,覆盖重发?\n{cdnVerDir}\n{deployVerDir}", "覆盖", "取消"))
return;
// 覆盖重发只勾部分平台时,未勾的旧平台 AB 会与新服务器 DLL 不一致——需用户明确确认
if (Directory.Exists(cdnVerDir))
{
var known = new[] { "pc", "android", "ios", "webgl" };
var chosen = new HashSet<string>(platforms.Select(p => p.Name));
var stale = Directory.GetDirectories(cdnVerDir)
.Select(Path.GetFileName)
.Where(n => known.Contains(n) && !chosen.Contains(n))
.ToArray();
if (stale.Length > 0 &&
!EditorUtility.DisplayDialog("生成小游戏更新",
$"版本 {spec.gameId}/{version} 下这些平台不在本次勾选中,将保留旧包并与新服务器 DLL 不一致:\n{string.Join(", ", stale)}\n\n继续?(建议全平台重发或换新版本号)", "继续", "取消"))
return;
}
string tmp = Path.Combine(RepoRoot, "Temp/MiniGamePublish", spec.gameId);
string keyPath = Path.Combine(RepoRoot, PrivateKeyRel);
bool signed = File.Exists(keyPath);
try
{
if (Directory.Exists(tmp)) Directory.Delete(tmp, true);
Directory.CreateDirectory(tmp);
// 1) 服务器 DLL
Progress("dotnet build (server)", 0.05f);
string serverProj = Path.Combine(RepoRoot, "Server/games-src", spec.serverSrcDir, spec.serverProject);
RunOrThrow("dotnet build (server)", "dotnet", $"build \"{serverProj}\" -c Release -nologo");
string serverBin = Path.Combine(Path.GetDirectoryName(serverProj), "bin/Release/netstandard2.1");
RequireFile(Path.Combine(serverBin, spec.serverAssembly));
RequireFile(Path.Combine(serverBin, spec.coreDll));
// 2) 客户端 DLL(Core 取服务器构建产物——两端同一 ILUnityEditorPath 用当前 Editor
Progress("dotnet build (client)", 0.15f);
string clientProj = Path.Combine(RepoRoot, spec.clientProject);
RunOrThrow("dotnet build (client)", "dotnet",
$"build \"{clientProj}\" -c Release -nologo -p:UnityEditorPath=\"{UnityEditorDir}\"");
string clientBin = Path.Combine(Path.GetDirectoryName(clientProj), "bin/Release/netstandard2.1");
RequireFile(Path.Combine(clientBin, spec.clientDll));
// 3) DLL → Assets staging.bytes 才能作为 TextAsset 进 AB
Progress("导入 DLL 为 TextAsset", 0.25f);
string stagingFull = Path.Combine(Application.dataPath, "MiniGameStaging/code");
Directory.CreateDirectory(stagingFull);
File.Copy(Path.Combine(serverBin, spec.coreDll), Path.Combine(stagingFull, spec.coreDll + ".bytes"), true);
File.Copy(Path.Combine(clientBin, spec.clientDll), Path.Combine(stagingFull, spec.clientDll + ".bytes"), true);
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
string[] codeAssets =
{
$"{StagingAssetDir}/code/{spec.coreDll}.bytes",
$"{StagingAssetDir}/code/{spec.clientDll}.bytes",
};
// 4) 每平台打 AB
string[] resAssets = CollectResAssets(Path.GetFileName(gameDir));
var builds = new List<AssetBundleBuild>
{
new AssetBundleBuild { assetBundleName = CodeAbName, assetNames = codeAssets },
};
if (resAssets.Length > 0)
builds.Add(new AssetBundleBuild { assetBundleName = ResAbName, assetNames = resAssets });
else
Debug.LogWarning($"[MiniGamePublish] {gameDir}/res 为空,跳过资源 AB(仅发代码 AB)");
foreach (var pf in platforms)
{
Progress($"BuildAssetBundles ({pf.Name})", 0.35f);
string abOut = Path.Combine(tmp, "ab", pf.Name);
Directory.CreateDirectory(abOut);
var manifest = BuildPipeline.BuildAssetBundles(
abOut, builds.ToArray(), BuildAssetBundleOptions.ChunkBasedCompression, pf.Target);
if (manifest == null) throw new Exception($"BuildAssetBundles 失败: {pf.Name}");
RequireFile(Path.Combine(abOut, CodeAbName));
}
// 5) resolved-spec.json
var resolved = new ResolvedSpecJson
{
gameId = spec.gameId, version = version, minFrameworkVersion = spec.minFrameworkVersion,
playerCount = spec.playerCount, tickRateHz = spec.tickRateHz,
serverAssembly = spec.serverAssembly, serverEntryType = spec.serverEntryType,
coreDll = spec.coreDll, clientDll = spec.clientDll, clientEntryType = spec.clientEntryType,
codeAb = CodeAbName,
assets = resAssets.Length > 0 ? new List<string> { ResAbName } : new List<string>(),
};
string specPath = Path.Combine(tmp, "resolved-spec.json");
File.WriteAllText(specPath, JsonUtility.ToJson(resolved, true), new UTF8Encoding(false));
// 6) PublishTool.Cli 落位(先临时目录,成功后整体 Move,防 Cdn.Runner 提供半成品)
Progress("dotnet build (PublishTool.Cli)", 0.55f);
RunOrThrow("dotnet build (PublishTool.Cli)", "dotnet",
$"build \"{Path.Combine(RepoRoot, CliProject)}\" -c Release -nologo");
string cliDll = Path.Combine(RepoRoot, CliDll);
RequireFile(cliDll);
string keyArg = signed ? $" --key \"{keyPath}\"" : "";
// 6a) 服务器:只汇集需要的两个 DLL 作为 src
Progress("发布 server", 0.65f);
string serverSrc = Path.Combine(tmp, "server-src");
Directory.CreateDirectory(serverSrc);
File.Copy(Path.Combine(serverBin, spec.serverAssembly), Path.Combine(serverSrc, spec.serverAssembly), true);
File.Copy(Path.Combine(serverBin, spec.coreDll), Path.Combine(serverSrc, spec.coreDll), true);
string outServer = Path.Combine(tmp, "out-server");
RunOrThrow("PublishTool.Cli (server)", "dotnet",
$"\"{cliDll}\" --mode server --src \"{serverSrc}\" --out \"{outServer}\" --spec \"{specPath}\"{keyArg}");
// 6b) 客户端:每平台一次,src = 该平台 AB 输出目录
var outClients = new List<KeyValuePair<string, string>>();
foreach (var pf in platforms)
{
Progress($"发布 client ({pf.Name})", 0.75f);
string outClient = Path.Combine(tmp, "out-client-" + pf.Name);
RunOrThrow($"PublishTool.Cli (client {pf.Name})", "dotnet",
$"\"{cliDll}\" --mode client --src \"{Path.Combine(tmp, "ab", pf.Name)}\" --out \"{outClient}\" --spec \"{specPath}\"{keyArg}");
outClients.Add(new KeyValuePair<string, string>(pf.Name, outClient));
}
// 7) 原子落位:客户端全部就位后才落服务器——服务器 game.json 是新版本"生效"开关,
// 先落它而客户端 Move 失败会导致网关广播新版本但 CDN 缺包
Progress("落位 CDN/deploy", 0.9f);
foreach (var kv in outClients)
MoveIntoPlace(kv.Value, Path.Combine(cdnVerDir, kv.Key));
MoveIntoPlace(outServer, deployVerDir);
var sb = new StringBuilder();
sb.AppendLine($"生成完成:{spec.gameId} v{version}" + (signed ? "(已签名)" : "(未签名:无 " + PrivateKeyRel + ""));
sb.AppendLine("服务器: " + deployVerDir);
foreach (var kv in outClients)
sb.AppendLine($"客户端[{kv.Key}]: " + Path.Combine(cdnVerDir, kv.Key));
Debug.Log("[MiniGamePublish] " + sb);
EditorUtility.DisplayDialog("生成小游戏更新", sb.ToString(), "OK");
}
catch (Exception e)
{
Debug.LogError("[MiniGamePublish] 失败: " + e);
EditorUtility.DisplayDialog("生成小游戏更新失败", e.Message, "OK");
}
finally
{
EditorUtility.ClearProgressBar();
CleanupStaging();
try { if (Directory.Exists(tmp)) Directory.Delete(tmp, true); } catch { /* 被占用时留给下次 Run 清 */ }
}
}
private static void Progress(string info, float p)
=> EditorUtility.DisplayProgressBar("生成小游戏更新", info, p);
private static string[] CollectResAssets(string gameDirName)
{
string resPath = $"Assets/MiniGames/{gameDirName}/res";
if (!AssetDatabase.IsValidFolder(resPath)) return Array.Empty<string>();
return AssetDatabase.FindAssets("", new[] { resPath })
.Select(AssetDatabase.GUIDToAssetPath)
.Distinct()
.Where(p => !AssetDatabase.IsValidFolder(p))
.ToArray();
}
// 备份交换式落位:先把旧版挪到 .old,Move 新版成功后再删 .old;失败则回滚,避免"删旧后搬新失败"两头皆空
private static void MoveIntoPlace(string src, string dst)
{
Directory.CreateDirectory(Path.GetDirectoryName(dst));
string backup = dst + ".old";
if (Directory.Exists(backup)) Directory.Delete(backup, true);
bool hadOld = Directory.Exists(dst);
if (hadOld) Directory.Move(dst, backup);
try
{
Directory.Move(src, dst);
}
catch
{
if (hadOld && !Directory.Exists(dst)) Directory.Move(backup, dst); // 回滚旧版
throw;
}
if (hadOld) Directory.Delete(backup, true);
}
private static void RequireFile(string p)
{ if (!File.Exists(p)) throw new Exception("缺少构建产物: " + p); }
private static void CleanupStaging()
{
try
{
string full = Path.Combine(Application.dataPath, "MiniGameStaging");
bool dirty = false;
if (Directory.Exists(full)) { Directory.Delete(full, true); dirty = true; }
string meta = full + ".meta";
if (File.Exists(meta)) { File.Delete(meta); dirty = true; }
if (dirty) AssetDatabase.Refresh();
}
catch (Exception e)
{
Debug.LogWarning("[MiniGamePublish] 清理 staging 失败(不影响产物): " + e.Message);
}
}
// 起进程并收敛 stdout/stderr(事件式读取避免缓冲区互锁);非 0 退出码抛异常带输出尾部
private static string RunOrThrow(string step, string file, string args)
{
var psi = new System.Diagnostics.ProcessStartInfo
{
FileName = file, Arguments = args, WorkingDirectory = RepoRoot,
UseShellExecute = false, CreateNoWindow = true,
RedirectStandardOutput = true, RedirectStandardError = true,
StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8,
};
var sb = new StringBuilder();
using (var p = new System.Diagnostics.Process { StartInfo = psi })
{
p.OutputDataReceived += (_, e) => { if (e.Data != null) lock (sb) sb.AppendLine(e.Data); };
p.ErrorDataReceived += (_, e) => { if (e.Data != null) lock (sb) sb.AppendLine(e.Data); };
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
if (!p.WaitForExit(600_000))
{
try { p.Kill(); } catch { }
throw new Exception($"{step} 超时(>600s),已终止进程");
}
p.WaitForExit(); // 排干异步输出缓冲(有超时版 WaitForExit 不等 BeginOutputReadLine 完成)
string output = sb.ToString();
if (p.ExitCode != 0)
{
string tail = output.Length > 4000 ? output.Substring(output.Length - 4000) : output;
throw new Exception($"{step} 失败 (exit {p.ExitCode}):\n{tail}");
}
return output;
}
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 78411d4c938b22d4199fff6531c2920f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0ce88e84dc949614a82238427013eaec
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+178
View File
@@ -0,0 +1,178 @@
using System;
using System.Threading;
using UnityEditor;
using UnityEngine;
using System.IO;
using System.Diagnostics;
[InitializeOnLoad]
public static class CustomPlayModeHandler
{
static DateTime m_lastModified;
static bool m_enterPlayAfterServerReady;
static double m_waitServerStartTime;
const double WAIT_SERVER_TIMEOUT_SECONDS = 20.0;
static CustomPlayModeHandler()
{
string strLastTime = PlayerPrefs.GetString("LastModifiedTime");
if (strLastTime != null && strLastTime != "")
{
m_lastModified = DateTime.Parse(strLastTime);
//Debug.Log($"LastEditTime : {strLastTime}");
}
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
}
//[MenuItem("Tools/Run External Exe")]
public static void RunExe()
{
System.Diagnostics.Process pro;
string exePath = "../XDevNode/XNode.exe"; // 滻Ϊexeļ·
string curPath = System.IO.Directory.GetCurrentDirectory();
string runPath = $"{curPath}/{exePath}";//@"D:\UD\XWorld\XWorldClient\60s\..\XDevNode\XNode.exe";
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
info.FileName = runPath;
info.Arguments = "xid3278136192177 param2=488";//XID
info.WorkingDirectory = $"{curPath}/../XDevNode";
try
{
//Thread.Sleep(500);
pro = System.Diagnostics.Process.Start(info);
pro.EnableRaisingEvents = true;
//pro.Exited += new EventHandler(myProcess_Exited);
}
catch (System.ComponentModel.Win32Exception ex)
{
Console.WriteLine("ϵͳҲָļ/r{0}", ex.ToString());
return;
}
}
static bool IsProcessRunning(string processName)
{
// ȡͬ
Process[] processes = Process.GetProcessesByName(processName);
// ҵһ̣򷵻 true
return processes.Length > 0;
}
static void StartProcess(string executablePath)
{
RunExe();
}
private static void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (state == PlayModeStateChange.ExitingEditMode)
{
if (!m_enterPlayAfterServerReady && !XWorldUtil.IsPcMiniGameGatewayReady())
{
UnityEngine.Debug.Log("PC MiniGame Gateway is not ready. Starting it before entering Play Mode...");
EditorApplication.isPlaying = false;
m_enterPlayAfterServerReady = true;
m_waitServerStartTime = EditorApplication.timeSinceStartup;
XWorldUtil.OpenLocalServerAll();
EditorApplication.update -= WaitForServerThenEnterPlay;
EditorApplication.update += WaitForServerThenEnterPlay;
return;
}
m_enterPlayAfterServerReady = false;
EditorApplication.update -= WaitForServerThenEnterPlay;
XWorldUtil.OpenLocalServerAll();
//luaǷб仯server lua
/*if (IsPathChange())
{
string srcPath = "../Lua/server";
string dstPath = "../XDevNode/Data/XWorld/Script";
Packager.CopyPath(srcPath, dstPath);
//Thread.Sleep(1000);
PlayerPrefs.SetString("LastModifiedTime", m_lastModified.ToString());
}//*/
//Debug.Log("ģʽִԶ߼");
UnityEngine.Debug.Log("PC MiniGame Gateway checked. Legacy XNode auto-start is disabled for this flow.");
string processName = "XNode";
string executablePath = "../XDevNode/XNode.exe";
if (false && !IsProcessRunning(processName))
{
StartProcess(executablePath);
}
else
{
UnityEngine.Debug.Log("Legacy XNode server startup skipped.");
//Console.WriteLine($"{processName} ѾС");
}
}
else if (state == PlayModeStateChange.ExitingPlayMode)
{
UnityEngine.Debug.Log("Exist Playing");
}
}
private static void WaitForServerThenEnterPlay()
{
if (XWorldUtil.IsPcMiniGameGatewayReady())
{
EditorApplication.update -= WaitForServerThenEnterPlay;
UnityEngine.Debug.Log("PC MiniGame Gateway is ready. Entering Play Mode.");
EditorApplication.EnterPlaymode();
return;
}
if (EditorApplication.timeSinceStartup - m_waitServerStartTime > WAIT_SERVER_TIMEOUT_SECONDS)
{
EditorApplication.update -= WaitForServerThenEnterPlay;
m_enterPlayAfterServerReady = false;
UnityEngine.Debug.LogError("Timed out waiting for PC MiniGame Gateway. Check XWorld/Server/Open Latest Log.");
}
}
public static bool IsPathChange()
{
if (m_lastModified == null)
{
m_lastModified = DateTime.Now;
UnityEngine.Debug.Log($"Now Time");
return true;
}
else
{
DateTime lastModified = m_lastModified;
lastModified = RecursiveLastEditTime("../Lua/server", lastModified);
if ((lastModified - m_lastModified).TotalSeconds > 1)
{
m_lastModified = lastModified;
UnityEngine.Debug.Log($"LastEditTime Change: {m_lastModified}");
return true;
}
}
return false;
}
static DateTime RecursiveLastEditTime(string path, DateTime lastTime)
{
string[] names = Directory.GetFiles(path);
string[] dirs = Directory.GetDirectories(path);
foreach (string filename in names)
{
DateTime lastModified = File.GetLastWriteTime(filename);
if (lastModified > lastTime)
lastTime = lastModified;
}
foreach (string dir in dirs)
{
if (dir.IndexOf(".svn") >= 0)
{
continue;
}
//paths.Add(dir.Replace('\\', '/'));
lastTime = RecursiveLastEditTime(dir, lastTime);
}
return lastTime;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 320e3c8c55bdb1b49a72d97694c543cd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 42e415b5498e64649820a541b7304052
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,478 @@
using System;
using System.IO;
using Unity.VisualScripting.FullSerializer;
using UnityEditor;
using UnityEngine;
public static class GroundTools
{
[MenuItem("GroundTools/GroundToolWindow")]
public static void OpenGroundToolWindow()
{
GroundToolWindow window = EditorWindow.GetWindow<GroundToolWindow>("地形工具");
window.Show();
}
}
public class GroundToolWindow : EditorWindow
{
private string configPath = "Assets/Editor/GroundToolConfig.asset";
private GroundToolConfig groundToolConfig;
private GameObject selectedGround;
private bool isConfigChange = false;
private float lastChangeTime = 0;// Time.realtimeSinceStartup;
private void OnEnable()
{
// 窗口打开时加载配置
LoadConfig();
}
private void LoadConfig()
{
// 尝试从指定路径加载配置
groundToolConfig = AssetDatabase.LoadAssetAtPath<GroundToolConfig>(configPath);
if (groundToolConfig == null)
{
// 如果配置不存在,则创建一个新的
groundToolConfig = CreateInstance<GroundToolConfig>();
// 确保目录存在
string directory = Path.GetDirectoryName(configPath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
// 创建资产文件
AssetDatabase.CreateAsset(groundToolConfig, configPath);
AssetDatabase.SaveAssets();
Debug.Log("创建新的地形工具配置文件: " + configPath);
}
}
private void SaveConfig()
{
if (groundToolConfig != null)
{
EditorUtility.SetDirty(groundToolConfig); // 确保Unity知道资产需要保存
AssetDatabase.SaveAssets(); // 保存资产
isConfigChange = false;
Debug.Log("地形工具配置已保存。");
}
}
/// <summary>
/// 绘制编辑器窗口UI
/// </summary>
private void OnGUI()
{
GUILayout.Label("地形创建工具", EditorStyles.boldLabel);
// 创建地形按钮
if (GUILayout.Button("创建地形"))
{
//选择需要存储文件的路径
CreateGround();
}
EditorGUILayout.Space(10);
// 参数设置
groundToolConfig.width = EditorGUILayout.IntField("横格", groundToolConfig.width);
groundToolConfig.length = EditorGUILayout.IntField("纵格", groundToolConfig.length);
groundToolConfig.height = EditorGUILayout.FloatField("高度", groundToolConfig.height);
groundToolConfig.perlinScale = EditorGUILayout.Slider("噪声缩放", groundToolConfig.perlinScale, 0.01f, 1f);
groundToolConfig.groundIncline = EditorGUILayout.Slider("地面坡度", groundToolConfig.groundIncline, 0f, 1f);
EditorGUILayout.Space(10);
groundToolConfig.power = EditorGUILayout.Slider("过渡平滑度", groundToolConfig.power, 1f, 5f);
groundToolConfig.matSplit1 = EditorGUILayout.Slider("纹理占比分割1", groundToolConfig.matSplit1, 0f, 0.8f);
groundToolConfig.matSplit2 = EditorGUILayout.Slider("纹理占比分割2", groundToolConfig.matSplit2, 0.1f, 0.9f);
groundToolConfig.matSplit3 = EditorGUILayout.Slider("纹理占比分割3", groundToolConfig.matSplit3, 0.2f, 1f);
EditorGUILayout.Space(10);
groundToolConfig.texGround1 = EditorGUILayout.ObjectField("纹理1", groundToolConfig.texGround1, typeof(Texture), false) as Texture;
groundToolConfig.texGround2 = EditorGUILayout.ObjectField("纹理2", groundToolConfig.texGround2, typeof(Texture), false) as Texture;
groundToolConfig.texGround3 = EditorGUILayout.ObjectField("纹理3", groundToolConfig.texGround3, typeof(Texture), false) as Texture;
groundToolConfig.texGround4 = EditorGUILayout.ObjectField("纹理4", groundToolConfig.texGround4, typeof(Texture), false) as Texture;
EditorGUILayout.Space(10);
if (GUILayout.Button("随机参数"))
{
UnityEngine.Random.InitState((int)DateTime.Now.Ticks);
groundToolConfig.randOffset = UnityEngine.Random.Range(0f, 100f);
}
groundToolConfig.randOffset = EditorGUILayout.FloatField("随机性", groundToolConfig.randOffset);
groundToolConfig.randJitter = EditorGUILayout.Slider("纹理扰动", groundToolConfig.randJitter,0, 1);
EditorGUILayout.Space(10);
EditorGUILayout.Space(10);
// 选择地形对象
selectedGround = EditorGUILayout.ObjectField("选择地形", selectedGround, typeof(GameObject), true) as GameObject;
GUI.enabled = selectedGround != null;
// 修改地形按钮
if (GUILayout.Button("修改地形"))
{
ChangeGround();
}
if (GUI.changed)
{
isConfigChange = true;
lastChangeTime = Time.realtimeSinceStartup;
}
if (isConfigChange && Time.realtimeSinceStartup - lastChangeTime > 5f)
{
SaveConfig();
}
GUI.enabled = true;
}
/// <summary>
/// 创建地形
/// </summary>
private void CreateGround()
{
// 创建游戏对象
GameObject ground = new GameObject("Ground_" + groundToolConfig.width + "x" + groundToolConfig.length);
// 添加网格过滤器和网格渲染器
MeshFilter meshFilter = ground.AddComponent<MeshFilter>();
MeshRenderer meshRenderer = ground.AddComponent<MeshRenderer>();
// 创建网格
Mesh mesh = CreateGroundMesh(groundToolConfig.width, groundToolConfig.length, groundToolConfig.height, groundToolConfig.perlinScale);
// 应用网格
meshFilter.sharedMesh = mesh;
// 添加碰撞器
MeshCollider collider = ground.AddComponent<MeshCollider>();
collider.sharedMesh = mesh;
// 设置材质
meshRenderer.material = new Material(Shader.Find("Standard"));
// 注册撤销操作并选中对象
Undo.RegisterCreatedObjectUndo(ground, "Create Ground");
Selection.activeGameObject = ground;
// 更新选中的地形对象
selectedGround = ground;
}
/// <summary>
/// 修改地形
/// </summary>
private void ChangeGround()
{
if (selectedGround == null)
{
Debug.LogError("请先选择一个地形对象");
return;
}
MeshFilter meshFilter = selectedGround.GetComponent<MeshFilter>();
if (meshFilter == null) return;
// 创建新网格
Mesh mesh = meshFilter.sharedMesh;//CreateGroundMesh(width, length, height, perlinScale);
// 记录撤销
Undo.RecordObject(meshFilter, "Change Ground");
// 应用网格
meshFilter.sharedMesh = mesh;
float[,] heightMap = ModifyVertexHeight(mesh);
ModifyMaterial(selectedGround.GetComponent<MeshRenderer>(), heightMap);
// 更新碰撞器
MeshCollider collider = selectedGround.GetComponent<MeshCollider>();
if (collider != null)
{
Undo.RecordObject(collider, "Change Ground Collider");
collider.sharedMesh = mesh;
}
}
/// <summary>
/// 创建地形网格
/// </summary>
private Mesh CreateGroundMesh(int width, int length, float height, float perlinScale)
{
Mesh mesh = new Mesh();
mesh.name = "Ground_" + width + "x" + length + "_Mesh";
int resolutionX = Mathf.CeilToInt(groundToolConfig.width);
int resolutionZ = Mathf.CeilToInt(groundToolConfig.length);
float halfWidth = width * 0.5f;
float halfLength = length * 0.5f;
// 创建顶点
Vector3[] vertices = new Vector3[(resolutionX + 1) * (resolutionZ + 1)];
float[,] heightMap = GenerateHeightMap(groundToolConfig.width, groundToolConfig.length, groundToolConfig.height, groundToolConfig.perlinScale);
for (int z = 0; z <= resolutionZ; z++)
{
for (int x = 0; x <= resolutionX; x++)
{
float xPos = x;// * width / resolutionX - halfWidth;
float zPos = z;// * length / resolutionZ - halfLength;
// 使用Perlin噪声生成高度
float y = 0;
if (perlinScale > 0)
{
y = heightMap[x, z];
}
vertices[z * (resolutionX + 1) + x] = new Vector3(xPos, y, zPos);
}
}
// 创建三角形
int[] triangles = new int[resolutionX * resolutionZ * 6];
int triangleIndex = 0;
for (int z = 0; z < resolutionZ; z++)
{
for (int x = 0; x < resolutionX; x++)
{
int vertexIndex = z * (resolutionX + 1) + x;
triangles[triangleIndex++] = vertexIndex;
triangles[triangleIndex++] = vertexIndex + resolutionX + 1;
triangles[triangleIndex++] = vertexIndex + 1;
triangles[triangleIndex++] = vertexIndex + 1;
triangles[triangleIndex++] = vertexIndex + resolutionX + 1;
triangles[triangleIndex++] = vertexIndex + resolutionX + 2;
}
}
// 创建UV坐标
Vector2[] uvs = new Vector2[(resolutionX + 1) * (resolutionZ + 1)];
for (int z = 0; z <= resolutionZ; z++)
{
for (int x = 0; x <= resolutionX; x++)
{
uvs[z * (resolutionX + 1) + x] = new Vector2((float)x / resolutionX, (float)z / resolutionZ);
}
}
// 设置网格数据
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
return mesh;
}
//修改模型顶点高度
private float[,] ModifyVertexHeight(Mesh mesh)
{
float[,] heightMap = GenerateHeightMap(groundToolConfig.width, groundToolConfig.length, groundToolConfig.height, groundToolConfig.perlinScale);
//for (int i = 0; i < vertices.Length; i++)
//{
// vertices[i].y = heightMap[i % (width + 1), i / (width + 1)];
//}
int resolutionX = Mathf.CeilToInt(groundToolConfig.width);
int resolutionZ = Mathf.CeilToInt(groundToolConfig.length);
Vector3[] vertices = new Vector3[(resolutionX + 1) * (resolutionZ + 1)];
for (int z = 0; z <= resolutionZ; z++)
{
for (int x = 0; x <= resolutionX; x++)
{
float xPos = x;// * width / resolutionX - halfWidth;
float zPos = z;// * length / resolutionZ - halfLength;
// 使用Perlin噪声生成高度
float y = 0;
if (groundToolConfig.perlinScale > 0)
{
y = heightMap[x, z];
}
vertices[z * (resolutionX + 1) + x] = new Vector3(xPos, y, zPos);
}
}
// 创建三角形
int[] triangles = new int[resolutionX * resolutionZ * 6];
int triangleIndex = 0;
for (int z = 0; z < resolutionZ; z++)
{
for (int x = 0; x < resolutionX; x++)
{
int vertexIndex = z * (resolutionX + 1) + x;
triangles[triangleIndex++] = vertexIndex;
triangles[triangleIndex++] = vertexIndex + resolutionX + 1;
triangles[triangleIndex++] = vertexIndex + 1;
triangles[triangleIndex++] = vertexIndex + 1;
triangles[triangleIndex++] = vertexIndex + resolutionX + 1;
triangles[triangleIndex++] = vertexIndex + resolutionX + 2;
}
}
// 创建UV坐标
Vector2[] uvs = new Vector2[(resolutionX + 1) * (resolutionZ + 1)];
for (int z = 0; z <= resolutionZ; z++)
{
for (int x = 0; x <= resolutionX; x++)
{
uvs[z * (resolutionX + 1) + x] = new Vector2((float)x / resolutionX, (float)z / resolutionZ);
}
}
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
return heightMap;
}
//填入材质
private void ModifyMaterial(MeshRenderer meshRenderer, float[,] heightMap)
{
// 设置材质
Material mtl = new Material(Shader.Find("XWorld/XTerrain"));
//设置_LayerTex0 _LayerTex1 _LayerTex2 _LayerTex3 和_Control贴图
mtl.SetTexture("_LayerTex3", groundToolConfig.texGround4);
mtl.SetTexture("_LayerTex2", groundToolConfig.texGround3);
mtl.SetTexture("_LayerTex1", groundToolConfig.texGround2);
mtl.SetTexture("_LayerTex0", groundToolConfig.texGround1);
//生成一个rgba四通道的控制贴图,随机分配四种材质的混合度
Texture2D controlTex = new Texture2D(groundToolConfig.width, groundToolConfig.length, TextureFormat.RGBA32, false);
for (int z = 0; z <= groundToolConfig.width; z++)
{
for (int x = 0; x <= groundToolConfig.length; x++)
{
//float h1 = heightMap[x, z]/height;
float h1 = Mathf.PerlinNoise(groundToolConfig.randOffset + z * groundToolConfig.perlinScale, groundToolConfig.randOffset + x * groundToolConfig.perlinScale);
float h2 = Mathf.PerlinNoise(groundToolConfig.randOffset + 107 + z * groundToolConfig.perlinScale, groundToolConfig.randOffset + 107 + x * groundToolConfig.perlinScale);
Color coefficients = new Color(0, 0, 0, 0);
float perlinValue = h1 * (1 - groundToolConfig.randJitter) + h2 * groundToolConfig.randJitter;
float p;
float Split12 = (groundToolConfig.matSplit1 + groundToolConfig.matSplit2)/2.0f;
float Split23 = (groundToolConfig.matSplit3 + groundToolConfig.matSplit2) / 2.0f; ;
// 确定主导纹理区间
if (perlinValue < Split12)//0.33f)//
{
if (perlinValue < groundToolConfig.matSplit1)
{
p = 0.5f - Mathf.Pow((groundToolConfig.matSplit1 - perlinValue) / groundToolConfig.matSplit1, groundToolConfig.power)*0.5f;
// 纹理0主导:R通道为主,平滑过渡到纹理1
coefficients.r = 1.0f - p;
coefficients.g = p;
}
else
{
p = 0.5f + Mathf.Pow((perlinValue - groundToolConfig.matSplit1) / (Split12 - groundToolConfig.matSplit1), groundToolConfig.power)*0.5f;
coefficients.r = 1.0f - p;
coefficients.g = p;
}
//p = Mathf.Pow(perlinValue / groundToolConfig.matSplit1, groundToolConfig.power);
//// 纹理1主导:R通道为主,平滑过渡到纹理2
//coefficients.r = 1.0f - p;
//coefficients.g = p;
}
else if (perlinValue < Split23)//0.66f)//
{
if(perlinValue < groundToolConfig.matSplit2)
{
p = 0.5f - Mathf.Pow(((groundToolConfig.matSplit2 - perlinValue) / (groundToolConfig.matSplit2 - Split12)), groundToolConfig.power)*0.5f;
}
else
{
p = 0.5f + Mathf.Pow(((perlinValue - groundToolConfig.matSplit2) / (Split23 - groundToolConfig.matSplit2)), groundToolConfig.power)*0.5f;
}
coefficients.g = 1.0f - p;
coefficients.b = p;
//p = Mathf.Pow(((perlinValue - groundToolConfig.matSplit1) / (groundToolConfig.matSplit2 - groundToolConfig.matSplit1)), groundToolConfig.power);
//// 纹理2主导:G通道为主,平滑过渡到相邻纹理
//coefficients.g = 1.0f - p;
//coefficients.b = p;
}
else
{
if(perlinValue < groundToolConfig.matSplit3)
{
p = 0.5f - Mathf.Pow(((groundToolConfig.matSplit3 - perlinValue) / (groundToolConfig.matSplit3 - Split23)), groundToolConfig.power)*0.5f;
}
else
{
p = 0.5f + Mathf.Pow(((perlinValue - groundToolConfig.matSplit3) / (1.0f - groundToolConfig.matSplit3)), groundToolConfig.power)*0.5f;
}
coefficients.b = 1.0f - p;
coefficients.a = p;
//p = Mathf.Pow(((perlinValue - groundToolConfig.matSplit2) / (1.0f - groundToolConfig.matSplit2)), groundToolConfig.power);
//// 纹理3主导:B通道为主
//coefficients.b = 1.0f - p;
//coefficients.a = p;
}
controlTex.SetPixel(z, x, coefficients);
}
}
controlTex.Apply();
mtl.SetTexture("_Control", controlTex);
meshRenderer.material = mtl;
}
public float[,] GenerateHeightMap(int x, int z, float heightScale = 1f, float PerlinScale = 0.01f)
{
float[,] heightMap = new float[x + 1, z + 1];
//生成一个N分之一宽和高的高度图
int N = 16;
int quarterX = x / N;
int quarterZ = z / N;
float[,] quarterHeightMap = new float[quarterX + 1, quarterZ + 1];
//for (int i = 0; i <= quarterX; i++)
//{
// for (int j = 0; j <= quarterZ; j++)
// {
// quarterHeightMap[i, j] = Mathf.PerlinNoise(randOffset + i * 0.1f, randOffset + j * 0.1f) * heightScale*2;
// }
//}
//将四分之一高度图叠加到总的高度图上
int f33 = 0, f66 = 0, f100 = 0;
for (int i = 0; i <= x; i++)
{
for (int j = 0; j <= z; j++)
{
//heightMap[i, j] = Mathf.PerlinNoise(i * 0.1f, j * 0.1f) * heightScale + quarterHeightMap[i / N, j / N];
//heightMap[i, j] = quarterHeightMap[i / N, j / N];
float h1 = Mathf.PerlinNoise(groundToolConfig.randOffset + i * PerlinScale, groundToolConfig.randOffset + j * PerlinScale) * heightScale;
float h2 = Mathf.PerlinNoise(groundToolConfig.randOffset + i * PerlinScale * groundToolConfig.groundIncline, groundToolConfig.randOffset + j * PerlinScale * groundToolConfig.groundIncline) * heightScale;
heightMap[i, j] = h1 > h2? h1 : h2;
if (h2 < 0.33f)
{
f33++;
}
else if (h2 < 0.66f)
{
f66++;
}
else if (h2 <= 1.0f)
{
f100++;
}
}
}
Debug.Log($"TotalCount: {f33}, {f66}, {f100}");
return heightMap;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ece4136e36bcf5048b2dc0cc5b8f5a09
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,177 @@
using System;
using UnityEditor;
using UnityEngine;
public static class GroundCreate
{
//[MenuItem("GroundTools/GroundCreate")]
/// <summary>
/// 创建一个100x100单位的地表模型
/// </summary>
public static void CreateGround()
{
// 设置网格参数
int width = 128;
int length = 128;
// 创建游戏对象
GameObject ground = new GameObject($"Ground");
// 添加网格过滤器和网格渲染器
MeshFilter meshFilter = ground.AddComponent<MeshFilter>();
MeshRenderer meshRenderer = ground.AddComponent<MeshRenderer>();
UnityEngine.Random.InitState((int)DateTime.Now.Ticks);
float randOffset = UnityEngine.Random.Range(0f, 100f);
// 创建网格
Mesh mesh = new Mesh();
mesh.name = $"Ground_{width}X{length}_Mesh";
float halfWidth = width * 0.5f;
float halfLength = length * 0.5f;
//创建一个随机高度图,并填入到顶点的y上
float[,] heightMap = GenerateHeightMap(width, length);
//for (int z = 0; z <= length; z++)
//{
// for (int x = 0; x <= width; x++)
// {
// heightMap[x, z] = Mathf.PerlinNoise(x * 0.1f, z * 0.1f) * 2f - 1f;
// }
//}
// 创建顶点
Vector3[] vertices = new Vector3[(width + 1) * (length + 1)];
for (int z = 0; z <= length; z++)
{
for (int x = 0; x <= width; x++)
{
vertices[z * (width + 1) + x] = new Vector3(x - halfWidth, heightMap[x, z], z - halfLength);
}
}
// 创建三角形
int[] triangles = new int[width * length * 6];
int triangleIndex = 0;
for (int z = 0; z < length; z++)
{
for (int x = 0; x < width; x++)
{
int vertexIndex = z * (width + 1) + x;
triangles[triangleIndex++] = vertexIndex;
triangles[triangleIndex++] = vertexIndex + width + 1;
triangles[triangleIndex++] = vertexIndex + 1;
triangles[triangleIndex++] = vertexIndex + 1;
triangles[triangleIndex++] = vertexIndex + width + 1;
triangles[triangleIndex++] = vertexIndex + width + 2;
}
}
// 创建UV坐标
Vector2[] uvs = new Vector2[(width + 1) * (length + 1)];
for (int z = 0; z <= length; z++)
{
for (int x = 0; x <= width; x++)
{
uvs[z * (width + 1) + x] = new Vector2((float)x / width, (float)z / length);
}
}
// 设置网格数据
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
// 应用网格
meshFilter.sharedMesh = mesh;
// 添加碰撞器
MeshCollider collider = ground.AddComponent<MeshCollider>();
collider.sharedMesh = mesh;
// 设置材质
meshRenderer.material = new Material(Shader.Find("XWorld/XTerrain"));
//设置_LayerTex0 _LayerTex1 _LayerTex2 _LayerTex3 和_Control贴图
meshRenderer.material.SetTexture("_LayerTex0", AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Arts/scene/Terrain/Texture/grass.png"));
meshRenderer.material.SetTexture("_LayerTex1", AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Arts/scene/Terrain/Texture/blick.png"));
meshRenderer.material.SetTexture("_LayerTex2", AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Arts/scene/Terrain/Texture/mud.png"));
meshRenderer.material.SetTexture("_LayerTex3", AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Arts/scene/Terrain/Texture/sand.png"));
//生成一个rgba四通道的控制贴图,随机分配四种材质的混合度
Texture2D controlTex = new Texture2D(width, length, TextureFormat.RGBA32, false);
float PerlinRandom = 0.05f;
for (int z = 0; z < length; z++)
{
for (int x = 0; x < width; x++)
{
//float h = heightMap[x, z];
float h1 = Mathf.PerlinNoise(randOffset + z * PerlinRandom, randOffset + x * PerlinRandom);
float hLerp;
Color color;// = new Color(0, 0, 0, 0);
if (h1 < 0.33f)
{
hLerp = (0.33f - h1)*3;
color = new Color(0, 0, hLerp, 1 - hLerp);
}
else if (h1 < 0.66f)
{
hLerp = (0.66f - h1) * 3;
color = new Color(0, hLerp, 1- hLerp, 0);
}
else
{
hLerp = (1.0f - h1) * 3;
color = new Color(hLerp, 1 - hLerp, 0, 0);
}
controlTex.SetPixel(x, z, color);
}
}
controlTex.Apply();
meshRenderer.material.SetTexture("_Control", controlTex);
// 注册撤销操作并选中对象
Undo.RegisterCreatedObjectUndo(ground, "Create 100x100 Ground");
Selection.activeGameObject = ground;
}
//生成x * z的高度图,增加一个浮动变化的高度和一个不均匀的高度变化
//heightScale 高度缩放因子
//heightOffset 高度偏移量
public static float[,] GenerateHeightMap(int x, int z, float heightScale = 20f, float PerlinRandom = 0.01f)
{
float[,] heightMap = new float[x + 1, z + 1];
UnityEngine.Random.InitState(Time.frameCount);
Debug.Log("Random Seed: " + Time.frameCount);
//生成一个N分之一宽和高的高度图
int N = 16;
int quarterX = x / N;
int quarterZ = z / N;
float[,] quarterHeightMap = new float[quarterX + 1, quarterZ + 1];
for (int i = 0; i <= quarterX; i++)
{
for (int j = 0; j <= quarterZ; j++)
{
quarterHeightMap[i, j] = Mathf.PerlinNoise(i * 0.1f, j * 0.1f) * heightScale*2;
}
}
//将四分之一高度图叠加到总的高度图上
for (int i = 0; i <= x; i++)
{
for (int j = 0; j <= z; j++)
{
//heightMap[i, j] = Mathf.PerlinNoise(i * 0.1f, j * 0.1f) * heightScale + quarterHeightMap[i / N, j / N];
//heightMap[i, j] = quarterHeightMap[i / N, j / N];
float h1 = Mathf.PerlinNoise(i * PerlinRandom, j * PerlinRandom) * heightScale;
float h2 = Mathf.PerlinNoise(i * PerlinRandom*5, j * PerlinRandom*5) * heightScale;
heightMap[i, j] = h1 > h2? h1 : h2;
}
}
return heightMap;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ff4bce06a097bd4489beb1dc676d328c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,29 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: e6914217da6edb34baad8872f8642df3, type: 3}
m_Name: GroundToolConfig
m_EditorClassIdentifier:
randOffset: 24.258888
randJitter: 0.382
width: 256
length: 256
height: 30
perlinScale: 0.05
groundIncline: 0
matSplit1: 0.088
matSplit2: 0.285
matSplit3: 0.593
power: 4.12
texGround1: {fileID: 2800000, guid: 57d24bd9d5619994fb7856632f627ea5, type: 3}
texGround2: {fileID: 2800000, guid: d6d26791584699a4ca75b0c5b9f173f2, type: 3}
texGround3: {fileID: 2800000, guid: 741c6de7ade0623478730047979b094b, type: 3}
texGround4: {fileID: 2800000, guid: 4d4a4a42f2189504b8bd44c09ace0136, type: 3}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ddbf17bfa8fc8fd4eab0bf98d05492c7
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,25 @@
using UnityEngine;
// 创建菜单项,方便在项目中创建该资产
[CreateAssetMenu(fileName = "GroundToolConfig", menuName = "GroundTools/Ground Tool Configuration")]
public class GroundToolConfig : ScriptableObject
{
// 将所有需要保存的参数定义为public字段或[SerializeField]的私有字段
public float randOffset = 0f;
public float randJitter = 0.1f;// 随机扰动
public int width = 128;
public int length = 128;
public float height = 30f;
public float perlinScale = 0.05f;
public float groundIncline = 0.01f;
public float matSplit1 = 0.25f;
public float matSplit2 = 0.5f;
public float matSplit3 = 0.75f;
public float power = 2f;
// 纹理(Texture)是Unity引擎对象的引用,本身可以被序列化
public Texture texGround1;
public Texture texGround2;
public Texture texGround3;
public Texture texGround4;
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e6914217da6edb34baad8872f8642df3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,253 @@
using System;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
namespace XGameEditor
{
/// <summary>
/// 收集 shader 变体(ShaderVariantCollection)并保存到 Assets/Game/Shader/Game.shadervariants
/// 该文件会被活跃打包流程打进 game_shader.unity3d,运行时由 Game.Init() 加载并 WarmUp。
///
/// 关键作用:被包含进构建的 SVC 所引用的变体不会被 URP 的 "Strip Unused Variants" 剔除,
/// 从而修复"从 AssetBundle 加载的预设(如 Main)在真机上平行光/光照不起效"的问题。
///
/// 提供两个入口:
/// - Tools/Shader/自动收集Art材质变体 :自动遍历 Assets/Game/Art 下所有材质,
/// 在临时场景里逐个建 cube 渲染一遍并收集(推荐)。
/// - Tools/Shader/收集当前Shader变体到SVC:手动版,收集"当前编辑器会话已渲染过"的变体。
///
/// 说明:用到的 4 个 ShaderUtil 方法在 2022.3 里是 internal,公开 API 不可见,
/// 因此通过反射调用(参见 UnityCsReference/Editor/Mono/ShaderUtil.bindings.cs)。
/// 光照相关变体只有在材质被"实际渲染"时才会由 URP 设置并被跟踪,所以必须渲染 cube。
/// </summary>
public static class ShaderVariantCollector
{
private const string ArtDir = "Assets/Game/Art";
// 放在 Assets/Game/Shader 顶层:活跃打包流程 HybridCLRBuild.BuildHotFix 里
// AddBuildMap("game_shader.unity3d","*.*","Assets/Game/Shader") 会(非递归地)把顶层文件打进 game_shader.unity3d。
private const string OutputDir = "Assets/Game/Shader";
private const string OutputPath = OutputDir + "/Game.shadervariants";
private const string TempScenePath = "Assets/Scenes/__temp_shadervariant_collect.unity";
// ---------------- 反射封装的 internal ShaderUtil 接口 ----------------
private static MethodInfo GetMethod(string name)
{
var m = typeof(ShaderUtil).GetMethod(
name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (m == null)
Debug.LogError($"[ShaderVariantCollector] 反射找不到 ShaderUtil.{name}" +
"当前 Unity 版本可能改了该内部接口。");
return m;
}
private static void ClearCollection()
{
GetMethod("ClearCurrentShaderVariantCollection")?.Invoke(null, null);
}
private static bool SaveCollection(string path)
{
var m = GetMethod("SaveCurrentShaderVariantCollection");
if (m == null) return false;
m.Invoke(null, new object[] { path });
return true;
}
private static int GetTrackedShaderCount()
{
var m = GetMethod("GetCurrentShaderVariantCollectionShaderCount");
return m != null ? (int)m.Invoke(null, null) : -1;
}
private static int GetTrackedVariantCount()
{
var m = GetMethod("GetCurrentShaderVariantCollectionVariantCount");
return m != null ? (int)m.Invoke(null, null) : -1;
}
// ---------------- 自动收集 Assets/Game/Art 下所有材质 ----------------
[MenuItem("Tools/Shader/自动收集Art材质变体")]
public static void AutoCollectArtMaterials()
{
if (!Directory.Exists(ArtDir))
{
EditorUtility.DisplayDialog("目录不存在", $"找不到目录:\n{ArtDir}", "好");
return;
}
// 先让用户保存当前场景,避免丢失未保存内容
if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
return;
// 1. 遍历材质
string[] guids = AssetDatabase.FindAssets("t:Material", new[] { ArtDir });
if (guids.Length == 0)
{
EditorUtility.DisplayDialog("没有材质", $"{ArtDir} 下没有找到任何材质。", "好");
return;
}
if (guids.Length > 3000 &&
!EditorUtility.DisplayDialog("材质较多",
$"共找到 {guids.Length} 个材质,将创建同等数量的 cube 渲染,可能较慢且占用内存。是否继续?",
"继续", "取消"))
return;
// 2. 新建带默认相机+平行光的临时场景并保存到 Assets/Scenes
Scene scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
string sceneDir = Path.GetDirectoryName(TempScenePath);
if (!Directory.Exists(sceneDir)) Directory.CreateDirectory(sceneDir);
Camera cam = Object.FindObjectOfType<Camera>();
if (cam == null)
cam = new GameObject("Capture Camera", typeof(Camera)).GetComponent<Camera>();
Light light = Object.FindObjectOfType<Light>();
if (light == null)
light = new GameObject("Directional Light", typeof(Light)).GetComponent<Light>();
light.type = LightType.Directional;
light.intensity = 1f;
light.shadows = LightShadows.Soft;
light.transform.rotation = Quaternion.Euler(50f, -30f, 0f);
RenderTexture rt = null;
try
{
// 3. 网格排布,逐个材质创建 cube 并赋上去
const float spacing = 2.2f;
int cols = Mathf.CeilToInt(Mathf.Sqrt(guids.Length));
float half = (cols - 1) * spacing * 0.5f;
int created = 0;
for (int i = 0; i < guids.Length; i++)
{
string path = AssetDatabase.GUIDToAssetPath(guids[i]);
var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
if (mat == null || mat.shader == null) continue;
if (i % 50 == 0)
EditorUtility.DisplayProgressBar("收集Shader变体",
$"创建 cube ({i + 1}/{guids.Length})", (float)i / guids.Length);
int col = i % cols;
int row = i / cols;
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = mat.name;
var collider = cube.GetComponent<Collider>();
if (collider != null) Object.DestroyImmediate(collider);
cube.transform.position = new Vector3(col * spacing - half, row * spacing - half, 0f);
cube.GetComponent<MeshRenderer>().sharedMaterial = mat;
created++;
}
// 4. 正交相机正对网格,渲染到 RT,保证全部进视锥被实际渲染
float gridExtent = cols * spacing * 0.5f + spacing;
cam.orthographic = true;
cam.orthographicSize = gridExtent;
cam.aspect = 1f;
cam.clearFlags = CameraClearFlags.SolidColor;
cam.backgroundColor = Color.gray;
cam.transform.position = new Vector3(0f, 0f, -20f);
cam.transform.rotation = Quaternion.identity;
cam.nearClipPlane = 0.1f;
cam.farClipPlane = 100f;
EditorSceneManager.SaveScene(scene, TempScenePath);
rt = new RenderTexture(2048, 2048, 24);
cam.targetTexture = rt;
// 采集前清空,确保结果只包含本次渲染的变体
ClearCollection();
EditorUtility.DisplayProgressBar("收集Shader变体", "渲染中...", 0.9f);
// 多渲染几帧,确保各变体都被编译并跟踪
for (int k = 0; k < 4; k++)
cam.Render();
cam.targetTexture = null;
int variantCount = GetTrackedVariantCount();
int shaderCount = GetTrackedShaderCount();
// 5. 保存 SVC
if (!Directory.Exists(OutputDir)) Directory.CreateDirectory(OutputDir);
bool ok = SaveCollection(OutputPath);
AssetDatabase.ImportAsset(OutputPath, ImportAssetOptions.ForceUpdate);
AssetDatabase.Refresh();
Debug.Log($"[ShaderVariantCollector] 自动收集完成: {OutputPath}\n" +
$" 材质: {guids.Length}, 创建cube: {created}, " +
$"shader数: {shaderCount}, 变体数: {variantCount}");
if (!ok || variantCount <= 0)
{
EditorUtility.DisplayDialog("收集异常",
$"变体数={variantCount}。\n若为 0,可能是 URP 下编辑器 Camera.Render 未触发跟踪," +
"可改用 Play 模式 + Tools/Shader/收集当前Shader变体到SVC 兜底。", "好");
}
else
{
EditorUtility.DisplayDialog("收集完成",
$"已写入: {OutputPath}\n材质: {guids.Length}\nshader数: {shaderCount}\n变体数: {variantCount}\n\n现在可以重新打包构建。",
"好");
var asset = AssetDatabase.LoadAssetAtPath<ShaderVariantCollection>(OutputPath);
if (asset != null) EditorGUIUtility.PingObject(asset);
}
}
finally
{
EditorUtility.ClearProgressBar();
if (rt != null)
{
if (cam != null) cam.targetTexture = null;
rt.Release();
Object.DestroyImmediate(rt);
}
}
}
// ---------------- 手动收集(当前会话已渲染过的变体) ----------------
[MenuItem("Tools/Shader/收集当前Shader变体到SVC")]
public static void SaveCurrentVariants()
{
if (GetMethod("SaveCurrentShaderVariantCollection") == null) return;
int variantCount = GetTrackedVariantCount();
int shaderCount = GetTrackedShaderCount();
if (variantCount == 0 &&
!EditorUtility.DisplayDialog("没有可收集的变体",
"当前跟踪到的 shader 变体为 0。\n\n请先进入 Play 模式并显示出问题界面/模型,让相关 shader 实际渲染一次,再执行本命令。",
"我知道了", "取消"))
return;
if (!Directory.Exists(OutputDir)) Directory.CreateDirectory(OutputDir);
if (!SaveCollection(OutputPath)) return;
AssetDatabase.ImportAsset(OutputPath, ImportAssetOptions.ForceUpdate);
AssetDatabase.Refresh();
Debug.Log($"[ShaderVariantCollector] 已保存变体集合: {OutputPath}\n" +
$" shader 数: {shaderCount}, 变体数: {variantCount}");
EditorUtility.DisplayDialog("收集完成",
$"已写入: {OutputPath}\nshader 数: {shaderCount}\n变体数: {variantCount}\n\n现在可以重新打包构建。", "好");
var asset = AssetDatabase.LoadAssetAtPath<ShaderVariantCollection>(OutputPath);
if (asset != null) EditorGUIUtility.PingObject(asset);
}
[MenuItem("Tools/Shader/清空已跟踪变体")]
public static void ClearTrackedVariants()
{
ClearCollection();
Debug.Log("[ShaderVariantCollector] 已清空当前跟踪的 shader 变体,可重新进入 Play 重新采集。");
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2c39064f03a1c95408249fc79d9fac7d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+43
View File
@@ -0,0 +1,43 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: b29e98153ec2fbd44b8f7da1b41194e8, type: 3}
m_Name: SpineSettings
m_EditorClassIdentifier:
defaultScale: 0.01
defaultMix: 0.2
defaultShader: Spine/Skeleton
defaultZSpacing: 0
defaultInstantiateLoop: 1
defaultPhysicsPositionInheritance: {x: 1, y: 1}
defaultPhysicsRotationInheritance: 1
showHierarchyIcons: 1
reloadAfterPlayMode: 1
setTextureImporterSettings: 1
textureSettingsReference:
fixPrefabOverrideViaMeshFilter: 0
removePrefabPreviewMeshes: 0
applyAdditiveMaterial: 0
blendModeMaterialMultiply: {fileID: 0}
blendModeMaterialScreen: {fileID: 0}
blendModeMaterialAdditive: {fileID: 0}
atlasTxtImportWarning: 1
textureImporterWarning: 1
componentMaterialWarning: 1
skeletonDataAssetNoFileError: 1
workflowMismatchDialog: 1
skeletonDataAssetMismatchWarning: 1
splitComponentChangeWarning: 0
autoReloadSceneSkeletons: 1
handleScale: 1
mecanimEventIncludeFolderName: 1
timelineDefaultMixDuration: 0
timelineUseBlendDuration: 1
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5936fb33f8b6da542b52eb002552da33
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7c2193da1f3f8174eb96bfaea88b8e92
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 00114f9cc610c674799c31d48128c48c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,338 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
using System.Collections.Generic;
using System;
using XLua;
using System.Reflection;
using System.Linq;
//配置的详细介绍请看Doc下《XLua的配置.doc》
public static class ExampleConfig
{
/***************如果你全lua编程,可以参考这份自动化配置***************/
//--------------begin 纯lua编程配置参考----------------------------
//static List<string> exclude = new List<string> {
// "HideInInspector", "ExecuteInEditMode",
// "AddComponentMenu", "ContextMenu",
// "RequireComponent", "DisallowMultipleComponent",
// "SerializeField", "AssemblyIsEditorAssembly",
// "Attribute", "Types",
// "UnitySurrogateSelector", "TrackedReference",
// "TypeInferenceRules", "FFTWindow",
// "RPC", "Network", "MasterServer",
// "BitStream", "HostData",
// "ConnectionTesterStatus", "GUI", "EventType",
// "EventModifiers", "FontStyle", "TextAlignment",
// "TextEditor", "TextEditorDblClickSnapping",
// "TextGenerator", "TextClipping", "Gizmos",
// "ADBannerView", "ADInterstitialAd",
// "Android", "Tizen", "jvalue",
// "iPhone", "iOS", "Windows", "CalendarIdentifier",
// "CalendarUnit", "CalendarUnit",
// "ClusterInput", "FullScreenMovieControlMode",
// "FullScreenMovieScalingMode", "Handheld",
// "LocalNotification", "NotificationServices",
// "RemoteNotificationType", "RemoteNotification",
// "SamsungTV", "TextureCompressionQuality",
// "TouchScreenKeyboardType", "TouchScreenKeyboard",
// "MovieTexture", "UnityEngineInternal",
// "Terrain", "Tree", "SplatPrototype",
// "DetailPrototype", "DetailRenderMode",
// "MeshSubsetCombineUtility", "AOT", "Social", "Enumerator",
// "SendMouseEvents", "Cursor", "Flash", "ActionScript",
// "OnRequestRebuild", "Ping",
// "ShaderVariantCollection", "SimpleJson.Reflection",
// "CoroutineTween", "GraphicRebuildTracker",
// "Advertisements", "UnityEditor", "WSA",
// "EventProvider", "Apple",
// "ClusterInput", "Motion",
// "UnityEngine.UI.ReflectionMethodsCache", "NativeLeakDetection",
// "NativeLeakDetectionMode", "WWWAudioExtensions", "UnityEngine.Experimental",
//};
//static bool isExcluded(Type type)
//{
// var fullName = type.FullName;
// for (int i = 0; i < exclude.Count; i++)
// {
// if (fullName.Contains(exclude[i]))
// {
// return true;
// }
// }
// return false;
//}
//[LuaCallCSharp]
//public static IEnumerable<Type> LuaCallCSharp
//{
// get
// {
// List<string> namespaces = new List<string>() // 在这里添加名字空间
// {
// "UnityEngine",
// "UnityEngine.UI"
// };
// var unityTypes = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
// where !(assembly.ManifestModule is System.Reflection.Emit.ModuleBuilder)
// from type in assembly.GetExportedTypes()
// where type.Namespace != null && namespaces.Contains(type.Namespace) && !isExcluded(type)
// && type.BaseType != typeof(MulticastDelegate) && !type.IsInterface && !type.IsEnum
// select type);
// string[] customAssemblys = new string[] {
// "Assembly-CSharp",
// };
// var customTypes = (from assembly in customAssemblys.Select(s => Assembly.Load(s))
// from type in assembly.GetExportedTypes()
// where type.Namespace == null || !type.Namespace.StartsWith("XLua")
// && type.BaseType != typeof(MulticastDelegate) && !type.IsInterface && !type.IsEnum
// select type);
// return unityTypes.Concat(customTypes);
// }
//}
////自动把LuaCallCSharp涉及到的delegate加到CSharpCallLua列表,后续可以直接用lua函数做callback
//[CSharpCallLua]
//public static List<Type> CSharpCallLua
//{
// get
// {
// var lua_call_csharp = LuaCallCSharp;
// var delegate_types = new List<Type>();
// var flag = BindingFlags.Public | BindingFlags.Instance
// | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly;
// foreach (var field in (from type in lua_call_csharp select type).SelectMany(type => type.GetFields(flag)))
// {
// if (typeof(Delegate).IsAssignableFrom(field.FieldType))
// {
// delegate_types.Add(field.FieldType);
// }
// }
// foreach (var method in (from type in lua_call_csharp select type).SelectMany(type => type.GetMethods(flag)))
// {
// if (typeof(Delegate).IsAssignableFrom(method.ReturnType))
// {
// delegate_types.Add(method.ReturnType);
// }
// foreach (var param in method.GetParameters())
// {
// var paramType = param.ParameterType.IsByRef ? param.ParameterType.GetElementType() : param.ParameterType;
// if (typeof(Delegate).IsAssignableFrom(paramType))
// {
// delegate_types.Add(paramType);
// }
// }
// }
// return delegate_types.Where(t => t.BaseType == typeof(MulticastDelegate) && !hasGenericParameter(t) && !delegateHasEditorRef(t)).Distinct().ToList();
// }
//}
//--------------end 纯lua编程配置参考----------------------------
/***************热补丁可以参考这份自动化配置***************/
//[Hotfix]
//static IEnumerable<Type> HotfixInject
//{
// get
// {
// return (from type in Assembly.Load("Assembly-CSharp").GetTypes()
// where type.Namespace == null || !type.Namespace.StartsWith("XLua")
// select type);
// }
//}
//--------------begin 热补丁自动化配置-------------------------
//static bool hasGenericParameter(Type type)
//{
// if (type.IsGenericTypeDefinition) return true;
// if (type.IsGenericParameter) return true;
// if (type.IsByRef || type.IsArray)
// {
// return hasGenericParameter(type.GetElementType());
// }
// if (type.IsGenericType)
// {
// foreach (var typeArg in type.GetGenericArguments())
// {
// if (hasGenericParameter(typeArg))
// {
// return true;
// }
// }
// }
// return false;
//}
//static bool typeHasEditorRef(Type type)
//{
// if (type.Namespace != null && (type.Namespace == "UnityEditor" || type.Namespace.StartsWith("UnityEditor.")))
// {
// return true;
// }
// if (type.IsNested)
// {
// return typeHasEditorRef(type.DeclaringType);
// }
// if (type.IsByRef || type.IsArray)
// {
// return typeHasEditorRef(type.GetElementType());
// }
// if (type.IsGenericType)
// {
// foreach (var typeArg in type.GetGenericArguments())
// {
// if (typeArg.IsGenericParameter) {
// //skip unsigned type parameter
// continue;
// }
// if (typeHasEditorRef(typeArg))
// {
// return true;
// }
// }
// }
// return false;
//}
//static bool delegateHasEditorRef(Type delegateType)
//{
// if (typeHasEditorRef(delegateType)) return true;
// var method = delegateType.GetMethod("Invoke");
// if (method == null)
// {
// return false;
// }
// if (typeHasEditorRef(method.ReturnType)) return true;
// return method.GetParameters().Any(pinfo => typeHasEditorRef(pinfo.ParameterType));
//}
// 配置某Assembly下所有涉及到的delegate到CSharpCallLua下,Hotfix下拿不准那些delegate需要适配到lua function可以这么配置
//[CSharpCallLua]
//static IEnumerable<Type> AllDelegate
//{
// get
// {
// BindingFlags flag = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
// List<Type> allTypes = new List<Type>();
// var allAssemblys = new Assembly[]
// {
// Assembly.Load("Assembly-CSharp")
// };
// foreach (var t in (from assembly in allAssemblys from type in assembly.GetTypes() select type))
// {
// var p = t;
// while (p != null)
// {
// allTypes.Add(p);
// p = p.BaseType;
// }
// }
// allTypes = allTypes.Distinct().ToList();
// var allMethods = from type in allTypes
// from method in type.GetMethods(flag)
// select method;
// var returnTypes = from method in allMethods
// select method.ReturnType;
// var paramTypes = allMethods.SelectMany(m => m.GetParameters()).Select(pinfo => pinfo.ParameterType.IsByRef ? pinfo.ParameterType.GetElementType() : pinfo.ParameterType);
// var fieldTypes = from type in allTypes
// from field in type.GetFields(flag)
// select field.FieldType;
// return (returnTypes.Concat(paramTypes).Concat(fieldTypes)).Where(t => t.BaseType == typeof(MulticastDelegate) && !hasGenericParameter(t) && !delegateHasEditorRef(t)).Distinct();
// }
//}
//--------------end 热补丁自动化配置-------------------------
//黑名单
[BlackList]
public static List<List<string>> BlackList = new List<List<string>>() {
new List<string>(){"System.Xml.XmlNodeList", "ItemOf"},
new List<string>(){"UnityEngine.WWW", "movie"},
#if UNITY_WEBGL
new List<string>(){"UnityEngine.WWW", "threadPriority"},
#endif
new List<string>(){"UnityEngine.Texture2D", "alphaIsTransparency"},
new List<string>(){"UnityEngine.Security", "GetChainOfTrustValue"},
new List<string>(){"UnityEngine.CanvasRenderer", "onRequestRebuild"},
new List<string>(){"UnityEngine.Light", "areaSize"},
new List<string>(){"UnityEngine.Light", "lightmapBakeType"},
new List<string>(){"UnityEngine.WWW", "MovieTexture"},
new List<string>(){"UnityEngine.WWW", "GetMovieTexture"},
new List<string>(){"UnityEngine.AnimatorOverrideController", "PerformOverrideClipListCleanup"},
#if !UNITY_WEBPLAYER
new List<string>(){"UnityEngine.Application", "ExternalEval"},
#endif
new List<string>(){"UnityEngine.GameObject", "networkView"}, //4.6.2 not support
new List<string>(){"UnityEngine.Component", "networkView"}, //4.6.2 not support
new List<string>(){"System.IO.FileInfo", "GetAccessControl", "System.Security.AccessControl.AccessControlSections"},
new List<string>(){"System.IO.FileInfo", "SetAccessControl", "System.Security.AccessControl.FileSecurity"},
new List<string>(){"System.IO.DirectoryInfo", "GetAccessControl", "System.Security.AccessControl.AccessControlSections"},
new List<string>(){"System.IO.DirectoryInfo", "SetAccessControl", "System.Security.AccessControl.DirectorySecurity"},
new List<string>(){"System.IO.DirectoryInfo", "CreateSubdirectory", "System.String", "System.Security.AccessControl.DirectorySecurity"},
new List<string>(){"System.IO.DirectoryInfo", "Create", "System.Security.AccessControl.DirectorySecurity"},
new List<string>(){"UnityEngine.MonoBehaviour", "runInEditMode"},
};
#if UNITY_2018_1_OR_NEWER
[BlackList]
public static List<Type> BlackGenericTypeList = new List<Type>()
{
typeof(Span<>),
typeof(ReadOnlySpan<>)
};
private static bool IsBlacklistedGenericType(Type type)
{
if (!type.IsGenericType) return false;
return BlackGenericTypeList.Contains(type.GetGenericTypeDefinition());
}
[BlackList]
public static Func<MemberInfo, bool> GenericTypeFilter = (memberInfo) =>
{
switch (memberInfo)
{
case PropertyInfo propertyInfo:
return IsBlacklistedGenericType(propertyInfo.PropertyType);
case ConstructorInfo constructorInfo:
return constructorInfo.GetParameters().Any(p => IsBlacklistedGenericType(p.ParameterType));
case MethodInfo methodInfo:
return methodInfo.GetParameters().Any(p => IsBlacklistedGenericType(p.ParameterType));
default:
return false;
}
};
[BlackList]
public static Func<MemberInfo, bool> MethodFilter = (memberInfo) =>
{
if (memberInfo.DeclaringType.IsGenericType && memberInfo.DeclaringType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
if (memberInfo.MemberType == MemberTypes.Constructor)
{
ConstructorInfo constructorInfo = memberInfo as ConstructorInfo;
var parameterInfos = constructorInfo.GetParameters();
if (parameterInfos.Length > 0)
{
if (typeof(System.Collections.IEnumerable).IsAssignableFrom(parameterInfos[0].ParameterType))
{
return true;
}
}
}
else if (memberInfo.MemberType == MemberTypes.Method)
{
var methodInfo = memberInfo as MethodInfo;
if (methodInfo.Name == "TryAdd" || methodInfo.Name == "Remove" && methodInfo.GetParameters().Length == 2)
{
return true;
}
}
}
return false;
};
#endif
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 1b852d3c62124624888d03e611f7b1fc
timeCreated: 1534126175
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e866a5f1000c29940843aece98d0c706
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
File diff suppressed because it is too large Load Diff
+12
View File
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f9f175d9e85601f4da903e391b8b7c77
timeCreated: 1482299911
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 9f94464b9267f9b4cbf2f98681e22880
folderAsset: yes
timeCreated: 1479105499
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,34 @@
using UnityEngine;
using System.Collections.Generic;
using XLua;
using System.IO;
using System.Text;
using System.Linq;
using CSObjectWrapEditor;
public class LinkXmlGen : ScriptableObject
{
public TextAsset Template;
public static IEnumerable<CustomGenTask> GetTasks(LuaEnv lua_env, UserConfig user_cfg)
{
LuaTable data = lua_env.NewTable();
var assembly_infos = (from type in (user_cfg.ReflectionUse.Concat(user_cfg.LuaCallCSharp))
group type by type.Assembly.GetName().Name into assembly_info
select new { FullName = assembly_info.Key, Types = assembly_info.ToList()}).ToList();
data.Set("assembly_infos", assembly_infos);
yield return new CustomGenTask
{
Data = data,
Output = new StreamWriter(GeneratorConfig.common_path + "/link.xml",
false, Encoding.UTF8)
};
}
[GenCodeMenu]//加到Generate Code菜单里头
public static void GenLinkXml()
{
Generator.CustomGen(ScriptableObject.CreateInstance<LinkXmlGen>().Template.text, GetTasks);
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 5fa8c6bd6daed854c98654418f48a830
timeCreated: 1482482561
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences:
- Template: {fileID: 4900000, guid: 384feb229d259f549bbbac9e910b782b, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
<%
require "TemplateCommon"
%>
<linker>
<%ForEachCsList(assembly_infos, function(assembly_info)%>
<assembly fullname="<%=assembly_info.FullName%>">
<%ForEachCsList(assembly_info.Types, function(type)
%><type fullname="<%=type:ToString()%>" preserve="all"/>
<%end)%>
</assembly>
<%end)%>
</linker>
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 384feb229d259f549bbbac9e910b782b
timeCreated: 1481621844
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
+638
View File
@@ -0,0 +1,638 @@
using System;
using System.Collections.Generic;
using XLua;
using System.Reflection;
using System.Collections;
using UnityEngine;
public static class LuaGen
{
[LuaCallCSharp]
public static List<Type> LuaCallCSharp = new List<Type>()
{
typeof(UnityEngine.Video.VideoPlayer.EventHandler),
typeof(Action<byte[]>),
typeof(DateTime),
typeof(Dictionary<int, int>),
typeof(Dictionary<string, object>),
typeof(Dictionary<string,string>),
typeof(Dictionary<string,string>),
typeof(Dictionary<long,string>),
typeof(Dictionary<string,string>.Enumerator),
typeof(IEnumerator),
typeof(KeyValuePair<string,string>),
typeof(List<int>),
typeof(List<string>),
typeof(List<UnityEngine.Component>),
typeof(LuaEnv),
typeof(object),
typeof(System.Net.Dns),
typeof(System.Net.Sockets.AddressFamily),
typeof(System.Net.Sockets.SocketError),
typeof(System.Runtime.CompilerServices.ExtensionAttribute),
typeof(TimeSpan),
typeof(Convert),
typeof(UnityEngine.NetworkReachability),
typeof(UnityEngine.AI.NavMeshAgent),
typeof(UnityEngine.AI.NavMeshObstacle),
typeof(UnityEngine.AnimationClip),
typeof(UnityEngine.AnimationCurve),
typeof(UnityEngine.Animator),
typeof(UnityEngine.AnimatorStateInfo),
typeof(UnityEngine.Application),
typeof(UnityEngine.Behaviour),
typeof(UnityEngine.Bounds),
typeof(UnityEngine.BoxCollider),
typeof(UnityEngine.Camera),
typeof(UnityEngine.Camera.MonoOrStereoscopicEye),
typeof(UnityEngine.Camera.StereoscopicEye),
typeof(UnityEngine.Rendering.Universal.CameraExtensions),
typeof(UnityEngine.Rendering.Universal.UniversalAdditionalCameraData),
//typeof(Cinemachine.CinemachineBrain),
//typeof(Cinemachine.CinemachineVirtualCamera),
//typeof(Cinemachine.LensSettings),
typeof(UnityEngine.Canvas),
typeof(UnityEngine.CanvasGroup),
typeof(UnityEngine.Collider),
typeof(UnityEngine.Color),
typeof(UnityEngine.ColorUtility),
typeof(UnityEngine.Component),
typeof(UnityEngine.Debug),
typeof(UnityEngine.Events.UnityEvent),
typeof(UnityEngine.EventSystems.BaseEventData),
typeof(UnityEngine.EventSystems.PhysicsRaycaster),
typeof(UnityEngine.EventSystems.PointerEventData),
typeof(UnityEngine.EventSystems.PointerEventData.FramePressState),
typeof(UnityEngine.EventSystems.PointerEventData.InputButton),
typeof(UnityEngine.EventSystems.UIBehaviour),
typeof(UnityEngine.GameObject),
typeof(UnityEngine.GUIUtility),
typeof(UnityEngine.Input),
typeof(UnityEngine.Keyframe),
typeof(UnityEngine.LayerMask),
typeof(UnityEngine.LineRenderer),
typeof(UnityEngine.Material),
typeof(UnityEngine.Mathf),
typeof(UnityEngine.Matrix4x4),
typeof(UnityEngine.MonoBehaviour),
typeof(UnityEngine.Networking.DownloadHandler),
typeof(UnityEngine.Networking.DownloadHandlerBuffer),
typeof(UnityEngine.Networking.DownloadHandlerTexture),
typeof(UnityEngine.Networking.UnityWebRequest),
typeof(UnityEngine.Networking.UnityWebRequestAsyncOperation),
typeof(UnityEngine.Object),
typeof(UnityEngine.ParticleSystem),
typeof(UnityEngine.ParticleSystem.MainModule),
typeof(UnityEngine.Playables.PlayableDirector),
typeof(UnityEngine.PlayerPrefs),
typeof(UnityEngine.Quaternion),
typeof(UnityEngine.Random),
typeof(UnityEngine.Ray),
typeof(UnityEngine.Ray2D),
typeof(UnityEngine.RaycastHit),
typeof(UnityEngine.Rect),
typeof(UnityEngine.RectTransform),
typeof(UnityEngine.RectTransform.Axis),
typeof(UnityEngine.RectTransform.Edge),
typeof(UnityEngine.RectTransformUtility),
typeof(UnityEngine.Renderer),
typeof(UnityEngine.RenderTexture),
typeof(UnityEngine.Resources),
typeof(UnityEngine.Rigidbody),
typeof(UnityEngine.RuntimeAnimatorController),
typeof(UnityEngine.RuntimePlatform),
typeof(UnityEngine.Screen),
typeof(UnityEngine.SleepTimeout),
typeof(UnityEngine.SkinnedMeshRenderer),
typeof(UnityEngine.Sprite),
typeof(UnityEngine.SystemInfo),
typeof(UnityEngine.TextAsset),
typeof(UnityEngine.Texture),
typeof(UnityEngine.Texture2D),
typeof(UnityEngine.ImageConversion),
typeof(UnityEngine.Texture2D.EXRFlags),
typeof(UnityEngine.Time),
typeof(UnityEngine.TouchPhase),
typeof(UnityEngine.Transform),
typeof(UnityEngine.GameObject),
typeof(UnityEngine.UI.Button),
typeof(UnityEngine.UI.Button.ButtonClickedEvent),
typeof(UnityEngine.UI.Dropdown),
typeof(UnityEngine.UI.GridLayoutGroup),
typeof(UnityEngine.UI.GridLayoutGroup.Axis),
typeof(UnityEngine.UI.GridLayoutGroup.Constraint),
typeof(UnityEngine.UI.GridLayoutGroup.Corner),
typeof(UnityEngine.UI.HorizontalLayoutGroup),
typeof(UnityEngine.UI.Image),
typeof(UnityEngine.UI.Image.FillMethod),
typeof(UnityEngine.UI.Image.Origin180),
typeof(UnityEngine.UI.Image.Origin360),
typeof(UnityEngine.UI.Image.Origin360),
typeof(UnityEngine.UI.Image.Origin90),
typeof(UnityEngine.UI.Image.OriginHorizontal),
typeof(UnityEngine.UI.Image.OriginVertical),
typeof(UnityEngine.UI.Image.Type),
typeof(UnityEngine.UI.InputField),
typeof(UnityEngine.UI.InputField.CharacterValidation),
typeof(UnityEngine.UI.InputField.ContentType),
typeof(UnityEngine.UI.InputField.InputType),
typeof(UnityEngine.UI.InputField.LineType),
typeof(UnityEngine.UI.InputField.OnChangeEvent),
typeof(UnityEngine.UI.InputField.SubmitEvent),
typeof(UnityEngine.UI.InputField.OnValidateInput),
typeof(UnityEngine.UI.LayoutGroup),
typeof(UnityEngine.UI.LayoutRebuilder),
typeof(UnityEngine.UI.MaskableGraphic),
typeof(UnityEngine.UI.MaskableGraphic.CullStateChangedEvent),
typeof(UnityEngine.UI.RawImage),
typeof(UnityEngine.UI.Scrollbar),
typeof(UnityEngine.UI.Scrollbar.Direction),
typeof(UnityEngine.UI.Scrollbar.ScrollEvent),
typeof(UnityEngine.UI.ScrollRect),
typeof(UnityEngine.UI.ScrollRect.MovementType),
typeof(UnityEngine.UI.ScrollRect.ScrollbarVisibility),
typeof(UnityEngine.UI.ScrollRect.ScrollRectEvent),
typeof(UnityEngine.UI.Selectable),
typeof(UnityEngine.UI.Selectable.Transition),
typeof(UnityEngine.UI.Slider),
typeof(UnityEngine.UI.Slider.Direction),
typeof(UnityEngine.UI.Slider.SliderEvent),
typeof(UnityEngine.UI.Text),
typeof(UnityEngine.UI.Toggle),
typeof(UnityEngine.UI.Toggle.ToggleEvent),
typeof(UnityEngine.UI.Toggle.ToggleTransition),
typeof(UnityEngine.UI.CanvasScaler),
typeof(UnityEngine.Vector2),
typeof(UnityEngine.Vector2Int),
typeof(UnityEngine.Vector3),
typeof(UnityEngine.Vector3Int),
typeof(List<UnityEngine.Vector3>),
typeof(UnityEngine.Vector4),
typeof(UnityEngine.WaitForEndOfFrame),
typeof(UnityEngine.TextMesh),
typeof(UnityEngine.Profiling.Profiler),
typeof(XGame.XWebSocket),
typeof(XGame.lsocket),
typeof(UnityEngine.Timeline.ActivationTrack),
typeof(UnityEngine.Timeline.ControlTrack),
typeof(UnityEngine.Timeline.ControlPlayableAsset),
typeof(UnityEngine.Video.VideoPlayer),
typeof(UnityEngine.LayerMask),
typeof(Action<bool>),
typeof(Func<string, string>),
typeof(Action<int>),
typeof(Func<UnityEngine.Networking.DownloadHandler>),
typeof(TimeZoneInfo),
typeof(DayOfWeek),
typeof(DG.Tweening.ShortcutExtensions),
typeof(DG.Tweening.TweenExtensions),
typeof(DG.Tweening.TweenSettingsExtensions),
typeof(DG.Tweening.Ease),
typeof(DG.Tweening.RotateMode),
//typeof(DG.Tweening.Tween),
typeof(DG.Tweening.DOTween),
typeof(DG.Tweening.DOTweenModuleUI),
//typeof(XGame.Utility),
#if DEVELOPMENT || RELEASE
typeof(GYGame.GMToolViewBuilder),
typeof(MobileConsole.UI.GenericNodeView),
typeof(MobileConsole.UI.CheckboxNodeView),
typeof(MobileConsole.UI.DropdownNodeView),
typeof(MobileConsole.UI.InputNodeView),
typeof(MobileConsole.UI.SliderNodeView),
typeof(MobileConsole.UI.CategoryNodeView),
#endif
};
[GCOptimize]
public static List<Type> GCOptimizeList = new List<Type>()
{
};
[CSharpCallLua]
public static List<Type> CSharpCallLua = new List<Type>()
{
typeof(IEnumerator),
typeof(UnityEngine.Events.UnityAction),
typeof(UnityEngine.Events.UnityAction<UnityEngine.Vector2>),
typeof(UnityEngine.Events.UnityAction<int>),
typeof(UnityEngine.Events.UnityAction<int,UnityEngine.GameObject>),
typeof(UnityEngine.Events.UnityAction<int,bool>),
typeof(UnityEngine.Events.UnityAction<int,int>),
typeof(UnityEngine.LayerMask),
typeof(UnityEngine.EventSystems.PhysicsRaycaster),
typeof(Action<string[]>),
typeof(Action<UnityEngine.Transform>),
typeof(Action<bool, string>),
typeof(Action<UnityEngine.Object>),
typeof(Action<UnityEngine.EventSystems.PointerEventData>),
typeof(Action<UnityEngine.GameObject>),
typeof(Action<UnityEngine.EventSystems.BaseEventData>),
typeof(Action<UnityEngine.Vector3>),
typeof(UnityEngine.Events.UnityAction<bool>),
typeof(UnityEngine.Events.UnityAction<int>),
typeof(UnityEngine.Events.UnityAction<float>),
typeof(UnityEngine.UI.InputField.OnValidateInput),
typeof(Action<string, int, char>),
typeof(Action<string, string, string, Action, Action>),
typeof(Action<string, string, string, object, Action>),
typeof(Action<System.Net.Sockets.SocketError>),
typeof(Action<XGame.XWebSocket, string>),
typeof(Action<byte[]>),
typeof(Action<float>),
typeof(Action<bool>),
typeof(Action<float,float,float,bool>),
typeof(Action<uint>),
typeof(Action<int>),
typeof(Action<string, byte[]>),
typeof(Func<int, List<string>>),
typeof(Func<LuaTable>),
typeof(Func<int, int, int, int>),
typeof(Func<int, int, int, bool>),
typeof(Func<int, int, LuaTable>),
typeof(Func<bool, int, LuaTable>),
typeof(Func<bool, bool, int, LuaTable>),
typeof(Func<int, int, bool>),
typeof(Action<int, Action>),
typeof(Action<int, Action, Action, int>),
typeof(Action<int, int, Action<bool>>),
typeof(Func<int, string>),
typeof(Func<int, bool>),
typeof(Func<bool>),
typeof(Action<int, UnityEngine.EventSystems.PointerEventData>),
typeof(Func<int, LuaTable>),
typeof(Action<int, Action<int>>),
typeof(Action<string>),
typeof(Action<string,string>),
typeof(UnityEngine.EventSystems.PointerEventData),
typeof(Func<UnityEngine.GameObject,int,bool>),
typeof(Action<long,string>),
typeof(Action<UnityEngine.RectTransform, int>),
typeof(Action<int, UnityEngine.RectTransform>),
typeof(DG.Tweening.Core.DOGetter<UnityEngine.Vector2>),
typeof(DG.Tweening.Core.DOGetter<UnityEngine.Vector3>),
typeof(DG.Tweening.Core.DOGetter<float>),
typeof(DG.Tweening.Core.DOGetter<int>),
typeof(DG.Tweening.Core.DOSetter<float>),
typeof(DG.Tweening.Core.DOSetter<int>),
#if DEVELOPMENT || RELEASE
typeof(MobileConsole.UI.GenericNodeView.Callback),
typeof(MobileConsole.UI.CheckboxNodeView.Callback),
typeof(MobileConsole.UI.DropdownNodeView.Callback),
typeof(MobileConsole.UI.InputNodeView.Callback),
typeof(MobileConsole.UI.SliderNodeView.Callback),
#endif
};
private static Type[] Elements =
{
typeof(bool),
typeof(int),
typeof(float),
typeof(double),
typeof(string),
typeof(object)
};
private static List<Type[]> GetElementsList()
{
List<Type[]> list1= new List<Type[]>();
//List<Type[]> list1 = XGame.Utility.GetPermutation(Elements, 3);
//List<Type[]> list2 = XGame.Utility.GetPermutation(Elements, 2);
//list1.AddRange(list2);
//for (int i = 0; i < Elements.Length; i++)
//{
// Type e = Elements[i];
// list1.Add(new[]
// {
// e
// });
// list1.Add(new[]
// {
// e,
// e
// });
// list1.Add(new[]
// {
// e,
// e,
// e
// });
//}
//for (int i = 0; i < list2.Count; ++i)
//{
// Type[] elements = list2[i];
// Type e1 = elements[0];
// Type e2 = elements[1];
// list1.Add(new[]
// {
// e1,
// e1,
// e2
// });
// list1.Add(new[]
// {
// e1,
// e2,
// e1
// });
// list1.Add(new[]
// {
// e2,
// e1,
// e1
// });
//}
return list1;
}
private static List<Type> GetCSharpCallLua()
{
List<Type[]> list = GetElementsList();
List<Type> csharpCallLua = new List<Type>();
for (int i = 0; i < list.Count; ++i)
{
Type[] elements = list[i];
Type actionGeneric = null;
Type funcGeneric = null;
switch (elements.Length)
{
case 1:
actionGeneric = typeof(Action<>);
funcGeneric = typeof(Func<>);
break;
case 2:
actionGeneric = typeof(Action<,>);
funcGeneric = typeof(Func<,>);
break;
case 3:
actionGeneric = typeof(Action<,,>);
funcGeneric = typeof(Func<,,>);
break;
}
if (actionGeneric != null)
{
csharpCallLua.Add(actionGeneric.MakeGenericType(elements));
}
if (funcGeneric != null)
{
csharpCallLua.Add(funcGeneric.MakeGenericType(elements));
}
}
return csharpCallLua;
}
[CSharpCallLua]
public static List<Type> CSharpCallLuaAuto = GetCSharpCallLua();
[BlackList]
public static List<List<string>> BlackList = new List<List<string>>()
{
new List<string>()
{
"UnityEngine.Texture2D",
"alphaIsTransparency"
},
new List<string>()
{
"UnityEngine.Security",
"GetChainOfTrustValue"
},
new List<string>()
{
"UnityEngine.CanvasRenderer",
"onRequestRebuild"
},
new List<string>()
{
"UnityEngine.Light",
"areaSize"
},
new List<string>()
{
"UnityEngine.AnimatorOverrideController",
"PerformOverrideClipListCleanup"
},
#if !UNITY_WEBPLAYER
new List<string>()
{
"UnityEngine.Application",
"ExternalEval"
},
#endif
new List<string>()
{
"UnityEngine.GameObject",
"networkView"
},
new List<string>()
{
"UnityEngine.Component",
"networkView"
},
new List<string>()
{
"System.IO.FileInfo",
"GetAccessControl",
"System.Security.AccessControl.AccessControlSections"
},
new List<string>()
{
"System.IO.FileInfo",
"SetAccessControl",
"System.Security.AccessControl.FileSecurity"
},
new List<string>()
{
"System.IO.DirectoryInfo",
"GetAccessControl",
"System.Security.AccessControl.AccessControlSections"
},
new List<string>()
{
"System.IO.DirectoryInfo",
"SetAccessControl",
"System.Security.AccessControl.DirectorySecurity"
},
new List<string>()
{
"System.IO.DirectoryInfo",
"CreateSubdirectory",
"System.String",
"System.Security.AccessControl.DirectorySecurity"
},
new List<string>()
{
"System.IO.DirectoryInfo",
"Create",
"System.Security.AccessControl.DirectorySecurity"
},
new List<string>()
{
"UnityEngine.MonoBehaviour",
"runInEditMode"
},
new List<string>()
{
"UnityEngine.Input",
"IsJoystickPreconfigured",
"System.String"
},
new List<string>()
{
"UnityEngine.Texture",
"imageContentsHash"
},
new List<string>()
{
"UnityEngine.UI.Text",
"OnRebuildRequested"
},
new List<string>()
{
"XGame.Actor",
"RidToActorDict"
},
new List<string>()
{
"XGame.Actor",
"GetInspectedData",
"XGame.PropertyInspectorBehaviour"
},
new List<string>()
{
"XGame.Utility",
"GetBuildPlatformName",
"UnityEditor.BuildTarget"
},
new List<string>()
{
"XGame.FileManager",
"OnFileChange",
"System.Object",
"System.IO.FileSystemEventArgs",
},
new List<string>()
{
"XGame.FileManager",
"OnFileRename",
"System.Object",
"System.IO.RenamedEventArgs",
},
new List<string>()
{
"XGame.FileManager",
"OnFileError",
"System.Object",
"System.IO.ErrorEventArgs",
},
new List<string>(){ "UnityEngine.Material", "IsChildOf", "UnityEngine.Material"},
new List<string>(){ "UnityEngine.Material", "RevertAllPropertyOverrides"},
new List<string>(){ "UnityEngine.Material", "IsPropertyOverriden", "System.Int32"},
new List<string>(){ "UnityEngine.Material", "IsPropertyOverriden", "System.String"},
new List<string>(){ "UnityEngine.Material", "IsPropertyLocked", "System.Int32"},
new List<string>(){ "UnityEngine.Material", "IsPropertyLocked", "System.String"},
new List<string>(){ "UnityEngine.Material", "IsPropertyLockedByAncestor", "System.Int32"},
new List<string>(){ "UnityEngine.Material", "IsPropertyLockedByAncestor", "System.String"},
new List<string>(){ "UnityEngine.Material", "SetPropertyLock","System.Int32", "System.Boolean"},
new List<string>(){ "UnityEngine.Material", "SetPropertyLock", "System.String", "System.Boolean"},
new List<string>(){ "UnityEngine.Material", "ApplyPropertyOverride","UnityEngine.Material", "System.String", "System.Boolean"},
new List<string>(){ "UnityEngine.Material", "ApplyPropertyOverride","UnityEngine.Material", "System.Int32", "System.Boolean"},
new List<string>(){ "UnityEngine.Material", "RevertPropertyOverride", "System.Int32"},
new List<string>(){ "UnityEngine.Material", "RevertPropertyOverride", "System.String"},
new List<string>(){ "UnityEngine.Material", "parent"},
new List<string>(){ "UnityEngine.Material", "isVariant"},
new List<string>() { "RenderHeads.Media.AVProVideo.MediaPlayer", "EditorUpdate" },
new List<string>() { "RenderHeads.Media.AVProVideo.MediaPlayer", "CheckEditorAudioMute" },
new List<string>() { "RenderHeads.Media.AVProVideo.MediaPlayer", "EditorAllPlayersDispose" },
new List<string>() { "RenderHeads.Media.AVProVideo.MediaPlayer", "GetPlatformOptions", "RenderHeads.Media.AVProVideo.Platform" },
new List<string>() { "RenderHeads.Media.AVProVideo.MediaPlayer", "GetPlatformOptionsVariable", "RenderHeads.Media.AVProVideo.Platform" },
new List<string>() { "RenderHeads.Media.AVProVideo.MediaPlayer", "SaveFrameToExr" },
new List<string>() { "RenderHeads.Media.AVProVideo.MediaPlayer", "SaveFrameToPng" },
new List<string>() { "RenderHeads.Media.AVProVideo.MediaPlayer", "InternalMediaLoadedEvent" },
new List<string>() { "UnityEngine.MonoBehaviour", "EnableScriptReloadInCheckConsistency", "System.Boolean"},
};
#if UNITY_2018_1_OR_NEWER
[BlackList]
public static Func<MemberInfo, bool> MethodFilter = (memberInfo) =>
{
if (memberInfo.DeclaringType.IsGenericType && memberInfo.DeclaringType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
if (memberInfo.MemberType == MemberTypes.Constructor)
{
ConstructorInfo constructorInfo = memberInfo as ConstructorInfo;
ParameterInfo[] parameterInfos = constructorInfo.GetParameters();
if (parameterInfos.Length > 0)
{
if (typeof(IEnumerable).IsAssignableFrom(parameterInfos[0].ParameterType))
{
return true;
}
}
}
else if (memberInfo.MemberType == MemberTypes.Method)
{
MethodInfo methodInfo = memberInfo as MethodInfo;
if (methodInfo.Name == "TryAdd" || methodInfo.Name == "Remove" && methodInfo.GetParameters().Length == 2)
{
return true;
}
}
}
if (memberInfo.DeclaringType.IsGenericType && memberInfo.DeclaringType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
if (memberInfo.MemberType == MemberTypes.Method)
{
MethodInfo methodInfo = memberInfo as MethodInfo;
if (methodInfo.Name == "Deconstruct")
{
return true;
}
}
}
if (memberInfo.MemberType == MemberTypes.Method)
{
MethodInfo methodInfo = memberInfo as MethodInfo;
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
foreach (ParameterInfo param in parameterInfos)
{
if (typeof(ReadOnlySpan<char>).IsAssignableFrom(param.ParameterType)
|| typeof(ReadOnlySpan<byte>).IsAssignableFrom(param.ParameterType)
|| typeof(ReadOnlySpan<int>).IsAssignableFrom(param.ParameterType)
|| typeof(ReadOnlySpan<Vector3>).IsAssignableFrom(param.ParameterType)
|| typeof(Span<char>).IsAssignableFrom(param.ParameterType)
|| typeof(Span<byte>).IsAssignableFrom(param.ParameterType)
|| typeof(Span<bool>).IsAssignableFrom(param.ParameterType)
|| typeof(Span<Vector3>).IsAssignableFrom(param.ParameterType)
)
{
return true;
}
}
}
return false;
};
#endif
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e968a5a3fb13be64ebbc3a8ede2b23a2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+5
View File
@@ -0,0 +1,5 @@
fileFormatVersion: 2
guid: 9c7307955fb71fc4090eb2a906a78a0a
folderAsset: yes
DefaultImporter:
userData:
@@ -0,0 +1,589 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
<%ForEachCsList(namespaces, function(namespace)%>using <%=namespace%>;<%end)%>
<%
require "TemplateCommon"
local OpNameMap = {
op_Addition = "__AddMeta",
op_Subtraction = "__SubMeta",
op_Multiply = "__MulMeta",
op_Division = "__DivMeta",
op_Equality = "__EqMeta",
op_UnaryNegation = "__UnmMeta",
op_LessThan = "__LTMeta",
op_LessThanOrEqual = "__LEMeta",
op_Modulus = "__ModMeta",
op_BitwiseAnd = "__BandMeta",
op_BitwiseOr = "__BorMeta",
op_ExclusiveOr = "__BxorMeta",
op_OnesComplement = "__BnotMeta",
op_LeftShift = "__ShlMeta",
op_RightShift = "__ShrMeta",
}
local OpCallNameMap = {
op_Addition = "+",
op_Subtraction = "-",
op_Multiply = "*",
op_Division = "/",
op_Equality = "==",
op_UnaryNegation = "-",
op_LessThan = "<",
op_LessThanOrEqual = "<=",
op_Modulus = "%",
op_BitwiseAnd = "&",
op_BitwiseOr = "|",
op_ExclusiveOr = "^",
op_OnesComplement = "~",
op_LeftShift = "<<",
op_RightShift = ">>",
}
local obj_method_count = 0
local obj_getter_count = 0
local obj_setter_count = 0
local meta_func_count = operators.Count
local cls_field_count = 1
local cls_getter_count = 0
local cls_setter_count = 0
ForEachCsList(methods, function(method)
if method.IsStatic then
cls_field_count = cls_field_count + 1
else
obj_method_count = obj_method_count + 1
end
end)
ForEachCsList(events, function(event)
if event.IsStatic then
cls_field_count = cls_field_count + 1
else
obj_method_count = obj_method_count + 1
end
end)
ForEachCsList(getters, function(getter)
if getter.IsStatic then
if getter.ReadOnly then
cls_field_count = cls_field_count + 1
else
cls_getter_count = cls_getter_count + 1
end
else
obj_getter_count = obj_getter_count + 1
end
end)
ForEachCsList(setters, function(setter)
if setter.IsStatic then
cls_setter_count = cls_setter_count + 1
else
obj_setter_count = obj_setter_count + 1
end
end)
ForEachCsList(lazymembers, function(lazymember)
if lazymember.IsStatic == 'true' then
if 'CLS_IDX' == lazymember.Index then
cls_field_count = cls_field_count + 1
elseif 'CLS_GETTER_IDX' == lazymember.Index then
cls_getter_count = cls_getter_count + 1
elseif 'CLS_SETTER_IDX' == lazymember.Index then
cls_setter_count = cls_setter_count + 1
end
else
if 'METHOD_IDX' == lazymember.Index then
obj_method_count = obj_method_count + 1
elseif 'GETTER_IDX' == lazymember.Index then
obj_getter_count = obj_getter_count + 1
elseif 'SETTER_IDX' == lazymember.Index then
obj_setter_count = obj_setter_count + 1
end
end
end)
local generic_arg_list, type_constraints = GenericArgumentList(type)
%>
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class <%=CSVariableName(type)%>Wrap<%=generic_arg_list%> <%=type_constraints%>
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(<%=CsFullTypeName(type)%>);
Utils.BeginObjectRegister(type, L, translator, <%=meta_func_count%>, <%=obj_method_count%>, <%=obj_getter_count%>, <%=obj_setter_count%>);
<%ForEachCsList(operators, function(operator)%>Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "<%=(OpNameMap[operator.Name]):gsub('Meta', ''):lower()%>", <%=OpNameMap[operator.Name]%>);
<%end)%>
<%ForEachCsList(methods, function(method) if not method.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=method.Name%>", _m_<%=method.Name%>);
<% end end)%>
<%ForEachCsList(events, function(event) if not event.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=event.Name%>", _e_<%=event.Name%>);
<% end end)%>
<%ForEachCsList(getters, function(getter) if not getter.IsStatic then %>Utils.RegisterFunc(L, Utils.GETTER_IDX, "<%=getter.Name%>", _g_get_<%=getter.Name%>);
<%end end)%>
<%ForEachCsList(setters, function(setter) if not setter.IsStatic then %>Utils.RegisterFunc(L, Utils.SETTER_IDX, "<%=setter.Name%>", _s_set_<%=setter.Name%>);
<%end end)%>
<%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'false' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>);
<%end end)%>
Utils.EndObjectRegister(type, L, translator, <% if type.IsArray or ((indexers.Count or 0) > 0) then %>__CSIndexer<%else%>null<%end%>, <%if type.IsArray or ((newindexers.Count or 0) > 0) then%>__NewIndexer<%else%>null<%end%>,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, <%=cls_field_count%>, <%=cls_getter_count%>, <%=cls_setter_count%>);
<%ForEachCsList(methods, function(method) if method.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=method.Overloads[0].Name%>", _m_<%=method.Name%>);
<% end end)%>
<%ForEachCsList(events, function(event) if event.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=event.Name%>", _e_<%=event.Name%>);
<% end end)%>
<%ForEachCsList(getters, function(getter) if getter.IsStatic and getter.ReadOnly then %>Utils.RegisterObject(L, translator, Utils.CLS_IDX, "<%=getter.Name%>", <%=CsFullTypeName(type).."."..getter.Name%>);
<%end end)%>
<%ForEachCsList(getters, function(getter) if getter.IsStatic and (not getter.ReadOnly) then %>Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "<%=getter.Name%>", _g_get_<%=getter.Name%>);
<%end end)%>
<%ForEachCsList(setters, function(setter) if setter.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_SETTER_IDX, "<%=setter.Name%>", _s_set_<%=setter.Name%>);
<%end end)%>
<%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'true' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>);
<%end end)%>
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
<%
if constructors.Count == 0 and (not type.IsValueType) then
%>return LuaAPI.luaL_error(L, "<%=CsFullTypeName(type)%> does not have a constructor!");<%
else %>
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
<%
local hasZeroParamsCtor = false
ForEachCsList(constructors, function(constructor, ci)
local parameters = constructor:GetParameters()
if parameters.Length == 0 then
hasZeroParamsCtor = true
end
local def_count = constructor_def_vals[ci]
local param_count = parameters.Length
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local real_param_count = param_count - def_count
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
local in_pos = 0
%>if(LuaAPI.lua_gettop(L) <%=has_v_params and ">=" or "=="%> <%=in_num + 1 - def_count - (has_v_params and 1 or 0)%><%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
local parameterType = parameter.ParameterType
if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1
%> && <%=GetCheckStatement(parameterType, in_pos+1, has_v_params and pi == param_count - 1)%><%
end
end)%>)
{
<%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
%><%=GetCasterStatement(parameter.ParameterType, pi+2, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%>;
<%end)%>
var gen_ret = new <%=CsFullTypeName(type)%>(<%ForEachCsList(parameters, function(parameter, pi) if pi >= real_param_count then return end; if pi ~=0 then %><%=', '%><% end ;if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end)%>);
<%=GetPushStatement(type, "gen_ret")%>;
<%local in_pos = 0
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
end
if parameter.ParameterType.IsByRef then
%><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>;
<%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then
%><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+1, LocalName(parameter.Name))%>;
<%end%>
<%
end
end)
%>
return <%=out_num + 1%>;
}
<%end)
if (not hasZeroParamsCtor) and type.IsValueType then
%>
if (LuaAPI.lua_gettop(L) == 1)
{
<%=GetPushStatement(type, "default(" .. CsFullTypeName(type).. ")")%>;
return 1;
}
<%end%>
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%> constructor!");
<% end %>
}
<% if type.IsArray or ((indexers.Count or 0) > 0) then %>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int __CSIndexer(RealStatePtr L)
{
<%if type.IsArray then %>
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2))
{
int index = (int)LuaAPI.lua_tonumber(L, 2);
<%=GetSelfStatement(type)%>;
LuaAPI.lua_pushboolean(L, true);
<%=GetPushStatement(type:GetElementType(), "gen_to_be_invoked[index]")%>;
return 2;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
<%elseif indexers.Count > 0 then
%>try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
<%
ForEachCsList(indexers, function(indexer)
local paramter = indexer:GetParameters()[0]
%>
if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(paramter.ParameterType, 2)%>)
{
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(paramter.ParameterType, 2, "index", true)%>;
LuaAPI.lua_pushboolean(L, true);
<%=GetPushStatement(indexer.ReturnType, "gen_to_be_invoked[index]")%>;
return 2;
}
<%end)%>
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
<%end%>
LuaAPI.lua_pushboolean(L, false);
return 1;
}
<% end %>
<%if type.IsArray or ((newindexers.Count or 0) > 0) then%>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int __NewIndexer(RealStatePtr L)
{
<%if type.IsArray or newindexers.Count > 0 then %>ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%>
<%if type.IsArray then
local elementType = type:GetElementType()
%>
try {
if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2) && <%=GetCheckStatement(elementType, 3)%>)
{
int index = (int)LuaAPI.lua_tonumber(L, 2);
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(elementType, 3, "gen_to_be_invoked[index]")%>;
LuaAPI.lua_pushboolean(L, true);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
<%elseif newindexers.Count > 0 then%>
try {
<%ForEachCsList(newindexers, function(newindexer)
local keyType = newindexer:GetParameters()[0].ParameterType
local valueType = newindexer:GetParameters()[1].ParameterType
%>
if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(keyType, 2)%> && <%=GetCheckStatement(valueType, 3)%>)
{
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%if IsStruct(valueType) then%><%=GetCasterStatement(valueType, 3, "gen_value", true)%>;
gen_to_be_invoked[key] = gen_value;<%else
%><%=GetCasterStatement(valueType, 3, "gen_to_be_invoked[key]")%>;<%end%>
LuaAPI.lua_pushboolean(L, true);
return 1;
}
<%end)%>
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
<%end%>
LuaAPI.lua_pushboolean(L, false);
return 1;
}
<% end %>
<%ForEachCsList(operators, function(operator) %>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int <%=OpNameMap[operator.Name]%>(RealStatePtr L)
{
<% if operator.Name ~= "op_UnaryNegation" and operator.Name ~= "op_OnesComplement" then %>
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
<%ForEachCsList(operator.Overloads, function(overload)
local left_param = overload:GetParameters()[0]
local right_param = overload:GetParameters()[1]
%>
if (<%=GetCheckStatement(left_param.ParameterType, 1)%> && <%=GetCheckStatement(right_param.ParameterType, 2)%>)
{
<%=GetCasterStatement(left_param.ParameterType, 1, "leftside", true)%>;
<%=GetCasterStatement(right_param.ParameterType, 2, "rightside", true)%>;
<%=GetPushStatement(overload.ReturnType, "leftside " .. OpCallNameMap[operator.Name] .. " rightside")%>;
return 1;
}
<%end)%>
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to right hand of <%=OpCallNameMap[operator.Name]%> operator, need <%=CsFullTypeName(type)%>!");
<%else%>
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
<%=GetCasterStatement(type, 1, "rightside", true)%>;
<%=GetPushStatement(operator.Overloads[0].ReturnType, OpCallNameMap[operator.Name] .. " rightside")%>;
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
<%end%>
}
<%end)%>
<%ForEachCsList(methods, function(method)%>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_<%=method.Name%>(RealStatePtr L)
{
try {
<%
local need_obj = not method.IsStatic
if MethodCallNeedTranslator(method) then
%>
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
<%end%>
<%if need_obj then%>
<%=GetSelfStatement(type)%>;
<%end%>
<%if method.Overloads.Count > 1 then%>
int gen_param_count = LuaAPI.lua_gettop(L);
<%end%>
<%ForEachCsList(method.Overloads, function(overload, oi)
local parameters = MethodParameters(overload)
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local param_offset = method.IsStatic and 0 or 1
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (overload.ReturnType.FullName ~= "System.Void")
local def_count = method.DefaultValues[oi]
local param_count = parameters.Length
local real_param_count = param_count - def_count
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
if method.Overloads.Count > 1 then
%>if(gen_param_count <%=has_v_params and ">=" or "=="%> <%=in_num+param_offset-def_count - (has_v_params and 1 or 0)%><%
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
local parameterType = parameter.ParameterType
if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1;
%>&& <%=GetCheckStatement(parameterType , in_pos+param_offset, has_v_params and pi == param_count - 1)%><%
end
end)%>) <%end%>
{
<%if overload.Name == "get_Item" and overload.IsSpecialName then
local keyType = overload:GetParameters()[0].ParameterType%>
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%=GetPushStatement(overload.ReturnType, "gen_to_be_invoked[key]")%>;
<%elseif overload.Name == "set_Item" and overload.IsSpecialName then
local keyType = overload:GetParameters()[0].ParameterType
local valueType = overload:GetParameters()[1].ParameterType%>
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%=GetCasterStatement(valueType, 3, "gen_value", true)%>;
gen_to_be_invoked[key] = gen_value;
<% else
in_pos = 0;
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
%><%if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
%><%=GetCasterStatement(parameter.ParameterType, in_pos+param_offset, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%><%
else%><%=CsFullTypeName(parameter.ParameterType)%> <%=LocalName(parameter.Name)%><%end%>;
<%end)%>
<%
if has_return then
%> var gen_ret = <%
end
%><%if method.IsStatic then
%><%=CsFullTypeName(type).."."..UnK(overload.Name)%><%
else
%>gen_to_be_invoked.<%=UnK(overload.Name)%><%
end%>( <%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if pi ~= 0 then %>, <% end; if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end) %> );
<%
if has_return then
%> <%=GetPushStatement(overload.ReturnType, "gen_ret")%>;
<%
end
local in_pos = 0
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
end
if parameter.ParameterType.IsByRef then
%><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>;
<%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then
%><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+param_offset, LocalName(parameter.Name))%>;
<%end%>
<%
end
end)
end
%>
<%if NeedUpdate(type) and not method.IsStatic then%>
<%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>;
<%end%>
return <%=out_num+(has_return and 1 or 0)%>;
}
<% end)%>
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
<%if method.Overloads.Count > 1 then%>
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=method.Overloads[0].Name%>!");
<%end%>
}
<% end)%>
<%ForEachCsList(getters, function(getter)
if getter.IsStatic and getter.ReadOnly then return end --readonly static
%>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_<%=getter.Name%>(RealStatePtr L)
{
try {
<%if AccessorNeedTranslator(getter) then %> ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%>
<%if not getter.IsStatic then%>
<%=GetSelfStatement(type)%>;
<%=GetPushStatement(getter.Type, "gen_to_be_invoked."..UnK(getter.Name))%>;<% else %> <%=GetPushStatement(getter.Type, CsFullTypeName(type).."."..UnK(getter.Name))%>;<% end%>
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
<%end)%>
<%ForEachCsList(setters, function(setter)
local is_struct = IsStruct(setter.Type)
%>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_<%=setter.Name%>(RealStatePtr L)
{
try {
<%if AccessorNeedTranslator(setter) then %>ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%>
<%if not setter.IsStatic then %>
<%=GetSelfStatement(type)%>;
<%if is_struct then %><%=GetCasterStatement(setter.Type, 2, "gen_value", true)%>;
gen_to_be_invoked.<%=UnK(setter.Name)%> = gen_value;<% else
%><%=GetCasterStatement(setter.Type, 2, "gen_to_be_invoked." .. UnK(setter.Name))%>;<%end
else
if is_struct then %><%=GetCasterStatement(setter.Type, 1, "gen_value", true)%>;
<%=CsFullTypeName(type)%>.<%=UnK(setter.Name)%> = gen_value;<%else
%> <%=GetCasterStatement(setter.Type, 1, CsFullTypeName(type) .."." .. UnK(setter.Name))%>;<%end
end%>
<%if NeedUpdate(type) and not setter.IsStatic then%>
<%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>;
<%end%>
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
<%end)%>
<%ForEachCsList(events, function(event) if not event.IsStatic then %>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _e_<%=event.Name%>(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
int gen_param_count = LuaAPI.lua_gettop(L);
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(event.Type, 3, "gen_delegate", true)%>;
if (gen_delegate == null) {
return LuaAPI.luaL_error(L, "#3 need <%=CsFullTypeName(event.Type)%>!");
}
if (gen_param_count == 3)
{
<%if event.CanAdd then%>
if (LuaAPI.xlua_is_eq_str(L, 2, "+")) {
gen_to_be_invoked.<%=UnK(event.Name)%> += gen_delegate;
return 0;
}
<%end%>
<%if event.CanRemove then%>
if (LuaAPI.xlua_is_eq_str(L, 2, "-")) {
gen_to_be_invoked.<%=UnK(event.Name)%> -= gen_delegate;
return 0;
}
<%end%>
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!");
return 0;
}
<%end end)%>
<%ForEachCsList(events, function(event) if event.IsStatic then %>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _e_<%=event.Name%>(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
int gen_param_count = LuaAPI.lua_gettop(L);
<%=GetCasterStatement(event.Type, 2, "gen_delegate", true)%>;
if (gen_delegate == null) {
return LuaAPI.luaL_error(L, "#2 need <%=CsFullTypeName(event.Type)%>!");
}
<%if event.CanAdd then%>
if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "+")) {
<%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> += gen_delegate;
return 0;
}
<%end%>
<%if event.CanRemove then%>
if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "-")) {
<%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> -= gen_delegate;
return 0;
}
<%end%>
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!");
}
<%end end)%>
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8503038eabbabe44dac0f5f749d4411a
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,517 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
<%ForEachCsList(namespaces, function(namespace)%>using <%=namespace%>;<%end)%>
<%
require "TemplateCommon"
local OpNameMap = {
op_Addition = "__AddMeta",
op_Subtraction = "__SubMeta",
op_Multiply = "__MulMeta",
op_Division = "__DivMeta",
op_Equality = "__EqMeta",
op_UnaryNegation = "__UnmMeta",
op_LessThan = "__LTMeta",
op_LessThanOrEqual = "__LEMeta",
op_Modulus = "__ModMeta",
op_BitwiseAnd = "__BandMeta",
op_BitwiseOr = "__BorMeta",
op_ExclusiveOr = "__BxorMeta",
op_OnesComplement = "__BnotMeta",
op_LeftShift = "__ShlMeta",
op_RightShift = "__ShrMeta",
}
local OpCallNameMap = {
op_Addition = "+",
op_Subtraction = "-",
op_Multiply = "*",
op_Division = "/",
op_Equality = "==",
op_UnaryNegation = "-",
op_LessThan = "<",
op_LessThanOrEqual = "<=",
op_Modulus = "%",
op_BitwiseAnd = "&",
op_BitwiseOr = "|",
op_ExclusiveOr = "^",
op_OnesComplement = "~",
op_LeftShift = "<<",
op_RightShift = ">>",
}
local obj_method_count = 0
local obj_getter_count = 0
local obj_setter_count = 0
local meta_func_count = operators.Count
local cls_field_count = 1
local cls_getter_count = 0
local cls_setter_count = 0
ForEachCsList(methods, function(method)
if method.IsStatic then
cls_field_count = cls_field_count + 1
else
obj_method_count = obj_method_count + 1
end
end)
ForEachCsList(events, function(event)
if event.IsStatic then
cls_field_count = cls_field_count + 1
else
obj_method_count = obj_method_count + 1
end
end)
ForEachCsList(getters, function(getter)
if getter.IsStatic then
if getter.ReadOnly then
cls_field_count = cls_field_count + 1
else
cls_getter_count = cls_getter_count + 1
end
else
obj_getter_count = obj_getter_count + 1
end
end)
ForEachCsList(setters, function(setter)
if setter.IsStatic then
cls_setter_count = cls_setter_count + 1
else
obj_setter_count = obj_setter_count + 1
end
end)
ForEachCsList(lazymembers, function(lazymember)
if lazymember.IsStatic == 'true' then
if 'CLS_IDX' == lazymember.Index then
cls_field_count = cls_field_count + 1
elseif 'CLS_GETTER_IDX' == lazymember.Index then
cls_getter_count = cls_getter_count + 1
elseif 'CLS_SETTER_IDX' == lazymember.Index then
cls_setter_count = cls_setter_count + 1
end
else
if 'METHOD_IDX' == lazymember.Index then
obj_method_count = obj_method_count + 1
elseif 'GETTER_IDX' == lazymember.Index then
obj_getter_count = obj_getter_count + 1
elseif 'SETTER_IDX' == lazymember.Index then
obj_setter_count = obj_setter_count + 1
end
end
end)
local v_type_name = CSVariableName(type)
local generic_arg_list, type_constraints = GenericArgumentList(type)
%>
namespace XLua
{
public partial class ObjectTranslator
{
public void __Register<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L) <%=type_constraints%>
{
System.Type type = typeof(<%=CsFullTypeName(type)%>);
Utils.BeginObjectRegister(type, L, this, <%=meta_func_count%>, <%=obj_method_count%>, <%=obj_getter_count%>, <%=obj_setter_count%>);
<%ForEachCsList(operators, function(operator)%>Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "<%=(OpNameMap[operator.Name]):gsub('Meta', ''):lower()%>", <%=v_type_name%><%=OpNameMap[operator.Name]%><%=generic_arg_list%>);
<%end)%>
<%ForEachCsList(methods, function(method) if not method.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=method.Name%>", <%=v_type_name%>_m_<%=method.Name%><%=generic_arg_list%>);
<% end end)%>
<%ForEachCsList(events, function(event) if not event.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=event.Name%>", <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>);
<% end end)%>
<%ForEachCsList(getters, function(getter) if not getter.IsStatic then %>Utils.RegisterFunc(L, Utils.GETTER_IDX, "<%=getter.Name%>", <%=v_type_name%>_g_get_<%=getter.Name%><%=generic_arg_list%>);
<%end end)%>
<%ForEachCsList(setters, function(setter) if not setter.IsStatic then %>Utils.RegisterFunc(L, Utils.SETTER_IDX, "<%=setter.Name%>", <%=v_type_name%>_s_set_<%=setter.Name%><%=generic_arg_list%>);
<%end end)%>
<%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'false' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>);
<%end end)%>
Utils.EndObjectRegister(type, L, this, <% if type.IsArray or ((indexers.Count or 0) > 0) then %>__CSIndexer<%=v_type_name%><%=generic_arg_list%><%else%>null<%end%>, <%if type.IsArray or ((newindexers.Count or 0) > 0) then%>__NewIndexer<%=v_type_name%><%=generic_arg_list%><%else%>null<%end%>,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance<%=v_type_name%><%=generic_arg_list%>, <%=cls_field_count%>, <%=cls_getter_count%>, <%=cls_setter_count%>);
<%ForEachCsList(methods, function(method) if method.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=method.Overloads[0].Name%>", <%=v_type_name%>_m_<%=method.Name%><%=generic_arg_list%>);
<% end end)%>
<%ForEachCsList(events, function(event) if event.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=event.Name%>", <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>);
<% end end)%>
<%ForEachCsList(getters, function(getter) if getter.IsStatic and getter.ReadOnly then %>Utils.RegisterObject(L, this, Utils.CLS_IDX, "<%=getter.Name%>", <%=CsFullTypeName(type).."."..getter.Name%>);
<%end end)%>
<%ForEachCsList(getters, function(getter) if getter.IsStatic and (not getter.ReadOnly) then %>Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "<%=getter.Name%>", <%=v_type_name%>_g_get_<%=getter.Name%><%=generic_arg_list%>);
<%end end)%>
<%ForEachCsList(setters, function(setter) if setter.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_SETTER_IDX, "<%=setter.Name%>", <%=v_type_name%>_s_set_<%=setter.Name%><%=generic_arg_list%>);
<%end end)%>
<%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'true' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>);
<%end end)%>
Utils.EndClassRegister(type, L, this);
}
int __CreateInstance<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%
if constructors.Count == 0 and (not type.IsValueType) then
%>return LuaAPI.luaL_error(L, "<%=CsFullTypeName(type)%> does not have a constructor!");<%
else %>
ObjectTranslator translator = this;
<%
local hasZeroParamsCtor = false
ForEachCsList(constructors, function(constructor, ci)
local parameters = constructor:GetParameters()
if parameters.Length == 0 then
hasZeroParamsCtor = true
end
local def_count = constructor_def_vals[ci]
local param_count = parameters.Length
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local real_param_count = param_count - def_count
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
local in_pos = 0
%>if(gen_param_count <%=has_v_params and ">=" or "=="%> <%=in_num + 1 - def_count - (has_v_params and 1 or 0)%><%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
local parameterType = parameter.ParameterType
if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1
%> && <%=GetCheckStatement(parameterType, in_pos+1, has_v_params and pi == param_count - 1)%><%
end
end)%>)
{
<%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
%><%=GetCasterStatement(parameter.ParameterType, pi+2, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%>;
<%end)%>
var gen_ret = new <%=CsFullTypeName(type)%>(<%ForEachCsList(parameters, function(parameter, pi) if pi >= real_param_count then return end; if pi ~=0 then %><%=', '%><% end ;if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end)%>);
<%=GetPushStatement(type, "gen_ret")%>;
<%local in_pos = 0
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
end
if parameter.ParameterType.IsByRef then
%><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>;
<%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then
%><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+1, LocalName(parameter.Name))%>;
<%end%>
<%
end
end)
%>
return <%=out_num + 1%>;
}
<%end)
if (not hasZeroParamsCtor) and type.IsValueType then
%>
if (gen_param_count == 1)
{
<%=GetPushStatement(type, "default(" .. CsFullTypeName(type).. ")")%>;
return 1;
}
<%end%>
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%> constructor!");
<% end %>
}
<% if type.IsArray or ((indexers.Count or 0) > 0) then %>
int __CSIndexer<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%if type.IsArray then %>
ObjectTranslator translator = this;
if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2))
{
int index = (int)LuaAPI.lua_tonumber(L, 2);
<%=GetSelfStatement(type)%>;
LuaAPI.lua_pushboolean(L, true);
<%=GetPushStatement(type:GetElementType(), "gen_to_be_invoked[index]")%>;
return 2;
}
<%elseif indexers.Count > 0 then
%>ObjectTranslator translator = this;
<%
ForEachCsList(indexers, function(indexer)
local paramter = indexer:GetParameters()[0]
%>
if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(paramter.ParameterType, 2)%>)
{
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(paramter.ParameterType, 2, "index", true)%>;
LuaAPI.lua_pushboolean(L, true);
<%=GetPushStatement(indexer.ReturnType, "gen_to_be_invoked[index]")%>;
return 2;
}
<%end)
end%>
LuaAPI.lua_pushboolean(L, false);
return 1;
}
<% end %>
<%if type.IsArray or ((newindexers.Count or 0) > 0) then%>
int __NewIndexer<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%if type.IsArray or newindexers.Count > 0 then %>ObjectTranslator translator = this;<%end%>
<%if type.IsArray then
local elementType = type:GetElementType()
%>
if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2) && <%=GetCheckStatement(elementType, 3)%>)
{
int index = (int)LuaAPI.lua_tonumber(L, 2);
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(elementType, 3, "gen_to_be_invoked[index]")%>;
LuaAPI.lua_pushboolean(L, true);
return 1;
}
<%elseif newindexers.Count > 0 then%>
<%ForEachCsList(newindexers, function(newindexer)
local keyType = newindexer:GetParameters()[0].ParameterType
local valueType = newindexer:GetParameters()[1].ParameterType
%>
if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(keyType, 2)%> && <%=GetCheckStatement(valueType, 3)%>)
{
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%if IsStruct(valueType) then%><%=GetCasterStatement(valueType, 3, "gen_value", true)%>;
gen_to_be_invoked[key] = gen_value;<%else
%><%=GetCasterStatement(valueType, 3, "gen_to_be_invoked[key]")%>;<%end%>
LuaAPI.lua_pushboolean(L, true);
return 1;
}
<%end)
end%>
LuaAPI.lua_pushboolean(L, false);
return 1;
}
<% end %>
<%ForEachCsList(operators, function(operator) %>
int <%=v_type_name%><%=OpNameMap[operator.Name]%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
ObjectTranslator translator = this;
<% if operator.Name ~= "op_UnaryNegation" and operator.Name ~= "op_OnesComplement" then
ForEachCsList(operator.Overloads, function(overload)
local left_param = overload:GetParameters()[0]
local right_param = overload:GetParameters()[1]
%>
if (<%=GetCheckStatement(left_param.ParameterType, 1)%> && <%=GetCheckStatement(right_param.ParameterType, 2)%>)
{
<%=GetCasterStatement(left_param.ParameterType, 1, "leftside", true)%>;
<%=GetCasterStatement(right_param.ParameterType, 2, "rightside", true)%>;
<%=GetPushStatement(overload.ReturnType, "leftside " .. OpCallNameMap[operator.Name] .. " rightside")%>;
return 1;
}
<%end)%>
return LuaAPI.luaL_error(L, "invalid arguments to right hand of <%=OpCallNameMap[operator.Name]%> operator, need <%=CsFullTypeName(type)%>!");
<%else%>
<%=GetCasterStatement(type, 1, "rightside", true)%>;
<%=GetPushStatement(operator.Overloads[0].ReturnType, OpCallNameMap[operator.Name] .. " rightside")%>;
return 1;
<%end%>
}
<%end)%>
<%ForEachCsList(methods, function(method)%>
int <%=v_type_name%>_m_<%=method.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%
local need_obj = not method.IsStatic
if MethodCallNeedTranslator(method) then
%>
ObjectTranslator translator = this;
<%end%>
<%if need_obj then%>
<%=GetSelfStatement(type)%>;
<%end%>
<%ForEachCsList(method.Overloads, function(overload, oi)
local parameters = MethodParameters(overload)
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local param_offset = method.IsStatic and 0 or 1
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (overload.ReturnType.FullName ~= "System.Void")
local def_count = method.DefaultValues[oi]
local param_count = parameters.Length
local real_param_count = param_count - def_count
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
if method.Overloads.Count > 1 then
%>if(gen_param_count <%=has_v_params and ">=" or "=="%> <%=in_num+param_offset-def_count - (has_v_params and 1 or 0)%><%
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
local parameterType = parameter.ParameterType
if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1;
%>&& <%=GetCheckStatement(parameterType , in_pos+param_offset, has_v_params and pi == param_count - 1)%><%
end
end)%>) <%end%>
{
<%if overload.Name == "get_Item" and overload.IsSpecialName then
local keyType = overload:GetParameters()[0].ParameterType%>
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%=GetPushStatement(overload.ReturnType, "gen_to_be_invoked[key]")%>;
<%elseif overload.Name == "set_Item" and overload.IsSpecialName then
local keyType = overload:GetParameters()[0].ParameterType
local valueType = overload:GetParameters()[1].ParameterType%>
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%=GetCasterStatement(valueType, 3, "gen_to_be_invoked[key]")%>;
<% else
in_pos = 0;
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
%><%if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
%><%=GetCasterStatement(parameter.ParameterType, in_pos+param_offset, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%><%
else%><%=CsFullTypeName(parameter.ParameterType)%> <%=LocalName(parameter.Name)%><%end%>;
<%end)%>
<%
if has_return then
%>var gen_ret = <%
end
%><%if method.IsStatic then
%><%=CsFullTypeName(type).."."..UnK(overload.Name)%><%
else
%>gen_to_be_invoked.<%=UnK(overload.Name)%><%
end%>( <%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if pi ~= 0 then %>, <% end; if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end) %> );
<%
if has_return then
%><%=GetPushStatement(overload.ReturnType, "gen_ret")%>;
<%
end
local in_pos = 0
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
end
if parameter.ParameterType.IsByRef then
%><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>;
<%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then
%><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+param_offset, LocalName(parameter.Name))%>;
<%end%>
<%
end
end)
end
%>
<%if NeedUpdate(type) and not method.IsStatic then%>
<%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>;
<%end%>
return <%=out_num+(has_return and 1 or 0)%>;
}
<% end)%>
<%if method.Overloads.Count > 1 then%>
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=method.Overloads[0].Name%>!");
<%end%>
}
<% end)%>
<%ForEachCsList(getters, function(getter)
if getter.IsStatic and getter.ReadOnly then return end --readonly static
%>
int <%=v_type_name%>_g_get_<%=getter.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%if AccessorNeedTranslator(getter) then %>ObjectTranslator translator = this;<%end%>
<%if not getter.IsStatic then%>
<%=GetSelfStatement(type)%>;
<%=GetPushStatement(getter.Type, "gen_to_be_invoked."..UnK(getter.Name))%>;<% else %> <%=GetPushStatement(getter.Type, CsFullTypeName(type).."."..UnK(getter.Name))%>;<% end%>
return 1;
}
<%end)%>
<%ForEachCsList(setters, function(setter)
local is_struct = IsStruct(setter.Type)
%>
int <%=v_type_name%>_s_set_<%=setter.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%if AccessorNeedTranslator(setter) then %>ObjectTranslator translator = this;<%end%>
<%if not setter.IsStatic then %>
<%=GetSelfStatement(type)%>;
<%if is_struct then %><%=GetCasterStatement(setter.Type, 2, "gen_value", true)%>;
gen_to_be_invoked.<%=UnK(setter.Name)%> = gen_value;<% else
%><%=GetCasterStatement(setter.Type, 2, "gen_to_be_invoked." .. UnK(setter.Name))%>;<%end
else
if is_struct then %><%=GetCasterStatement(setter.Type, 1, "gen_value", true)%>;
<%=CsFullTypeName(type)%>.<%=UnK(setter.Name)%> = gen_value;<%else
%><%=GetCasterStatement(setter.Type, 1, CsFullTypeName(type) .."." .. UnK(setter.Name))%>;<%end
end%>
<%if NeedUpdate(type) and not setter.IsStatic then%>
<%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>;
<%end%>
return 0;
}
<%end)%>
<%ForEachCsList(events, function(event) if not event.IsStatic then %>
int <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
ObjectTranslator translator = this;
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(event.Type, 3, "gen_delegate", true)%>;
if (gen_delegate == null) {
return LuaAPI.luaL_error(L, "#3 need <%=CsFullTypeName(event.Type)%>!");
}
if (gen_param_count == 3)
{
<%if event.CanAdd then%>
if (LuaAPI.xlua_is_eq_str(L, 2, "+")) {
gen_to_be_invoked.<%=UnK(event.Name)%> += gen_delegate;
return 0;
}
<%end%>
<%if event.CanRemove then%>
if (LuaAPI.xlua_is_eq_str(L, 2, "-")) {
gen_to_be_invoked.<%=UnK(event.Name)%> -= gen_delegate;
return 0;
}
<%end%>
}
LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!");
return 0;
}
<%end end)%>
<%ForEachCsList(events, function(event) if event.IsStatic then %>
int <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
ObjectTranslator translator = this;
<%=GetCasterStatement(event.Type, 2, "gen_delegate", true)%>;
if (gen_delegate == null) {
return LuaAPI.luaL_error(L, "#2 need <%=CsFullTypeName(event.Type)%>!");
}
<%if event.CanAdd then%>
if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "+")) {
<%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> += gen_delegate;
return 0;
}
<%end%>
<%if event.CanRemove then%>
if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "-")) {
<%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> -= gen_delegate;
return 0;
}
<%end%>
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!");
}
<%end end)%>
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2bd79d95fd859724283926ad8fa4df30
timeCreated: 1501232428
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,104 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using System;
<%
require "TemplateCommon"
%>
namespace XLua
{
public partial class DelegateBridge : DelegateBridgeBase
{
<%
ForEachCsList(delegates_groups, function(delegates_group, group_idx)
local delegate = delegates_group.Key
local parameters = delegate:GetParameters()
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (delegate.ReturnType.FullName ~= "System.Void")
local return_type_name = has_return and CsFullTypeName(delegate.ReturnType) or "void"
local out_idx = has_return and 2 or 1
if has_return then out_num = out_num + 1 end
%>
public <%=return_type_name%> __Gen_Delegate_Imp<%=group_idx%>(<%ForEachCsList(parameters, function(parameter, pi)
if pi ~= 0 then
%>, <%
end
if parameter.IsOut and parameter.ParameterType.IsByRef then
%>out <%
elseif parameter.ParameterType.IsByRef then
%>ref <%
end
%><%=CsFullTypeName(parameter.ParameterType)%> p<%=pi%><%
end) %>)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.rawL;
int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference);
<%if CallNeedTranslator(delegate, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and parameters[param_count - 1].IsParamArray
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, 'p' .. pi, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
PCall(L, <%=has_v_params and ((in_num - 1) .. " + (p".. (param_count - 1) .. " == null ? 0 : p" .. (param_count - 1) .. ".Length)" ) or in_num%>, <%=out_num%>, errFunc);
<%ForEachCsList(parameters, function(parameter, pi)
if parameter.IsOut or parameter.ParameterType.IsByRef then
%><%=GetCasterStatement(parameter.ParameterType, "errFunc" .. (" + "..out_idx), 'p' .. pi)%>;
<%
out_idx = out_idx + 1
end
end) %>
<%if has_return then %><%=GetCasterStatement(delegate.ReturnType, "errFunc + 1", "__gen_ret", true)%>;<% end%>
LuaAPI.lua_settop(L, errFunc - 1);
<%if has_return then %>return __gen_ret;<% end%>
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end)%>
static DelegateBridge()
{
Gen_Flag = true;
}
public override Delegate GetDelegateByType(Type type)
{
<%
ForEachCsList(delegates_groups, function(delegates_group, group_idx)
ForEachCsList(delegates_group.Value, function(delegate)
if delegate.DeclaringType then
local delegate_type_name = CsFullTypeName(delegate.DeclaringType)
%>
if (type == typeof(<%=delegate_type_name%>))
{
return new <%=delegate_type_name%>(__Gen_Delegate_Imp<%=group_idx%>);
}
<%
end
end)
end)
%>
return null;
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3d992756e2469044484be75f78e4e556
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,128 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
<%
require "TemplateCommon"
local parameters = delegate:GetParameters()
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (delegate.ReturnType.Name ~= "Void")
%>
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class <%=CSVariableName(type)%>Wrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Utils.BeginObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, null, null, null, null, null);
Utils.BeginClassRegister(typeof(<%=CsFullTypeName(type)%>), L, null, 1, 0, 0);
Utils.EndClassRegister(typeof(<%=CsFullTypeName(type)%>), L, translator);
}
static Dictionary<string, LuaCSFunction> __MetaFucntions_Dic = new Dictionary<string, LuaCSFunction>(){
{"__call", __CallMeta},
{"__add", __AddMeta},
{"__sub", __SubMeta},
};
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CallMeta(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
if(LuaAPI.lua_gettop(L) == <%=in_num+1%> && <%=GetCheckStatement(type, 1)%><%
ForEachCsList(parameters, function(parameter)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1;
%>&& <%=GetCheckStatement(parameter.ParameterType, in_pos+1)%><%
end
end)%>)
{
<%
in_pos = 0;
ForEachCsList(parameters, function(parameter)
%><%
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
%><%=GetCasterStatement(parameter.ParameterType, in_pos+1, parameter.Name, true)%><%
else%><%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><%end%>;
<%end)%>
<%=GetSelfStatement(type)%>;
<%
if has_return then
%> var __cl_gen_ret = <%
end
%> __cl_gen_to_be_invoked( <%ForEachCsList(parameters, function(parameter, pi) if pi ~= 0 then %>, <% end; if parameter.IsOut then %>out <% elseif parameter.ParameterType.IsByRef then %>ref <% end %><%=parameter.Name%><% end) %> );
<%
if has_return then
%> <%=GetPushStatement(delegate.ReturnType, "__cl_gen_ret")%>;
<%
end
local in_pos = 0
ForEachCsList(parameters, function(parameter)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
end
if parameter.IsOut or parameter.ParameterType.IsByRef then
%><%=GetPushStatement(parameter.ParameterType:GetElementType(), parameter.Name)%>;
<%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then
%><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+param_offset, parameter.Name)%>;
<%end%>
<%
end
end)
%>
return <%=out_num+(has_return and 1 or 0)%>;
}
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to Delegate <%=CsFullTypeName(type)%>!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __AddMeta(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
<%=GetCasterStatement(type, 1, "leftside", true)%>;
<%=GetCasterStatement(type, 2, "rightside", true)%>;
<%=GetPushStatement(type, "leftside + rightside")%>;
return 1;
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __SubMeta(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
<%=GetCasterStatement(type, 1, "leftside", true)%>;
<%=GetCasterStatement(type, 2, "rightside", true)%>;
<%=GetPushStatement(type, "leftside - rightside")%>;
return 1;
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 33b33e1cd617f794b8c801a32f3b2539
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,102 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
<%
require "TemplateCommon"
local enum_or_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__bor
%>
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
<%ForEachCsList(types, function(type)
local fields = type2fields and type2fields[type] or type:GetFields(enum_or_op(CS.System.Reflection.BindingFlags.Public, CS.System.Reflection.BindingFlags.Static))
local fields_to_gen = {}
ForEachCsList(fields, function(field)
if field.Name ~= "value__" and not IsObsolute(field) then
table.insert(fields_to_gen, field)
end
end)
%>
public class <%=CSVariableName(type)%>Wrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Utils.BeginObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, null, null, null, null, null);
Utils.BeginClassRegister(typeof(<%=CsFullTypeName(type)%>), L, null, <%=fields.Length + 1%>, 0, 0);
<%if #fields_to_gen <= 20 then%>
<% ForEachCsList(fields, function(field)
if field.Name == "value__" or IsObsolute(field) then return end
%>
Utils.RegisterObject(L, translator, Utils.CLS_IDX, "<%=field.Name%>", <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>);
<%end)%>
<%else%>
Utils.RegisterEnumType(L, typeof(<%=CsFullTypeName(type)%>));
<%end%>
Utils.RegisterFunc(L, Utils.CLS_IDX, "__CastFrom", __CastFrom);
Utils.EndClassRegister(typeof(<%=CsFullTypeName(type)%>), L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CastFrom(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
LuaTypes lua_type = LuaAPI.lua_type(L, 1);
if (lua_type == LuaTypes.LUA_TNUMBER)
{
translator.Push<%=CSVariableName(type)%>(L, (<%=CsFullTypeName(type)%>)LuaAPI.xlua_tointeger(L, 1));
}
<%if #fields_to_gen > 0 then%>
else if(lua_type == LuaTypes.LUA_TSTRING)
{
<%if #fields_to_gen <= 20 then%>
<%
local is_first = true
ForEachCsList(fields, function(field, i)
if field.Name == "value__" or IsObsolute(field) then return end
%><%=(is_first and "" or "else ")%>if (LuaAPI.xlua_is_eq_str(L, 1, "<%=field.Name%>"))
{
translator.Push<%=CSVariableName(type)%>(L, <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>);
}
<%
is_first = false
end)
%>else
{
return LuaAPI.luaL_error(L, "invalid string for <%=CsFullTypeName(type)%>!");
}
<%else%>
try
{
translator.TranslateToEnumToTop(L, typeof(<%=CsFullTypeName(type)%>), 1);
}
catch (System.Exception e)
{
return LuaAPI.luaL_error(L, "cast to " + typeof(<%=CsFullTypeName(type)%>) + " exception:" + e);
}
<%end%>
}
<%end%>
else
{
return LuaAPI.luaL_error(L, "invalid lua type for <%=CsFullTypeName(type)%>! Expect number or string, got + " + lua_type);
}
return 1;
}
}
<%end)%>
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ae16c73aad9a21a44aef65decb7e4928
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,99 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
<%
require "TemplateCommon"
local enum_or_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__bor
%>
namespace XLua
{
public partial class ObjectTranslator
{
<%ForEachCsList(types, function(type)
local fields = type2fields and type2fields[type] or type:GetFields(enum_or_op(CS.System.Reflection.BindingFlags.Public, CS.System.Reflection.BindingFlags.Static))
local fields_to_gen = {}
ForEachCsList(fields, function(field)
if field.Name ~= "value__" and not IsObsolute(field) then
table.insert(fields_to_gen, field)
end
end)
local v_type_name = CSVariableName(type)
%>
public void __Register<%=v_type_name%>(RealStatePtr L)
{
Utils.BeginObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, this, 0, 0, 0, 0);
Utils.EndObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, this, null, null, null, null, null);
Utils.BeginClassRegister(typeof(<%=CsFullTypeName(type)%>), L, null, <%=fields.Length + 1%>, 0, 0);
<%if #fields_to_gen <= 20 then%>
<% ForEachCsList(fields, function(field)
if field.Name == "value__" or IsObsolute(field) then return end
%>
Utils.RegisterObject(L, this, Utils.CLS_IDX, "<%=field.Name%>", <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>);
<%end)%>
<%else%>
Utils.RegisterEnumType(L, typeof(<%=CsFullTypeName(type)%>));
<%end%>
Utils.RegisterFunc(L, Utils.CLS_IDX, "__CastFrom", __CastFrom<%=v_type_name%>);
Utils.EndClassRegister(typeof(<%=CsFullTypeName(type)%>), L, this);
}
int __CastFrom<%=v_type_name%>(RealStatePtr L, int __gen_top)
{
LuaTypes lua_type = LuaAPI.lua_type(L, 1);
if (lua_type == LuaTypes.LUA_TNUMBER)
{
Push<%=v_type_name%>(L, (<%=CsFullTypeName(type)%>)LuaAPI.xlua_tointeger(L, 1));
}
<%if #fields_to_gen > 0 then%>
else if(lua_type == LuaTypes.LUA_TSTRING)
{
<%if #fields_to_gen <= 20 then%>
<%
local is_first = true
ForEachCsList(fields, function(field, i)
if field.Name == "value__" or IsObsolute(field) then return end
%><%=(is_first and "" or "else ")%>if (LuaAPI.xlua_is_eq_str(L, 1, "<%=field.Name%>"))
{
Push<%=v_type_name%>(L, <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>);
}
<%
is_first = false
end)
%>else
{
return LuaAPI.luaL_error(L, "invalid string for <%=CsFullTypeName(type)%>!");
}
<%else%>
try
{
TranslateToEnumToTop(L, typeof(<%=CsFullTypeName(type)%>), 1);
}
catch (System.Exception e)
{
return LuaAPI.luaL_error(L, "cast to " + typeof(<%=CsFullTypeName(type)%>) + " exception:" + e);
}
<%end%>
}
<%end%>
else
{
return LuaAPI.luaL_error(L, "invalid lua type for <%=CsFullTypeName(type)%>! Expect number or string, got + " + lua_type);
}
return 1;
}
<%end)%>
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ea84a5ee7abf8e347a810eb7848add46
timeCreated: 1501232428
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,385 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using XLua;
using System;
<%
require "TemplateCommon"
%>
namespace XLua.CSObjectWrap
{
public class <%=CSVariableName(type)%>Bridge : LuaBase, <%=CsFullTypeName(type)%>
{
public static LuaBase __Create(int reference, LuaEnv luaenv)
{
return new <%=CSVariableName(type)%>Bridge(reference, luaenv);
}
public <%=CSVariableName(type)%>Bridge(int reference, LuaEnv luaenv) : base(reference, luaenv)
{
}
<%
ForEachCsList(methods, function(method)
local parameters = method:GetParameters()
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (method.ReturnType.FullName ~= "System.Void")
local return_type_name = has_return and CsFullTypeName(method.ReturnType) or "void"
local out_idx = has_return and 2 or 1
if has_return then out_num = out_num + 1 end
%>
<%=return_type_name%> <%=CsFullTypeName(method.DeclaringType)%>.<%=method.Name%>(<%ForEachCsList(parameters, function(parameter, pi)
if pi ~= 0 then
%>, <%
end
if parameter.IsOut and parameter.ParameterType.IsByRef then
%>out <%
elseif parameter.ParameterType.IsByRef then
%>ref <%
end
%><%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><%
end) %>)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
<%if CallNeedTranslator(method, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "<%=method.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(err_func - 1);
}
if(!LuaAPI.lua_isfunction(L, -1))
{
LuaAPI.xlua_pushasciistring(L, "no such function <%=method.Name%>");
luaEnv.ThrowExceptionFromError(err_func - 1);
}
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.lua_remove(L, -3);
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
int __gen_error = LuaAPI.lua_pcall(L, <%=has_v_params and ((in_num) .. " + (".. parameters[param_count - 1].Name .. " == null ? 0 : " .. parameters[param_count - 1].Name .. ".Length)" ) or (in_num + 1)%>, <%=out_num%>, err_func);
if (__gen_error != 0)
luaEnv.ThrowExceptionFromError(err_func - 1);
<%ForEachCsList(parameters, function(parameter)
if parameter.IsOut or parameter.ParameterType.IsByRef then
%><%=GetCasterStatement(parameter.ParameterType, "err_func" .. (" + "..out_idx), parameter.Name)%>;
<%
out_idx = out_idx + 1
end
end) %>
<%if has_return then %><%=GetCasterStatement(method.ReturnType, "err_func + 1", "__gen_ret", true)%>;<% end%>
LuaAPI.lua_settop(L, err_func - 1);
<%if has_return then %>return __gen_ret;<% end%>
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end)%>
<%
ForEachCsList(propertys, function(property)
%>
<%=CsFullTypeName(property.PropertyType)%> <%=CsFullTypeName(property.DeclaringType)%>.<%=property.Name%>
{
<%if property.CanRead then%>
get
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int oldTop = LuaAPI.lua_gettop(L);
<%if not JustLuaType(property.PropertyType) then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "<%=property.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(oldTop);
}
<%=GetCasterStatement(property.PropertyType, "-1", "__gen_ret", true)%>;
LuaAPI.lua_pop(L, 2);
return __gen_ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end%>
<%if property.CanWrite then%>
set
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int oldTop = LuaAPI.lua_gettop(L);
<%if not JustLuaType(property.PropertyType) then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "<%=property.Name%>");
<%=GetPushStatement(property.PropertyType, "value")%>;
if (0 != LuaAPI.xlua_psettable(L, -3))
{
luaEnv.ThrowExceptionFromError(oldTop);
}
LuaAPI.lua_pop(L, 1);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end%>
}
<%end)%>
<%ForEachCsList(events, function(event) %>
event <%=CsFullTypeName(event.EventHandlerType)%> <%=CsFullTypeName(event.DeclaringType)%>.<%=event.Name%>
{<%local parameters = event:GetAddMethod():GetParameters()%>
add
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
<%if CallNeedTranslator(event:GetAddMethod(), "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "add_<%=event.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(err_func - 1);
}
if(!LuaAPI.lua_isfunction(L, -1))
{
LuaAPI.xlua_pushasciistring(L, "no such function add_<%=event.Name%>");
luaEnv.ThrowExceptionFromError(err_func - 1);
}
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.lua_remove(L, -3);
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
int __gen_error = LuaAPI.lua_pcall(L, 2, 0, err_func);
if (__gen_error != 0)
luaEnv.ThrowExceptionFromError(err_func - 1);
LuaAPI.lua_settop(L, err_func - 1);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
remove
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
<%if CallNeedTranslator(event:GetRemoveMethod(), "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "remove_<%=event.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(err_func - 1);
}
if(!LuaAPI.lua_isfunction(L, -1))
{
LuaAPI.xlua_pushasciistring(L, "no such function remove_<%=event.Name%>");
luaEnv.ThrowExceptionFromError(err_func - 1);
}
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.lua_remove(L, -3);
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
int __gen_error = LuaAPI.lua_pcall(L, 2, 0, err_func);
if (__gen_error != 0)
luaEnv.ThrowExceptionFromError(err_func - 1);
LuaAPI.lua_settop(L, err_func - 1);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
}
<%end)%>
<%ForEachCsList(indexers, function(indexer)
local ptype = (indexer:GetGetMethod() or indexer:GetSetMethod()):GetParameters()[0].ParameterType
local pname = (indexer:GetGetMethod() or indexer:GetSetMethod()):GetParameters()[0].Name
%>
<%=CsFullTypeName(indexer.PropertyType)%> <%=CsFullTypeName(indexer.DeclaringType)%>.this[<%=CsFullTypeName(ptype)%> <%=pname%>]
{<%if indexer:GetGetMethod() then
local method = indexer:GetGetMethod()
local parameters = method:GetParameters()
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (method.ReturnType.FullName ~= "System.Void")
local return_type_name = has_return and CsFullTypeName(method.ReturnType) or "void"
local out_idx = has_return and 2 or 1
if has_return then out_num = out_num + 1 end
%>
get
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
<%if CallNeedTranslator(method, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "<%=method.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(err_func - 1);
}
if(!LuaAPI.lua_isfunction(L, -1))
{
LuaAPI.xlua_pushasciistring(L, "no such function <%=method.Name%>");
luaEnv.ThrowExceptionFromError(err_func - 1);
}
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.lua_remove(L, -3);
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
int __gen_error = LuaAPI.lua_pcall(L, <%=has_v_params and ((in_num) .. " + " .. parameters[param_count - 1].Name .. ".Length" ) or (in_num + 1)%>, <%=out_num%>, err_func);
if (__gen_error != 0)
luaEnv.ThrowExceptionFromError(err_func - 1);
<%ForEachCsList(parameters, function(parameter)
if parameter.IsOut or parameter.ParameterType.IsByRef then
%><%=GetCasterStatement(parameter.ParameterType, "err_func" .. (" + "..out_idx), parameter.Name)%>;
<%
out_idx = out_idx + 1
end
end) %>
<%if has_return then %><%=GetCasterStatement(method.ReturnType, "err_func + 1", "__gen_ret", true)%>;<% end%>
LuaAPI.lua_settop(L, err_func - 1);
<%if has_return then %>return __gen_ret;<% end%>
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end%>
<%if indexer:GetSetMethod() then
local method = indexer:GetSetMethod()
local parameters = method:GetParameters()
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (method.ReturnType.FullName ~= "System.Void")
local return_type_name = has_return and CsFullTypeName(method.ReturnType) or "void"
local out_idx = has_return and 2 or 1
if has_return then out_num = out_num + 1 end
%>
set
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
<%if CallNeedTranslator(method, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "<%=method.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(err_func - 1);
}
if(!LuaAPI.lua_isfunction(L, -1))
{
LuaAPI.xlua_pushasciistring(L, "no such function <%=method.Name%>");
luaEnv.ThrowExceptionFromError(err_func - 1);
}
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.lua_remove(L, -3);
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
int __gen_error = LuaAPI.lua_pcall(L, <%=has_v_params and ((in_num) .. " + " .. parameters[param_count - 1].Name .. ".Length" ) or (in_num + 1)%>, <%=out_num%>, err_func);
if (__gen_error != 0)
luaEnv.ThrowExceptionFromError(err_func - 1);
<%ForEachCsList(parameters, function(parameter)
if parameter.IsOut or parameter.ParameterType.IsByRef then
%><%=GetCasterStatement(parameter.ParameterType, "err_func" .. (" + "..out_idx), parameter.Name)%>;
<%
out_idx = out_idx + 1
end
end) %>
<%if has_return then %><%=GetCasterStatement(method.ReturnType, "err_func + 1", "__gen_ret", true)%>;<% end%>
LuaAPI.lua_settop(L, err_func - 1);
<%if has_return then %>return __gen_ret;<% end%>
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end%>
}
<%end)%>
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7165d08e91378494dadeb10e5338accb
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,140 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using System;
using System.Collections.Generic;
using System.Reflection;
<%
require "TemplateCommon"
%>
namespace XLua.CSObjectWrap
{
public class XLua_Gen_Initer_Register__
{
<%
local split_method_perfix = 'wrapInit'
local split_method_count = 0
local wrap_in_split_method = 0
local max_wrap_in_split_method = 50
%>
<%ForEachCsList(wraps, function(wrap)%>
<%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator)
{
<%end%>
translator.DelayWrapLoader(typeof(<%=CsFullTypeName(wrap)%>), <%=CSVariableName(wrap)%>Wrap.__Register);
<%if wrap_in_split_method == max_wrap_in_split_method then
wrap_in_split_method = 0
split_method_count = split_method_count + 1
%>
}
<%else
wrap_in_split_method = wrap_in_split_method + 1
end
end)%>
<% if generic_wraps then
for generic_def, instances in pairs(generic_wraps) do
for _, args in ipairs(instances) do
local generic_arg_list = "<"
ForEachCsList(args, function(generic_arg, gai)
if gai ~= 0 then generic_arg_list = generic_arg_list .. ", " end
generic_arg_list = generic_arg_list .. CsFullTypeName(generic_arg)
end)
generic_arg_list = generic_arg_list .. ">"
%>
<%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator)
{
<%end%>
translator.DelayWrapLoader(typeof(<%=generic_def.Name:gsub("`%d+", "") .. generic_arg_list%>), <%=CSVariableName(generic_def)%>Wrap<%=generic_arg_list%>.__Register);
<%if wrap_in_split_method == max_wrap_in_split_method then
wrap_in_split_method = 0
split_method_count = split_method_count + 1
%>
}
<%else
wrap_in_split_method = wrap_in_split_method + 1
end
end
end
end%>
<%if wrap_in_split_method ~= 0 then
split_method_count = split_method_count + 1
%>}<%end%>
static void Init(LuaEnv luaenv, ObjectTranslator translator)
{
<%for i = 1, split_method_count do%>
<%=split_method_perfix%><%=(i - 1)%>(luaenv, translator);
<%end%>
<%ForEachCsList(itf_bridges, function(itf_bridge)%>
translator.AddInterfaceBridgeCreator(typeof(<%=CsFullTypeName(itf_bridge)%>), <%=CSVariableName(itf_bridge)%>Bridge.__Create);
<%end)%>
}
static XLua_Gen_Initer_Register__()
{
XLua.LuaEnv.AddIniter(Init);
}
}
}
namespace XLua
{
public partial class ObjectTranslator
{
static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ s_gen_reg_dumb_obj = new XLua.CSObjectWrap.XLua_Gen_Initer_Register__();
static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ gen_reg_dumb_obj {get{return s_gen_reg_dumb_obj;}}
}
internal partial class InternalGlobals
{
<%
local type_to_methods = {}
local seq_tbl = {}
ForEachCsList(extension_methods, function(extension_method, idx)
local parameters = extension_method:GetParameters()
local type = parameters[0].ParameterType
if not type_to_methods[type] then
type_to_methods[type] = {type = type}
table.insert(seq_tbl, type_to_methods[type])
end
table.insert(type_to_methods[type], {method = extension_method, index = idx})
%>
delegate <%=CsFullTypeName(extension_method.ReturnType)%> __GEN_DELEGATE<%=idx%>(<%ForEachCsList(parameters, function(parameter, pi)
%><%if pi ~= 0 then%>, <%end%><%if parameter.IsOut then %>out <% elseif parameter.ParameterType.IsByRef then %>ref <% end %> <%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><%
end)%>);
<%end)%>
static InternalGlobals()
{
extensionMethodMap = new Dictionary<Type, IEnumerable<MethodInfo>>()
{
<%for _, methods_info in ipairs(seq_tbl) do%>
{typeof(<%=CsFullTypeName(methods_info.type)%>), new List<MethodInfo>(){
<% for _, method_info in ipairs(methods_info) do%>
new __GEN_DELEGATE<%=method_info.index%>(<%=CsFullTypeName(method_info.method.DeclaringType)%>.<%=method_info.method.Name%>)
#if UNITY_WSA && !UNITY_EDITOR
.GetMethodInfo(),
#else
.Method,
#endif
<% end%>
}},
<%end%>
};
genTryArrayGetPtr = StaticLuaCallbacks.__tryArrayGet;
genTryArraySetPtr = StaticLuaCallbacks.__tryArraySet;
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e416b82ec9fe340458f97cf1e3468ef7
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,140 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using System;
using System.Collections.Generic;
using System.Reflection;
<%
require "TemplateCommon"
%>
namespace XLua.CSObjectWrap
{
public class XLua_Gen_Initer_Register__
{
<%
local split_method_perfix = 'wrapInit'
local split_method_count = 0
local wrap_in_split_method = 0
local max_wrap_in_split_method = 50
%>
<%ForEachCsList(wraps, function(wrap)%>
<%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator)
{
<%end%>
translator.DelayWrapLoader(typeof(<%=CsFullTypeName(wrap)%>), translator.__Register<%=CSVariableName(wrap)%>);
<%if wrap_in_split_method == max_wrap_in_split_method then
wrap_in_split_method = 0
split_method_count = split_method_count + 1
%>
}
<%else
wrap_in_split_method = wrap_in_split_method + 1
end
end)%>
<% if generic_wraps then
for generic_def, instances in pairs(generic_wraps) do
for _, args in ipairs(instances) do
local generic_arg_list = "<"
ForEachCsList(args, function(generic_arg, gai)
if gai ~= 0 then generic_arg_list = generic_arg_list .. ", " end
generic_arg_list = generic_arg_list .. CsFullTypeName(generic_arg)
end)
generic_arg_list = generic_arg_list .. ">"
%>
<%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator)
{
<%end%>
translator.DelayWrapLoader(typeof(<%=generic_def.Name:gsub("`%d+", "") .. generic_arg_list%>), translator.__Register<%=CSVariableName(generic_def)%><%=generic_arg_list%>);
<%if wrap_in_split_method == max_wrap_in_split_method then
wrap_in_split_method = 0
split_method_count = split_method_count + 1
%>
}
<%else
wrap_in_split_method = wrap_in_split_method + 1
end
end
end
end%>
<%if wrap_in_split_method ~= 0 then
split_method_count = split_method_count + 1
%>}<%end%>
static void Init(LuaEnv luaenv, ObjectTranslator translator)
{
<%for i = 1, split_method_count do%>
<%=split_method_perfix%><%=(i - 1)%>(luaenv, translator);
<%end%>
<%ForEachCsList(itf_bridges, function(itf_bridge)%>
translator.AddInterfaceBridgeCreator(typeof(<%=CsFullTypeName(itf_bridge)%>), <%=CSVariableName(itf_bridge)%>Bridge.__Create);
<%end)%>
}
static XLua_Gen_Initer_Register__()
{
XLua.LuaEnv.AddIniter(Init);
}
}
}
namespace XLua
{
public partial class ObjectTranslator
{
static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ s_gen_reg_dumb_obj = new XLua.CSObjectWrap.XLua_Gen_Initer_Register__();
static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ gen_reg_dumb_obj {get{return s_gen_reg_dumb_obj;}}
}
internal partial class InternalGlobals
{
<%
local type_to_methods = {}
local seq_tbl = {}
ForEachCsList(extension_methods, function(extension_method, idx)
local parameters = extension_method:GetParameters()
local type = parameters[0].ParameterType
if not type_to_methods[type] then
type_to_methods[type] = {type = type}
table.insert(seq_tbl, type_to_methods[type])
end
table.insert(type_to_methods[type], {method = extension_method, index = idx})
%>
delegate <%=CsFullTypeName(extension_method.ReturnType)%> __GEN_DELEGATE<%=idx%>(<%ForEachCsList(parameters, function(parameter, pi)
%><%if pi ~= 0 then%>, <%end%><%if parameter.IsOut then %>out <% elseif parameter.ParameterType.IsByRef then %>ref <% end %> <%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><%
end)%>);
<%end)%>
static InternalGlobals()
{
extensionMethodMap = new Dictionary<Type, IEnumerable<MethodInfo>>()
{
<%for _, methods_info in ipairs(seq_tbl) do%>
{typeof(<%=CsFullTypeName(methods_info.type)%>), new List<MethodInfo>(){
<% for _, method_info in ipairs(methods_info) do%>
new __GEN_DELEGATE<%=method_info.index%>(<%=CsFullTypeName(method_info.method.DeclaringType)%>.<%=method_info.method.Name%>)
#if UNITY_WSA && !UNITY_EDITOR
.GetMethodInfo(),
#else
.Method,
#endif
<% end%>
}},
<%end%>
};
genTryArrayGetPtr = StaticLuaCallbacks.__tryArrayGet;
genTryArraySetPtr = StaticLuaCallbacks.__tryArraySet;
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 46c7366d55afbf1459674448d92c44c8
timeCreated: 1501232428
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,233 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using System;
<%
require "TemplateCommon"
%>
namespace XLua
{
public partial class ObjectTranslator
{
<%if purevaluetypes.Count > 0 then
local init_class_name = "IniterAdder" .. CSVariableName(purevaluetypes[0].Type)
%>
class <%=init_class_name%>
{
static <%=init_class_name%>()
{
LuaEnv.AddIniter(Init);
}
static void Init(LuaEnv luaenv, ObjectTranslator translator)
{
<%ForEachCsList(purevaluetypes, function(type_info)
if not type_info.Type.IsValueType then return end
local full_type_name = CsFullTypeName(type_info.Type)%>
translator.RegisterPushAndGetAndUpdate<<%=full_type_name%>>(translator.Push<%=CSVariableName(type_info.Type)%>, translator.Get, translator.Update<%=CSVariableName(type_info.Type)%>);<%
end)%>
<%ForEachCsList(tableoptimzetypes, function(type_info)
local full_type_name = CsFullTypeName(type_info.Type)%>
translator.RegisterCaster<<%=full_type_name%>>(translator.Get);<%
end)%>
}
}
static <%=init_class_name%> s_<%=init_class_name%>_dumb_obj = new <%=init_class_name%>();
static <%=init_class_name%> <%=init_class_name%>_dumb_obj {get{return s_<%=init_class_name%>_dumb_obj;}}
<%end%>
<%ForEachCsList(purevaluetypes, function(type_info)
local type_id_var_name = CSVariableName(type_info.Type) .. '_TypeID'
local enum_ref_var_name = CSVariableName(type_info.Type)..'_EnumRef'
local full_type_name = CsFullTypeName(type_info.Type)
local is_enum = type_info.Type.IsEnum
%>int <%=type_id_var_name%> = -1;<%if is_enum then%>
int <%=enum_ref_var_name%> = -1;
<%end%>
public void Push<%=CSVariableName(type_info.Type)%>(RealStatePtr L, <%=full_type_name%> val)
{
if (<%=type_id_var_name%> == -1)
{
bool is_first;
<%=type_id_var_name%> = getTypeId(L, typeof(<%=full_type_name%>), out is_first);
<%if is_enum then%>
if (<%=enum_ref_var_name%> == -1)
{
Utils.LoadCSTable(L, typeof(<%=full_type_name%>));
<%=enum_ref_var_name%> = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
}
<%end%>
}
<%if is_enum then%>
if (LuaAPI.xlua_tryget_cachedud(L, (int)val, <%=enum_ref_var_name%>) == 1)
{
return;
}
<%
end
if type_info.Flag == CS.XLua.OptimizeFlag.PackAsTable then
%>
<%if PushObjectNeedTranslator(type_info) then %> ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%>
LuaAPI.xlua_pushcstable(L, <%=type_info.FieldInfos.Count%>, <%=type_id_var_name%>);
<%ForEachCsList(type_info.FieldInfos, function(fieldInfo)%>
LuaAPI.xlua_pushasciistring(L, "<%=fieldInfo.Name%>");
<%=GetPushStatement(fieldInfo.Type, "val."..fieldInfo.Name)%>;
LuaAPI.lua_rawset(L, -3);
<%end)%>
<%else%>
IntPtr buff = LuaAPI.xlua_pushstruct(L, <%=is_enum and 4 or type_info.Size%>, <%=type_id_var_name%>);
if (!CopyByValue.Pack(buff, 0, <%=is_enum and "(int)" or ""%>val))
{
throw new Exception("pack fail fail for <%=full_type_name%> ,value="+val);
}
<%
end
if is_enum then
%>
LuaAPI.lua_getref(L, <%=enum_ref_var_name%>);
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.xlua_rawseti(L, -2, (int)val);
LuaAPI.lua_pop(L, 1);
<%end%>
}
public void Get(RealStatePtr L, int index, out <%=full_type_name%> val)
{
LuaTypes type = LuaAPI.lua_type(L, index);
if (type == LuaTypes.LUA_TUSERDATA )
{
if (LuaAPI.xlua_gettypeid(L, index) != <%=type_id_var_name%>)
{
throw new Exception("invalid userdata for <%=full_type_name%>");
}
IntPtr buff = LuaAPI.lua_touserdata(L, index);<%if is_enum then%>
int e;
<%end%>if (!CopyByValue.UnPack(buff, 0, out <%=is_enum and "e" or "val"%>))
{
throw new Exception("unpack fail for <%=full_type_name%>");
}<%if is_enum then%>
val = (<%=full_type_name%>)e;
<%end%>
}<%if not is_enum then%>
else if (type ==LuaTypes.LUA_TTABLE)
{
CopyByValue.UnPack(this, L, index, out val);
}<%end%>
else
{
val = (<%=full_type_name%>)objectCasters.GetCaster(typeof(<%=full_type_name%>))(L, index, null);
}
}
public void Update<%=CSVariableName(type_info.Type)%>(RealStatePtr L, int index, <%=full_type_name%> val)
{
<%if type_info.Flag == CS.XLua.OptimizeFlag.PackAsTable then%>
if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TTABLE)
{
return;
}
<%else%>
if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA)
{
if (LuaAPI.xlua_gettypeid(L, index) != <%=type_id_var_name%>)
{
throw new Exception("invalid userdata for <%=full_type_name%>");
}
IntPtr buff = LuaAPI.lua_touserdata(L, index);
if (!CopyByValue.Pack(buff, 0, <%=is_enum and "(int)" or ""%>val))
{
throw new Exception("pack fail for <%=full_type_name%> ,value="+val);
}
}
<%end%>
else
{
throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index));
}
}
<%end)%>
// table cast optimze
<%ForEachCsList(tableoptimzetypes, function(type_info)
local full_type_name = CsFullTypeName(type_info.Type)
%>
public void Get(RealStatePtr L, int index, out <%=full_type_name%> val)
{
LuaTypes type = LuaAPI.lua_type(L, index);
if (type == LuaTypes.LUA_TUSERDATA )
{
val = (<%=full_type_name%>)FastGetCSObj(L, index);
}
else if (type == LuaTypes.LUA_TTABLE)
{
val = new <%=full_type_name%>();
int top = LuaAPI.lua_gettop(L);
<%ForEachCsList(type_info.Fields, function(fieldInfo)%>
if (Utils.LoadField(L, index, "<%=fieldInfo.Name%>"))
{
Get(L, top + 1, out val.<%=fieldInfo.Name%>);
}
LuaAPI.lua_pop(L, 1);
<%end)%>
}<%if not type_info.Type.IsValueType then%>
else if (type == LuaTypes.LUA_TNIL || type == LuaTypes.LUA_TNONE)
{
val = null;
}<%end%>
else
{
throw new Exception("can not cast " + LuaAPI.lua_type(L, index) + " to " + typeof(<%=full_type_name%>));
}
}
<%end)%>
}
public partial class StaticLuaCallbacks
{
internal static bool __tryArrayGet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int index)
{
<%ForEachCsList(purevaluetypes, function(type_info, idx)
if not type_info.Type.IsValueType then return end
local full_type_name = CsFullTypeName(type_info.Type)
%>
<%=(idx == 0 and '' or 'else ')%>if (type == typeof(<%=full_type_name%>[]))
{
<%=full_type_name%>[] array = obj as <%=full_type_name%>[];
translator.Push<%=CSVariableName(type_info.Type)%>(L, array[index]);
return true;
}<%
end)%>
return false;
}
internal static bool __tryArraySet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int array_idx, int obj_idx)
{
<%
local is_first = true
ForEachCsList(purevaluetypes, tableoptimzetypes, function(type_info)
local full_type_name = CsFullTypeName(type_info.Type)
%>
<%=(is_first and '' or 'else ')%>if (type == typeof(<%=full_type_name%>[]))
{
<%=full_type_name%>[] array = obj as <%=full_type_name%>[];
translator.Get(L, obj_idx, out array[array_idx]);
return true;
}<%
is_first = false
end)%>
return false;
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d1a916469d261d447972d287b6c5b7a0
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,123 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLuaBase.lua_CSFunction;
#endif
using System;
<%
require "TemplateCommon"
%>
namespace XLua
{
public static partial class CopyByValue
{
<%ForEachCsList(type_infos, function(type_info)
local full_type_name = CsFullTypeName(type_info.Type)
%>
<%if type_info.IsRoot then
ForEachCsList(type_info.FieldInfos, function(fieldInfo) fieldInfo.Name = UnK(fieldInfo.Name) end)
%>
public static void UnPack(ObjectTranslator translator, RealStatePtr L, int idx, out <%=full_type_name%> val)
{
val = new <%=full_type_name%>();
int top = LuaAPI.lua_gettop(L);
<%ForEachCsList(type_info.FieldInfos, function(fieldInfo)%>
if (Utils.LoadField(L, idx, "<%=fieldInfo.Name%>"))
{
<%if fieldInfo.IsField then%>
translator.Get(L, top + 1, out val.<%=fieldInfo.Name%>);
<%else%>
var <%=fieldInfo.Name%> = val.<%=fieldInfo.Name%>;
translator.Get(L, top + 1, out <%=fieldInfo.Name%>);
val.<%=fieldInfo.Name%> = <%=fieldInfo.Name%>;
<%end%>
}
LuaAPI.lua_pop(L, 1);
<%end)%>
}
<%end%>
public static bool Pack(IntPtr buff, int offset, <%=full_type_name%> field)
{
<%
local offset_inner = 0
if not type_info.FieldGroup then
ForEachCsList(type_info.FieldInfos, function(fieldInfo)
%>
if(!Pack(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%>, field.<%=fieldInfo.Name%>))
{
return false;
}
<%
offset_inner = offset_inner + fieldInfo.Size
end)
else
ForEachCsList(type_info.FieldGroup, function(group)
%>
if(!LuaAPI.xlua_pack_float<%=(group.Count == 1 and "" or group.Count)%>(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%><%
ForEachCsList(group, function(fieldInfo, i)
%>, field.<%=fieldInfo.Name%><%
end)
%>))
{
return false;
}
<%
offset_inner = offset_inner + group.Count * 4
end)
end%>
return true;
}
public static bool UnPack(IntPtr buff, int offset, out <%=full_type_name%> field)
{
field = default(<%=full_type_name%>);
<%
local offset_inner = 0
if not type_info.FieldGroup then
ForEachCsList(type_info.FieldInfos, function(fieldInfo)
if fieldInfo.IsField then
%>
if(!UnPack(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%>, out field.<%=fieldInfo.Name%>))
{
return false;
}
<%else%>
var <%=fieldInfo.Name%> = field.<%=fieldInfo.Name%>;
if(!UnPack(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%>, out <%=fieldInfo.Name%>))
{
return false;
}
field.<%=fieldInfo.Name%> = <%=fieldInfo.Name%>;
<%
end
offset_inner = offset_inner + fieldInfo.Size
end)
else
ForEachCsList(type_info.FieldGroup, function(group)
%>
<%ForEachCsList(group, function(fieldInfo)%>float <%=fieldInfo.Name%> = default(float);
<%end)%>
if(!LuaAPI.xlua_unpack_float<%=(group.Count == 1 and "" or group.Count)%>(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%><%
ForEachCsList(group, function(fieldInfo)
%>, out <%=fieldInfo.Name%><%
end)
%>))
{
return false;
}
<%ForEachCsList(group, function(fieldInfo)%>field.<%=fieldInfo.Name%> = <%=fieldInfo.Name%>;
<%end)%>
<%
offset_inner = offset_inner + group.Count * 4
end)
end%>
return true;
}
<%end)%>
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c9ef7e8f2a3b37744aad49b99370c16b
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,471 @@
-- Tencent is pleased to support the open source community by making xLua available.
-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
-- http://opensource.org/licenses/MIT
-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
local friendlyNameMap = {
["System.Object"] = "object",
["System.String"] = "string",
["System.Boolean"] = "bool",
["System.Byte"] = "byte",
["System.Char"] = "char",
["System.Decimal"] = "decimal",
["System.Double"] = "double",
["System.Int16"] = "short",
["System.Int32"] = "int",
["System.Int64"] = "long",
["System.SByte"] = "sbyte",
["System.Single"] = "float",
["System.UInt16"] = "ushort",
["System.UInt32"] = "uint",
["System.UInt64"] = "ulong",
["System.Void"] = "void",
}
local csKeywords = {
"abstract", "as", "base", "bool",
"break", "byte", "case", "catch",
"char", "checked", "class", "const",
"continue", "decimal", "default", "delegate",
"do", "double", "else", "enum",
"event", "explicit", "extern", "false",
"finally", "fixed", "float", "for",
"foreach", "goto", "if", "implicit",
"in", "int", "interface",
"internal", "is", "lock", "long",
"namespace", "new", "null", "object",
"operator", "out", "override",
"params", "private", "protected", "public",
"readonly", "ref", "return", "sbyte",
"sealed", "short", "sizeof", "stackalloc",
"static", "string", "struct", "switch",
"this", "throw", "true", "try",
"typeof", "uint", "ulong", "unchecked",
"unsafe", "ushort", "using", "virtual",
"void", "volatile", "while"
}
for _, kw in ipairs(csKeywords) do
csKeywords[kw] = '@'..kw
end
for i = 1, #csKeywords do
csKeywords[i] = nil
end
function UnK(symbol)
return csKeywords[symbol] or symbol
end
local fixChecker = {
--["System.String"] = "LuaAPI.lua_isstring",
["System.Boolean"] = "LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type",
["System.Byte"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.Char"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
--["System.Decimal"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.Double"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.Int16"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.Int32"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
--["System.Int64"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.SByte"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.Single"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.UInt16"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.UInt32"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
--["System.UInt64"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.IntPtr"] = "LuaTypes.LUA_TLIGHTUSERDATA == LuaAPI.lua_type",
}
local typedCaster = {
["System.Byte"] = "LuaAPI.xlua_tointeger",
["System.Char"] = "LuaAPI.xlua_tointeger",
["System.Int16"] = "LuaAPI.xlua_tointeger",
["System.SByte"] = "LuaAPI.xlua_tointeger",
["System.Single"] = "LuaAPI.lua_tonumber",
["System.UInt16"] = "LuaAPI.xlua_tointeger",
}
local fixCaster = {
["System.Double"] = "LuaAPI.lua_tonumber",
["System.String"] = "LuaAPI.lua_tostring",
["System.Boolean"] = "LuaAPI.lua_toboolean",
["System.Byte[]"] = "LuaAPI.lua_tobytes",
["System.IntPtr"] = "LuaAPI.lua_touserdata",
["System.UInt32"] = "LuaAPI.xlua_touint",
["System.UInt64"] = "LuaAPI.lua_touint64",
["System.Int32"] = "LuaAPI.xlua_tointeger",
["System.Int64"] = "LuaAPI.lua_toint64",
}
local fixPush = {
["System.Byte"] = "LuaAPI.xlua_pushinteger",
["System.Char"] = "LuaAPI.xlua_pushinteger",
["System.Int16"] = "LuaAPI.xlua_pushinteger",
["System.Int32"] = "LuaAPI.xlua_pushinteger",
["System.Int64"] = "LuaAPI.lua_pushint64",
["System.SByte"] = "LuaAPI.xlua_pushinteger",
["System.Single"] = "LuaAPI.lua_pushnumber",
["System.UInt16"] = "LuaAPI.xlua_pushinteger",
["System.UInt32"] = "LuaAPI.xlua_pushuint",
["System.UInt64"] = "LuaAPI.lua_pushuint64",
["System.Double"] = "LuaAPI.lua_pushnumber",
["System.String"] = "LuaAPI.lua_pushstring",
["System.Byte[]"] = "LuaAPI.lua_pushstring",
["System.Boolean"] = "LuaAPI.lua_pushboolean",
["System.IntPtr"] = "LuaAPI.lua_pushlightuserdata",
["System.Decimal"] = "translator.PushDecimal",
["System.Object"] = "translator.PushAny",
}
local notranslator = {
["System.Byte"] = true,
["System.Char"] = true,
["System.Int16"] = true,
["System.Int32"] = true,
["System.Int64"] = true,
["System.SByte"] = true,
["System.Single"] = true,
["System.UInt16"] = true,
["System.UInt32"] = true,
["System.UInt64"] = true,
["System.Double"] = true,
["System.String"] = true,
["System.Boolean"] = true,
["System.Void"] = true,
["System.IntPtr"] = true,
["System.Byte[]"] = true,
}
function ForEachCsList(...)
local list_count = select('#', ...) - 1
local callback = select(list_count + 1, ...)
for i = 1, list_count do
local list = select(i, ...)
for i = 0, (list.Count or list.Length) - 1 do
callback(list[i], i)
end
end
end
function CalcCsList(list, predicate)
local count = 0
for i = 0, (list.Count or list.Length) - 1 do
if predicate(list[i], i) then count = count + 1 end
end
return count
end
function IfAny(list, predicate)
for i = 0, (list.Count or list.Length) - 1 do
if predicate(list[i], i) then return true end
end
return false
end
local genPushAndUpdateTypes
function SetGenPushAndUpdateTypes(list)
genPushAndUpdateTypes = {}
ForEachCsList(list, function(t)
genPushAndUpdateTypes[t] = true
end)
end
local xLuaClasses
function SetXLuaClasses(list)
xLuaClasses = {}
ForEachCsList(list, function(t)
xLuaClasses[t.Name] = true
end)
end
local objType = typeof(CS.System.Object)
local valueType = typeof(CS.System.ValueType)
local function _CsFullTypeName(t)
if t.IsArray then
local element_name, element_is_array = _CsFullTypeName(t:GetElementType())
if element_is_array then
local bracket_pos = element_name:find('%[')
return element_name:sub(1, bracket_pos - 1) .. '[' .. string.rep(',', t:GetArrayRank() - 1) .. ']' .. element_name:sub(bracket_pos, -1), true
else
return element_name .. '[' .. string.rep(',', t:GetArrayRank() - 1) .. ']', true
end
elseif t.IsByRef then
return _CsFullTypeName(t:GetElementType())
elseif t.IsGenericParameter then
return (t.BaseType == objType or t.BaseType == valueType) and t.Name or _CsFullTypeName(t.BaseType) --TODO:应该判断是否类型约束
end
local name = t.FullName:gsub("&", ""):gsub("%+", ".")
if not t.IsGenericType then
return friendlyNameMap[name] or name
end
local genericParameter = ""
ForEachCsList(t:GetGenericArguments(), function(at, ati)
if ati ~= 0 then genericParameter = genericParameter .. ', ' end
genericParameter = genericParameter .. _CsFullTypeName(at)
end)
return name:gsub("`%d+", '<' .. genericParameter .. '>'):gsub("%[[^,%]].*", ""), false
end
function CsFullTypeName(t)
if t.DeclaringType then
local name = _CsFullTypeName(t)
local declaringTypeName = _CsFullTypeName(t.DeclaringType);
return xLuaClasses[declaringTypeName] and ("global::" .. name) or name
else
local name = _CsFullTypeName(t)
return xLuaClasses[name] and ("global::" .. name) or name
end
end
function CSVariableName(t)
if t.IsArray then
return CSVariableName(t:GetElementType()) .. '_'.. t:GetArrayRank() ..'_'
end
return t:ToString():gsub("&", ""):gsub("%+", ""):gsub("`", "_"):gsub("%.", ""):gsub("%[", "_"):gsub("%]", "_"):gsub(",", "")
end
local function getSafeFullName(t)
if t == nil then
return ""
end
if t.IsGenericParameter then
return t.BaseType == objType and t.Name or getSafeFullName(t.BaseType)
end
if not t.FullName then return "" end
return t.FullName:gsub("&", "")
end
function GetCheckStatement(t, idx, is_v_params)
local cond_start = is_v_params and "(LuaTypes.LUA_TNONE == LuaAPI.lua_type(L, ".. idx ..") || " or ""
local cond_end = is_v_params and ")" or ""
local testname = getSafeFullName(t)
if testname == "System.String" or testname == "System.Byte[]" then
return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TSTRING)" .. cond_end
elseif testname == "System.Int64" then
return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || LuaAPI.lua_isint64(L, ".. idx .."))" .. cond_end
elseif testname == "System.UInt64" then
return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || LuaAPI.lua_isuint64(L, ".. idx .."))" .. cond_end
elseif testname == "System.Decimal" then
return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || translator.IsDecimal(L, ".. idx .."))" .. cond_end
elseif testname == "XLua.LuaTable" then
return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TTABLE)" .. cond_end
elseif testname == "XLua.LuaFunction" then
return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TFUNCTION)" .. cond_end
end
return cond_start .. (fixChecker[testname] or ("translator.Assignable<" .. CsFullTypeName(t).. ">")) .. "(L, ".. idx ..")" .. cond_end
end
local delegateType = typeof(CS.System.Delegate)
local ExtensionAttribute = typeof(CS.System.Runtime.CompilerServices.ExtensionAttribute)
function IsExtensionMethod(method)
return method:IsDefined(ExtensionAttribute, false)
end
function IsDelegate(t)
return delegateType:IsAssignableFrom(t)
end
function MethodParameters(method)
if not IsExtensionMethod(method) then
return method:GetParameters()
else
local parameters = method:GetParameters()
if parameters[0].ParameterType.IsInterface then
return parameters
end
local ret = {}
for i = 1, parameters.Length - 1 do
ret[i - 1] = parameters[i]
end
ret.Length = parameters.Length - 1
return ret
end
end
function IsStruct(t)
if t.IsByRef then t = t:GetElementType() end
return t.IsValueType and not t.IsPrimitive
end
function NeedUpdate(t)
if t.IsByRef then t = t:GetElementType() end
return t.IsValueType and not t.IsPrimitive and not t.IsEnum and t ~= typeof(CS.System.Decimal)
end
function GetCasterStatement(t, idx, var_name, need_declare, is_v_params)
local testname = getSafeFullName(t)
local statement = ""
local is_struct = IsStruct(t)
if need_declare then
statement = CsFullTypeName(t) .. " " .. var_name
if is_struct and not typedCaster[testname] and not fixCaster[testname] then
statement = statement .. ";"
else
statement = statement .. " = "
end
elseif not is_struct then
statement = var_name .. " = "
end
if is_v_params then
return statement .. "translator.GetParams<" .. CsFullTypeName(t:GetElementType()).. ">" .. "(L, ".. idx ..")"
elseif typedCaster[testname] then
return statement .. "(" .. CsFullTypeName(t) .. ")" ..typedCaster[testname] .. "(L, ".. idx ..")"
elseif IsDelegate(t) then
return statement .. "translator.GetDelegate<" .. CsFullTypeName(t).. ">" .. "(L, ".. idx ..")"
elseif fixCaster[testname] then
return statement .. fixCaster[testname] .. "(L, ".. idx ..")"
elseif testname == "System.Object" then
return statement .. "translator.GetObject(L, ".. idx ..", typeof(" .. CsFullTypeName(t) .."))"
elseif is_struct then
return statement .. "translator.Get(L, ".. idx ..", out " .. var_name .. ")"
elseif t.IsGenericParameter and not t.DeclaringMethod then
return statement .. "translator.GetByType<"..t.Name..">(L, ".. idx ..")"
else
return statement .. "("..CsFullTypeName(t)..")translator.GetObject(L, ".. idx ..", typeof(" .. CsFullTypeName(t) .."))"
end
end
local paramsAttriType = typeof(CS.System.ParamArrayAttribute)
function IsParams(pi)
if (not pi.IsDefined) then
return pi.IsParamArray
end
return pi:IsDefined(paramsAttriType, false)
end
local obsoluteAttriType = typeof(CS.System.ObsoleteAttribute)
function IsObsolute(f)
return f:IsDefined(obsoluteAttriType, false)
end
local objectType = typeof(CS.System.Object)
function GetSelfStatement(t)
local fulltypename = CsFullTypeName(t)
local is_struct = IsStruct(t)
if is_struct then
return fulltypename .. " gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked)"
else
if t == objectType then
return "object gen_to_be_invoked = translator.FastGetCSObj(L, 1)"
else
return fulltypename .. " gen_to_be_invoked = (" .. fulltypename .. ")translator.FastGetCSObj(L, 1)"
end
end
end
local GetNullableUnderlyingType = CS.System.Nullable.GetUnderlyingType
function GetPushStatement(t, variable, is_v_params)
if is_v_params then
local item_push = GetPushStatement(t:GetElementType(), variable..'[__gen_i]')
return 'if ('.. variable ..' != null) { for (int __gen_i = 0; __gen_i < ' .. variable .. '.Length; ++__gen_i) ' .. item_push .. '; }'
end
if t.IsByRef then t = t:GetElementType() end
local testname = getSafeFullName(t)
if fixPush[testname] then
return fixPush[testname] .. "(L, ".. variable ..")"
elseif genPushAndUpdateTypes[t] then
return "translator.Push".. CSVariableName(t) .."(L, "..variable..")"
elseif t.IsGenericParameter and not t.DeclaringMethod then
return "translator.PushByType(L, "..variable..")"
elseif t.IsInterface or GetNullableUnderlyingType(t) then
return "translator.PushAny(L, "..variable..")"
else
return "translator.Push(L, "..variable..")"
end
end
function GetUpdateStatement(t, idx, variable)
if t.IsByRef then t = t:GetElementType() end
if typeof(CS.System.Decimal) == t then error('Decimal not update!') end
if genPushAndUpdateTypes[t] then
return "translator.Update".. CSVariableName(t) .."(L, ".. idx ..", "..variable..")"
else
return "translator.Update(L, ".. idx ..", "..variable..")"
end
end
function JustLuaType(t)
return notranslator[getSafeFullName(t)]
end
function CallNeedTranslator(overload, isdelegate)
if not overload.IsStatic and not isdelegate then return true end
local ret_type_name = getSafeFullName(overload.ReturnType)
if not notranslator[ret_type_name] then return true end
local parameters = overload:GetParameters()
return IfAny(overload:GetParameters(), function(parameter)
return IsParams(parameter) or (not notranslator[getSafeFullName(parameter.ParameterType)])
end)
end
function MethodCallNeedTranslator(method)
return IfAny(method.Overloads, function(overload) return CallNeedTranslator(overload) end)
end
function AccessorNeedTranslator(accessor)
return not accessor.IsStatic or not JustLuaType(accessor.Type)
end
function PushObjectNeedTranslator(type_info)
return IfAny(type_info.FieldInfos, function(field_info) return not JustLuaType(field_info.Type) end)
end
local GenericParameterAttributes = CS.System.Reflection.GenericParameterAttributes
local enum_and_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__band
local has_generic_flag = function(f1, f2)
return (f1 ~= GenericParameterAttributes.None) and (enum_and_op(f1, f2) == f2)
end
function GenericArgumentList(type)
local generic_arg_list = ""
local type_constraints = ""
if type.IsGenericTypeDefinition then
generic_arg_list = "<"
local constraints = {}
ForEachCsList(type:GetGenericArguments(), function(generic_arg, gai)
local constraint = {}
if gai ~= 0 then generic_arg_list = generic_arg_list .. ", " end
generic_arg_list = generic_arg_list .. generic_arg.Name
if has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.ReferenceTypeConstraint) then
table.insert(constraint, 'class')
end
if has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) then
table.insert(constraint, 'struct')
end
ForEachCsList(generic_arg:GetGenericParameterConstraints(), function(gpc)
if gpc ~= typeof(CS.System.ValueType) or not has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) then
table.insert(constraint, CsFullTypeName(gpc))
end
end)
if not has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) and has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.DefaultConstructorConstraint) then
table.insert(constraint, 'new()')
end
if #constraint > 0 then
table.insert(constraints, 'where ' .. generic_arg.Name .. ' : ' .. table.concat(constraint, ','))
end
end)
generic_arg_list = generic_arg_list .. ">"
if #constraints > 0 then
type_constraints = table.concat(constraints, ',')
end
end
return generic_arg_list, type_constraints
end
function LocalName(name)
return "_" .. name
end
@@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: cb41d53afe75a9443b182e284298feeb
TextScriptImporter:
userData:
+20
View File
@@ -0,0 +1,20 @@
using UnityEngine;
using System.Collections;
namespace XLua
{
public class TemplateRef : ScriptableObject
{
public TextAsset LuaClassWrap;
public TextAsset LuaClassWrapGCM;
public TextAsset LuaDelegateBridge;
public TextAsset LuaDelegateWrap;
public TextAsset LuaEnumWrap;
public TextAsset LuaEnumWrapGCM;
public TextAsset LuaInterfaceBridge;
public TextAsset LuaRegister;
public TextAsset LuaRegisterGCM;
public TextAsset LuaWrapPusher;
public TextAsset PackUnpack;
public TextAsset TemplateCommon;
}
}
@@ -0,0 +1,25 @@
fileFormatVersion: 2
guid: 4898604144dd928468ddca1af81d58ae
timeCreated: 1501232546
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences:
- LuaClassWrap: {fileID: 4900000, guid: 8503038eabbabe44dac0f5f749d4411a, type: 3}
- LuaClassWrapGCM: {fileID: 4900000, guid: 2bd79d95fd859724283926ad8fa4df30, type: 3}
- LuaDelegateBridge: {fileID: 4900000, guid: 3d992756e2469044484be75f78e4e556, type: 3}
- LuaDelegateWrap: {fileID: 4900000, guid: 33b33e1cd617f794b8c801a32f3b2539, type: 3}
- LuaEnumWrap: {fileID: 4900000, guid: ae16c73aad9a21a44aef65decb7e4928, type: 3}
- LuaEnumWrapGCM: {fileID: 4900000, guid: ea84a5ee7abf8e347a810eb7848add46, type: 3}
- LuaInterfaceBridge: {fileID: 4900000, guid: 7165d08e91378494dadeb10e5338accb,
type: 3}
- LuaRegister: {fileID: 4900000, guid: e416b82ec9fe340458f97cf1e3468ef7, type: 3}
- LuaRegisterGCM: {fileID: 4900000, guid: 46c7366d55afbf1459674448d92c44c8, type: 3}
- LuaWrapPusher: {fileID: 4900000, guid: d1a916469d261d447972d287b6c5b7a0, type: 3}
- PackUnpack: {fileID: 4900000, guid: c9ef7e8f2a3b37744aad49b99370c16b, type: 3}
- TemplateCommon: {fileID: 4900000, guid: cb41d53afe75a9443b182e284298feeb, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: